text:
Q: why is my sequence file being read twice in my hadoop mapper class? i have a SequenceFile with 1264 records. each key is unique for each record. my problem is that my mapper seems to be reading this file twice or it is being read twice. for sanity checking, i have written a little utility class to read the SequenceFile and indeed, there are only 1264 records (i.e. SequenceFile.Reader).
in my reducer, i should only get 1 record per Iterable, however, when i iterate over the iterable (Iterator), i get 2 records per Key (always 2 per key, and not 1 or 3 or something else per Key).
the logging output of my Job is below. i am not sure why, but why is it that the "Total input paths to process" is 2? when i run my Job, i tried -Dmapred.input.dir=/data and also -Dmapred.input.dir=/data/part-r-00000, but still, the total paths to process is 2.
any ideas is appreciated.
12/03/01 05:28:30 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
12/03/01 05:28:30 INFO input.FileInputFormat: Total input paths to process : 2
12/03/01 05:28:31 INFO mapred.JobClient: Running job: job_local_0001
12/03/01 05:28:31 INFO input.FileInputFormat: Total input paths to process : 2
12/03/01 05:28:31 INFO mapred.MapTask: io.sort.mb = 100
12/03/01 05:28:31 INFO mapred.MapTask: data buffer = 79691776/99614720
12/03/01 05:28:31 INFO mapred.MapTask: record buffer = 262144/327680
12/03/01 05:28:31 INFO mapred.MapTask: Starting flush of map output
12/03/01 05:28:31 INFO mapred.MapTask: Finished spill 0
12/03/01 05:28:31 INFO mapred.TaskRunner: Task:attempt_local_0001_m_000000_0 is done. And is in the process of commiting
12/03/01 05:28:31 INFO mapred.LocalJobRunner:
12/03/01 05:28:31 INFO mapred.TaskRunner: Task 'attempt_local_0001_m_000000_0' done.
12/03/01 05:28:31 INFO mapred.MapTask: io.sort.mb = 100
12/03/01 05:28:31 INFO mapred.MapTask: data buffer = 79691776/99614720
12/03/01 05:28:31 INFO mapred.MapTask: record buffer = 262144/327680
12/03/01 05:28:31 INFO mapred.MapTask: Starting flush of map output
12/03/01 05:28:31 INFO mapred.MapTask: Finished spill 0
12/03/01 05:28:31 INFO mapred.TaskRunner: Task:attempt_local_0001_m_000001_0 is done. And is in the process of commiting
12/03/01 05:28:31 INFO mapred.LocalJobRunner:
12/03/01 05:28:31 INFO mapred.TaskRunner: Task 'attempt_local_0001_m_000001_0' done.
12/03/01 05:28:31 INFO mapred.LocalJobRunner:
12/03/01 05:28:31 INFO mapred.Merger: Merging 2 sorted segments
12/03/01 05:28:31 INFO mapred.Merger: Down to the last merge-pass, with 2 segments left of total size: 307310 bytes
12/03/01 05:28:31 INFO mapred.LocalJobRunner:
12/03/01 05:28:32 INFO mapred.TaskRunner: Task:attempt_local_0001_r_000000_0 is done. And is in the process of commiting
12/03/01 05:28:32 INFO mapred.LocalJobRunner:
12/03/01 05:28:32 INFO mapred.TaskRunner: Task attempt_local_0001_r_000000_0 is allowed to commit now
12/03/01 05:28:32 INFO mapred.JobClient:  map 100% reduce 0%
12/03/01 05:28:32 INFO output.FileOutputCommitter: Saved output of task 'attempt_local_0001_r_000000_0' to results
12/03/01 05:28:32 INFO mapred.LocalJobRunner: reduce > reduce
12/03/01 05:28:32 INFO mapred.TaskRunner: Task 'attempt_local_0001_r_000000_0' done.
12/03/01 05:28:33 INFO mapred.JobClient:  map 100% reduce 100%
12/03/01 05:28:33 INFO mapred.JobClient: Job complete: job_local_0001
12/03/01 05:28:33 INFO mapred.JobClient: Counters: 12
12/03/01 05:28:33 INFO mapred.JobClient:   FileSystemCounters
12/03/01 05:28:33 INFO mapred.JobClient:     FILE_BYTES_READ=1320214
12/03/01 05:28:33 INFO mapred.JobClient:     FILE_BYTES_WRITTEN=1275041
12/03/01 05:28:33 INFO mapred.JobClient:   Map-Reduce Framework
12/03/01 05:28:33 INFO mapred.JobClient:     Reduce input groups=1264
12/03/01 05:28:33 INFO mapred.JobClient:     Combine output records=0
12/03/01 05:28:33 INFO mapred.JobClient:     Map input records=2528
12/03/01 05:28:33 INFO mapred.JobClient:     Reduce shuffle bytes=0
12/03/01 05:28:33 INFO mapred.JobClient:     Reduce output records=2528
12/03/01 05:28:33 INFO mapred.JobClient:     Spilled Records=5056
12/03/01 05:28:33 INFO mapred.JobClient:     Map output bytes=301472
12/03/01 05:28:33 INFO mapred.JobClient:     Combine input records=0
12/03/01 05:28:33 INFO mapred.JobClient:     Map output records=2528
12/03/01 05:28:33 INFO mapred.JobClient:     Reduce input records=2528

My mapper class is very simple. It reads in a text file. To each line, it appends "m" to the line.
public class MyMapper extends Mapper<LongWritable, Text, LongWritable, Text> {

 private static final Log _log = LogFactory.getLog(MyMapper.class);

 @Override
 public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  String s = (new StringBuilder()).append(value.toString()).append("m").toString();
  context.write(key, new Text(s));
  _log.debug(key.toString() + " => " + s);
 }
}

My reducer class is also very simple. It simply appends "r" to the line.
public class MyReducer extends Reducer<LongWritable, Text, LongWritable, Text> {

private static final Log _log = LogFactory.getLog(MyReducer.class);

@Override
public void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
 for(Iterator<Text> it = values.iterator(); it.hasNext();) {
  Text txt = it.next();
  String s = (new StringBuilder()).append(txt.toString()).append("r").toString();
  context.write(key, new Text(s));
  _log.debug(key.toString() + " => " + s);
  }
 }
}

my Job class is as follows.
public class MyJob extends Configured implements Tool {

public static void main(String[] args) throws Exception {
 ToolRunner.run(new Configuration(), new MyJob(), args);
}

@Override
public int run(String[] args) throws Exception {
 Configuration conf = getConf();
 Path input = new Path(conf.get("mapred.input.dir"));
 Path output = new Path(conf.get("mapred.output.dir"));

 System.out.println("input = " + input);
 System.out.println("output = " + output);

 Job job = new Job(conf, "dummy job");
 job.setMapOutputKeyClass(LongWritable.class);
 job.setMapOutputValueClass(Text.class);
 job.setOutputKeyClass(LongWritable.class);
 job.setOutputValueClass(Text.class);

 job.setMapperClass(MyMapper.class);
 job.setReducerClass(MyReducer.class);

 FileInputFormat.addInputPath(job, input);
 FileOutputFormat.setOutputPath(job, output);

 job.setJarByClass(MyJob.class);

 return job.waitForCompletion(true) ? 0 : 1;
 }
}

my input data looks like the following.
T, T
T, T
T, T
F, F
F, F
F, F
F, F
T, F
F, T

after running my Job, i get an output like the following.
0   T, Tmr
0   T, Tmr
6   T, Tmr
6   T, Tmr
12  T, Tmr
12  T, Tmr
18  F, Fmr
18  F, Fmr
24  F, Fmr
24  F, Fmr
30  F, Fmr
30  F, Fmr
36  F, Fmr
36  F, Fmr
42  T, Fmr
42  T, Fmr
48  F, Tmr
48  F, Tmr

did i do something wrong with setting up my Job? i tried the following way to run my Job, and in this approach, the file only gets read once. why is this? the System.out.println(inpath) and System.out.println(outpath) values are identical! help?
public class MyJob2 {

public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length != 2) {
      System.err.println("Usage: MyJob2 <in> <out>");
      System.exit(2);
    }

    String sInput = args[0];
    String sOutput = args[1];

    Path input = new Path(sInput);
    Path output = new Path(sOutput);

    System.out.println("input = " + input);
    System.out.println("output = " + output);

    Job job = new Job(conf, "dummy job");
    job.setMapOutputKeyClass(LongWritable.class);
    job.setMapOutputValueClass(Text.class);
    job.setOutputKeyClass(LongWritable.class);
    job.setOutputValueClass(Text.class);

    job.setMapperClass(MyMapper.class);
    job.setReducerClass(MyReducer.class);

    FileInputFormat.addInputPath(job, input);
    FileOutputFormat.setOutputPath(job, output);

    job.setJarByClass(MyJob2.class);

    int result = job.waitForCompletion(true) ? 0 : 1;
    System.exit(result);
 }
}

A: i got help from the hadoop mailing list. my problem was with the line below.
FileInputFormat.addInputPath(job, input);

this line simply appends input back to config. after commenting this line out, the input file is read only once now. in fact, i also commented out the other line,
FileOutputFormat.setOutputPath(job, output);

and everything still works.

A: I've had a similar problem, but for a different reason: linux apparently created a hidden copy of my input file (~input.txt), so that's a second way of getting this error..


text:
Q: How to improve a 'rsync' command in order to create all sub-directories needed if those doesn't exist yet? I am using Ruby on Rails and the Capistrano gem. I would like to improve the following command that runs in a recipe (I was inspired by the blog post "Uploading files for enki using capistrano"):
rsync -qrpt --delete --rsh=ssh public/system/assets/users/001 #{user}@#{domain}:/www/.../shared/system/assets/001

so to make possible to create sub-directories "on the fly". At this time, since on the remote machine the assets/users/001 directory does not exist yet, I get the following error:
rsync: mkdir "/www/.../shared/system/assets/users/001" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at main.c(595) [Receiver=3.0.7]
rsync: connection unexpectedly closed (8 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /SourceCache/rsync/rsync-40/rsync/io.c(452) [sender=2.6.9]

How can I create all needed sub-directories so to avoid errors?
BTW: what the -qrpt part means?

A: Try adding the -R option:
-R, --relative              use relative path names

per http://ubuntuforums.org/showthread.php?t=1670723
read http://ss64.com/bash/rsync.html
-r, --recursive             recurse into directories
-p, --perms                 preserve permissions
-q, --quiet                 decrease verbosity
-t, --times                 preserve times

A: Not sure how you'd do it from within Rsync, but here's a Ruby solution.
Call safe_create_path with your desired path before the rsync script.
# Creates a path with all subdirectories in case any doesn't exist.
def safe_create_path(path_name)
  safe_create_helper(path_name)
end

def safe_create_helper(path_name)
  dir_name = File.dirname(path_name)
  if (!File.directory?(dir_name))
    safe_create_helper(path_name)
  end
  Dir.mkdir(path_name)
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Service with multiple broadcastreceivers I have a service running in background and a broadcastreceiver that alerts me when an app is installed. Can i register another broadcastreceiver that notifies me when an app is uninstalled, in the same service?
public class Service extends android.app.Service {
    BroadcastReceiver receiver;
    ...

public class InstallationReceiver extends BroadcastReceiver{

        public InstallationReceiver() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "DS notify APP INSTALLED").show();

        }
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onStart(Intent intent, int startId) {
    //Set the intentFilter and register the receiver
    counter++;
    super.onStart(intent, startId);
    Toast ts = Toast.makeText(this, "Ds Started"+counter+" times" , Toast.LENGTH_LONG);
    ts.setGravity(Gravity.CENTER, 0,0);
    ts.show();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
    intentFilter.addDataScheme("package");
    receiver = new InstallationReceiver();
    registerReceiver(receiver, intentFilter);

}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast ts = Toast.makeText(this, "Ds stopped" , Toast.LENGTH_LONG);
    ts.setGravity(Gravity.CENTER, 0,0);
    ts.show();
}

EDIT: Added code of my working code with only a receiver for installation events. It is nested in service class, so i don't need to declare it as receiver in manifest. My question is: Can i nest another receiver (I.E. receiver for uninstall events) in the same way i did for installation receiver?

A: It should be possible even with just the original broadcast receiver, you just need to go into your manifest and add the necessary intent to that receivers intent-filter. Registering another receiver to accomplish this is acceptable if you don't want to bother coding up the logic to differentiate between the two, and is probably a better situation long term if you plan on adding different functionality.
I don't know myself what specific intent there is to listen for an uninstall, but if you found the install intent, it should be similar.

A: Yes, you can do pretty much anything in this area, just listen register to get a PACKAGE_REMOVED intent
See: http://developer.android.com/guide/faq/framework.html#7


text:
Q: php Uncaught Error: Class 'BitWasp\Bitcoin\Key\PrivateKeyFactory' not found im trying to add a library to my php. I already downloaded all the files from composer but a fatal error happended. here is my code :
  require_once('vendor/autoload.php');
      use BitWasp\Bitcoin\Bitcoin;
      use BitWasp\Bitcoin\Address\AddressCreator;
      use BitWasp\Bitcoin\Key\PrivateKeyFactory;
      use BitWasp\Bitcoin\Key\KeyToScript\Factory\P2pkhScriptDataFactory;

        //Rest of my code

ERROR 1 -> Uncaught Error: Class 'BitWasp\Bitcoin\Key\PrivateKeyFactory' not found
ERROR 2 -> Class 'BitWasp\Bitcoin\Key\PrivateKeyFactory' not found

A: Shouldn't that namespace be BitWasp\Bitcoin\Key\Factory\PrivateKeyFactory?
See here https://github.com/Bit-Wasp/bitcoin-php/blob/1.0/src/Key/Factory/PrivateKeyFactory.php#L5


text:
Q: Tensorflow: There is a difference in gradient and loss for the same structure With gradient and loss, I experiment with the learning process of a neural network.
I assumed that learning process(loss function value, gradient value) are same if learning conditions(model structure, initialization, batch input stream) of two models are same.
Under the same initialization, I thought that the gradient and loss calculated for each model would be the same, but the result was not.
The code I have run is the most basic learning code, as shown below.
(to constrained the randomness of dropout, I just deactivated the dropout layer)
import tensorflow as tf
import numpy as np
#from pprint import pprint
from tensorflow.examples.tutorials.mnist import input_data

batch_size = 128
test_size = 256

def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01, seed=1))

def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden):

    l1a = tf.nn.relu(tf.nn.conv2d(X, w,                       # l1a shape=(?, 28, 28, 32)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1],              # l1 shape=(?, 14, 14, 32)
                        strides=[1, 2, 2, 1], padding='SAME')
    #l1 = tf.nn.dropout(l1, p_keep_conv)

    l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,                     # l2a shape=(?, 14, 14, 64)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1],              # l2 shape=(?, 7, 7, 64)
                        strides=[1, 2, 2, 1], padding='SAME')
    #l2 = tf.nn.dropout(l2, p_keep_conv)

    l3a = tf.nn.relu(tf.nn.conv2d(l2, w3,                     # l3a shape=(?, 7, 7, 128)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1],              # l3 shape=(?, 4, 4, 128)
                        strides=[1, 2, 2, 1], padding='SAME')
    l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]])    # reshape to (?, 2048)
    #l3 = tf.nn.dropout(l3, p_keep_conv)

    l4 = tf.nn.relu(tf.matmul(l3, w4))
    #l4 = tf.nn.dropout(l4, p_keep_hidden)

    pyx = tf.matmul(l4, w_o)
    return pyx

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1)  # 28x28x1 input img
teX = teX.reshape(-1, 28, 28, 1)  # 28x28x1 input img

X0 = tf.placeholder("float", [None, 28, 28, 1], name='input_0')
X1 = tf.placeholder("float", [None, 28, 28, 1], name='input_1')
Y  = tf.placeholder("float", [None, 10])

with tf.variable_scope('00'):
    w0_1 = init_weights([3, 3, 1, 32])       # 3x3x1 conv, 32 outputs
    w0_2 = init_weights([3, 3, 32, 64])     # 3x3x32 conv, 64 outputs
    w0_3 = init_weights([3, 3, 64, 128])    # 3x3x32 conv, 128 outputs
    w0_4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs
    w0_o = init_weights([625, 10])         # FC 625 inputs, 10 outputs (labels)

with tf.variable_scope('01'):
    w1_1 = init_weights([3, 3, 1, 32])       # 3x3x1 conv, 32 outputs
    w1_2 = init_weights([3, 3, 32, 64])     # 3x3x32 conv, 64 outputs
    w1_3 = init_weights([3, 3, 64, 128])    # 3x3x32 conv, 128 outputs
    w1_4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs
    w1_o = init_weights([625, 10])         # FC 625 inputs, 10 outputs (labels)

p_keep_conv = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")

py_x0 = model(X0, w0_1, w0_2, w0_3, w0_4, w0_o, p_keep_conv, p_keep_hidden)
py_x1 = model(X1, w1_1, w1_2, w1_3, w1_4, w1_o, p_keep_conv, p_keep_hidden)

cost0 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x0, labels=Y))
cost1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x1, labels=Y))

model_0_vars = [tensor for tensor in tf.trainable_variables() if '00/' in tensor.name]
model_1_vars = [tensor for tensor in tf.trainable_variables() if '01/' in tensor.name]

#pprint(model_0_vars)
#pprint(model_1_vars)

train_op_model_0_grad = tf.train.RMSPropOptimizer(0.001, 0.9).compute_gradients(cost0, var_list = model_0_vars)
train_op_model_0_apply= tf.train.RMSPropOptimizer(0.001, 0.9).apply_gradients(train_op_model_0_grad)

train_op_model_1_grad = tf.train.RMSPropOptimizer(0.001, 0.9).compute_gradients(cost1, var_list = model_1_vars)
train_op_model_1_apply= tf.train.RMSPropOptimizer(0.001, 0.9).apply_gradients(train_op_model_1_grad)

predict_op_0 = tf.argmax(py_x0, 1)
predict_op_1 = tf.argmax(py_x1, 1)

# Launch the graph in a session
with tf.Session() as sess:
    # you need to initialize all variables
    tf.initialize_all_variables().run()

    step = 0
    for i in range(2):
        #check_weight_tmp = sess.run([model_0_vars, model_1_vars])
        #check_weight.append(check_weight_tmp)

        training_batch = zip(range(0, len(trX), batch_size),
                             range(batch_size, len(trX)+1, batch_size))

        for start, end in training_batch:
            step +=1

            grad0, grad1 = \
            sess.run([train_op_model_0_grad, train_op_model_1_grad],
                     feed_dict={X0: trX[start:end], X1: trX[start:end], Y: trY[start:end],
                                p_keep_conv: 0.8, p_keep_hidden: 0.5})

            cost0_r, cost1_r = \
            sess.run([cost0, cost1],
                     feed_dict={X0: trX[start:end], X1: trX[start:end], Y: trY[start:end],
                                p_keep_conv: 0.8, p_keep_hidden: 0.5})

            sess.run([train_op_model_0_apply, train_op_model_1_apply],
                      feed_dict={X0: trX[start:end], X1: trX[start:end], Y: trY[start:end],
                                 p_keep_conv: 0.8, p_keep_hidden: 0.5})

            print("STEP: {0:5d}, {1:3.6f}, {2:3.6f}, {3:3.6f}".format(step, cost0_r, cost1_r, cost0_r - cost1_r))

        #test_indices = np.arange(len(teX)) # Get A Test Batch
        #np.random.shuffle(test_indices)
        #test_indices = test_indices[0:test_size]

        #print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==
        #                 sess.run(predict_op_0,
        #                          feed_dict={X: teX[test_indices],
        #                                     Y: teY[test_indices],
        #                                     p_keep_conv: 1.0,
        #                                     p_keep_hidden: 1.0})))

There is a noticeable difference in loss from the 200th epoch.
I think I have missed it, but I can't figure it out even I spend a long time to look at it.
I would appreciate if you could let me know what I am missing.

A: This difference in loss can happen because of overfitting, when the program has already trained itself to recognise the data, and is now over-generalises input. I experienced it myself while training an audio tool.


text:
Q: Groovy SQL ignores order by clause in dynamic select statement I am using Groovy SQL in a Grails application to query against a database that isn't hooked up as the application's datasource. By default for the page, the SQL select statement doesn't contain an order by clause. If the user clicks on one of the  tags, I want to dynamically change the query to sort on the specified column in the specified direction. When I attempt to add the order by clause to the select statement, I get a (caught) SQLException that says that my query was improperly ended.
My query:
sql.eachRow("select * from mytable where type = 'SUMMARY' and acolumn=${columnValue} order by ${sortColumn} ${sortOrder}") { row ->
                    results << row.toRowResult()
                }

I can get around the problem by sorting the returned list however I would like to do it in the SQL statement if at all possible. Is this a known problem?

A: It's Groovy trying to replace all your params with ? and making a PreparedStatement
This doesn't work with the ORDER BY clause, so you need to use Sql.expand
Try:
sql.eachRow( "select * from mytable where type = 'SUMMARY' and acolumn=${columnValue} order by ${Sql.expand(sortColumn)} ${Sql.expand(sortOrder)}") { row ->
  results << row.toRowResult()
}


text:
Q: CredentialCache.DefaultCredentials how to get the username and or password For debugging purpose I wanted to look in the value of username and password of CredentialCache.DefaultCredentials.
I see that there are 2 properties of username and password in CredentialCache.DefaultCredentials and doing

*

*CredentialCache.DefaultCredentials.username

*CredentialCache.DefaultCredentials.passwrod

does not print anything what should I do?


text:
Q: Map in C++ give the key and get the string I have created a map like this :   std::map<int, std::string> mapID;
INPUT: mapID[1] = "string!";
and I want to print element with the key is the s.
For example
cout << "The string is : " << mapID.at(s)->second << endl;

OR
cout << "The string is : " << mapID.find(s)->second << endl;

But I have the error

error: no matching function for call to 'std::map >::at(std::string&)'

UPDATE:
while(getline(file,s))
                   {
                           cout<< s << endl;
                           number = atoi(s.c_str());

                         cout << "The string is: " << mapID.at(number)<< endl;
}

A: If you look at the reference http://en.cppreference.com/w/cpp/container/map/at you will see, that method "at" returns a second element of pair. In your case it is std::string.
The code should be
cout << "The string is : " << mapID.at(1) << endl;

A: Since C++11, .at() returns a reference to the mapped value of the element identified with key k.
Your example was good if you used an iterator as you can then access your pair element made by your map.
Here is an example with an iterator
auto it = mapID.find(1);
cout << "The string is : " << it->second << endl;

OR with .at()
cout << "The string is : " << mapID.at(1) << endl;

But beware that .at() will throw if the element is not found in your map as it can't create it like the [] operator


text:
Q: Несколько контроллеров Добрый вечер! Мне нужно сделать несколько вариантов вытяжки из базы. То есть пользователь выбирает по какому критерию сортировать(логин, почта, id и тд). Нужно сделать это на laravel. Собственно вопрос в том, как мне подключить несколько контроллеров к одной view? Не хочется делать для каждого варианта сортировки отдельную страницу

A: Вам нет нужды подключать несколько Controllers для решения вашего вопроса. Контроллер отвечает за обработку запросов.
В данном случае, насколько я понял, перед вами стоит задача вывода на странице разных сущностей в зависимости от того, какие параметры передал пользователь.
Соответственно, в нужном методе контроллера вы проверяете введенные пользователем параметры, и в зависимости от них решаете, с какой из моделей (или несколькими сразу) вы будете работать. Далее полученные из моделей данные передаете в ваш view.


text:
Q: Sharepoint query with elevated privileges A Webpart needs to access a Sharepoint List (read mode). If the user is admin, there isn't problem (works as espected), but if the user hasn't permissions to access, I must use "RunWithElevatedPrivileges" method.
The problem is that seems that the query don't return the correct results. What I'm missing?
        SPList demoList = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            SPSite oSite = SPControl.GetContextSite(HttpContext.Current); // ADDED
            SPWeb oWeb = oSite.OpenWeb();                                 // ADDED
            demoList = oWeb.Lists["nameList"];
        });
        // demoList has 3 Elements (admin and no admin user) OK

        SPListItemCollection collListItems = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            SPQuery oQuery = new SPQuery() { Query = "<OrderBy><FieldRef Name='Date' Ascending='False' /></OrderBy>" };
            collListItems = demoList.GetItems(oQuery);
        });

        //
        //IF ADMIN
        //collListItems.Count ==>3

        //IF NO ADMIN
        //collListItems.Count ==>0

A: You need to create new object with elevated privieges.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    SPSite oSite = new SPSite(SPContext.Current.Site.ID);
    SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID);
    demoList = oWeb.Lists["nameList"];
});

Also, you should dispose of the newly created objects and there is no need for two delegates.
SPSecurity.RunWithElevatedPrivileges(delegate {
    using (SPSite oSite =new SPSite(SPContext.Current.Site.ID))
    using (SPWeb oWeb = oSite.OpenWeb()) {
        var demoList = oWeb.Lists["nameList"];
        SPQuery oQuery = new SPQuery
                            { Query = "<OrderBy><FieldRef Name='Date' Ascending='False' /></OrderBy>" };
        SPListItemCollection collListItems = demoList.GetItems(oQuery);

        //IF ADMIN
        //collListItems.Count ==>3

        //IF NO ADMIN
        //collListItems.Count ==>0
    }
});

A: If you create the Site and Web objects (or access them from the current SPContext) outside the elevated block, they will have the permissions of the currently logged-in user. So your query, even though it is in an elevated block, is not using elevated permissions. You need to create new Site and Web objects inside the elevated block, then get access to the list, and then run the query to get the expected results.
Here's a resource that explains further. Even though it was done for SharePoint 2007, it applies to SharePoint 2010.
Running Commands with Elevated Privileges in Windows SharePoint Services 3.0
http://msdn.microsoft.com/en-us/library/bb466220(v=office.12).aspx

A: If you want to include a write operation in SharePoint List, then add     SPWeb.ValidateFormDigest() or SPUtility.ValidateFormDigest() line before RWEP Method.
SPUtility.ValidateFormDigest();
SPSecurity.RunWithElevatedPrivileges(delegate()
{

}


text:
Q: gtk.FileChooser backend example According to the documentationgtk.FileChooserDialog(title=None, parent=None, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=None, backend=None) accepts a backend parameter: backend :
The name of the specific filesystem backend to use.
Can someone explain how this can be used, as after trawling for quite some time the None default seems to be the only use case I can find.
Thanks.

A: I can't find a concrete example, but according to this the parameter was used to specify a custom VFS type, such as gnome-vfs to use GVFS. It was deprecated in 2.14, which was released in 2008, and is completely absent in GTK+ 3. (GVFS can now use fuse to mount its VFS directly onto the filesystem.) You don't need to worry about it.


text:
Q: Cropping specific part of the image I am building a windows phone 8 camera app. After a photograph has been taken i want to give the user the option of cropping specific part of the image. Like if there are some specific objects in the image, when crop option is selected, it should highlight or outline that specific part of the image, and it should be able to crop it, rather than manually cropping it.
Any specific ways to do it?.
Thanks In advance.

A: One way would be to create a WriteableBitmap and do a TranslateTransform of the original image into the WritableBitmap.  Something like::
Image workImage = new Image { Source = originalImage, Width = originalWidth, Height = originalHeight };

WriteableBitmap writeableBitmap = new WriteableBitmap(newWidth, newHeight);
writeableBitmap.Render(temporaryImage, new TranslateTransform { X = (originalWidth – newWidth) / -2, Y = (originalHeight – newHEight) / -2 });
writeableBitmap.Invalidate();

//... or some other stream
Stream newImageStream = new MemoryStream();
//set whatever quality settings you like if 75 is no good
writeableBitmap.SaveJpeg(newImageStream, newWidth, newHeight, 0, 75);

// TODO: do something with newImageStream


text:
Q: Pausing a block of code from being run in google cloud functions/Dialogflow I am using pusher to listen to a particular event being sent from another server.
I have successfully bind to the event but my problem is the code moves past the binding and executes the rest of the code.
I have tried using Await but that doesn't help also
I can't use setTimeout because the message to be received in the pusher event is determined by if the user completes payment.
The code
await pusher.bind(trans_id, function(data) {
        if (data.message === 'success') {
            agent.add('Transaction was successful');
        } else {
            agent.add('Transaction was unsuccessful');
        }
    });

    agent.add('Transaction Successful');

    console.log('We got here');

As you can see, the code is not waiting for the pusher.bind to execute, it jumps straight to the next agent.add and console.log
Environment: Google Cloud Functions
The code is for DialogFlow
Any help please

A: Just continue your program logic inside the callback. pusher.bind finishes execution very quickly, it's the callback that gets executed later.
pusher.bind(trans_id, function(data) {
        if (data.message === 'success') {
            agent.add('Transaction was successful');
        } else {
            agent.add('Transaction was unsuccessful');
        }

        console.log('We got here');
    });


text:
Q: Make list-group-items in adjacent columns same height I have a series of Bootstrap columns that contain a panel with a list group inside each.
Each list group consists of the same number of items, however because of differences in the text, the height of each list-group-item is different, causing them to mis-align across the page.
I would like each list-group-item to align, to get the appearance of a table. I can achieve this by giving the list-group-item a height value, but since the text is dynamic and may change this is not a perfect solution.
Ideally, I would like to have a CSS only solution without JavaScript.
My current HTML is below. You may need to open the snippet full screen to avoid Bootstrap column issues.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

People

            Results in death or permanent disability of employees.

            Results in partial permanent disability, injuries or illness of 3 employees or more.

            Injury or illness resulting in one or more work days lost.

            Minor illness or injury to employees resulting in one day's absence.

Minor illness or injury to employees with no absent days.

Environment

Irreversible environmental damage.

Reversible environment damage.

Mitigable environment damage where restoration activities can be done.

Little environmental damage.

Minimal environmental damage.

Financial

Amount of loss: 1M or more.

Amount of loss: 200,000 but less than 1M.>

Amount of loss: 10,000 but less than 200,000.

Amount of loss: 5,000 but les than 10,000.

Amount of loss: Less than 5,000.

What I would like it to look like using fixed heights:

.list-group-item {
  height:50px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

People

            Results in death or permanent disability of employees.

            Results in partial permanent disability, injuries or illness of 3 employees or more.

            Injury or illness resulting in one or more work days lost.

            Minor illness or injury to employees resulting in one day's absence.

Minor illness or injury to employees with no absent days.

Environment

Irreversible environmental damage.

Reversible environment damage.

Mitigable environment damage where restoration activities can be done.

Little environmental damage.

Minimal environmental damage.

Financial

Amount of loss: 1M or more.

Amount of loss: 200,000 but less than 1M.>

Amount of loss: 10,000 but less than 200,000.

Amount of loss: 5,000 but les than 10,000.

Amount of loss: Less than 5,000.

Can anyone advise a (preferably) CSS only way to get each list-group-item to align across the entire row?

A: Since your lists are in different elements, most of the css only ways that could be used to achieve this are out of the window (margin/padding hack, for example)
What you could do, is to make an educated guess about how many rows the longest text would have on each screen size, and set the min-height of all .list-group-items to that value (i have used em unit here, but you can use whatever works for you better).
First do it for the largest screen size, then use media queries ( @media (max-width: 768px) for example) to override it for smaller screens.
This would work in all browsers, except in some older versions of IE.
Note: Please open the snippet in full screen to see its effects on large screen.
Update
Based on the new info you have given, you could do a trick with my solution:
Restrict the maximum length of the text users can enter to a reasonable length (250 characters, for example), and fix the item heights on what height the longest text may result. Use long words in a test text to check how much the line numbers may vary.

.list-group-item {
  min-height:6em; // this is it
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

People

            Results in death or permanent disability of employees.

            Results in partial permanent disability, injuries or illness of 3 employees or more.

            Injury or illness resulting in one or more work days lost.

            Minor illness or injury to employees resulting in one day's absence.

Minor illness or injury to employees with no absent days.

Environment

Irreversible environmental damage.

Reversible environment damage.

Mitigable environment damage where restoration activities can be done.

Little environmental damage.

Minimal environmental damage.

Financial

Amount of loss: 1M or more.

Amount of loss: 200,000 but less than 1M.>

Amount of loss: 10,000 but less than 200,000.

Amount of loss: 5,000 but les than 10,000.

Amount of loss: Less than 5,000.

A: You can do something like this by adding media queries.

.panel{ height: 400px;}/*set height according to the first panel*/

Do this for all screen size devices as shown below.
You can also add some padding (top & bottom) to list items of Panel-.

 and Panel-3.
Happy coding :-)

/* Large desktops and laptops */
@media (min-width: 1200px) {
.panel{
height: 400px ! important;}
  .list-group-2 .list-group-item{
  padding-top: 18px! important;
  padding-bottom: 18px! important;}

  .list-group-3 .list-group-item{
  padding-top: 18px! important;
  padding-bottom: 18px! important;}

}

/* Landscape tablets and medium desktops */
@media (min-width: 992px) and (max-width: 1199px) {

}

/* Portrait tablets and small desktops */
@media (min-width: 768px) and (max-width: 991px) {

}

/* Landscape phones and portrait tablets */
@media (max-width: 767px) {
.panel{
height: 510px ! important;}
  .list-group-2 .list-group-item{
  padding-top: 16px! important;
  padding-bottom: 16px! important;}

  .list-group-3 .list-group-item{
  padding-top: 16px! important;
  padding-bottom: 16px! important;}
}

/* Portrait phones and smaller */
@media (max-width: 480px) {
.panel{
height: 510px ! important;}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

People

            Results in death or permanent disability of employees.

            Results in partial permanent disability, injuries or illness of 3 employees or more.

            Injury or illness resulting in one or more work days lost.

            Minor illness or injury to employees resulting in one day's absence.

Minor illness or injury to employees with no absent days.

Environment

Irreversible environmental damage.

Reversible environment damage.

Mitigable environment damage where restoration activities can be done.

Little environmental damage.

Minimal environmental damage.

Financial

Amount of loss: 1M or more.

Amount of loss: 200,000 but less than 1M.>

Amount of loss: 10,000 but less than 200,000.

Amount of loss: 5,000 but les than 10,000.

Amount of loss: Less than 5,000.

A: try this
fix the height for list-group.

.list-group
   {
   height:380px;
 }
.list-group-item {
  height:70px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

People

            Results in death or permanent disability of employees.

            Results in partial permanent disability, injuries or illness of 3 employees or more.

            Injury or illness resulting in one or more work days lost.

            Minor illness or injury to employees resulting in one day's absence.

Minor illness or injury to employees with no absent days.

Environment

Irreversible environmental damage.

Reversible environment damage.

Mitigable environment damage where restoration activities can be done.

Little environmental damage.

Minimal environmental damage.

Financial

Amount of loss: 1M or more.

Amount of loss: 200,000 but less than 1M.>

Amount of loss: 10,000 but less than 200,000.

Amount of loss: 5,000 but les than 10,000.

Amount of loss: Less than 5,000.


text:
Q: How can I set the java.library.path used by eclipse from a POM? I'm using maven to define my projects. One of my dependencies requires a native DLL at runtime, and consequently it's needed in tests and for debugging. The native DLL is available at a known location. I want a solution that I can check in once and will work for all developers without manual setup by each dev.
I know I can set the java.libary.path manually in "run configurations", which will allow it to find the native DLL, but this requires manual setup for each developer.
I know I can also set the java.library.path for a given project dependency, but again this is local to a particular developer.
Finally I know I can set the surefire plugin to specify the java.library.path, but this is only useful for tests triggered via maven - so it's great for our build server, but doesn't help devs using the JUnit runner in eclipse, or wanting to debug or run code directly from eclipse.
Is there a way out?

A: I've found that the eclipse m2e connector that goes with the maven-nativedependencies-plugin seems to fix this.
According to the mavennatives docs:

Since version 0.0.7 of the maven-nativedependencies-plugin if you have
  m2eclipse installed and the nativedependencies plugin configured the
  unpacking of natives will run automatically, you don't need the
  eclipse plugin to unpack them. However in order to setup the
  java.library.path environment variable in eclipse you will have to do
  it either manually or automatically using the eclipse plugin.
This Eclipse plugin is an extension to m2eclipse, it detects if you
  have the maven plugin configured, and if you do it executes the
  unpacking of natives, and configures the Native Library Location.
If you import a maven project that has the mavennatives plugin
  configured, and you have the m2eclipse integration plugin, on import
  the natives will be extracted, also when performing a clean from
  eclipse the natives will be extracted.
So, if you use both these tools, using native dependencies requires no
  manual configuration, other than whats in the pom, just run your app
  and it works.

If I have the connector installed, and add mavennatives to my POM, then reload the pom (right-click on project in package explorer > maven > update project), the "Native library location" of the project is populated automatically (to see this, right click on project > properties > java build path > libraries > native library location)

This seems to work for debugging, JUnit runner, etc.
It does require that every developer install the plugin, which is manual (as manual as installing eclipse); however, at least once installed once it will work for any/all native depdendencies configured for mavennatives via a POM.

A: The Properties Maven Plugin may help you passing the system properties by using properties:set-system-properties to set system properties.
The example should be look like the following: -
<properties>
    <java.library.path>some/path</java.library.path>
</properties>

I hope this may help.


text:
Q: It it true that some transitive verbs are only followed by a noun or a clause as its direct object, not infinitive or gerund As I looked at my dictionary, "confirm" is a transitive verb and it's followed by a noun (e.g I confirm my attendance) or that clause (e.g I confirm (that) I will join the meeting) as its direct object. However, I do not find gerund or to infinitive as its direct clause.
Is what i said correct? and are there any other verbs like that?
Thanks for your replies!

A:
[1]  I confirm [my attendance].
[2] I confirm [that I will join the meeting].

Preliminary point: A verb is only transitive if it actually has a direct object in the clause that contains it.
There are many verbs that can be trans or intrans, and "confirm" is one of them. In [1] "confirm" has the noun phrase my attendance" as direct object and hence is transitive. But in [2] the that clause is complement of "confirm", not direct object, and hence "confirm " is intransitive.
Some (but not all) verbs can take gerund-participials or infinitivals as complement. These are called 'catenative' verbs, and the clauses that contain them are called catenative constructions. But the clausal complements are not objects, but catenative complements.
For example, in I regret locking the door, "regret" is a catenative verb, and the gerund-participial clause "locking the door" is its catenative complement, not direct object.  Similarly, in I want to see a doctor, "want" is a catenative verb, and the infinitival clause "to see a doctor" is catenative complement, not direct object.
Note that with only a very few exceptions, clauses do not function as objects.


text:
Q: How to disable checkbox if it's checked when using checklist-model? I'm using this checklist-model directive to loop through a list of checkboxes it can save objects to the database and can check the values that exist in tabs array in the pop object:
so the pop is the main object that has a property of array of tabs
<md-input-container class="md-block" flex-gt-sm="25" flex="45" content-layout-align="center start" ng-repeat="tab in allTabs">
    <md-checkbox checklist-model="pop.tabs" checklist-value="tab" >
        {{tab.name}}
    </md-checkbox>
</md-input-container>

I want to add a feature that if a checkbox is already selected then disable it, but my try ended up with disabling any checkbox that is selected (not only those already checked)

A: The solution is easy:
in the initialize function (the function that get called when the page is loaded):
    const selectedIds = pop.tabs.map(x=>x.id);
    $scope.selectedIds = selectedIds;

and then added ng-disabled directive:
    <md-input-container ng-repeat="tab in allTabs">
                    <md-checkbox checklist-model="pop.tabs" checklist-value="tab" ng-disabled="selectedIds.includes(tab.id)">
                        {{tab.name}}
                    </md-checkbox>
                </md-input-container>

I tried to make this outside the initialize method but the newly selected ids are added to the tabs array of the pop object.


text:
Q: PyMongo select fields on a full-text search Folks,
I trying to use the fields argument on find method, I got the follow error code:
TypeError: __init__() got multiple values for keyword argument 'fields'

Code:
mongo.db.products.find({ '$text': { '$search': string } }, { 'score': { '$meta': 'textScore' } }, fields=('name', 'foo', 'bar',))

Without full-text search the fields argument works fine.

A: For pymongo the "projection part" for the 'textScore' needs to be included in the "fields" specification in the full form:
mongo.db.products.find(
    { '$text': { '$search': string } },
    fields=({ 'name': 1, 'foo': 1, 'bar': 1, 'score': { '$meta': 'textScore' } )
)


text:
Q: Foundation framework error $key is not available in $foundation-pallette I have foundation version 6.3.0 installed for a project and all of a sudden it started throwing the error "$key is not available in $foundation-pallette" I'm confused because I did not change anything in the bower component foundation color.scss file. I did update the settings file but nothing that I think would throw in error in the color.scss file.
So I did some research and could not find information particular to my situation. I tried reinstalling the bower components and also the sass node module.
Any help or point in the right direction would be great!
my terminal error image - 1

A: After researching, I think there may have been something wrong with my local project file. I reverted to an old commit and that solved the issue. I think it actually wasn't the scss file, but I may have defined a color in my styles somewhere that actually wasn't defined in my settings.scss. Therefore, throwing the error.


text:
Q: Objective C and c++ import problem. Simple but I don't get it I'm using cocos2d and box2d.(iPhone SDK) If I want to import box2d I add this to the top of the file #import "Box2D.h" and then I rename my class to ".mm". Now I have just a class without a ".m" file just a ".h" file.
It looks like that and if I import box2d it gives me many errors because box2d is c++ and normally i need to change it to ".mm" but i cant.
#import "Box2D.h"

// Defines individual types of messages that can be sent over the network. One type per packet.
typedef enum
{
    kPacketTypeTime = 1,
    kPacketTypePosition = 2,
    kPacketTypeStartSignal = 3,
} EPacketTypes;

// Note: EPacketType type; must always be the first entry of every Packet struct
// The receiver will first assume the received data to be of type SBasePacket, so it can identify the actual packet by type.
typedef struct
{
    EPacketTypes type;
} SBasePacket;

// the packet for transmitting a score variable
typedef struct
{
    EPacketTypes type;

    float time;
} STimePacket;

// packet to transmit a position
typedef struct
{
    EPacketTypes type;

    b2Vec2 position; //*******************************important**
    float rotation;

} SPositionPacket;

// packet to transmit a start signal
typedef struct
{
    EPacketTypes type;

    BOOL startGame;

} SStartSignalPacket;

Why I want to do this? Look at the "**important" in my code. I want to use b2Vec2.
Thank you very much for reading.
Have a nice day :)

A: Try to rename header to .hh, cause compiler still treats it as Objective C


text:
Q: How to insert a loop block/statement after scanf My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen. I tried to look for a solution but the results are not what I wanted. What should I do about it?
#include <stdio.h>

int main(){

int A,B;
char Y, N, C;

        printf("Enter value 1: ");
        scanf("%i", &B);
        printf("\nEnter value 2: ");
        scanf("%i", &A);

printf("= %i", A+B);

printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);

if (C==Y){
    This should contain code that will repeat the action again.
}
else if(C==N){
    printf("PROGRAM USE ENDED.");
}
else{
    printf("Error.");
}
}

A: You need a do while loop that checks if pressed key is y or not
int main(void) {
float x,y,sum;
char ch;
do {
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}


text:
Q: YAML - Manage different branches within one location Switching from Classic over to YAML for one pipeline where I would like to only have to update the YAML on the main branch and not the release branches. it should still trigger off any branch though.
trigger:
  branches:
    include:
    - refs/heads/main
    - refs/heads/*
  paths:
    include:
    - src
  batch: True
jobs:
- template: templates/code-analysis.yml
- job: Job_2
  displayName: Main Branch
  timeoutInMinutes: 90
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  steps:
  - checkout: self
    submodules: recursive
    fetchDepth: 100
  - template: templates/update-version.yml
  - task: WindowsMachineFileCopy@2
    displayName: Copy files
    continueOnError: True
    inputs:
      SourcePath: src
      MachineNames: server1,server2
      AdminUserName: $(AdminUserName)
      AdminPassword: $(AdminPassword)
      TargetPath: Websites\dev
      AdditionalArguments: $(RoboCopyAdditionalArguments)
  - template: templates/run-and-publish-tests.yml
  - task: PowerShell@2
    displayName: Generate Docs
- deployment: UpdateBeta
  displayName: Beta
  timeoutInMinutes: 90
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/release/22.02'))
  environment: "Beta"
  strategy:
    runOnce:
      deploy:
        steps:
        - checkout: self
          submodules: recursive
          fetchDepth: 100
        - template: templates/update-version.yml
        - task: WindowsMachineFileCopy@2
          displayName: Copy files from src for upcoming release
          continueOnError: True
          inputs:
            SourcePath: src
            MachineNames: server12,server22
            AdminUserName: $(AdminUserName)
            AdminPassword: $(AdminPassword)
            TargetPath: Websites\next
            AdditionalArguments: $(RoboCopyAdditionalArguments)
        - template: templates/run-and-publish-tests.yml
- deployment: UpdateBetaRelease
  displayName: Beta Release
  timeoutInMinutes: 90
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/release/22.01'))
  pool:
    name: Hospital Team
  environment: "Beta Release"
  strategy:
    runOnce:
      deploy:
        steps:
        - checkout: self
          submodules: recursive
          fetchDepth: 100
        - template: templates/update-version.yml
        - task: WindowsMachineFileCopy@2
          displayName: Copy files from src for release
          continueOnError: True
          inputs:
            SourcePath: src
            MachineNames: server111
            AdminUserName: $(AdminUserName)
            AdminPassword: $(AdminPassword)
            TargetPath: Websites\release
            AdditionalArguments: $(RoboCopyAdditionalArguments)
        - template: templates/run-and-publish-tests.yml

But as it stands right now, I must update each branch with the updated servers or arguments needed, which leads to a little more complexity than I want as I would prefer to just manage all of the branches off the main branch yaml. Is there a better way?

A: If you want the YAML pipeline can be run for a branch, the YAML files of the pipeline definition must be existing in the branch.
Currently, we have no method to maintain the YAML files of the pipeline which is for multiple branches in only one branch.
I have tried with the repository resources feature, and it can't meet your demands.


text:
Q: Mouseout is not woking properly(jquery) I am trying to trigger both event on one element.mouseover is working fine but its not working for mouse out.please suggest me if i am missing something.
$(".edit_title_section").mouseover(function(){
    $("#link_title").addClass("link_title_highlight");
    $(".edit_title_section").show();
});
$(".edit_title_secttion").mouseout(function(){
    alert("check alert");
});

A: There's a typo in the selector:
 // $(".edit_title_secttion") - 2 't's in 'secttion`, there should be 1:
 $(".edit_title_section")....

Better yet, hook both events of the same selector;
$(".edit_title_section")
    .mouseover(function() {
        $("#link_title").addClass("link_title_highlight");
        $(".edit_title_section").show();
    })
    .mouseout(function() {
        alert("check alert");
    });


text:
Q: groups by name and provider, then group by month and then get the average of month wise in mongoose I want to groups by name and provider, then group by month, and then get the average of month-wise in mongoose
the expected result, average group by name and month. Thanks
my collection in MongoDB looks like below:
{
    "_id" : ObjectId("614d713c28af063f4cffbb6f"),
    "name" : "Chibi Doge",
    "id" : "0x7c8e01e8df38f001bcefb3b8901ad5d64374dbdf",
    "logo" : "https://img.rarible.com/prod/image/upload/t_avatar_big/prod-collections/0x7c8e01e8df38f001bcefb3b8901ad5d64374dbdf/avatar/Qmdp79f2nP8HRYwwQiEDuRcy6F9ysW4WPdG5QiSvpd57Hu",
    "provider" : "rarible",
    "totalSalesUsd" : 27436.1841495685,
    "totalNFTs" : 59,
    "createdAt" : ISODate("2021-09-24T06:33:32.708Z"),
    "updatedAt" : ISODate("2021-09-24T06:33:32.537Z"),
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("614d713d28af063f4cffbb73"),
    "name" : "",
    "id" : "0xa7206d878c5c3871826dfdb42191c49b1d11f466",
    "logo" : "https://img.rarible.com/prod/image/upload/t_avatar_big/prod-collections/0xa7206d878c5c3871826dfdb42191c49b1d11f466/avatar/QmYCxLp2puXnnarXHyTcY9onjMqrTAUNQskpirL5VPFF6B",
    "provider" : "rarible",
    "totalSalesUsd" : 26176.2678881893,
    "totalNFTs" : 7,
    "createdAt" : ISODate("2021-09-24T06:33:33.228Z"),
    "updatedAt" : ISODate("2021-09-24T06:33:33.057Z"),
    "__v" : 0
}

I write a query which results in the below result:
[
    {
        "_id": {
            "provider": "superrare",
            "name": "batsoupyum2"
        },
        "data": [
            {
                "provider": "superrare",
                "name": "batsoupyum2",
                "totalSalesUsd" : 26176.2678881893,
                "createdAt": "2021-09-24T06:23:32.802Z"
            },
            {
                "provider": "superrare",
                "name": "batsoupyum2",
                "totalSalesUsd" : 26176.2678881893,
                "createdAt": "2021-08-24T06:33:32.708Z"
            }
        ]
    }
    ]

and the query is
collection.aggregate([
    {
      $group: {
        _id: {
          provider: "$provider",
          name: "$name",
          // month: { $month: "$createdAt" },
          // avgQuantity: { $avg: "$totalSalesUsd" }
        },
        data: {
        $push: {
          provider: "$provider",
             name: "$name",
             totalSalesUsd: "$totalSalesUsd",
             createdAt: "$createdAt"
            // average: "$_id.average"
          },
         },
      },
    },
])

How can I do this using the mongoose.js framework?

A: You're quite close, what you want to do is add another $group stage, you need to start by $grouping on provider AND time, and only then you group again on just the provider, like so:
db.collection.aggregate([
  {
    $group: {
      _id: {
        provider: "$provider",
        name: "$name",
        month: {
          $month: "$createdAt"
        },
        year: {
          $year: "$createdAt"
        }
      },
      avgQuantity: {
        $avg: "$totalSalesUsd"
      }
    }
  },
  {
    $group: {
      _id: {
        provider: "$_id.provider",
        name: "$_id.name"
      },
      data: {
        $push: {
          provider: "$_id.provider",
          name: "$_id.name",
          avgQuantity: "$avgQuantity",
          month: "$_id.month",
          year: "$_id.year"
        }
      }
    }
  }
])

Mongo Playground


text:
Q: Is there any alternative for isDisplay() method in selenium webdriver? I am trying to use isDisplay() method in my selenium script.
While I am using this method I have found this method returns false every time.
Is there any other way to use this method or alternative of this method?
Scroll_UP is done successfully. But If element is display, Scroll_UP is not terminate.And I need return value also.
Thanks in advance.

code logic which I write
public static boolean scroll_Up_Until_FindWebe(WebElement dragEle, WebElement ele, int scrollPoint)
{
int numberOfPixelsToDragTheScrollbarUp = -10;
for (int i = scrollPoint; i > 10; i = i +numberOfPixelsToDragTheScrollbarUp)
{
if (ele.isDisplayed()) //if the tag options is displayed
{
Log4J.logp.info("Ending scroll_Up_Until_FindWebe - Element is found");
return true;
}
dragger.moveToElement(dragEle).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarUp).release().build().perform();
}
Thread.sleep(500);
return scroll_Up_Until_FindWebe(dragEle, ele, 30);
}


text:
Q: Mysql `using` syntax for multiple tables and one joining column Instead of
SELECT * FROM a, b, c
WHERE a.jid = b.jid AND b.jid = c.jid
or
SELECT * FROM a JOIN b USING(jid) JOIN c USING(jid)
I'd like to use something like:
SELECT * FROM a, b, c USING(jid)
This may not seem like much of a convenience but when my query runs accross 4 tables and perhaps more, this could be a real helper.
I.e. there's one column that unites quite a few tables in my database. Is there a way to query multiple tables by naming that column only once?

A: You can use NATURAL JOIN to automatically join the tables based on columns with the same name. However, you will need to make sure that jid will be the ONLY column with the same name, otherwise you will not get the results that you want.

A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the common columns in the two tables being joined. Common columns are columns that have the same name in both tables.

SELECT * FROM a
NATURAL JOIN b
NATURAL JOIN c;


text:
Q: Ruby, how to overwrite the setter ("=") method to allow 2 parameters? I am trying to create a quick set method for my multi component variable (in my real code it is a Vector2d).
I would like to use an overwritten version of the = method.
For example:
def my_vector=(x, y)
  @my_vector = Vector2d.new(x, y)
end

But it is not working because when I try to call this method I receive an error:
my_vector=1, 2 # => wrong number of arguments (given 1, expected 2)
my_vector=(1, 2) # => syntax error, unexpected ',', expecting ')'
my_vector=[1, 2] # => wrong number of arguments (given 1, expected 2)

This is my test suite:
# With one param it works
def my_var=(value)
  @var = value
end

self.my_var=1
puts "var: " + @var.to_s

# With 2 params it doesn't work
def my_other_var=(value1, value2)
  @other_var_component_1 = value1
  @other_var_component_2 = value2
end

# Nothing works:
# self.my_other_var=1, 2
# self.my_other_var=(1, 2)
# self.my_other_var=[1, 2]
puts "other_var_component_1: " + @other_var_component_1.to_s
puts "other_var_component_2: " + @other_var_component_2.to_s

A: As @eugen correctly says, you cannot pass two arguments to a setter like
self.my_vector = 1, 2

The nearest thing you can achieve is to unpack the argument using pattern matching:
def myvector=(arg)
  arg => [x, y]
  @my_vector = Vector2d.new(x, y)
end

foo.my_vector = [1, 2]

An alternative is to define a simple helper method v so you can write
foo.my_vector = v 1, 2

A: You're defining a method named my_vector= (or my_other_var= in your 2nd example).
If you're just trying to call it with
my_vector = 1, 2

ruby will interpret that as an assignment to the my_vector variable.
You'll have to use send in order to call the method you've defined, as in
self.send :my_vector=, 1, 2

That's kind of ugly, but I don't see another way around this.

A: Slight modification to the supplied code to use an array argument instead:
 def my_other_var=(values)
   @other_var_component_1 = values[0]
   @other_var_component_2 = values[1]
 end

 self.my_other_var=[1, 2]

"other_var_component_1: " + @other_var_component_1.to_s
#=>  other_var_component_1: 1
"other_var_component_2: " + @other_var_component_2.to_s
#=>  other_var_component_2: 2


text: Q: Change management of aerial photos of same fields I am looking for an automated solution with capable to stitch aerial photographs and the result can be integrated into Google Maps. Furthermore it has an ability to show discrepancies on a new layer from photos taken  different points in time. For this demands which GIS software could be a solution? Possible to automate this workflow?


text:
Q: Why does java.util.Optional.ofNullable() expect @NonNullable? Trying to wrap my head around why a utility class whose sole purpose is to wrap null, expects @NonNullable argument. Example below produces unexpected (to me) null type mismatch errors in Eclipse.

Null type mismatch (type annotations): required '@NonNull IoSession'
but this expression has type '@Nullable IoSession'

I wouldn't have written the code this way, but I'm stuck between the coding standards of a 3rd party I'm trying to contribute to, and the realities of a 4th party library whose interface I'm trying to implement, so I'm stuck trying to make everyone happy while still making everything work.
Given the specific callback method signature, what is the best way to handle the implementation correctly while producing the least compiler warnings (before applying suppression). Before trying java.util.Optional, I was just doing simple null checks, but as you know, the compiler still warns of

Potential null pointer access: this expression has a '@Nullable' type

in spite of the null check... another 3rd party coding standard is no compiler errors or warnings, while using the least suppression possible, to achieve that.
import static java.util.Optional.ofNullable;

import java.util.Optional;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;

@NonNullByDefault // @NonNullByDefault required and enforced by frameworks coding standards (3rd party)
public class MyClass extends CumulativeProtocolDecoder {

    @Override          // implementation of 4th party callback, necessitating @Nullable annotation
    protected boolean doDecode(@Nullable IoSession s, @Nullable IoBuffer i, @Nullable ProtocolDecoderOutput o) {

        Optional<IoSession> session = Optional.ofNullable(s); // Null type mismatch (type annotations): required '@NonNull IoSession' but this expression has type '@Nullable IoSession'
        Optional<IoBuffer> in = Optional.ofNullable(i); // Null type mismatch (type annotations): required '@NonNull IoBuffer' but this expression has type '@Nullable IoBuffer'
        Optional<ProtocolDecoderOutput> out = ofNullable(o); // Null type mismatch (type annotations): required '@NonNull ProtocolDecoderOutput' but this expression has type '@Nullable ProtocolDecoderOutput'

        return true;
    }

}


text:
Q: Data handling for matplotlib histogram with error bars I've got a data set which is a list of tuples in python like this:
dataSet = [(6.1248199999999997, 27), (6.4400500000000003, 4), (5.9150600000000004, 1), (5.5388400000000004, 38), (5.82559, 1), (7.6892199999999997, 2), (6.9047799999999997, 1), (6.3516300000000001, 76), (6.5168699999999999, 1), (7.4382099999999998, 1), (5.4493299999999998, 1), (5.6254099999999996, 1), (6.3227700000000002, 1), (5.3321899999999998, 11), (6.7402300000000004, 4), (7.6701499999999996, 1), (5.4589400000000001, 3), (6.3089700000000004, 1), (6.5926099999999996, 2), (6.0003000000000002, 5), (5.9845800000000002, 1), (6.4967499999999996, 2), (6.51227, 6), (7.0302600000000002, 1), (5.7271200000000002, 49), (7.5311300000000001, 7), (5.9495800000000001, 2), (5.1487299999999996, 18), (5.7637099999999997, 6), (5.5144500000000001, 44), (6.7988499999999998, 1), (5.2578399999999998, 1)]

Where the first element of the tuple is an energy and the second a counter, how many sensor where affected.
I want to create a histogram to study the relation between the number of affected sensors and the energy. I'm pretty new to matplotlib (and python), but this is what I've done so far:
import math
import matplotlib.pyplot as plt

dataSet = [(6.1248199999999997, 27), (6.4400500000000003, 4), (5.9150600000000004, 1), (5.5388400000000004, 38), (5.82559, 1), (7.6892199999999997, 2), (6.9047799999999997, 1), (6.3516300000000001, 76), (6.5168699999999999, 1), (7.4382099999999998, 1), (5.4493299999999998, 1), (5.6254099999999996, 1), (6.3227700000000002, 1), (5.3321899999999998, 11), (6.7402300000000004, 4), (7.6701499999999996, 1), (5.4589400000000001, 3), (6.3089700000000004, 1), (6.5926099999999996, 2), (6.0003000000000002, 5), (5.9845800000000002, 1), (6.4967499999999996, 2), (6.51227, 6), (7.0302600000000002, 1), (5.7271200000000002, 49), (7.5311300000000001, 7), (5.9495800000000001, 2), (5.1487299999999996, 18), (5.7637099999999997, 6), (5.5144500000000001, 44), (6.7988499999999998, 1), (5.2578399999999998, 1)]

binWidth = .2
binnedDataSet = []
#create another list and append the "binning-value"
for item in dataSet:
    binnedDataSet.append((item[0], item[1], math.floor(item[0]/binWidth)*binWidth))

energies, sensorHits, binnedEnergy = [[q[i] for q in binnedDataSet] for i in (0,1,2)]
plt.plot(binnedEnergy, sensorHits, 'ro')
plt.show()

This works so far (although it doesn't even look like a histogram ;-) but OK), but now I want to calculate the mean value for each bin and append some error bars.
What's the way to do it? I looked at histogram examples for matplotlib, but they all use one-dimensional data which will be counted, so you get a frequency spectrum… That's not really what I want.

A: I am somewhat confused by exactly what you are trying to do, but I think this (to first order) will do what I think you want:
bin_width = .2
bottom = 5.0
top = 8.0

binned_data = [0.0] * int(math.ceil(((top - bottom) / bin_width)))
binned_count = [0] * int(math.ceil(((top - bottom) / bin_width)))
n_bins = len(binned_data)
for E, cnt in dataSet:
    if E < bottom or E > top:
        print 'out of range'
        continue
    bin_id = int(math.floor(n_bins * (E - bottom) / (top - bottom)))
    binned_data[bin_id] += cnt
    binned_count[bin_id] += 1

binned_avergaed_data = [C_sum / hits if hits > 0 else 0 for C_sum, hits in zip(binned_data, binned_count)]

bin_edges = [bottom + j * bin_width for j in range(len(binned_data))]

plt.bar(bin_edges, binned_avergaed_data, width=bin_width)

I would also suggest looking into numpy, it would make this much simpler to write.


text:
Q: How can I get from a list of characters representing a permutation to graphics showing the cycles? I am trying to graphically represent cycles in various permutations of the alphabet, and have a question in two parts.
I have
cycles[r_] := Identity @@ PermutationCycles@
   (FirstPosition[CharacterRange["A", "Z"], #][[1]] & /@ Characters[r])

cyclesGraph[r_] :=
 Graph[#, VertexLabels -> "Name", EdgeShapeFunction -> (Arrow[#, 0.1] &)] & /@
   Map[letter[#[[1]]] \[DirectedEdge] letter[#[[2]]] &, #, {2}] & @
      Map[Partition[#, 2, 1, {1, 1}] &, cycles[r], {1}]

so that
cyclesGraph["AJDKSIRUXBLHWTMCQGZNPYFVOE"]

produces

Which is fine as far as as it goes but:

*

*I have a lot of Maps and applications that seem messy to me and wonder whether there isn't a better idiom for processing my list of characters into cycles and from there into the list of edges expected by Graph.

*While I need both of these functions, I also need an additional one that combines all the graphs into a single one, with the letters of the alphabet arranged evenly in sequence around the circumference, and each the edges for each cycle indicated in a different style (e.g color).
How can I do a better job of getting from a list of characters representing a permutation to cycle graphics, especially one that combines and distinguishes all cycles in a single figure?

A: s = "AJDKSIRUXBLHWTMCQGZNPYFVOE";
pc = PermutationCycles[ToCharacterCode@s - 64] // First;
Graph[Flatten[Thread[# -> RotateRight@#] & /@ pc],
      VertexLabels -> Table[i -> FromCharacterCode[i + 64], {i, Flatten@pc}],
      ImagePadding -> 12]

Perhaps better:
pc = (PermutationCycles[ToCharacterCode@s - 64] // First) /.
                                         x_?NumericQ :> FromCharacterCode[x + 64]
Graph[CharacterRange["A", "Z"], Flatten[Thread[# -> RotateRight@#] & /@ pc],
      VertexLabels -> "Name", ImagePadding -> 12,
      VertexCoordinates -> ({Cos@#, Sin@#} & /@ Range[0, 2 Pi - 1/26, 2 Pi/26])]

A: Not going to win a beauty contest, but you might get some ideas:
string = "AJDKSIRUXBLHWTMCQGZNPYFVOE";
rules[cycle_] := Thread[DirectedEdge[cycle, RotateLeft[cycle]]];
edges = MapIndexed[Style[#1, Thick, ColorData[2][#2[[1]]]] &,
   rules /@ PermutationCycles[LetterNumber /@ Characters[string], Identity], {2}];
verts = PermutationCycles[LetterNumber /@ Characters[string],
   Identity];
styles = Flatten@MapIndexed[# -> ColorData[2][#2[[1]]] &, verts, {2}];
coords = ({Cos[2 \[Pi]/26 #], Sin[2 \[Pi]/26 #]} & /@ Flatten@verts);

Graph[Flatten@edges, VertexCoordinates -> coords,
 VertexLabels -> Thread[Range[26] -> CharacterRange["A", "Z"]],
 VertexStyle -> styles, Background -> Gray,ImageSize -> Large]

Of course one can get a bit "fancier" using EdgeShapeFunction:
drawLines[points_List] :=
 If[points[[1]] != points[[-1]], {Arrowheads[{0, .025, 0.025, .05}],
   Arrow[BSplineCurve[{points[[1]], {0, 0}, points[[-1]]},
     SplineWeights -> {2, 3, 2}]]}, Opacity[0]]

Graph[Flatten@edges, VertexCoordinates -> coords,
 VertexLabels -> Thread[Range[26] -> CharacterRange["A", "Z"]],
 VertexStyle -> styles, EdgeShapeFunction -> (drawLines[#1] &),
 ImageSize -> Large, Background -> Gray]

A: ClearAll[cyclesF, edgesF]
cyclesF = Map[FromCharacterCode,
            64 + PermutationCycles[ToCharacterCode@# - 64][[1]], {-1}] &;
edgesF = Developer`PartitionMap[DirectedEdge @@ # &, #, 2, 1, {1, 1}] & /@
           cyclesF[#] &;

str = "AJDKSIRUXBLHWTMCQGZNPYFVOE";
colors = {Red, Green, Blue, Orange, Cyan, Yellow};
vl = cyclesF@str;
el = edgesF@str;
e = Join @@ (el);
v = DeleteDuplicates[Join @@ vl];
vc = GraphEmbedding[CompleteGraph[Length@v]];
estyle = Join @@ (Thread /@ Thread[el -> colors]);
vstyle = Join @@ (Thread /@ Thread[vl -> colors]);

Graph[e, VertexSize -> .5, VertexLabels -> Placed["Name", Center],
 EdgeStyle -> estyle, VertexStyle -> vstyle, VertexCoordinates -> Thread[v -> vc]]

Or, use HighlightGraph:
g1 = Graph[e, VertexSize -> .5, VertexLabels -> Placed["Name", Center],
          VertexCoordinates -> Thread[v -> vc]];

HighlightGraph[g1,
 Flatten@{Thread[Style[##]] & @@@ Thread[vl -> colors],
          Thread[Style[##]] & @@@ Thread[{el , colors}]}]
(* same picture *)


text:
Q: How *exactly* are you supposed to use useContext? I'm familiar with Redux, but I'm having a hard time grasping the concept of useContext.
I have the following code;
export default () => {
    const PlayerStatusContext = React.createContext(null);
    const [playerStatus, setPlayerStatus] = useState({
        playerHealth: 5,
        playerCoins: 0,
        playerMoves: 0,
        currentLevel: 1,
    });
    const usePlayerStatus = () => useContext(PlayerStatusContext);
    return (
            <PlayerStatusContext.Provider value={ playerStatus, setPlayerStatus } >
                 <ChildComponent />
            </PlayerStatusContext.Provider>
    )
}

And in the childComponent;
export default ({playerStatus, setPlayerStatus}) => {

    return (
        <Wrapper>
            <button onClick={() => {
                console.log(playerStatus)
            }}>Log status</button>

            <button onClick={() => {
                setPlayerStatus({
                    playerHealth: 6,
                    playerCoins: 1,
                    playerMoves: 1,
                    currentLevel: 2,
                })
            }}>Update Test</button>
        </Wrapper>
    )
}

Now, I've been told that I shouldn't pass playerStatus and setPlayerStatus directly, and I should wrap them in a handler. How exactly should I go about doing this, and what's the benefit of doing so?

A: Your ChildComponent should look like this:
const ChildComponent = () => {
    const { playerStatus, setPlayerStatus } = usePlayerStatus();

    return (
        // remaining code
    );
}

If you pass the value and the callback through context, you don't need to pass as props. Alternatively, if you want to pass them explicitly, you can return
<ChildComponent
    playerStatus={playerStatus}
    setPlayerStatus={setPlayerStatus}
/>

in your parent, but then you don't need the context.


text:
Q: Extract all tokens from string using regex in Scala I have a string like "httpx://__URL__/__STUFF__?param=value"
This sample is a url by convention...it could be anything with zero or more __X__ tokens in it.
I want to use a regex to extract a list of all the tokens, so output here would be List("__URL__","__STUFF__").  Remember, I don't know beforehand how many (if any) tokens may be in the input string.
I've been struggling but unable to come up with a regex expression that will do the trick.
Something like this did not work:
(?:.?(__[a-zA-Z0-9]+__).?)+

A: Scala Regex, which is just a wrapper around Java Regex, will never return multiple subgroups for repetitions.
The only way about it is to have a regex for the token, and then find it multiple times. You pretty much already have everything you want:
"__[a-zA-Z0-9]+__".r findAllIn "httpx://__URL__/__STUFF__?param=value"

That returns an Iterator. Use .toSeq or similar to convert into a collection.

A: Greg, have you tried a simple
_+[^_]+_+

This will match all the __TOKENS__
It doesn't do any check for any __TOKENLIKE__ string after the ?params, but you have mentioned you are not only using that for urls. If you need some refinement, please let us know.

A: Combine a regex with split:
def urlPathComponents(s: String): Option[Array[String]] =
  """(?<=http(s?)://)[^?]+""".r findFirstIn s map (_.split("/"))


text:
Q: upload file and text in loopback Hello guys i m new too loopback, so don't know if it is possible or not
<form>
  <input type="text" id name="product">
  <input type="text" id name="productdesc">
  <input type="file" id name="product">
</form>

Demo image of form:

This demo form i m try to save to database  using model  rest api (model named as product)
Note: just try to save input text field and  file path url. i have created a container, using container i can easly upload a file to folder name as storage/file inside server folder.  hHow I can do that? Any suggestion would be great


text:
Q: OOP Trying to get propery of non-object via prepared statements I am trying to create a user class that will have the registration & login, etc functions that can be used for my website. However, when I try and check if the username exists, I get the following error:

Notice: Trying to get property of non-object in C:\inetpub\wwwroot\includes\user.class.php on line 22

I done a tonne of googling, and there was loads of information, but none of it was telling me why its giving me this error and how to fix it?
I have just started with OOP PHP, and prepared statements, so my code may be a bit wobbly.
This is the select function that I am using in my dbc class:
public function select($columns = array(), $table, $variables = '', $order = '') {
        // Are the required variables empty or equals null?
        if(empty($columns) || empty($table)) {
            return false;
        }

        // Set $order and $variables to false
        if($order == '' || $order == null) {
            $order = false;
        }else if($variables == '' || $variables == null) {
            $variables = false;
        }

        // Check if $columns is an array
        if(!is_array($columns)) {
            return false;
        }

        // Set $fields as an array
        $fields = array();
        // Individualise the array
        foreach($columns as $field) {
            $fields[] = $field;
        }

        // Sepeate all individuals with commas
        $fields = implode(', ', $fields);

        // Finalise the MySQLi query
        if($variables == false && $order == false) {
            $query = "SELECT $fields FROM $table";
        }else if($variables != false && $order == false) {
            $query = "SELECT $fields FROM $table WHERE $variables";
        }else if($variables == false && $order != false) {
            $query = "SELECT $fields FROM $table ORDER BY $order";
        }else if($variables != false && $order != false) {
            $query = "SELECT $fields FROM $table WHERE $variables ORDER BY $order";
        }

        // Prepare the query for executing
        $stmt = $this->connection->prepare($query);

        // Execute the query
        $stmt->execute();

        // Get the results of the query
        $result = $stmt->get_result();

        // Set the results to a variable
        while($row = ( is_object($result)) ? $result->fetch_assoc() : $result->fetch_object() ) {
            $results[] = $row;
        }

        // Return the results as array 0
        return $results[0];
    }

And this is the register function in the user class:
ublic function register($username, $password, $confirmpassword, $email, $firstname, $lastname) {
        if(empty($username) || empty($password) || empty($confirmpassword) || empty($email) || empty($firstname) || empty($lastname)) {
            return false;
        }

        if($password === $confirmpassword) {
            $dbc = new dbc();

            $hash = '_HG.g2Sxa.';
            $encryptpassword = md5(md5($hash . $password));

            $usernameQuery = $dbc->select(array('*'), 'users', 'username="' . $username .'"');
            $usernameCount = $usernameQuery->num_rows;

            if($usernameCount != 0) {
                echo 'Username already exists!';
            }

            $userdata = array(
                'username' => $username,
                'password' => $encryptpassword,
                'email' => $email,
                'firstname' => $firstname,
                'lastname' => $lastname,
                'status' => '1',
                'ip' => '127.0.0.1'
            );

            $dbc->insert('users', $userdata);
        }else {
            return false;
        }
    }

I haven't had this problem before, as I only get it when attempting to count how many rows were found. But if I wasn't counting, then it would work absolutely great.
If anyone knows how I can fix this, I would highly appreciate it.
Also, if there are any problems with my code, please mention it so I can create improvements.
Thanks,
Kieron

A: The error is here:
$usernameQuery = $dbc->select(array('*'), 'users', 'username="' . $username .'"');
$usernameCount = $usernameQuery->num_rows; // error is here

And it says Trying to get property of non-object, so the $usernameCount is not an object.
Possible reasons:

*

*Your select function returns false (it does in several places)

*The database query doesn't return any data, in this case there should be other notices like Undefined variable: results
Next, you do $usernameQuery->num_rows. I see no case at all where the $usernameQuery can have num_rows property. Your select returns the first data row in the best case and it will not have num_rows anyway.
And I actually don't see the point of such select implementation which reads all the data from the database and throws everything away except the first record.
If you need one record - use limit 1 in your SQL.
Also you should use bind_param to bind parameters to your SQL. At the moment you just pass strings without parameters, so there is actually no use of prepare.
Actually there are many more issues with this code. You may try to post it at https://codereview.stackexchange.com/ and ask for review.


text:
Q: How do I redirect Ansible to use files in a role directory? Salutations, I am deploying pods/applications to EKS via Ansible. My playbook runs a few kubectl apply -f commands in order to deploy EKS resources and all of the .yaml files are in that directory.
I would like to place these .yaml files that create each application in it's own ansible role/files directory in order to clean up the main ansible directory a bit (the .yaml files are becoming overwhelming and I only have two applications being deployed thus far).
The issue is this: When I move the .yaml files to it's respective /roles/files directory ansible still seems to look for the files in the main ansible directory instead of scanning the internal role directory.
How do I redirect Ansible to run the shell commands on .yamls in the role's file directory? Playbook below:
#
# Deploying Jenkins to AWS EKS
#
# Create Jenkins Namespace
- name: Create Jenkins Namespace & set it to default
  shell: |
    kubectl create namespace jenkins
    kubectl config set-context --current --namespace=jenkins
# Create Jenkins Service Account
- name: Create Jenkins Service Account
  shell: |
    kubectl create serviceaccount jenkins-master -n jenkins
    kubectl get secret $(kubectl get sa jenkins-master -n jenkins -o jsonpath={.secrets[0].name}) -n jenkins -o jsonpath={.data.'ca\.crt'} | base64 --decode
# Deploy Jenkins
- name: Deploy Jenkins Application
  shell: |
    kubectl apply -f jenkins-service.yaml
    kubectl apply -f jenkins-vol.yaml
    kubectl apply -f jenkins-role.yaml
    kubectl apply -f jenkins-configmap.yaml
    kubectl apply -f jenkins-deployment.yaml

Below is the role directory structure, Ansible doesn't check this location for the yaml files to run in the playbook above.

A: You could use the role_path variable, which contains the path to the currently executing role. You could write your tasks like:
- name: Deploy Jenkins Application
  shell: |
    kubectl apply -f {{ role_path }}/files/jenkins-service.yaml
    kubectl apply -f {{ role_path }}/files/jenkins-vol.yaml
    ...

Alternately, a fileglob lookup might be easier:
- name: Deploy Jenkins Application
  command: kubectl apply -f {{ item }}
  loop: "{{ query('fileglob', '*.yaml') }}"

This would loop over all the *.yaml files in your role's files
directory.
You could consider replacing your use of kubectl with
the k8s module.
Lastly, rather than managing these resources using Ansible, you could
consider using kustomize, which I have found
to be easier to work with unless you're relying heavily on Ansible
templating.


text:
Q: getting error while running mrjob python scripting in hadoop cluster hi i want to sort movie ratings by a python script but i am getting error
`[root@sandbox-hdp maria_dev]# python RatingsBreakdown.py -r hadoop --hadoop-streaming-jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar u.data
No configs found; falling back on auto-configuration
No configs specified for hadoop runner
Looking for hadoop binary in $PATH...
Found hadoop binary: /usr/bin/hadoop
Using Hadoop version 3.1.1.3.0.1.0
Creating temp directory /tmp/RatingsBreakdown.maria_dev.20190830.233300.332634
STDERR: mkdir: Permission denied: user=root, access=WRITE, inode="/user/maria_dev"                     :maria_dev:hdfs:drwxr-xr-x
Traceback (most recent call last):
File "RatingsBreakdown.py", line 19, in <module>
RatingsBreakdown.run()
File "/usr/lib/python2.7/site-packages/mrjob/job.py", line 446, in run
mr_job.execute()
File "/usr/lib/python2.7/site-packages/mrjob/job.py", line 473, in execute
super(MRJob, self).execute()
File "/usr/lib/python2.7/site-packages/mrjob/launch.py", line 202, in execute
self.run_job()
File "/usr/lib/python2.7/site-packages/mrjob/launch.py", line 247, in run_job
return self._handle(name, path, path)
File "/usr/lib/python2.7/site-packages/mrjob/fs/composite.py", line 118, in _han                     dle
return getattr(fs, name)(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/mrjob/fs/hadoop.py", line 298, in mkdir
raise IOError("Could not mkdir %s" % path)
IOError: Could not mkdir hdfs:///user/maria_dev/tmp/mrjob/RatingsBreakdown.maria_d                     ev.20190830.233300.332634/files/wd`

can you plese describe what is the problem here

A: Please take a look at these 2 references:
Permission denied at hdfs
Permission denied: user=root, access=WRITE, inode="/user":hdfs:supergroup:dr

A: i found that hortonworks take a lot of time to boot up
when i booted up correctly it worked fine
it took about 1 hour to boot


text:
Q: How do I fix error 1303 during TI Connect install? I recently purchased a TI-84 Plus graphing calculator, and I'm trying install the TI Connect software in order to connect the calculator to my computer via the USB cable. Unfortunately, I'm getting this error while trying to install the program:

Error 1303. The installation has insufficient privileges to access
  this directory: E:\Data\Timothy\Documents\MyTIData. The installation
  cannot continue. Log on as administrator or contact your system
  administrator.

However, my account is the only account on my PC, and it has administrative privileges. I've also tried running the installer with Run as Administrator, but with no luck. If I create the folder MyTIData manually, I receive this error:

Error 1317. An error occurred while attempting to create the
  directory: E:\Data\Timothy\Documents\MyTIData

I've reapplied the security settings to the E:\Data folder (and all its sub-directories) to Full for my account. I've also gone into Computer Management, and given SYSTEM full privileges for the entire disk. I've also logged out, logged back in, restarted, etc. but still, no luck.
Now, I should mention that my Documents folder is not at the default location. I changed it due to my C: disk being a 90GB SSD, so I moved all my personal data onto the extra storage disk (which is ~1TB). I don't know if that is causing the issue, but it can't hurt throwing it out there.
So why can't I install this program? Google'ing the problem brings up this error for various other installers (such as Visual Studio and Microsoft Office), but nothing for TI Connect. All the solutions are the same: Give the folder Full privileges...but I've already done this! I've also tried running the installer with and without the calculator plugged in, but it didn't change anything. In the prompt that contains the error, repeatedly clicking Retry or waiting a few moments before clicking Retry also produces no result.

A: Ok, I seemed to have solved the problem. It seems that although my actual Documents folder was on the E: drive, the system thinks of it on the C: drive (because I simply changed its location, I guess). When I gave SYSTEM full privileges to the entire E: drive, it didn't give full privileges to the Documents folder. I created MyTIData, and added SYSTEM to the access privileges list, and gave it Full access. After this, the install continued without error.


text:
Q: Huawei dongle keeps on disconnecting when idle. How do I stop this? I have a Huawei E172 USB dongle that works perfectly with Precise. However it keeps on disconnecting the internet connection when I'm not doing anything that requires internet connection. I think it has to do with Powertop tunables. I have turned so many things off in this section. Here is the list of the things I turned off:

A: You can try changing the state of your mobile broadband from the Tunables tab.
As the Powertop web site doesn't have any useful documentation, I was unable to find any concrete answers. However, you can have a look at the website: http://www.lesswatts.org/projects/powertop/
Some more links:

*

*http://www.admin-magazine.com/Articles/PowerTOP

A: A temporary solution would be to prevent the internet connection from idling with a simple script.
Create file /etc/cron.d/ping
# /etc/cron.d/ping
# ping every one minute
* * * * * nobody ping -c 1 -W 10 -q www.google.com >/dev/null 2>&1


text:
Q: X ray diffraction and the band theory I was look around stack exchange and couldn't find a good answer to this: What is the relation of the band theory of solids and the X-ray diffraction? We know that it EM wave is scattered (the process is difraction from reflection [diffraction grating]) only if there is a vector in reciprocal lattice such that $\Delta k=G$. But how can this be explained from the band theory? Is it possible to explain from phonons? How does this interaction occur?
Any hint is very appreciated.

A: X-ray diffraction is caused by deep, very atomic like electronic orbitals. These deep orbitals are tightly bound so they have resonance frequencies in the X-ray domain. The dielectric response can be found to a very good approximation from the sum of the atomic polarisabilities at each lattice site. This is why the response shows Bragg diffraction. Valence electrons, the subject of band structure calculations, contribute very little. Phonons are meV scale phenomena to be compared to the x-rays energy if multiple keV. Phonons may cause some broadening of the Bragg diffraction peaks because thermal motion affects the atomic positions.


text:
Q: Почему не работает первый код? а второй работает отлично

  Обратная сзязь ,Оставте ваш номер телефона и мы вам перезвоним

  <form method="post" name="form" id="2">

<input type="text" id="form_name" pattern="^[А-Яа-яЁё\s]+${1,17}" placeholder="Ваше имя" name="name">

<input type="tel" id="form_tel" pattern="[0-9+]{9,11}" placeholder="Ваш номер телефона" name="numb">

<textarea type="text" id="form_zak" placeholder="Ваш заказ" name="text"></textarea>
  </form> <input id="go" onclick="senddata();" type="submit" name="go" value="Отправить" />

Расчёт стоимости

  Место
  <form method="post">
    <select name="mes" id="mes">

            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="1100">Анна</option>
            <option  value="370">Александровка</option>
            <option  value="400">Бабяково</option>
            <option  value="1100">Бобров</option>
            <option  value="400">Берёзовка</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>
            <option  value="700">Архангельское село,Хохольский район</option>

        </select> М
    3<input name="num" id="nem" type="number" min="1" step="1">

 Марка<select name="mees" id="mees">

            <option  value="3150">m100</option>
            <option  value="3250">m150</option>
            <option  value="3400">m200</option>

        </select>

  </form>
  <input id="go" onclick="senddata();" type="submit" name="go" value="=" />

Контактные данные:

  <q>89023425523 </q> <q>5zcvxz@mail.ru</q> <q>5xhsxry@gmail.com</q>

php код точно правильный потомучто подключал через include и всё работало а теперь не хочет через ajax в чём ошибка первого кода?

A: У вас input type = "submit" находится не в форме


text:
Q: read complicated dataset in R My dataset look something like given below. The first number is the feature number and then colon and then the value associated with that specific feature. I am not sure how to import this dataset in R. Anyone has any ideas?

236:24 500:163 732:234 869:117 885:106 1249:103 1280:158 1889:119 2015:55 2718:126 3307:137 3578:25 3770:26 4139:128 4723:114 4957:82 5128:50 5420:124 5603:135 5897:34 5946:117 6069:154 6153:55 6347:87 6372:77 6666:109 6866:223 6984:39 7709:253 7950:87 8078:38 8945:141 9316:111 9948:103 9989:68 10276:43 10530:76 10532:55 10799:15 10802:20 10848:82 11347:16 11871:51 11883:105 12534:133 12601:13 12781:178 12798:116 12842:106 12916:7 12935:51 12968:154 13028:58 13330:105 13384:2 13568:47 13641:632 13829:18 13964:62 14385:93 14392:272 15280:140 15424:119 15492:52 15523:31 16311:23 16464:69 16478:94 16584:102 16586:107 16705:272 17138:108 17181:150 17526:280 17540:163 18007:114 18050:53 18180:2 18806:160 18943:73 19055:41 19255:88 19774:59 19889:72 19921:45
101:68 572:57 732:63 962:120 1304:61 1831:60 1889:58 1973:105 2518:161 2629:228 2990:158 3147:75 3578:11 3860:88 4011:18 4623:141 4684:411 4758:69 4820:120 6149:102 6234:134 6306:118 6866:147 6927:89 6988:51 7048:178 7193:31 7257:61 7709:229 8061:125 8202:188 8272:17 8759:165 9104:77 9325:135 9860:97 10055:684 10532:180 10735:64 10744:267 10820:120 10848:186 10923:128 10936:129 11203:160 11303:144 11668:87 11867:97 11871:207 12191:83 12238:193 12380:51 12968:164 13369:58 13929:39 14531:102 14800:130 14931:99 15314:91 15632:62 16165:7 16353:120 16584:137 17216:172 18372:31 18893:75 19133:93 19154:101 19165:133 19607:20 19784:141 19889:97 19921:60

A: Assuming your data is stored in input.txt,
input <- scan('input.txt', what = 'character')

data <- as.data.frame(matrix(as.numeric(unlist(strsplit(input, ':'))), ncol = 2))
colnames(data) <- c('Feature', 'Value')
str(data)
# 'data.frame': 158 obs. of  2 variables:
#   $ Feature: num  236 24 500 163 732 234 869 117 885 106 ...
#   $ Value  : num  18943 73 19055 41 19255 ...

Alternatively, you can use read.table to parse the input rather than manually splitting the strings which is slightly slower but more readable.
data <- read.table(text = input, sep = ':')
colnames(data) <- c('Feature', 'Value')
str(data)
# 'data.frame': 158 obs. of  2 variables:
#   $ Feature: num  236 24 500 163 732 234 869 117 885 106 ...
#   $ Value  : num  18943 73 19055 41 19255 ...

Edit: adapted for your dataset. Reads your Feature/Value pairs into a data frame.

url <- 'https://archive.ics.uci.edu/ml/machine-learning-databases/dexter/DEXTER/dexter_test.data'
input <- scan(url, what = 'character')
data <- as.data.frame(matrix(as.numeric(unlist(strsplit(input, ':'))), ncol = 2))
colnames(data) <- c('Feature','Value')
str(data)
# 'data.frame': 192449 obs. of  2 variables:
#  $ Feature: num  236 24 500 163 732 234 869 117 885 106 ...
#  $ Value  : num  79 10848 105 11018 76 ...


text:
Q: How to append last item to the array in swift3? I am using two arrays namely dateArray and combinedArray . The values of dateArray is appended to the comBinedArray. For this i am using the following code:
var dataArray = [Any]()
print(self.yourArray)
if let threeDayForecast = end.travelShopsData {
    for forecast in threeDayForecast {
        var index: Int = (threeDayForecast as NSArray).index(of: forecast)
        if self.dateArray.count != 0 {
            self.combinedArray.append(self.dateArray)
            print("combinedArray: \(self.combinedArray)")
            print("combinedArray count: \(self.combinedArray.count)")
        }
        self.dateArray.removeAll()
        self.nameArray.append(forecast.name as Any)
        self.addressArray.append(forecast.address as Any)
        dataArray.append(forecast.cashPointOperatingDays as Any)
        print(forecast.name as Any)
        print(forecast.address as Any)
        print(forecast.phoneNumber as Any)
        print(forecast.latitude as Any)
        print(forecast.longitude as Any)
        print(forecast.cashPointOperatingDays as Any)
        for var i in 0...forecast.cashPointOperatingDays.count/2 {
            var cashPointArray = forecast.cashPointOperatingDays[i ] as? [String: String]
            let retrieveArray = cashPointArray?["operatingDay"]
            self.dateArray.append(retrieveArray)
            print(i)
            print("Data Array: \(self.dateArray)")
            var joiner = ":"
            let str = self.dateArray.flatMap { $0 as? String }.joined()
            print("joinedStrings: \(str)")
        }
    }
}

But the problem is that dateArray is having 7 elements which is true in it but after appending to the combinedArray . The combinedArray only contains 6 elements. What is wrong with the above code?


text:
Q: How to find memory leak in Python MXNet? I am afraid that my Neural Network in MXNet, written in Python, has a memory leak. I have tried the MXNet profiler and the tracemalloc module to get an understanding of memory profiling, but I want to get information on any potential memory leaks, just like I'd do with valgrind in C.
I found Detecting Memory Leaks and Buffer Overflows in MXNet, and after managing to build like described in section "Using ASAN builds with MXNet", by replacing the "ubuntu_cpu" part in docker/Dockerfile.build.ubuntu_cpu -t mxnetci/build.ubuntu_cpu with "ubuntu_cpu_python", I tried executing in an AWS Sagemaker Notebook like this:
root@33e38e00f825:/work/mxnet# nosetests3 --verbose /home/ec2-user/SageMaker/run_predict.py

and I get this import error:

Failure: ImportError (No module named 'run_predict') ... ERROR

My run_predict.py looks like this:
#!/usr/bin/env python
def run_predict(n):
  # calling MXNet inference method

run_predict(-1)  # tried it putting it under 'if __name__ == "__main__":'

What I am missing in my script, what should I change?
The example script they use in the link is rnn_test.py, but even when I run this example, I still get an analogous Import Error.

A: In MXNet, we automatically test for this through examining the garbage collection records. You can find how it's implemented here: https://github.com/apache/incubator-mxnet/blob/c3aff732371d6177e5d522c052fb7258978d8ce4/tests/python/conftest.py#L26-L79