Q:

Tensorflow Hub Module's trainable variables are not updated during training

My question is quite similar to one asked here: https://github.com/tensorflow/hub/issues/269. But those question remains unanswered, so I will ask it here. Steps to reproduce:

tensorflow           1.14.0 tensorflow-hub       0.5.0 Python 3.7.4
  Windows 10

Here is the sample notebook with the problem reproduced:
https://colab.research.google.com/drive/1PKUyoQRP3othu6cu7v7N7yn8K2pjkuKP

Load a tensor_hub Inception 3 module as trainable:

    module_spec = hub.load_module_spec('https://tfhub.dev/google/imagenet/inception_v3/feature_vector/3')
    height, width = hub.get_expected_image_size(module_spec)
        with tf.Graph().as_default() as graph:
            resized_input_tensor =  tf.compat.v1.placeholder(tf.float32, [None, height, width, 3])
            module = hub.Module(module_spec, trainable=True, tags={"train"})
            bottleneck_tensor = module(inputs=dict(images=resized_input_tensor, batch_norm_momentum=0.997),signature="image_feature_vector_with_bn_hparams")

Save all the Trainable/Model/Global variables created at this moment to separate 'base model' lists (3 lists)
Example of vars:
base_model trainable_variables vars: 188, ['module/InceptionV3/Conv2d_1a_3x3/weights:0', 'module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta:0'..
base_model model_variables vars: 188, ['module/InceptionV3/Conv2d_1a_3x3/BatchNorm/moving_mean:0', 'module/InceptionV3/Conv2d_1a_3x3/BatchNorm/moving_variance:0
base_model variables vars: 0, [] #empty list
Add a custom classification layer on top of model:

    batch_size, previous_tensor_size = bottleneck_tensor.get_shape().as_list()
    ground_truth_input = tf.compat.v1.placeholder(tf.int64, [batch_size], name='GroundTruthInput')
    initial_value = tf.random.truncated_normal([previous_tensor_size, class_count], stddev=0.001)
    layer_weights = tf.Variable(initial_value, name='final_weights')
    layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
    logits = tf.matmul(hidden_layer, layer_weights) + layer_biases
    final_tensor = tf.nn.softmax(logits, name=final_tensor_name)

Again, get all newly added variable names into 3 new different 'Custom' lists:
custom trainable_variables vars: 2, ['final_weights:0', 'final_biases:0']
custom model_variables vars: 0, []
custom variables vars: 0, []
Add train operation. Because of base model has batch normalization, we have to care about update ops. That is why I use tf.contrib.training.create_train_op:

    cross_entropy_all = tf.compat.v1.losses.sparse_softmax_cross_entropy(labels=ground_truth_input, logits=logits)
    optimizer = tf.compat.v1.train.AdamOptimizer()

    #the update ops are set to the contents of the tf.GraphKeys.UPDATE_OPS collection.
    #variables to train will default to all tf.compat.v1.trainable_variables().
    train_step = tf.contrib.training.create_train_op(cross_entropy_mean, optimizer)

Again, get all newly added variable names into 3 new different 'Optimizer' lists:
optimizer trainable_variables vars: 0, []
optimizer model_variables vars: 0, []
optimizer variables vars: 383, ['global_step:0', 'beta1_power:0', 'beta2_power:0', 'module/InceptionV3/Conv2d_1a_3x3/weights/Adam:0', 'module/InceptionV3/Conv2d_1a_3x3/weights/Adam_1:0', 'module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta/Adam:0', 'module/InceptionV3/Conv2d_1a_3x3/BatchNorm/beta/Adam_1:0', 'module/InceptionV3/Conv2d_2a_3x3/weights/Adam:0', 'module/InceptionV3/Conv2d_2a_3x3/weights/Adam_1:0', 'module/InceptionV3/Conv2d_2a_3x3/BatchNorm/beta/Adam:0',...

Now do the regular training:

    with tf.compat.v1.Session(graph=graph) as sess:
        # Initialize all weights: for the module to their pretrained values,
        # and for the newly added retraining layer to random initial values.
        init = tf.compat.v1.global_variables_initializer()
        sess.run(init)

        #dump the checkssum for all the variables lists collected during graph building

        for i in range(1000):
            # Get a batch of input resized images values, calculated fresh
            (train_data, train_ground_truth) = get_random_batch_data(sess, image_lists....)

            #dump the checksum for all the variables lists collected during graph building

            # Feed the input placeholder and ground truth into the graph, and run a training
            # step.
            sess.run([train_step], feed_dict = {
                resized_input_tensor: train_data,
                ground_truth_input: train_ground_truth})

            #dump now again the checksum for all the variables lists collected during graph building

So, after the each training step the checksum is changed only for the two variable lists, custom trainable and optimizer global:

    base_model trainable_variables, 2697202.0, cf4682249fc1f48e9a346149f84e503d unchanged
    base_model model_variables,
        2936996.0, 6f995f5f0f032604a49a96ceec576cf7 unchanged
    base_model variables, 0, d41d8cd98f00b204e9800998ecf8427e unchanged
    custom trainable_variables, -0.7915199408307672, 889c333a56b9496d412eacdcbeb3bef1 **changed**
    custom model_variables, 0, d41d8cd98f00b204e9800998ecf8427e unchanged
    custom variables, 0, d41d8cd98f00b204e9800998ecf8427e unchanged
    optimizer trainable_variables, 0, d41d8cd98f00b204e9800998ecf8427e unchanged
    optimizer model_variables, 0, d41d8cd98f00b204e9800998ecf8427e unchanged
    optimizer variables,
        5580902.81437762, d2cb2d4b253a1c12452f560eea35ac42 **changed**

So, the question is, why base model's Trainable variables have not been changed ??
They are BatchNorm/moving_mean, BatchNorm/moving_variance, Conv2d_1a_3x3/weights, which definitely should be updated during training. Even more, moving_variance also should be changed, because UPDATE_OPS are included as dependency for the train step inside the tf.contrib.training.create_train_op call. I've checked the UPDATE_OPS list, it contains valid values like:
Update ops:
tf.Operation 'module_apply_image_feature_vector_with_bn_hparams/InceptionV3/InceptionV3/Conv2d_1a_3x3/BatchNorm/AssignMovingAvg/AssignSubVariableOp' type=AssignSubVariableOp>,

A:

Okay, after deep debugging of a issue I found that the problem is in following:
just getting the variable from a global variable list and getting it's value using eval() on it is not enough: it will return some value but it is not current (at least this is what happening for the variables of imported model with dtype=resource).
To calculate current value we have to get first a value tensor using variable.value() or variable.read_value() and doing eval() for it (for the returned 'value' tensor).
This resolves the question.


Q:

How to define day is sunday and Normal day. using switch case by date?

I have an error in this code. Please help me solve it.
function holiday($today) {

    $year = substr($today, 0, 4);

    switch($today) {

      case $year.'-01-01':
          $holiday = 'New Year';
          break;

      case $today:
          $today11 = new DateTime($today);
          $R= $today11->format('l') . PHP_EOL;
          $Sunday='0';

          if($R == 0) {
              $holiday = 'Sunday';
          } else {
              $holiday = 'Normal Day';
          }
      }

      return $holiday;
}

echo $tday= holiday($today);

A:

Try it:-
function holyday($today)
{
    $start_date = strtotime($today);

    if(date('z',$start_date) ==0)
    {
         return 'New Year';

    }else{

        if(date('l',$start_date) =='Sunday')
        {
             return 'Sunday';

        }else{

            return "Noraml Day";
        }
    }
}

echo holyday('2012-09-06');

Output = Noraml Day
echo holyday('2013-01-01');

Output = New year


Q:

TestContext is null when it is accessed from base class's virtual method

I have a base class ScriptBase which has a virtual function called MyTestInitialize(). When I call MyTestInitialize() from derived class, then the value of testContextInstance is null.
Is there any solution for this? Please help as I am new to Automation Testing.
Thanks in Advance
[CodedUITest]
public class ScriptsBase
{
    public ScriptsBase()
    {
    }

    private static TestContext bingTestContext;

    public static TestContext BingTestContext
    {
        get { return ScriptsBase.bingTestContext; }
        set { ScriptsBase.bingTestContext = value;}
    }

    #region TestInitialize
    //Use TestInitialize to run code before running each test
    [TestInitialize()]
    public virtual void MyTestInitialize()
    {
        Browser.CloseAllBrowsers();
        BingTestContext = testContextInstance;
    }
    #endregion

    #region TestCleanup
    //Use TestCleanup to run code after each test has run
    [TestCleanup()]
    public virtual void MyTestCleanup()
    {
        PPI.HomePage = new HomePageUI();
        Browser.CloseAllBrowsers();
    }
    #endregion

    #region TestContext
    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }
    private TestContext testContextInstance;
    #endregion
}

 public class DestinationMasterTestScripts : ScriptsBase
  {
       public DestinationMasterTestScripts()
       {
       }

       [TestInitialize()]
       public override void MyTestInitialize()
       {
           Console.WriteLine("Initialize");
           base.MyTestInitialize();
       }
   }

A:

Try creating a ClassInitialize method:
    private static TestContext bingTestContext

    [ClassInitialize]
    public static void ClassInit(TestContext con)
    {
      bingTestContext = con;
    }

A:

Another option is to declare the TestContext as abstract in your base class
public abstract TestContext TestContext { get; set; }

And override it in your most derived concrete class(es)
public override TestContext TestContext { get; set; }


Q:

convert 56 kbps to monthly usage in GB

From my internet connection (SIM card) of 56kbps (unlimited data) what would be total gigabytes of data I can consume provided I was using it continuously?
My basic math:
30 days = 2592000 seconds
56 * 2592000 = 145152000 kb  = 141750 MB = 141 GB
Does this calculation make sense?

A:

Your basic maths is good, unfortunately you were tricked by the notations which are unfortunately very confusing in this domain.
1) Lower case b stands for a bit, while capital B is a byte, which is made of 8 bits. So when you get 56 kb/s you actually get 56/8 = 7 kB/s.
This gives you 1814400 kB per month.
2) Now comes the second problem. The definition of what is a kB, a MB or a GB is not uniform. Normally you would expect that there are defined following powers of ten (as in any other science) in which case your 1814400 kB per month would convert into 18144 MB per month or 18.1 GB per month.
However for historical reason MB are sometimes defined as 1024 kB and GB as 1024 MB. In this case you would get 17719 MB per month or 17.3 GB per month.
Which convention you should use depend what you actually want to do with it. But such a small difference is probably irrelevant to you compared to potential fluctuations in the actual transfer rate of your connection.


Q:

Men and Women: Committee Selection

There is a club consisting of six distinct men and seven distinct women. How many ways can we select a committee of three men and four women?

A:

There are "$6$-choose-$3$" $=\binom{6}{3}$ ways to select the men, and "$7$-choose-$4$" =$\binom{7}{4}$ ways to select the women. That's because
$(1)$ We have a group of $6$ men, from which we need to choose $3$ for the committee.
$(2)$ We have $7$ women from which we need to choose $4$ to sit in on the committee.
Since anyone is either on the committee or not, there is no need to consider order: position or arrangement of those chosen for the committee isn't of concern here, so we don't need to consider permuting the chosen men or women.
So we just *multiply*$\;$ "ways of choosing men" $\times$ "ways of choosing women".
[Recall th Rule of the Product, also known as the multiplication principle.]
$$\binom 63 \cdot \binom 74 = \dfrac{6!}{3!3!} \cdot \dfrac{7!}{4!3!} = \dfrac{6\cdot 5\cdot 4}{3!}\cdot \dfrac{7\cdot 6\cdot 5}{3!}$$


Q:

How to prevent duplicate values from inserting mySQL considering two columns?

Here is my table:
Table Name: UserLinks
Link_ID   User_1   User_2
1         234325   100982
2         116727   299011
3         399082   197983
4         664323   272351

Basically, in this table a duplicate value is:
Link_ID   User_1    User_2
1         232       109
2         109       232

I have looked around and found that I should use INSERT IGNORE to prevent duplicate entries, but I am not sure how to write a query that considers that the relationship between User_1 and User_2 is the same as between User_2 and User_1.
Any advice/help is really appreciated.

A:

Thats a bit nasty, a commutative relationship between the 2 fields, but a unique index will not help given the values can be either way around.
If you could alter the code / data to ensure that the lower value of the ids was always placed in the user_1 field, that would at least then let the unique index work - but its a bit nasty.
Alternatively if the insertion is set based (e.g. not a row at a time but a set of rows) you could join to the existing data and anti-join based on both ways round e.g. :
(existing.user_1 = new.user_1 and existing.user_2 = new user_2)
 OR (existing.user_1 = new.user_2 and existing.user_2 = new user_1)

and in the where clause check to ensure no match was made (the anti part of the join)
where existing.link_id is null

That wouldn't be efficient for row at a time insertion though.


Q:

Linux Ubuntu 16.04.0 vs 16.04.3

I want to know the advantages and disadvantages of the two in terms of speed(reliability, stableness) and/or graphics performance(FPS). Linux 16.04.0 (4.4.0-21-generic)  or Linux 16.04.3 (4.10.0-28-generic).
My motherboard Driver/API is limited under Linux kernel 4.14.5, so Ubuntu 16.04 is my best choice. Please help me to choose between the two. Thank you.

A:

When you install Ubuntu 16.04, and fully upgrade it - it'll become 16.04.6 (the current release). So the end result is almost identical (when compared with a 16.04.3 install fully-upgraded).
However a new 16.04 LTS install comes with the generic 4.4 kernel, where as new installs with releases after 16.04.2 have the HWE kernel enabled by default (4.10 is EOL and you'll find yourself upgraded to 4.15) is useful for later hardware, but in theory is less stable (has had less testing in production).
Excluding kernel, they'll both upgrade to 16.04.6 or result in the same packages installed.  You can also opt to enable HWE if you install with 16.04, then they will be identical.
See https://wiki.ubuntu.com/Kernel/LTSEnablementStack for information about HWE kernels


Q:

Can a Visual C++ program be compiled and run on Mac OS X or Linux?

… and if so, how?
Specifically, I'd like to compile and run wavdiff on Mac OS X Snow Leopard 10.6.8. As far as I can tell (which isn't very far, since I'm a total novice at C++), this was created with MS Visual C++ or similar.
I'd be most grateful for answers that address the general case of compiling Visual C++ programs on Mac OS X or Linux, and that also address the specific challenge above.

A:

The C++ language is portable. In theory, C++ source code can be compiled to run on any platform.
However, there are a few caveats to be aware of:

behavior might be different on different platforms. The C++ standard leaves many things implementation-defined, which means that it's up to the individual platform and compiler how it should behave. For example, the size of common data types can (and will) vary across different platforms. A long is typically 64 bits wide on 64-bit Linux, but only 32-bit on 64-bit Windows. A wchar_t is 16 bits wide on Windows, but typically 32 bits on Linux. So if your code makes assumptions about implementation-defined behavior, it might not be portable (a classic example is code which assumes that a pointer can be stored into an int or unsigned int. That works great on a 32-bit machine, but on 64-bit, you end up trying to store 64 bits of data into a 32 bit wide object.
even if your code is portable, your dependencies may not be. The most obvious example is of course the OS APIs. Code which uses the Win32 API won't compile on platforms where it's not available (anywhere other than Windows). Code which relies on POSIX APIs won't compile if that's not available (Windows supports some POSIX APIs, but far from all).
C++ can mean a lot of different things. There's the ISO standardized language, which is portable, and then there's the dialect understood by individual compilers. Visual C++, GCC, and any other major C++ compiler, allow a set of language extensions which aren't part of the standard, and may not be allowed on a different compiler. If your code relies on those, it may not compile using other compilers. (For example, Visual C++ allows a non-const reference to bind to a temporary, which isn't strictly speaking allowed, and other compilers will reject it. GCC by default allows dynamically sized arrays allocated on the stack, which, again, is a non-standard extension, and which other compilers will reject.)

So it depends on the code, really. Clean, high-quality code tends to be portable with little trouble. Except of course for the parts that rely directly on OS services, which will have to be rewritten for a different OS (or where a cross-platform wrapper/library may be available which can be used to do the same thing in a portable manner)

A:

This program can not be easily ported (recompiled without source changes). At least not without changes to the source. It holds dependencies to Windows libraries and is tied to Windows API in certain parts.
The problem is not that it's coded in VC++, but that it has these dependencies. A program that is coded such that it has no platform-dependencies can be easily ported in a lot of cases by just recompiling on the target platform or with a switch to target a different platform.


Q:

Could md5 hash of a string be different one place to another?

Possible Duplicate:
Will the MD5 cryptographic hash function output be same in all programming languages?

Hi,
I have a problem about md5 hashing. Users can upload profile picures on my project. I am md5 hashing usernames for profile picture name. But there is something interesting. I am hashing a value both with a test page on my server and md5 encrypt websites with same result. When I use this encryption for renaming image, it produces something different. It produces different value on image manipulation file.
Do you have any idea?
This is my check script:
<?php echo md5('funky'); ?>

It produces below code on my server and also on md5encrypter.com :
6b818a3a6bf1234ed24c940021922b63

But it produces on my image manipulation file below code. I dont know what it is:
d41d8cd98f00b204e9800998ecf8427e

Script for sql query. $userId comes from logged in userId:
$sql = mysql_query("SELECT username FROM users WHERE userId='$userId'");
while($row=mysql_fetch_assoc($sql)){
  $username=$row['username'];
}

A:

d41d8cd98f00b204e9800998ecf8427e is the MD5 hash of an empty string, so somewhere you have failed to fill your string with something more useful...
MD5 will always produce the same output for a given input, otherwise it's not MD5. What I did was simply google for the hash you got, and it turned up a lot of hits. If I didn't get a hit, I would have searched some of the reverse MD5 dictionaries which are around to see if that gave some clues.
As luck would have it, your hash is simply the result of MD5(''), is very common. It clearly indicates you tried to obtain something from your DB, failed, and hashed it anyway.


Q:

Check equality of two axes in multidiimensional numpy array

I am given a 3-dimensional shape(n,m,k) numpy array. I'd like to view this as a 2-dimensional matrix containing vectors, i.e. a nxm matrix with a vector of size k. I'd now like to check for two such arrays of shape (n,m,k) wheter entry (x,y,:) in the first array is equal to (x,y,:) in the second array. Is there a method to do this in numpy without using loops?
I'd thought about something like A == B conditioned on the first and second axis.

A:

a = np.arange(27).reshape(3,3,3)
b = np.zeros_like(a)
b[0,1,2] = a[0,1,2]
b[1,2,0] = a[1,2,0]
b[2,1,:] = a[2,1,:] # this is the same 3-vector, n=2, m=1

(a == b).all(axis=2) # check whether all elements of last axis are equal
# array([[False, False, False],
#        [False, False, False],
#        [False,  True, False]])


Q:

laravel symlinks on a window machine

Using a windows server, I have a laravel installation.
I have a storage folder that I have created on 'root/storage'
When I save images from the website, the images are stored in this folder.
I use this to save the files:
Storage::disk('local')->put('course_badges/'.$pre_string . $request->file('badge')->getClientOriginalName(), File::get($request->file('badge')));

When I try to reference the file like so 'https://app.com/storage/file_name.jpg', laravel gives me a 'Sorry, the page you are looking for could not be found.'  error.
However is I copy the files to '/public/storage/'
The image is then referenced correctly.
I have run the: php artisan symlink function.
I have tried to run ln -s ../storage/ command in powershell, but windows tells me that ln is not recognized.
What I am trying to achieve is to have my files saved in the root/storage folder (and sub folders)
and to reference them using https:app.nam/storage/file

A:

I had simmilar issue
as u mentioned file is stored in root/storage means problem with symlink between root/storage to public/storage to fix this
remove storage folder from public dir

Note:- keep backup first

then run php artisan storage:link
it should work


Q:

Using Google Maps Data

Is it possible to obtain a dataset of all search results in a google maps search? For example: if I want a list of all gas stations in Chicago, complete with addresses, store name, latitude-longitude coordinates etc.
Is such a data set against Google user agreement terms? I only plan on using the data for academic research questions.

A:

Yes, it is possible, using the Google Places API.
Just for completeness sake: This is most definitely not open data. For an open alternative, have a look at Phil's answer about Open Street Maps.
If your usage complies with Google's terms depends on what exactly you plan to do with the data. I guess section 10.1.3 of the Google Maps/Google Earth APIs Terms of Service will be most relevant for you:

(a) No Unauthorized Copying, Modification, Creation of Derivative Works, or Display of the Content. You must not copy, translate, modify, or create a derivative work (including creating or contributing to a database) of, or publicly display any Content or any part thereof except as explicitly permitted under these Terms. For example, the following are prohibited: (i) creating server-side modification of map tiles; (ii) stitching multiple static map images together to display a map that is larger than permitted in the Maps APIs Documentation; (iii) creating mailing lists or telemarketing lists based on the Content; or (iv) exporting, writing, or saving the Content to a third party's location-based platform or service.
(b) No Pre-Fetching, Caching, or Storage of Content. You must not pre-fetch, cache, or store any Content, except that you may store: (i) limited amounts of Content for the purpose of improving the performance of your Maps API Implementation if you do so temporarily (and in no event for more than 30 calendar days), securely, and in a manner that does not permit use of the Content outside of the Service; and (ii) any content identifier or key that the Maps APIs Documentation specifically permits you to store. For example, you must not use the Content to create an independent database of "places" or other local listings information.
(c) No Mass Downloads or Bulk Feeds of Content. You must not use the Service in a manner that gives you or any other person access to mass downloads or bulk feeds of any Content, including but not limited to numerical latitude or longitude coordinates, imagery, visible map data, or places data (including business listings). For example, you are not permitted to offer a batch geocoding service that uses Content contained in the Maps API(s).


Q:

How can I classifying this License Plate images? Matlab , LPR ,

I want to perform automatic character recognition on licence plates. One of my preprocessing step is binarization. However I have four different class of images and I have to use a different automatic thresolding algorithm on each class to get good binarization results.
I would like to choose the right algorithm automaticaly, my idea is to first perform classification on the licence plates images. In the following picture, each row represent a class.
picture:
http://www.mathworks.com/matlabcentral/answers/uploaded_files/31813/class.jpg
I'm working with MATLAB, how can I do that?? what is the best way?
Any ideas are appreciated.

A:

Here's a procedure you should try in a first attempt :
You have RGB images, so each images is a 3*RC matrix, where R is the number of rows and C the number of columns.
We will consider each pixel of an image as a realization of a random vector $\mathbf{x}$ of dimention 3. Hence, having an image, you have RC realization of $\mathbf{x}$. With the classification exemple you gave, each classe has 4 images, so we have 4*R*C realization of $\mathbf{x}$. We are abble to estimate some stastical moments, that we hope will be good descriptor, such as mean, covariance etc ... (mean can be estimated with empirical mean or median).
Let's just stick with the mean for now. Let us call $m_1,m_2,m_3,m_4$ the means of each class you gave.
Now we have a new image we want to classify, we estimate it's 3-dimensional mean $\mathbf{\mu}$, then using nearest neighbour, the class is given by :
$$
C=\arg_i\min\left(\lVert\mathbf{\mu}-m_i \rVert _2\right)
$$
This is very basic.
You may improve this scheme using additional features like variance (diagonal of the covariance matrix) or covariance matrix. You may estimate variance or covariance using empirical variance or empirical covariance estimator (realy just the classical formulae). However the euclidian distance won't be a good distance since you will comparing inhomogenous vector (the features will be composed of mean + covariance), you'll want to use a more advanced distance such as Bhattacharyya distance for the special case of gaussian distribution.


Q:

iBeacon detection by Mobile Phone Browser

Does anyone know of a script available to access the Blue tooth driver in a mobile device (Apple and Android) to see if an iBeacon is in range?
I am building an Web Page that requires location sensing capabilities for security and this would be ideal.
Thanks in advance.

A:

Sorry, as of November 2016 there are no bindings for major mobile browsers to access Bluetooth LE scan results in general, or more specifically  beacon detections.


Q:

combining a variable with a link and making it href under php

i'm trying to do something like this in php:
    echo "watch here";

i have the video id's in $link and i want to combine it with http://www.youtube.com/watch?v= and send the user to that video when "watch here" is clicked. it gives the error
    Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in xxxxxxxxxx on line xxx

i'm pretty new to php, please help. thanks in advance.

A:

Try using single quotes for echo:
echo 'watch here';


Q:

Column Named Cannot be Found

I have 2 datagrid that needs to show data from 2 tables, I used 2 load table for each datagrid to show the data.
public diagnosechipcomplainprint()
{
    InitializeComponent();
    load_table();
}

void load_table()
{
    string query = "Select HospitalRecordNo,concat(Patient_Fname, ' ', Patient_Mname, ' ',Patient_Lname) as 'Patient Name',Age,Gender,DateOfBirth,Email,PatientContact from patientinfo;";

    MySqlConnection con = new MySqlConnection(connection);
    MySqlCommand com = new MySqlCommand(query, con);

    try
    {
        MySqlDataAdapter sd = new MySqlDataAdapter();
        sd.SelectCommand = com;
        DataTable dba = new DataTable();
        sd.Fill(dba);
        BindingSource bs = new BindingSource();
        bs.DataSource = dba;
        dataGridView1.DataSource = bs;
        sd.Update(dba);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

void load_table2()
{
    string query2 = "Select VisitNo, HospitalRecordNo, DateOfVisit from visit_details where HospitalRecordNo = '" + recordno.Text + "';";

    MySqlConnection con = new MySqlConnection(connection);
    MySqlCommand com = new MySqlCommand(query2, con);

    try
    {
        MySqlDataAdapter sd = new MySqlDataAdapter();
        sd.SelectCommand = com;
        DataTable dba = new DataTable();
        sd.Fill(dba);
        BindingSource bs = new BindingSource();
        bs.DataSource = dba;
        dataGridView2.DataSource = bs;
        sd.Update(dba);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

And when i do cell click on the first data grid the data from datagrid will show in label, but when i click on the second data grid it shows error.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
        recordno.Text =
        row.Cells["HospitalRecordNo"].Value.ToString();
        pname.Text = row.Cells["Patient Name"].Value.ToString();
        age.Text = row.Cells["Age"].Value.ToString();
        gender.Text = row.Cells["Gender"].Value.ToString();
        dateofbirth.Text = row.Cells["DateOfBirth"].Value.ToString();
        email.Text = row.Cells["Email"].Value.ToString();
        contact.Text = row.Cells["PatientContact"].Value.ToString();
    }
}

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row1 = dataGridView2.Rows[e.RowIndex];

        visitno.Text = row1.Cells["VisitNo"].Value.ToString();
        rec.Text = row1.Cells["HospitalRecordNo"].Value.ToString();
        dateofvisit.Text = row1.Cells["DateOfVisit"].Value.ToString();
        nurse.Text = row1.Cells["Nurse_on_duty"].Value.ToString();
        temp.Text = row1.Cells["Temperature"].Value.ToString();
        cardiac.Text = row1.Cells["Cardiac_Rate"].Value.ToString();
        respiratory.Text =
        row1.Cells["Respiratory_Rate"].Value.ToString();
        bloodpress.Text =
        row1.Cells["Blood_Pressure"].Value.ToString();
        weight.Text = row1.Cells["Weight"].Value.ToString();
        sat.Text = row1.Cells["02_Stat"].Value.ToString();
    }
}

That is the code i used in Cellclick datagrid view 2.
I hope you can help me. Thank you

A:

I found that query for second DataGridView only contains 3 column definitions, which actually you need 10 columns as mentioned in DataGridViewRow.Cells indexer:
// only 3 columns returned in result set
string query2 = "Select VisitNo, HospitalRecordNo, DateOfVisit from visit_details where HospitalRecordNo = '" + recordno.Text + "';";

You should mention all column names required by DataGridViewRow.Cells in query result set, with parameterized query to prevent SQL injection:
string query2 = @"Select VisitNo, HospitalRecordNo, DateOfVisit, Nurse_on_duty,
                  Temperature, Cardiac_Rate, Respiratory_Rate, Blood_Pressure,
                  Weight, 02_Stat
                  from visit_details where HospitalRecordNo = @RecordNo";

// MySqlCommand parameter assignment
com.Parameters.AddWithValue("@RecordNo", recordno.Text);


Q:

CNN Keras Object Localization - Bad predictions

I'm a beginner in machine learning and I currently am trying to predict the position of an object within an image that is part of a dataset I created.
This dataset contains about 300 images in total and contains 2 classes (Ace and Two).
I created a CNN that predicts whether it's an Ace or a two with about 88% accuracy.
Since this dataset was doing a great job, I decided to try and predict the position of the card (instead of the class). I read up some articles and from what I understood, all I had to do was to take the same CNN that I used to predict the class and to change the last layer for a Dense layer of 4 nodes.
That's what I did, but apparently this isn't working.
Here is my model:
model = Sequential()

model.add(Conv2D(64,(3,3),input_shape = (150,150,1)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=2))

model.add(Conv2D(32,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=2))

model.add(Dense(64))
model.add(Activation("relu"))

model.add(Flatten())
model.add(Dense(4))

model.compile(loss="mean_squared_error",optimizer='adam',metrics=[])

model.fit(X,y,batch_size=1,validation_split=0,
epochs=30,verbose=1,callbacks=[TENSOR_BOARD])

What I feed to my model:
X: a grayscaled Image of 150x150 pixels. Each pixels are rescaled between [0-1]
y: Smallest X coordinate, Highest Y coordinate, Width and Height of the object (each of those values are between [0-1].
And here's an example of predictions it gives me:
[array([ 28.66145 ,  41.278576,  -9.568813, -13.520659], dtype=float32)]

but what I really wanted was:
[0.32, 0.38666666666666666, 0.4, 0.43333333333333335]

I knew something was wrong here so I decided to train and test my CNN on a single image (so it should overfit and predict the right bounding box for this single image if it worked). Even after overfitting on this single image, the predicted values were ridiculously high.
So my question is:
 What am I doing wrong ?
EDIT 1
After trying @Matias's solution wich was to add a sigmoid activation function to the last layer, all of the output's values are now between [0,1].
But, even with this, the model still produces bad outputs.
For example, after training it 10 epochs on the same image, it predicted this:
[array([0.0000000e+00, 0.0000000e+00, 8.4378130e-18, 4.2288357e-07],dtype=float32)]

but what I expected was:
[0.2866666666666667, 0.31333333333333335, 0.44666666666666666, 0.5]

EDIT 2
Okay, so, after experimenting for quite a while, i've come to a conclusion that the problem was either my model (the way it is built)
or the lack of training data.
But even if it was caused by a lack of training data, I should have been able to overfit it on 1 image in order to get the right predictions for this one, right?
I created another post which asks about my last question since the original one has been answered and I don't want to completely re-edit the post since it would make the first answers kind of pointless.

A:

Since your targets (the Y values) are normalized to the [0, 1] range, the output of the model should match this range. For this you should use a sigmoid activation at the output layer, so the output is constrained to the [0, 1] range:
model.add(Dense(4, activation='sigmoid'))


Q:

c++ read actual input line

I am trying to get a string line from input. For example "This is great". In all cases I am getting either or "This" either " great". getline() method did not working as expected. Code tried:
string val;

while (true) {
    cout << message;
    getline(cin, val);
    if (val.length() <= length)
    {
        break;
    }
}

My target is to get all sentence. Is that possible?

A:

adding  cin.clear(); cin.sync(); solve the problem
string val;

while (true) {
    cin.clear();
    cin.sync();
    cout << message;
    getline(cin, val);
    if (val.length() <= length)
    {
        break;
    }
}


Q:

System.ServiceModel.Web.WebOperationContext.CreateTextResponse error

its complining on CreateTextResponse i am using VS2010 target framework is 3.5
error:
'System.ServiceModel.Web.WebOperationContext' does not contain a definition for 'CreateTextResponse' and no extension method 'CreateTextResponse' accepting a first argument of type 'System.ServiceModel.Web.WebOperationContext' could be found (are you missing a using directive or an assembly reference?)
[OperationContract]
[WebInvoke(UriTemplate = "", Method = "GET",
    BodyStyle=WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json)]
public Message Blah()
{
    var j = new { Name = "blah1", Data = "blah2" };

    JavaScriptSerializer s = new JavaScriptSerializer();
    string jsonClient = s.Serialize(j);

    return WebOperationContext.Current.CreateTextResponse("method(" + jsonClient + ");",
        "application/json; charset=utf-8", Encoding.UTF8);
}

A:

Quote from the documentation of the CreateTextResponse method:

Supported in: 4

This basically means that this method has been introduced in .NET 4.0. No need to look for it if you are targeting .NET 3.5. Guess it's time to upgrade :-)


Q:

how to check if rdd is empty using spark streaming?

I have following pyspark code which I am using to read log files from logs/ directory and then saving results to a text file only when it has the data in it ... in other words when RDD is not empty. But I am having issues implementing it. I have tried both take(1) and notempty. As this is dstream rdd we can't apply rdd methods to it. Please let me know if I am missing anything.
conf = SparkConf().setMaster("local").setAppName("PysparkStreaming")
sc = SparkContext.getOrCreate(conf = conf)

ssc = StreamingContext(sc, 3)   #Streaming will execute in each 3 seconds
lines = ssc.textFileStream('/Users/rocket/Downloads/logs/')  #'logs/ mean directory name
audit = lines.map(lambda x: x.split('|')[3])
result = audit.countByValue()
#result.pprint()
#result.foreachRDD(lambda rdd: rdd.foreach(sendRecord))
# Print the first ten elements of each RDD generated in this DStream to the console
if result.foreachRDD(lambda rdd: rdd.take(1)):
    result.pprint()
    result.saveAsTextFiles("/Users/rocket/Downloads/output","txt")
else:
    result.pprint()
    print("empty")

A:

The correct structure would be
import uuid

def process_batch(rdd):
    if not rdd.isEmpty():
        result.saveAsTextFiles("/Users/rocket/Downloads/output-{}".format(
          str(uuid.uuid4())
        ) ,"txt")

result.foreachRDD(process_batch)

That however, as you see above, requires a separate directory for each batch, as RDD API doesn't have append mode.
And alternative could be:
def process_batch(rdd):
    if not rdd.isEmpty():
       lines = rdd.map(str)
       spark.createDataFrame(lines, "string").save.mode("append").format("text").save("/Users/rocket/Downloads/output")


Q:

pow (power) template implementation from wiki

Possible Duplicate:
Template Metaprogramming - Difference Between Using Enum Hack and Static Const

please explain what for is enum used in following implementation of power template.
template<int B, int N>
struct Pow {
    // recursive call and recombination.
    enum{ value = B*Pow<B, N-1>::value };
};

template< int B >
struct Pow<B, 0> {
    // ''N == 0'' condition of termination.
    enum{ value = 1 };
};
int quartic_of_three = Pow<3, 4>::value;

I found it on wikipedia. Is there a difference between int and enum in this case?

A:

There could be a difference if you ever try to take an address of an static const int. In that case, the compiler will generate storage for the static const int. You can't take the address of an enum and the compiler will never generate storage for it.
See also Template Metaprogramming - Difference Between Using Enum Hack and Static Const


Q:

Setzung des Kommas bei aufeinanderfolgenden Frageworten (wie wer was...)

Ich glaube, ab und zu keine Kommata zwischen Frageworten, beispielsweise

wer wie
  wie wo
  wer wie was
  ...,

gesehen zu haben. Ich könnte mir etwa gut vorstellen, dass

Die Polizei weiß schon, wer wie warum das Geld geklaut hat.

richtig ist. (Ist es so?)
Frage: Ist eine Kommasetzung möglich, obligatorisch oder verboten? Kann man die Frageworte auch so verwenden

Warum wie hast du das gemacht?

oder so

Warum und wie hast du das gemacht?
Warum, wie hast du das gemacht?

A:

Man kann einige Beispiele konstruieren, die anscheinend mehrere Fragewörter miteinander verbinden:

Ich weiss, wer was getan hat.

Nur ist das wer in diesem Fall kein Fragewort (es handelt sich ja um keine Frage), sondern ein Relativpronomen, denn es leitet einen Relativsatz ein.
was ist in diesem Fall ebenfalls kein Fragepronomen, denn es wird immer noch nichts gefragt - sondern ein Indefinitpronomen und meint so viel wie "etwas".
In meinem Beispiel gibt es ein Komma, das zur Einleitung des Relativsatzes gesetzt werden muss.
Mehr als zwei solche "Frageworte" (es sind keine) in einem Satz zu verwenden, ergibt meiner Meinung nach keinen rechten Sinn - Dein Beispiel

Die Polizei weiß schon, wer wie warum das Geld geklaut hat.

scheint mir kein korrekter Satz zu sein. Trennt man die Indefinitpronomen wie und warum durch ein "und", wird der Satz akzeptabel.

Die Polizei weiß schon, wer wie und warum das Geld geklaut hat.

Die Frage nach der Kommasetzung stellt sich also gar nicht.
Und

wer, wie, was, wieso, weshalb, warum?

geht einem nur so leicht von der Zunge, weil es jahrzehntelang der "Slogan" der "Sesamstraße" war.

A:

Zu diesem Thema gibt es einen Beitrag im Blog von Dr. Bopp. In dem dort diskutierten Beispiel kommt noch ein viertes, mit und angefügtes Fragewort vor - für Deine Frage also entsprechend zu

Die Polizei weiß schon, wer wie, wo und warum das Geld geklaut hat.

Die Antwort (angewandt auf Deine Frage) stellt dar, dass die Fragewörter wie, wo und warum wie aufgezählte Adverbialbestimungen funktionieren, bezogen auf den Satz "Wer hat das Geld geklaut". Entsprechend gelten die Kommaregeln für Aufzählungen, während wer das Subjekt des Satzes darstellt und somit nicht vom Rest des Satzes abgetrennt wird. Formal spricht nichts dagegen, auch die verkürzte Form so zu behandeln, also

Die Polizei weiß schon, wer wie, warum das Geld geklaut hat.

Allerdings wird eine Aufzählung aus zwei Elementen meist mit und verbunden, weshalb diese Variante etwas fremd wirken mag. Interessant finde ich deshalb, dass Dr. Bopp auf zwei Alternativen hinweist. Zum einen darauf, dass man die Fragewörter als gleichwertig empfinden kann und er deshalb auch ein Komma nach "wer" akzeptieren würde, auch wenn die syntaktische Analyse das nicht hergibt. Zum anderen darauf, dass insbesondere in der Variante ohne und die Fragewörter eben auch als Platzhalter gesehen werden können in einem Satz, den man "ausgefüllt" auch nicht mit Kommas schreiben würde, etwa so:

Die Polizei weiß schon, wer mit List aus Habgier das Geld geklaut hat.

Aus diesem Blickwinkel gesehen, wäre auch Deine ursprüngliche Annahme richtig:

Die Polizei weiß schon, wer wie warum das Geld geklaut hat.

Auf Deine Anschlussfrage lässt sich das aber nicht übertragen. Hier handelt es sich auf jeden Fall um eine Aufzählung, bei der Du die Fragewörter mit Komma trennen oder mit und verbinden musst.


Q:

don't understand how to use navigation controller in iphone

I'm extremly new to iphone and I have the following misunderstanding.
All over internet the tutorials about how to use NavigationController programatically it says:
 NavigationController must be declared in applicationDidFinishLaunching and must be init with a root.After that you can add views to it.

I have this:
   A UIViewController class meaning(AdiViewController.h, AdiViewController.m and AdiViewController.xib) and no Delegate file meaning no applicationDidFinishLaunching method.
What I wanna do is from my class-AdiViewController when pressing a button to go to another view.
I understand that I need a NavigationController which should retain my views having the root AdiViewController.
But my problem is where should I initializate that NavigationController in viewDidAppear??...cause I don't have the Delegate files.
If you could provide a minimal example with this small issue of mine it would be great.I'm sure that for those how are senior this is nothing but still I don't get it.Thanks

A:

NavigationController must be declared in applicationDidFinishLaunching -> this is not true.
In your AdiViewController if you have button when you push that button you want to load navigation Controller right ?
// Hook this IBAction to your button in AdiViewController
- (IBAction)pushNavController
{
   AnotherViewController* rootView = [[AnotherViewController alloc] initWithNibName:@"Anotherview" bundle:nil];
   UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:rootView];
   [rootView release];
   [self presentModalViewController:navController animated:YES];
   [navController release];
}

If you are in AnotherViewController i.e., you are in root view controller of Navigation controller. You need to push and pop view controllers from there. For example if you have a button in AnotherViewController:
// push next view controller onto navigation controller's stack
    - (IBAction)pushNextViewController
    {
      NextViewController* nextView = [[NextViewController alloc] initWithNibName:@"NextView" bundle:nil];
      [self.navigationController pushViewController:nextView animated:YES];
      [nextView release];
    }

// Similarly if you want to go back to AnotherViewController from NextViewController you just pop that from navigation controller's stack
- (IBAction)pushNextViewController
    {
      [self.navigationController popViewControllerAnimated:YES];
    }


Q:

Proof that $\cos ^{-1}x=\pi+\tan^{-1}\frac{\sqrt{1-x^2}}{x}$ for $x \in [-1,0)$

I have tried to prove this result by checking the domain of two functions but every time I get entangled at the result so how to prove it.
$$\large{ \cos ^{-1} x = \pi + \tan ^{-1} \dfrac {\sqrt{1-x^2}}{x}}\quad\text{if}\; x \in [-1,0)$$

A:

The graphs for $\cos^{-1} x$ and $\tan^{-1}\frac{\sqrt{1-x^2}}{x}$ for $x\in [-1,0)$ would be as follows [from Desmos]:

From here, we can see that the graphs look similar and seem to have been shifted by a value of $\pi$. Therefore the fact that $\arccos^{-1} x = \pi + \arctan \frac{\sqrt{1-x^2}}{x}$ is correct graphically.
Now, onto a more analytical proof.
Let $\theta = \arccos x$,
Now, we can say that $\cos \theta = x$. From which follows,
$$\tan \theta = \frac{\sqrt{1-x^2}}{x}$$
Therefore under normal conditions we would have,
$$\arccos x = \arctan\frac{\sqrt{1-x^2}}{x}$$
However, these aren't normal circumstances since the range of the two for $x\in[-1,0)$ is different $\arctan x$ has a range $[\frac{-\pi}{2},\frac{\pi}{2}]$ whereas $\arccos x$ has a range of $[0,\pi]$. This would mean that we would need to shift one graph to fit on the other for cases where the ranges lie in different areas.
As you can see, at $x=-1, \arccos x = \pi$ whereas $\arctan \frac{\sqrt{1-x^2}}{x} = 0$ and at $x=0, \arccos x = \pi/2$ whereas $\arctan \frac{\sqrt{1-x^2}}{x} = -\pi/2$. Therefore we add $\pi$ to $\arctan \frac{\sqrt{1-x^2}}{x}$ to make the graph coincide.
Therefore,
$$\arccos x = \pi + \arctan \frac{\sqrt{1-x^2}}{x}$$

A:

Let $x = \cos t$ where $t\in (\frac{\pi}{2} , \pi]$. Then we have $$\cos ^{-1} x = \cos ^{-1}(\cos t) = t$$Also $$\pi + \tan ^{-1} \dfrac {\sqrt{1-x^2}}{x} = \pi + \tan ^{-1} \dfrac {\sqrt{1-\cos^2t}}{\cos t} = \pi + \tan ^{-1} \dfrac {|\sin t|}{\cos t} = \pi + \tan^{-1}(\tan t) $$
Because $t\in (\frac{\pi}{2} , \pi]$ then $\tan^{-1}(\tan t) = t - \pi$. So we have $$\pi + \tan^{-1}(\tan t) = t -\pi + \pi = t$$

A:

Note the domain of the equation is determined by $1-x^2\ge 0$ and $\tan^{-1}\frac{\sqrt{1-x^2}}x \le 0$, which lead to $x\in[-1,0)$. Let
$$f(x) = \tan^{-1}\frac{\sqrt{1-x^2}}x-\cos^{-1}x$$
Note
$$f’(x) = -\frac1{\sqrt{1-x^2}}-\left(  -\frac1{\sqrt{1-x^2}}\right)=0$$
Then, $f(x)$ is invariant, i.e.
$$f(x) =f(-1) = \tan^{-1}0-\cos^{-1}(-1)=- \pi$$
Thus,
$$ \cos^{-1}x=\pi+ \tan^{-1}\frac{\sqrt{1-x^2}}x$$


Q:

Find measure of the side of a quadrilateral

$PTSQ$ is a cyclic quadrilateral.Sides $TS$ and $PQ$ are extended to meet at $R$ such that $\angle SRQ=30^{\circ}$.Also $\angle QPT =60^{\circ}$.Given that $QR=12$ and $TS=10\sqrt3$ find $PQ$.

It is clear that $\triangle RSQ$ ~ $\triangle RPT$,but the following equation which forms is too complex to solve.Please help.

A:

I find a picture always helps.

Due to the two angles you have been given, $\angle T$ must be $90^{\circ}$.
Since the quadrilateral is cyclic, its opposite angles must be supplementary.  So now you know $\angle SQP$ must also be $90^{\circ}$ (as must $\angle RQS$).
Therefore, $\triangle RSQ$ is a 30-60-90 triangle; you have been given the length of $\overline{QR}$; the lengths of $\overline{QS}$ and $\overline{SR}$ follow.
The triangle "at large" $\triangle RPT$ must also be a 30-60-90 triangle.  Since you know $\overline {TS}$ (given), and $\overline{SR}$ is known, now you also know $\overline{TR}$.
From here, you can compute $\overline{PR}$, and, therefore, the requested $\overline{PQ}$.
As a test of the lengths you are solving for, you should be able to confirm The Power of a Point; namely, that
$$\overline{RQ} \cdot \overline{RP} = \overline{RS} \cdot \overline{RT}$$
Due to $\angle Q$ and $\angle T$ being right, you will also find that
$$\overline{PT}^2 + \overline{TS}^2 = \overline{PQ}^2 + \overline{QS}^2$$
from which you can incidentally deduce the diameter of the quadrilateral's circumscribing circle.


Q:

URL works fine as IMG SRC, but not as a DIV's background-image

Why won't the HTML and CSS below show the DIV with a background-image?  The same URL works fine as the SRC of an IMG element. https://jsfiddle.net/52ft1erg/1/

This is a DIV

This is an IMG:

A:

Turns out the problem was the space after "url". Arrrgh. url (https://... won't work but url(https://... will.
I wasted 20 minutes on this before realizing my (dumb) mistake.
I looked around SO for a while to see if this was a duplicate, and although there are several other reasons that background-image will fail while IMG SRC will succeed (e.g. spaces in the filename, lack of height/width on the element, browser differences, etc.) I couldn't find this particular root cause. So sharing as a Q&A on StackOverflow to prevent others from wasting their time too.


Q:

Create query for a child to use the parameters of the parent

Could you help me please.
I searched the internet and could not find any solutions.
How create query for a child to use the parameters of the parent?
var Photos = new Schema({
    photo_id: {type: String, required: true},
    photo_path_low: { type: String, required: true }
});

var Users = new Schema({
    user_id: { type: String, required: true },
    count_coins: { type: Number, default: 20 },
    photos_relation: [Photos]
});
...
... some code
...
PhotoModel.findOne().where('parent.count_coins').gt(1)..... // parent for Example

A:

For this case there are Object-references:
var Photos = new Schema({
    photo_id: {type: String, required: true},
    photo_path_low: { type: String, required: true }
    createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
});

Then, when you make your query, you can populate references like this:
Photo.findOne({_id: 123})
.populate('createdBy')
.exec(function(err, post) {
    // do stuff with post
});

You can find more in this mongoose documentation.


Q:

Update values in one column in same table to another in SQL Server

Am trying to update my 1 table with new id's based on below scenario

in each step the new_ID column gets updated if it was previously used as can be seen in step 2, 3,4. The table can hold a small set of records or millions. Trying to determine best approach with sql server.
My approach is with a stored proc with 2 update statements
update old_new set newid = @newValue where oldid = @OldValue
update old_new set newid = @newValue  where newid = @OldValue

This looks like a performance nightmare waiting to happen. Any guidance is appreciated.

A:

if you're concern about performance, you can combine both update into one :
update old_new set newid = @newValue where oldId = @OldValue or newid = @OldValue


Q:

How to multiply a 3D matrix with a 2D matrix efficiently in numpy

I have two multidimensional arrays, which I want to multiply with each other. One has the shape N,N,3 and the other has the shape N,N.
Let me set the stage:
I have an array of atom positions of the shape N,3:
atom_positions = [[x1,y1,z1],
                  [x2,y2,z2],
                  [x3,y3,z3],
                  ...
                            ]

From these I calculate an upper triangular matrix of distance vectors so that the resulting N,N,3 matrix contains all unique pair distance vectors r_ij of the vectors inside atom_positions:
pair_distance_vectors = [[[0,0,0],[x2-x1,y2-y1,z2-z1],[x3-x1,y3-y1,z3-z1],...],
                         [[0,0,0],[0,0,0]            ,[x3-x2,y3-y2,z3-z2],...],
                          ...
                                                                              ]

Now I want to normalize each of these pair distance vectors. For that I want to use my N,N pair_distances array, which contains the length of every vector inside pair_distance_vectors.
The formula for a single vector is:
r_ij/|r_ij|
I want to do that by doing a matrix multiplication, where every entry in the N,N array becomes a scalar by which a vector inside the N,N,3 array is multiplied. I'm pretty sure that this can be achieved somehow with numpy by using numpy.dot() or a different function, but I just can't find the answer myself. Also, I'm afraid if I do find a transformation which allows for this, that my maths will be faulty.
Here's some demonstration code, which achieves what I want in a very inefficient fashion:
import numpy as np

pair_distance_vectors = np.ones(shape=(2,2,3))
pair_distances = np.array(((1,2),(3,4)))
normalized_pair_distance_vectors  = np.zeros(shape=(2,2,3))

for i,vec_list in enumerate(pair_distance_vectors):
    for j,vec in enumerate(vec_list):
        normalized_pair_distance_vectors[i,j] = vec*pair_distances[i,j]

print(normalized_pair_distance_vectors)

Thanks in advance.
EDIT: Maybe this is clearer:
distance_vectors = [[[x11,y11,z11],[x12,y12,z12],[x13,y13,z13],...],
                    [[x21,y21,z21],[x22,y22,z22],[x23,y23,z23],...],
                    ...                                            ]

distance_matrix = [[r_11,r_12,r_13,...],
                   [r_21,r_22,r_23,...],
                    ...                 ]

norm_distance_vectors = some_operation(distance_vectors,distance_matrix)

norm_distance_vectors = [[r_11*[x11,y11,z11],r_12*[x12,y12,z12],r_13*[x13,y13,z13],...],
                         [r_21*[x21,y21,z21],r_22*[x22,y22,z22],r_23*[x23,y23,z23],...],
                          ...                                                    ]

A:

You won't need a loop. Trick is to expand your pair_distance in the 3rd dimension by repeating it m times (m being the dimension of your vectors, here 3D) and then divide two arrays element wise (works for any m-dimensional vectors, replace 3 with m):
pair_distances = np.repeat(pair_distances[:,:,None], 3, axis=2)
normalized_pair_distance_vectors = np.nan_to_num(pair_distance_vectors/ pair_distances)

Output for your example inputs:
[[[1.         1.         1.        ]
  [0.5        0.5        0.5       ]]

 [[0.33333333 0.33333333 0.33333333]
  [0.25       0.25       0.25      ]]]


Q:

Pass parameters from one method to another method of button.click

I got  a main button function, where i parse the textbox text values, then I pass those values to an another method.
After performing the first calculation, then i want to pass those parameters to another button function.
I want to assign  int valueOF1, int valueOF2to this method public void testfunction(object sender, EventArgs ea) from the main button.
How can i do this?? Thank you for your help.
This is the code:
private void b_calculate_Click(object sender, EventArgs e)
    {

        int valueOF1;
        int.TryParse(t_Offset1.Text, NumberStyles.Any,
                     CultureInfo.InvariantCulture.NumberFormat, out valueOF1);

        int valueOF2;
        int.TryParse(t_Offset2.Text, NumberStyles.Any,
                     CultureInfo.InvariantCulture.NumberFormat, out valueOF2);

        int pRows = PrimaryRadGridView.Rows.Count;
        int sRows = SecondaryRadGridView.Rows.Count;

        if (pRows == 1 && sRows == 1)
        {
            calculatePS(valueOF1, valueOF2);
        }

}

private void calculatePS(int valueOF1, int valueOF2)
{
    MessageBox.Show("You are using : P-S");
    // Do some calculation & go to the next function ///
    Button2.Enabled = true;
    Button2.Click += testfunction; // Here i want to pass the valueOF1 & valueOF2

}

public void testfunction(object sender, EventArgs ea)
{
    MessageBox.Show("you...!");
    Button2.Enabled = false;
}

A:

Within your function calculatePS change the last line as follows
Button2.Click += new EventHandler(delegate
{
  // within this delegate you can use your value0F1 and value0F2
  MessageBox.Show("you...!");
  Button2.Enabled = false;
});

A:

You can declare valueOF1 and valueOF2 as class fields, so you can access them from different methods.
Here's how the code could look like:
int valueOF1 = 0;
int valueOF2 = 0;

private void b_calculate_Click(object sender, EventArgs e)
{
    int.TryParse(t_Offset1.Text, NumberStyles.Any,
                 CultureInfo.InvariantCulture.NumberFormat, out valueOF1);

    int.TryParse(t_Offset2.Text, NumberStyles.Any,
                 CultureInfo.InvariantCulture.NumberFormat, out valueOF2);

    int pRows = PrimaryRadGridView.Rows.Count;
    int sRows = SecondaryRadGridView.Rows.Count;

    if (pRows == 1 && sRows == 1)
    {
        calculatePS();
    }
}

private void calculatePS()
{
    // ** you can use valueOF1 and valueOF2 here **

    MessageBox.Show("You are using : P-S");
    // Do some calculation & go to the next function ///
    Button2.Enabled = true;

    //probably no need to register the Button2.Click event handler
    //except when the form is created
    //
    //Button2.Click += testfunction;
}

public void testfunction(object sender, EventArgs ea)
{
    // ** you can use valueOF1 and valueOF2 here as well **

    MessageBox.Show("you...!");
    Button2.Enabled = false;
}

Additional Note: int.TryParse returns a bool value that tells you whether the parse succeeded. In case the return is false, you may want to handle the parse error somehow instead of continuing with the normal flow.


Q:

Can't target .net 3.5 after Windows update

All of my builds broke after one of the updates this week. Now I can't change the target framework
and I can only choose 4.0 system assemblies
Is there any way I can get around this without uninstalling all the latest updates? If I add the right version of the System dlls via browse, it uses hint paths, which means I will have to check the System dlls into git.
This has happened both on my machine and on our build machine after running Windows update, so that's the only thing I can guess caused the problem.
This is Windows 7 and seems to only apply to VS 2008. VS 2012 lets me change the framework and shows the correct path to the v2.0 System dlls.

A:

Look at the .NET Framework Targeting Pack page for issues like this.
Basically, under Windows 8 you need to explicitly enable .NET 3.5 in "Windows Features". For earlier versions of Windows it just needs to be installed - the page has a link to the download.


Q:

How can I execute a Java method more than once?

I need to run my/an Objects method a second time. Is this allowed? How can I do this?

A:

Not sure what you are trying to do, but you can simply call a method from itself (it's called  recursion):
void recursiveMethod() {
    System.out.println("Called the recursive method");
    recursiveMethod();
}

Calling that method will print the line "Called the recursive method" until you get a StackOverflowError.

A:

You can call the method again from inside itself (AKA recursion).  So, something like this:
public void myMethod() {
  // Do some stuff here.

  // Possible conditional statement...
  if(restart) {
    myMethod();  // This will "restart" the method.
  }
}

If you have a more specific example that you're thinking of, that may help improve your question.


Q:

Wix 3.5 Create Scheduled Task

I've got a couple of projects I'm using Wix 3.5 for, along with Paraffin which is going really well, but I'm stuck trying to figure out how to create a Windows Scheduled Task as part of the installation.
I could just run a bat file that creates the task, but I don't think that would give me the uninstall features that Wix has, nor allow me to define it as part of the setup UI.
Does anyone know how to create a scheduled task as part of the XML Configuration in Wix 3.5?

A:

I think you can't avoid writing a custom action for this. Here's the sample. Alternatively, you can wrap this functionality into WiXExtension and e.g. "tie" it to a component, but that's far more work to be done.


Q:

interesting strcmp implementation failure. (C)

I am working on a small project which I have no access to any C standard library.( building a microkernel in ARM structure from the scratch. Even printf had to be implemented )
Under this circumstance I implemented strcmp, using Duff's machine methodology.
the following is the entire code.
int
strcmp ( const char *str1, const char *str2 )
{
   while ( *str1 || *str2 )
       if ( *(str1++) != *(str2++) ) return *str1 - *str2;
   return 0;
}

It made sense; and for some while it seemed to work on test cases, until an end-system fail happened. I traced down and it came to this strcmp.
At first I thought it incremented str1 first then compared against str2 BEFORE str2 incremented. 1. It turned out not to be but could anyone please verify that it can happen in some cases?
I then figured that the problem was in *str1 - *str2 so changed it to return 1. i.e., the resulting code is as follows:
   while ( *str1 || *str2 )
       if ( *(str1++) != *(str2++) ) return 1;
   return 0;

while all I wanted was an 'equals' check, so changing into '1' bore no problem, but I still wonder why the original code failed. 2. Could someone give a light or a suggestion as to how it could have failed? I would rather want the strcmp to follow the standard C interface that it returns a non-zero value that tells more about the str1 and str2.
the test cases were:
code_t // a function pointer type
program_find ( char *program )
{
if (strcmp( program, "exit" ) == 0) return ....
else if (strcmp( program, "k1" ) == 0) return ....
else if (strcmp( program, "k3" ) == 0) return ....
else if (strcmp( program, "perf" ) == 0) return ....
else if (strcmp( program, "test_libc" ) == 0) return ....
}

when *program was "k3" it returned "k1", and "test_libc" returned "perf".
The original problem was solved by giving it "return 1", so this question is purely for C interests.
A suggestion or linkage to strcmp documentation is also welcome. I have seen the spec interface for IEEE

A:

You are using a post increment on str1 and str2 when doing the comparison.  This causes them to be incremented before doing the subtraction, so you are subtracting the wrong two characters.
A better implementation would be
int
strcmp ( const char *str1, const char *str2 )
{
   while ( *str1 || *str2 ) {
       if ( *str1 != *str2 ) return *str1 - *str2;
       ++str1;
       ++str2;
   }
   return 0;
}

A:

You have two problems:

You increment the pointers before performing the subtraction for the return value, so the return value is not correct;
The standard specific for strcmp() indicates that the elements of the strings are compared as unsigned char.

Fixing these problems:
int
strcmp ( const char *str1, const char *str2 )
{
    const unsigned char *s1 = (const unsigned char *)str1;
    const unsigned char *s2 = (const unsigned char *)str2;

    while (*s1 && *s1 == *s2) {
        s1++;
        s2++;
    }

    return *s1 - *s2;
}


Q:

How do I create a game after moving to the first office?

I moved to the new office, and there's no option to create a new game. I've hired 2 new staff and done the management course.

A:

Click any where around your office and pick "Develop New Game..." option.
Don't click your character or any of your staff members since that will open their personal menu. You can do resarch or train your staff or yourself from personal menus.


Q:

Find out if $f(x,y) = x^2-xy+4y^2$ has maximum or minimum with a constraint

I have a function $f(x,y)= x^2-xy+4y^2$ and the constraint: $x+y=1$
and I would like to find local and global extrema. I used the Lagrange multiplier method and found that the only critical point I am dealing with must be for $x=\frac34$ and $y= \frac14$. This is where I am a little bit stuck however. I do not really know whether this is a local or global maximum/minimum or even one of those at all. I tried finding a result with the Hessian matrix, but I did not get a result out of this. I also do not think that $\{x,y \in \mathbb R | x+y=1\}$ is compact, so I do not know whether or not my function even has a minimum or maximum in this domain.
What can I do here to finish? Any help is greatly appreciated!

A:

If you write $y=1-x$ then
$$f(x)=x^2-x(1-x)+4(1-x)^2=6x^2-9x+4$$
which has a minimum at $f_{min}=\frac{5}{8}$ and it happens for $x=\frac{3}{4}$.


Q:

Variable number of async threads with C++11

I'm working on a program where I'd like to use async in a loop. In the example code I've included there's only 10 elements, so I could easily create an explicit variable for each element. However, in my main program, the number of elements in the vector can vary. Ideally, I'd like to create a vector of async threads - one for every element in the array - which are pushed back on the async vector as I loop through.Then I want to wait for them all to complete, and then use "get()" to return all of their outputs.
The code below will call async by assigning an explicit variable for each thread, but does anyone know how to dynamically call async in a vector without having to explicitly assign a variable to it? Ideally, I'd like for this program to call "std::cout" once for each time it looped through, instead of just once.
#include <iostream>
#include <vector>
#include <string>
#include <future>

std::string hi (std::string input)
{
    return "hello, this is " + input;
}

int main()
{
    std::vector<std::string> test_vector( 10, "a test" );
    std::future<std::string> a;
    std::future<std::string> b;

    for ( int i = 0; i < test_vector.size ( ); i++ )
    {
        a = std::async(std::launch::async, hi, test_vector[i]);
    }

    std::cout << a.get() << std::endl;

    return 0;
 }

A:

You can solve this by creating a vector of futures to match your threads vector, something like this:
#include <iostream>
#include <vector>
#include <string>
#include <future>

std::string hi(const std::string& input)
{
    return "hello, this is " + input;
}

int main()
{
    std::vector<std::string> tests = {"one", "two", "three", "four"};
    std::vector<std::future<std::string>> futures;

    // add the futures to the futures vector as you launch
    // your asynchronous functions
    for(auto&& t: tests)
        futures.emplace_back(std::async(std::launch::async, hi, std::cref(t)));

    // collect your results
    for(auto&& f: futures)
        std::cout << f.get() << '\n';
}

Note the use of std::cref to pass by const reference. Use std::ref to pass non const references.

A:

An answer including std::cout:
std::vector<std::future<std::string>> a;
for (int i = 0; i < 10; ++i) {
  a.emplace_back(std::async(hi));
}
for (auto& element : a) {
  std::cout << element.get() << std::endl;
}

A:

If I understood correctly, could be something like:
std::vector<std::future<std::string>> vessel;
for ( int i = 0; i < test_vector.size ( ); i++ )
{
    std::future<std::string> aux;
    aux = std::async(std::launch::async, hi);
    vessel.push_back(aux);
}

Sorry I cannot post as a comment, but this way, depending on the logic, and if it works, then you should be able to dynamically manipulate the vector vessel.

Update
better yet:
vessel.push_back(new std::future<std::string>);
vessel[vessel.size()-1] = std::async(std::launch::async, hi);

this way you don't need to explicitly declare a variable. But you will have to delete once you are done:
for(int i=0; i<(int) vessel.size(); i++)
{
    delete vessel[i];
}


Q:

getting the context object after setting it using @ContextConfiguration

How do I get ApplicationContext object so that i can use it in my code, after setting context using@ContextConfiguration.
My test class extends AbstractTransactionalJUnit4SpringContextTests.

A:

I generaly just inject a copy of the Application Context into the unit test:
 @Autowired
   ApplicationContext context;

A:

AbstractTransactionalJUnit4SpringContextTests extends AbstractJUnit4SpringContextTests, which has a protected applicationContext field. Your test class can just use that.


Q:

CSS Animation Glitch, on hover

I have an over hover animation glitch. When you're near the bottom of the item, it jumps, uncontrollably, is there any fix?
Sample image :

.btn:hover{
    background-color: #2795de;
    -moz-transform: translate(0, -1.3em);
    -o-transform: translate(0, -1.3em);
    -webkit-transform: translate(0, -1.3em);
}

A:

Just set transition on .btn
.btn{
 -moz-transition: all 2s ease;
 -o-transition: all 2s ease;
 -webkit-transition: all 2s ease;
  }

 .btn:hover{
  background-color:#2795de;
 -moz-transform:translate(0,-1.3em);
 -o-transform:translate(0,-1.3em);
 -webkit-transform:translate(0,-1.3em);
  }

DEMO

.btn{
  width:200px;
  height:200px;
  border-radius:4px;
  background: red;
 -moz-transition: all 2s ease;
 -o-transition: all 2s ease;
 -webkit-transition: all 2s ease;
  }

 .btn:hover{
  background-color:#2795de;
 -moz-transform:translate(0,-1.3em);
 -o-transform:translate(0,-1.3em);
 -webkit-transform:translate(0,-1.3em);
  }
<div class=btn > HOVER ME </div>


Q:

Conditional probability problem: $n$ letters carrying the numbers $1,...,n$ are arranged randomly

$n$ letters with the numbers $1,...,n$ written on them are arranged randomly, and than are opened one by one.
Let $k \leq n$. Given that the number written on the $k$-th letter was the highest one out of the numbers written on the first $k$ letters, what is the probability that the number written on the $k$-th letter is $n$?

My try:
$A_i^j$ - the number $j$ is written on the $i$-th letter
$B$ - the number written on the $k$-th letter is $n$
$P(A_k^n)= \frac {P(B\,|\,A_k^n)\,P(A_k^n)}{P(B)}$
$P(B\,|\,A_k^n)=1$
$P(A_k^n)=\frac {1}{n}$
$P(B)=\Sigma_{j=1}^n P(B\,|\,A_k^j)\,P(A_k^j)=\Sigma_{j=k}^n P(B\,|\,A_k^j)\,P(A_k^j)=\Sigma_{j=k}^n \frac {(j-1)!}{(j-k)!}\,\frac {1}{n}$
I'm trying to express $P(A_k^n)$ solely as a function of $n$.
Is there a way to further simplify the sum I got for $P(B)$ or maybe there is a whole different approach to solve this problem?

A:

All permutations of the same set of letters that constitute the first $k$ letters are equally likely.  Therefore, we can ignore the fact that the highest number among those $k$ letters happened to be on the last ($k$-th) of those letters.
Then the problem becomes finding the probability that the highest among those $k$ letters is $n$.  But that is trivially the probability that $n$ appears among the first $k$ letters, and the probability of that is
$$
\frac{k}{n}
$$


Q:

How to get all algebraic associative operations on a finite set by efficient algorithm?

Number of binary operation on a set of 2 elements is 2^(2*2)=16.

Number of associative binary operation on that set is only 8.

Number of binary operation on a set of 3 elements is 3^(3*3)=19683.
Number of associative binary operation on that set is only 113.
How to know how many associative binary operations there are on a set of n elements?
Also in order to get all this 113 operations and write into file, it is necessary to write a program.
if I will try to get all 19683 operations and then check it`s associative property "a*(bc)==(ab)*c" for all 19683 operations, this will work but this should take a long time for n=4 elements!
How to write an efficient algorithm to solve this task?
Please help me!

A:

More than devising your own algorithm, this is a task for a mathematical model finder. For this task, I'd particularly recommend mace4, which part of the LADR library. It is specifically tuned to algebraic problems like this. The input (let's name it semigroups.in) would look like:
formulas(sos).
  (x * y) * z = x * (y * z).
end_of_list.

And then running it by mace4 -n 4 -N 4 -m 10000 <semigroup.in (find all 4-element models and print up to 10000 of them) produces a long output like
...

============================== MODEL =================================

interpretation( 4, [number=2331, seconds=0], [

        function(*(_,_), [
                           1, 2, 3, 3,
                           2, 3, 3, 3,
                           3, 3, 3, 3,
                           3, 3, 3, 3 ])
]).

============================== end of model ==========================

============================== STATISTICS ============================

For domain size 4.

Current CPU time: 0.00 seconds (total CPU time: 0.11 seconds).
Ground clauses: seen=64, kept=64.
Selections=2132, assignments=8520, propagations=6194, current_models=2331.
Rewrite_terms=210696, rewrite_bools=65151, indexes=11452.
Rules_from_neg_clauses=586, cross_offs=3767.

============================== end of statistics =====================

User_CPU=0.11, System_CPU=0.26, Wall_clock=0.

Exiting with 2331 models.

As you can see, it is very fast.
The library contains many other tools, such as isofilter that allows you to filter isomorphic variants of an algebra etc.


Q:

python 3.5.0 ::: printing dates and times

So I used datetime module to print dates and made it so far.
However I cannot print times...
Every time I run:
currentTime = datetime.time()
print (currentTime)

The result is:
00:00:00

I tried:
print(datetime.datetime.now())
>>>> 05-11-2015 19:00.173546

But I only want time: 19:00
Do you know how to do it? Is there a function for that?

A:

datetime.time() is equivalent to datetime.time(hours=0, minute=0):
>>> import datetime
>>> datetime.time()
datetime.time(0, 0)
>>> datetime.time(hour=0, minute=0)
datetime.time(0, 0)

datetime is a module. datetime.time is a class. datetime.time() is an instance of that class created using the default hour, minute values (0,0) e.g., to create time object that corresponds to 19:00 instead, you could use datetime.time(19, 0).
To print only time for an existing datettime.datetime or datetime.time instance, you could use %H:%M time format:
>>> import datetime
>>> current_time = datetime.datetime.now()
>>> print("{:%H:%M}".format(current_time))
08:40


Q:

Task Scheduler custom trigger - start when EventID is FOO and EventData.Data is BAR

I want to Windows Task Scheduler to start a custom task when a special event is logged to Windows Event Log. The event has EventID 6702 and when a data parameter is MyBackupJob. Here is my current custom trigger and it does not work:
<QueryList>
  <Query Id="0" Path="VisualSVNServerBackgroundJobs">
    <Select Path="VisualSVNServerBackgroundJobs">
            *[System[(EventID=6702)]] and *[EventData[Data[1]='MyBackupJob']]
    </Select>
  </Query>
</QueryList>

What's wrong?
Here is an example of the event from the log:
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="VisualSVN Background Job Service" />
  <EventID Qualifiers="49152">6702</EventID>
  <Level>2</Level>
  <Task>0</Task>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2020-05-11T12:53:34.650971500Z" />
  <EventRecordID>4885</EventRecordID>
  <Channel>VisualSVNServerBackgroundJobs</Channel>
  <Computer>svn1.example.com</Computer>
  <Security />
  </System>
- <EventData>
  <Data>{516B8AED-C3CF-4221-BC91-10B18BD3A56F}</Data>
  <Data>MyBackupJob</Data>
  <Data>{E3831378-33E1-4C8E-BE8A-CF08DB1CB7F0}</Data>
  <Data>Failed to backup 1 out of 2 repositories.</Data>
  <Data>00:00:00</Data>
  <Data>203</Data>
  </EventData>
  </Event>

A:

Try changing
*[System[(EventID=6702)]] and *[EventData[Data[1]='MyBackupJob']]

to
//Event[EventData[Data[2]="MyBackupJob"]][System[EventID=6702]]

and see if it works.


Q:

Keychain data security in jailbroken device

Storing sensitive data in keychain is a best practice in iOS. But using a jailbroken device an attacker can dump all the keychain data. (keychain-dumper)
Can anyone help me understand how to protect the data in a keychain, in case of a jailbroken device.

A:

It's not possible. If the device is jailbroken all data can be easily accessed.


Q:

d3 bar chart labels not getting updated on updating the chart with the new data

Below is the code getting called everytime when I click on a button or an option in the drop down menu in order to update my d3 bar chart graph with the new data.
The bars in the chart are properly updated according to the new data, but the labels of the bar chart are not getting replaced with the new ones, instead both old and new labels are displayed.
Please suggest something so that old labels are not shown on bars.
function updateGraph(data) {

          // scale the range of the data
          x.domain(data.map(function(d) { return d.Country; }));
          y.domain([0, d3.max(data, function(d) { return d.Value; })]);

          var bars = svg.selectAll(".bar").data(data);

          bars.enter().append("rect").attr("class", "bar");

          bars.transition().duration(200).attr("x", function(d) { return x(d.Country); })
          .attr("width", x.rangeBand())
          .attr("y", function(d) {return y(d.Value); })
          .attr("height", function(d) { return height - y(d.Value); });

          var texts = svg.selectAll(".text").data(data);

          texts.enter().append("text").attr("class","label").attr("x", (function(d) { return x(d.Country) + x.rangeBand() / 2 ; }  ))
                .attr("y", function(d) { return y(d.Value) + 1; })
                .attr("dy", ".75em")
                .text(function(d) { return d.Value; });

          texts.transition().duration(200).attr("x", (function(d) { return x(d.Country) + x.rangeBand() / 2 ; }  ))
                .attr("y", function(d) { return y(d.Value) + 1; })
                .attr("dy", ".75em")
                .text(function(d) { return d.Value; });

          bars.exit().remove();

          svg.selectAll(".axis").remove();

          svg.append("g")
             .attr("class", "x axis")
             .attr("transform", "translate(0," + height + ")")
             .call(xAxis);

          svg.append("g")
              .attr("class", "y axis")
              .call(yAxis)
              .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", ".71em")
              .style("text-anchor", "end")
              .text("Value");

        }

A:

You are not adding class to the text
This will select all DOM with class text
var texts = svg.selectAll(".text").data(data);

texts
.enter()
.append("text")
.attr("class","label text") <-- add text class here
.attr("x", (function(d) { return x(d.Country) + x.rangeBand() / 2 ; }  ))
                .attr("y", function(d) { return y(d.Value) + 1; })
                .attr("dy", ".75em")
                .text(function(d) { return d.Value; });

Now to remove all text on update
bars.exit().remove();
texts.exit().remove(); <--- add this to remove exited text


Q:

R: obtaining last Friday's date

I can get today's date:
Sys.Date( )

But how do I get last Friday's date?
I tried:
library(xts)
date1 <- Sys.Date( )
to.weekly(date1 )

But this gives an error.
Thank you for your help

A:

I think this should work:
library(lubridate)

Sys.Date() - wday(Sys.Date() + 1)

A:

Try this:
library(zoo)
lastfri(Sys.Date())

where lastfri is the same as the one line function nextfri in the this zoo vignette, zoo quickref vignette, except that ceiling is replaced with floor.  Note that lastfri is vectorized, i.e. it can take a vector of input dates and produces a vector of output dates.  For example,
library(zoo)
Sys.Date()
## 2015-03-10
lastfri(Sys.Date() + 0:6)
## [1] "2015-03-06" "2015-03-06" "2015-03-06" "2015-03-13" "2015-03-13"
## [6] "2015-03-13" "2015-03-13"

Thus last Friday was March 6th and we keep getting March 6th until the day advances to to next Friday at which point the last Friday is March 13th.
Aside:  Next Friday is Friday the 13th.

A:

Here is a function that finds the last date for any day of the week:
getlastdate <- function(day) {
library(lubridate)
dates <- seq((Sys.Date()-7), (Sys.Date()-1), by="days")
dates[wday(dates, label=T)==day]
}

getlastdate("Mon")

# "2015-03-09"

Enter the day of the week in abbreviated format:  i.e.
Sun   Mon Tues  Wed   Thurs Fri   Sat


Q:

What are Machine learning model characteristics?

This question I have received in some Machine Learning related interview and Here is the question

What questions would you ask to learn about machine learning model characteristics?

This is what I think:
I did a bit research on the internet & found this resource, but still not very clear about How ML model characteristics are equivalent to asking trade-off between different algorithms in supervised learning settings. What I understood and framed my answer is:

First, for simplicity, I assumed that this model is used for some supervised learning task(classification/ regression) then,

I would first try to find a learning algorithm used to create this model, because this will provide me with a clue of the created model and help me to talk about different issues within it(such as,

How complex or simple your model is(feature engineering!)?
What are your training & test errors(Model performance)

Both will help me to talk about the bias vs variance trade-off.
Furthermore, I could talk about different learning algorithm trade-offs in supervised settings.

Is the model based on identifying correlations i.e output variable can be expressed in terms of the linear/non-linear combination of features?
(targeting linear regression, logistic regression, SVM or Neural network algorithms, or
it's decision tree-based algorithms.

I am not confident enough that my answer is complete or correct (since I am not able to understand what precisely characteristics of a model are?), so I need this community's help to provide feedback! please feel free to add your suggestion to it!

A:

I'm a little torn on helping on this question because I think that you're being given good advice above about modifying your question and using this site in a better way. But at the same time, I hate when questions are closed so quickly on here because the people with those votes just do a terrible job with that privilege (a privilege that I have but rarely use because nothing should be closed here). So, I'm going to choose to help here but please use the feedback you're being given when posting here in the future.
When I interview most data scientists, I am looking for understanding of concepts and rationale. With this particular question, I don't think they are looking for deep detail; a smart scientist starts by getting a high view into the project. So I think that with this question, they want to see how you walk through the analysis. I would reply with the following, roughly in this order:

What is the business case the algorithm is trying to solve?
Is this algorithm predictive or is it doing categorizations?
How many factors are in the complete dataset? How many factors are actually used?
Is it a neural network or does it use "traditional approaches" like regression, decision trees, etc, etc?
Can you show me a confusion matrix for the results? What is the accuracy? What is the recall? What is the precision?
Can you show me an ROC curve?

I think that at this point, once you are given the information and have time to analyze it, you will be in a much better position to make statements about a particular model. Good luck!


Q:

C# UI multiple KeyDown Events ?? windows form application

I am working on an mp3 player with minimal UI, in C# using windowsForm app.
currently I have methods for open play and pause a song.
As I want the UI minimal,  I only display the fileName of the playing song.
Now the problem is when I am trying to assign a KeyDown Event for each method.
As all in my form I can select and map a KeyPress Event to is the Empty form, but it can only hold 1 KeyDown event, which now means I can only get 1 method to run..
How can I solve this ?
I assume I could use KeyPress and KeyUp events for my other 2 methods to run,   but I suppose theres a more clever solution ?
part of my code:  in this example,  OpenFile  works... but Play doesnt work at the same time,  because I havent assigned any EventHandler for it, I guess.  But as I dont want any button in the UI.,,  What can I then do ??
I dont want a traditional shortcut command either. like ctrl + key.
private void o(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.O)
            {
                openFileDialog1.ShowDialog();
            }
        }

        private void p(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.P)
            {
                player.Play();
            }
        }

A:

Simply
private void o(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.O)
        {
            openFileDialog1.ShowDialog();
        }

        else if (e.KeyCode == Keys.P)
        {
            player.Play();
        }
    }

you may want to define only one event-handler, but you can check for several keys pressed.


Q:

SELECT Only one value per ID - SQL Server

I dont know is this is possible at all, I´m not even sure how to google it.
Im using SQL Server 2014.
Right now I have a SP that outputs a table with data including MovementID, Vehicle, VehicleType and Total of sales.
But it groups all the vehicles ids and vehicles types with a total.
I need to separate vehicles, which I can.
The problem is that the totals appear duplicated, or triplicated etc.
So, how can I only select that column only one time per ID (MovementID in the example).
I'll keep trying, of course, but any idea would be appreciated.
[

A:

You can use LAG to see values of the previous row.
with q as (your query here)
select
  movementid, vehicleid, vecicletype,
  case when movementid = lag(movementid) over (order by movementid, vehicleid)
    then null else total
  end as total
from q
order by movementid, vehicleid;


Q:

Rails: How can I make an object available in all views?

I have a search object which is created in my Galleries controller and displayed in my Galleries View:
app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
  def index
    @galleries = Gallery.all
    @search = Search.new
  end

This object represents a search bar. I want to move the search bar into my layouts/application.html.erb view and make it available on all pages in the header. This would require me to make the search object globally available, and I am not sure how to do that. I tried sticking in ApplicationController and thought that would make it available in all views since everything inherence from there, but it didn't work. How can I make an object available in all views?

A:

You can do it with a before_action (aka. before_filter) in the ApplicationController, from which all your controllers should inherit.
class ApplicationController < ActionController::Base
  before_action :make_search

  def make_search
    @galleries = Gallery.all
    @search = Search.new
  end
end

This will make the function run before every action.
You can use skip_before_action :make_search to disable it in a specific controller, if you need to, or skip_before_action :make_search, only: :index to disable it for only the index action for a controller.
If you only want this for a few controllers, you could define make_search in the ApplicationController, and put the before_action :make_search in the controllers for which you want to enable it...


Q:

IQueryable extension method which becomes an expression

I'm writing an IQueryable implementation for an existing tool. One of the very common features of this tool is a query resembling Exists at the database. In order to support this, I want to extend IQueryable with a method such as the following:
public static IQueryable<T> WhereExists<T, U>(
    this IQueryable<T> Current,
    IQueryable<U> Other,
    Func<T, Field> CurrentSelector) where U : Entity
    {
        return WhereExists(Current, Other, x => x.ID, CurrentSelector);
    }

public static IQueryable<T> WhereExists<T, U>(
    this IQueryable<T> Current,
    IQueryable<U> Other,
    Func<U, Field> RemoteSelector,
    Func<T, Field> CurrentSelector) where  U : Entity
    {
        throw new NotImplementedException(
            "This method is only implemented for db-backed queries.");
    }

The presence of the extension method allows me to get past the compiler, the real functionality will be in the expression visitor.
The catch is that I'd like this to show up in the Expression, but it's running through to the extension method. Are there restrictions which must be followed to get this into the expression (such as with .Where, etc.)?

A:

Let's look how the .NET framework does it:
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
    return source.Provider.CreateQuery<TSource>(
       Expression.Call(null, ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression, Expression.Quote(predicate) }));
}

They package up the parameters into a call expression.
I recommend that you stick to the default Queryable methods as much as possible so that you don't have to do much of this trick.


Q:

Google Drive Api for installed application c#

Can someone please show a working example code of how to use google drive api for installed application? ( access_type=offline)
I found a few explanations, but can't get to a working flow.
Thanks

A:

Ok, What I used at least was not 'installed application', but 'web application'.
These are the steps to do:

Go to Google Developers Console and create a project.
Go to APIs & Auth
On APIs enable Drive API & Drive SDK.

4.On Credentials Create new Client ID for Web Application (Create your Consent screen, evev though we won't use it.)
In the Create Client ID window, add the url "https://developers.google.com/oauthplayground" to the AUTHORIZED REDIRECT URIS.
5.Go to the url you added on number 4
6.Click the gear on the right and configure:
OAuth flow: Server-side

Access type: Offline

Use your own OAuth credentials: Tick

Then copy your Client ID & Secret from the console.

7.On the left, choose Drive API -> https://www.googleapis.com/auth/drive, click Authorize APIs
8.A new window will open, asking you to accept Google OAuth... click Accept.
9.Click Exchange authorizaion code for tokens.
10.Copy & Save the Acess & Refresh tokens.
The code:
private static DriveService CreateServie(string applicationName)
{
  var tokenResponse = new TokenResponse
  {
    AccessToken = yourAccessToken,
    RefreshToken = yourRefreshToken,
  };

  var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
  {
    ClientSecrets = new ClientSecrets
    {
      ClientId = yourClientID,
      ClientSecret = yourClientSecret
    },
    Scopes = new[] { DriveService.Scope.Drive },
    DataStore = new FileDataStore(applicationName)
  });

  var credential = new UserCredential(apiCodeFlow, yourEMail, tokenResponse);

  var service = new DriveService(new BaseClientService.Initializer
  {
    HttpClientInitializer = credential,
    ApplicationName = applicationName
  });

  return service;
}


Q:

Neo4j Divide ( / ) by Zero ( 0 )

In neo4j I am querying
MATCH (n)-[t:x{x:"1a"}]->()
WHERE n.a > 1 OR n.b > 1 AND toFloat(n.a) / (n.a+n.b) * 100 < 90
RETURN DISTINCT n, toFloat(n.a) / (n.a + n.b) * 100
ORDER BY toFloat(n.a) / (n.a + n.b) * 100 DESC
LIMIT 10

but I got  / by zero  error.
Since I declared one of n.a or n.b should be 1, if both zero it should skip that row and I shouldn't get this error. This looks like a logic issue in Neo4j. There is no problem when I delete AND toFloat(n.a)/(n.a+n.b)*100 < 90 from WHERE clause. But I want the results only lower than 90. How can I overcome this?

A:

It seems the second condition, toFloat(na) / (na + nb) * 100 < 90, is tested before the first. Look at the Filter(1) operator in this execution plan:
+--------------+---------------+------+--------+--------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|     Operator | EstimatedRows | Rows | DbHits |                                            Identifiers |                                                                                Other |
+--------------+---------------+------+--------+--------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|   Projection |             1 |    3 |      0 | anon[111], anon[138], n, toFloat(n.a)/(n.a + n.b)* 100 |                                                                                anon[111]; anon[138] |
|          Top |             1 |    3 |      0 |                                   anon[111], anon[138] |                                                                                {  AUTOINT6};  |
|     Distinct |             0 |    3 |     24 |                                   anon[111], anon[138] |                                                                                anon[111], anon[138] |
|    Filter(0) |             0 |    3 |      6 |                                         anon[29], n, t |                                                                                t.x == {  AUTOSTRING0} |
|  Expand(All) |             1 |    3 |      6 |                                         anon[29], n, t |                                                                                (  n@7)-[t:x]->() |
|    Filter(1) |             1 |    3 |     34 |                                                      n | (Ors(List(n@7.a > {  AUTOINT1}, Multiply(Divide(ToFloatFunction(  n@7.a),Add(  n@7.a,  n@7.b)),{  AUTOINT3}) < {  AUTOINT4})) AND Ors(List(  n@7.a > {  AUTOINT1},   n.b > {  AUTOINT2}))) |
| AllNodesScan |             4 |    4 |      5 |                                                      n |                                                                                |
+--------------+---------------+------+--------+--------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

You can get around this by force breaking the filter into two clauses.
MATCH (n)-[t:x { x:"1a" }]->()
WHERE n.a > 1 OR n.b > 1
WITH n
WHERE toFloat(n.a) / (n.a + n.b) * 100 < 90
RETURN DISTINCT n, toFloat(n.a) / (n.a + n.b) * 100
ORDER BY toFloat(n.a) / (n.a + n.b) * 100 DESC
LIMIT 10

I found this behavior surprising, but as I think about it I suppose it isn't wrong for the execution engine to rearrange the filter in this way. There may be the assumption that the condition will abandon early on failing the first declared condition, but Cypher is exactly that: declarative. So we express the "what", not the "how", and in terms of the "what" A and B is equivalent to B and A.
Here is the query and a sample graph, you can check if it translates to your actual data:
http://console.neo4j.org/r/f6kxi5


Q:

Map behavior like in Google Maps application

I want to achive map behavior like in google maps application. Example: set marker on a shop somewhere in the bottom of the screen, click on that marker so info panel should open and overlay the marker, map moves it's content so marker is still visible. I don't know how to correctly quote this requirement so I've found nothing on that point in the internet. Is there any guide on this UI pattern?

A:

If you google it, you will find a lot of code and documentation regarding it. Please visit the link https://developers.google.com/maps/documentation/android/
you can start from here
https://developers.google.com/maps/documentation/android/start
you will find it very close to your requirement


Q:

Error in using the BSTR data type

My firebreath plugin project has a wrapper class of an active X control.
One of the method takes a BSTR data type variable as input, but when I try to call the method and pass a BSTR, i get an error.
I have even included the "WTypes.h" header file. But that doesnot seem to fix the problem.
So someone suggest an alternative.
short MakeCall (BSTR sNumber,short * nConnectionId );

The Makecall function  calls the Makecall function implemented by the active x control by using these paramters
The error
Error   1   error C2665: 'FB::variant_detail::conversion::convert_variant' : none of the 5 overloads could convert all the argument types   c:\users\research\downloads\firebreath-firebreath-firebreath-1.6.0rc1-15-g411c7fe\firebreath-firebreath-411c7fe\src\scriptingcore\variant.h 842 1   axWrapper

PS: After i searched about the error i find that fire breath doesnot support wide characters i.e uni code. So is there a way to use the unicode data type in firebreath.

A:

That error indicates that you are trying to convert a FB::variant into a BSTR, which is not something that FB::variant knows how to do. Most likely that means that you're trying to use a BSTR as a type in a method you registered on a JSAPIAuto object. JSAPIAuto will automatically convert types, but you have to use types that it understands, and BSTR is not one of them.
Instead, find whatever method is registered as a JSAPI method and change the BSTR to a std::wstring; then convert the wstring into a BSTR. This should work fine.
FireBreath does support unicode; you can use std::wstring for wide characters and std::string types coming from the browser will be UTF8. You can #include "utf8_tools.h" and use FB::utf8_to_wstring and FB::wstring_to_utf8 to convert between them.
Hope this helps