text:
Q: SQL: count occurencies per value, if not 3, then duplicate value with unique id I am having some problems with a Magento database, and need some help.
A table where videos are stored in, have 3 rows per video; one per store language.
The video values should therefore be added 3 times when I add a video to the website. However, about 1500 products only have videos for 1 or 2 languages.
Is there a way to check the table with a query and count if a value has 3 occurencies, and if not, duplicate the value with a unique store id (1-2-3)?
Any help would be highly appreciated.

A: You must use the unique composite index in several columns of your table, in the same way you can use count () in the sub query to know how many records you have store.


text:
Q: Xcode compile warnings: This block declaration is not a prototype I am loading dependencies with podfile and, although everything works as expected, I am worried about warnings produced by Xcode.
Is there anything that needs to be done with that?

A: Those warnings come from the dependencies that you included via CocoaPods. Generally, you don't need to do anything because of those warnings.
If you want to fix the underlying issue you should fork the Pod, fix the issue and create a Pull Request afterwards.
If you want to ignore the warnings you can add this to your Podfile. This will result in all warnings coming from Pods to be ignored, so they are not shown in Xcode.
# ignore all warnings from all pods
inhibit_all_warnings!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetch with 'If-None-Match': "etag" header always returning 200 in React Native app I'm encountering a very strange issue in a react native app where a simple fetch with an etag is always returning a 200 rather than an expected 304:
const response = await fetch(url, {
  method: 'GET',
  headers: {
    'If-None-Match': etag
  },
});

where etag is something like "33a64df551425fcc55e4d42a148795d9f25f89d4"
When I make this request directly through something like Postman/Insomnia, it is working and I get the appropriate 304 response.
Inspecting the app in Reactotron, I can see the network request header seems to be correct:

If I copy the JSON request as cURL I get the following:

curl -H "if-none-match:"33a64df551425fcc55e4d42a148795d9f25f89d4"" https://url/to/api

With a slight modification to show only the headers:

curl -sD - -o /dev/null -H "if-none-match:"33a64df551425fcc55e4d42a148795d9f25f89d4"" https://url/to/api

Which also only returns a 200, but if I escape the quotes around the etag like so, it works:

curl -sD - -o /dev/null -H "if-none-match:\"33a64df551425fcc55e4d42a148795d9f25f89d4\"" https://url/to/api

I'm genuinely confused because I've tried all variants of:
'If-None-Match': etag
'If-None-Match': `"${etag}"`
'If-None-Match': `\"${etag}\"`
'If-None-Match': '"' + etag + '"'

to no avail, what am I doing wrong?
Putting the same fetch request into an html file and testing in the browser works with the expected 304 status.

A: Under the hood, React Native is using NSURLCache which returns a 200 even when it receives a 304 from upstream, at least from what I've read online. Have a look using Charles Web Proxy or another such proxy from the App Store and you'll see the traffic over the network before it hits your app. Googling reveals a lot of edge cases around caching also, such as apparently not caching private responses by default.

A: I'm getting the same issue using Axios on a React Native App. I also tried the opposite 'If-Match' and getting 200, so it's as if the header is not even there.
const query = {
  method: 'GET',
  url: `someurl`,
  headers: {
    Authorization: `Bearer ${token}`,
    'If-Match': etag,
  },
};

let response = await axios(query);


text:
Q: How to reset the memory in New Game of Hangman? I am working on a Hangman game. Game is working as it should except that when i start a new game, i am unable to clear the data that was stored from the previous game. So it gives me a screen that looks like the following after the user clicks "play again".
Screenshot of Hangman Game - How it should look after clicking "play again"
Screenshot of Hangman Game after clicking "play again"
How do i reset the data so that the textview and the buttons after the startNewGame method is executed?
tried to use textView.setText("") to do a reset but it is not working. Appreciate if you can help shed some light for me. Thanks!
My Codes are as follows.
package com.desmondwong.hangmangame;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.Random;

public class GameActivity extends AppCompatActivity {

    //To reference the components
    ImageSwitcher imageSwitcher;
    TextView textView;
    TextView textViewScore;
    Button btn [] = new Button[26];

    //Images for the hangman
    int img [] = {R.drawable.img0,
            R.drawable.img1,
            R.drawable.img2,
            R.drawable.img3,
            R.drawable.img4,
            R.drawable.img5,
            R.drawable.img6,
            R.drawable.img7,
            R.drawable.img8};

    AlertDialog helpAlert;

    //Variables
    String strSecret = "", strGuess="", strText="";

    String strWords[] = {"APPLE", "ORANGE","BANANA"};

    int intError = 0; //Error made by player

    int livesRemaining = 8; //Lives remaining by player

    int numCorr = 0; //Correct letter guess by player

    Random random = new Random(); //Random generator

    public void startNewGame(){

        intError = 0; //Error made by player

        livesRemaining = 8; //Lives remaining by player

        numCorr = 0; //Correct letter guess by player

        imageSwitcher.removeAllViews();

        //textViewScore.setText(String.valueOf(livesRemaining));

        //textView.setText("");

        setupImageSwitcher();
        setup26Buttons();
        getSecretWord();

    }

    //To create help icon at top right
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //To create help icon at top right
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //case android.R.id.home:
               // NavUtils.navigateUpFromSameTask(this);
                //return true;
            case R.id.action_help:
                showHelp();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        //Retrieve the reference
        imageSwitcher = findViewById(R.id.imageSwitcher);
        textView = findViewById(R.id.textView);
        textViewScore = findViewById(R.id.textViewScore);
        textViewScore.setText(String.valueOf(livesRemaining));

        setupImageSwitcher();
        setup26Buttons();
        getSecretWord();

    }

    private void setup26Buttons() {

        GridLayout g = findViewById(R.id.gridLayout);

        //to create 26 buttons
        for(int i = 0; i<btn.length; i++) {

            btn[i] = new Button(this, null, R.attr.buttonStyleSmall); //Buttonsytlesmall so that it fits the screen
            btn[i].setText(""+(char)('A'+i)); //need to set back to char, as +i will set it back to integer. "" to set this to a String so it is sync to setText
            btn[i].setTag(""+(char)('A'+i));
            btn[i].setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onClick(View v) {

                    strGuess += v.getTag(); //Get letter that the player guessed and keep adding on to strGuess
                    v.setEnabled(false); //disable pressed button since the player already press
                    v.setBackgroundColor(android.R.color.black);

                    //Check for error guess. If the letter is not inside the strSecret, it will return less than 0
                    if (strSecret.indexOf(v.getTag().toString())<0){

                        intError++; //your error is added
                        int livesRemaining = 8;
                        livesRemaining -= intError; // Countdown based on errors recorded
                        textViewScore.setText(String.valueOf(livesRemaining));
                        imageSwitcher.setImageResource(img[intError]); //set the img no. to follow the error
                    }

                    else {

                        numCorr++;
                    }

                    boolean playerWin = true;
                    //Display all correct guesses
                    strText = ""; //reset the display

                    for (int i = 0 ; i<strSecret.length();i++){

                        char ch = strSecret.charAt(i); // get each character from strSecret

                        //To check if this letter can be found in strGuess
                        if(strGuess.indexOf(ch)>=0){
                            //found
                            strText += ch;

                        }

                        else{

                            //Not found
                            strText += "-";
                            playerWin=false;
                        }

                    }

                    textView.setText(strText);

                    if (playerWin) {

                        if (numCorr == strSecret.length()) {

                            //Toast.makeText(getApplicationContext(), "You won", Toast.LENGTH_LONG).show();

                            //let user know they have won, ask if they want to play again
                            AlertDialog.Builder winBuild = new AlertDialog.Builder(GameActivity.this);
                            winBuild.setTitle("Amazing! You save Batman!");

                            winBuild.setMessage("The Hangman\'s favourite fruit is:\n\n" + strSecret);

                            winBuild.setPositiveButton("Play Again",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            GameActivity.this.startNewGame();

                                        }
                                    });

                            winBuild.setNegativeButton("Exit",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            GameActivity.this.finish();

                                        }
                                    });
                            winBuild.show();

                        }

                    } else if (livesRemaining > 0) {

                        //still have lives remaining. do nothing
                    }

                    else {

                        //Toast.makeText(getApplicationContext(), "You Lost",Toast.LENGTH_LONG).show();

                        // Display Alert Dialog
                        AlertDialog.Builder loseBuild = new AlertDialog.Builder(GameActivity.this);
                        loseBuild.setTitle("Batman got executed!");
                        loseBuild.setMessage("You lose!\n\nThe answer was:\n\n"+ strSecret);
                        loseBuild.setPositiveButton("Play Again",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        GameActivity.this.startNewGame();
                                    }});

                        loseBuild.setNegativeButton("Exit",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        GameActivity.this.finish();
                                    }});

                        loseBuild.show();

                    }

                }

            });

            g.addView(btn[i]);

        }

    }

    private void getSecretWord() {

        int index = random.nextInt(strWords.length);
        strSecret = strWords[index];

        for(int i=0; i<strSecret.length(); i++) {

            strText += "-"; //to create multiple - for the unknown word

        }

        textView.setText(strText);

    }

    private void setupImageSwitcher() {

        //https://www.tutorialspoint.com/android/android_imageswitcher.htm
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

            @Override
            public View makeView() {

                ImageView imageView = new ImageView(getApplicationContext());

                imageView.setImageResource(R.drawable.img0);

                return imageView;
            }
        });

        Animation aniOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

        Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);

        imageSwitcher.setOutAnimation(aniOut);

        imageSwitcher.setOutAnimation(aniIn);
    }

    //show help information
    public void showHelp(){
        AlertDialog.Builder helpBuild = new AlertDialog.Builder(this);
        helpBuild.setTitle("Help");
        helpBuild.setMessage("Whisper the password (Hangman's favourite fruit) to save Batman\n\n"
                + "You only have 8 tries!");
        helpBuild.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        helpAlert.dismiss();
                    }});
        helpAlert = helpBuild.create();
        helpBuild.show();
    }

}

A: Your problem is every time you call startNewGame you:

*

*add a new text to the existing value of strText instead of setting a new one

*add new buttons in the btn array (without removing the old ones)

So you need to make sure startNewGame get rid off everything that has been created for the previous game and that you don't need anymore.
EDIT
One approach can be to have a 'Game' object that stores everything (strSecret, strGuess,...) instead of having them in the Activity.
Every time startNewGame is called, you do myGame = new Game(); so you're sure that all the previous data are gone.
EDIT 2
A quick fix is:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    //Retrieve the reference
    imageSwitcher = findViewById(R.id.imageSwitcher);
    textView = findViewById(R.id.textView);
    textViewScore = findViewById(R.id.textViewScore);
    textViewScore.setText(String.valueOf(livesRemaining));

    // ** QUICK FIX **
    btn = new Button[26];
    strText = "";

    setupImageSwitcher();
    setup26Buttons();
    getSecretWord();
}

EDIT 3 (Working improved example)
MainActivity
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import java.util.Random;

public class GameActivity extends AppCompatActivity {

    // Constants

    //Images for the hangman
    @DrawableRes
    private final static int img[] = {R.drawable.img0, // Img0 is when the player is dead
            R.drawable.img1,
            R.drawable.img2,
            R.drawable.img3,
            R.drawable.img4,
            R.drawable.img5,
            R.drawable.img6,
            R.drawable.img7,
            R.drawable.img8};

    private final static String strWords[] = {"APPLE", "ORANGE", "BANANA"};
    private final static Random random = new Random(); //Random generator

    // To reference the components
    private ImageSwitcher imageSwitcher;
    private TextView textView;
    private TextView textViewScore;

    // Other private fields
    private Game mGame;

    public void startNewGame() {
        mGame = new Game(img.length - 1); // The max lives is the size of the array - 1
        setup26Buttons();
        initSecretWord();
        imageSwitcher.reset();
        imageSwitcher.setImageResource(img[mGame.livesRemaining]);
        textViewScore.setText(String.valueOf(mGame.livesRemaining));
        textView.setText(mGame.hiddenWord);
    }

    //To create help icon at top right
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //To create help icon at top right
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_help:
                showHelpDialog();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        //Retrieve the reference
        imageSwitcher = findViewById(R.id.imageSwitcher);
        textView = findViewById(R.id.textView);
        textViewScore = findViewById(R.id.textViewScore);

        // Init the view components
        initImageSwitcher();

        // Start the game
        startNewGame();
    }

    private void setup26Buttons() {

        final GridLayout g = findViewById(R.id.gridLayout);
        g.removeAllViews(); // clear the children views (if exist)

        //to create 26 buttons
        final int maxLetters = 26;
        Button btn;
        for (int i = 0; i < maxLetters; i++) {

            btn = new Button(this, null, R.attr.buttonStyleSmall); //Buttonsytlesmall so that it fits the screen
            btn.setText(Character.toString((char) ('A' + i))); // Set the letter
            btn.setOnClickListener(listener);

            g.addView(btn);
        }
    }

    private final View.OnClickListener listener = new View.OnClickListener() {
        @SuppressLint("ResourceAsColor")
        @Override
        public void onClick(View v) {

            String guess = (((Button) v).getText()).toString();
            v.setEnabled(false); //disable pressed button since the player already press
            v.setBackgroundColor(android.R.color.black);

            // Check if the current letter is in the secret word
            if (!mGame.secretWord.contains(guess)) {
                mGame.livesRemaining--; // Remove a live
                imageSwitcher.setImageResource(img[mGame.livesRemaining]); //set the img no. to follow the error
                textViewScore.setText(String.valueOf(mGame.livesRemaining));

                if (mGame.livesRemaining == 0) {
                    showEndGameDialog("Batman got executed!", "You lose!\n\nThe answer was:\n\n" + mGame.secretWord);
                }
            } else {
                mGame.correctGuess += guess; // Add the letter to the ones correctly guessed
                //Display all correct guesses
                final StringBuilder sb = new StringBuilder();
                final char[] chars = mGame.secretWord.toCharArray();
                for (int i = 0; i < mGame.secretWord.length(); i++) {
                    //To check if this letter can be found in correctGuess
                    sb.append((mGame.correctGuess.contains(Character.toString(chars[i])))
                            ? chars[i] //found
                            : "-");
                }
                mGame.hiddenWord = sb.toString();
                textView.setText(mGame.hiddenWord);

                // If all the unique letters in the word have been found, it's a win
                if (mGame.correctGuess.length() == mGame.maxLetters) {
                    showEndGameDialog("Amazing! You save Batman!", "The Hangman\'s favourite fruit is:\n\n" + mGame.secretWord);
                }
            }
        }
    };

    private void showEndGameDialog(String title, String message) {
        new AlertDialog.Builder(GameActivity.this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("Play Again",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                GameActivity.this.startNewGame();
                            }
                        })
                .setNegativeButton("Exit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                GameActivity.this.finish();
                            }
                        })
                .show();
    }

    private void initSecretWord() {

        int index = random.nextInt(strWords.length);
        String secretWord = strWords[index];
        // Replace all the letters by '-' ('\p{L}' matches any letter)
        String hiddenWord = secretWord.replaceAll("\\p{L}", "-");

        mGame.maxLetters = countUniqueLettersInWord(secretWord);
        mGame.secretWord = secretWord;
        mGame.hiddenWord = hiddenWord;
    }

    /**
     * Calculate the number of unique letter in the word
     * E.g BANANA has 3 unique letters (B,A,N)
     *
     * @param word The word to count the unique letter in
     * @return The total of unique letters
     */
    private static int countUniqueLettersInWord(final String word) {
        char[] chars = word.toCharArray();
        int count = 0;
        char curr;
        boolean contains;
        for (int i = 0; i < chars.length; i++) {
            curr = chars[i];
            // Check if the same letter exists in the visited letters (from pos 0 to current letter)
            contains = false;
            for (int j = 0; j < i; j++) {
                if (curr == chars[j]) {
                    contains = true;
                    break; // Don't need to continue if the letter already exists.
                }
            }
            if (!contains)
                count++;
        }

        return count;
    }

    private void initImageSwitcher() {

        //https://www.tutorialspoint.com/android/android_imageswitcher.htm
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                return new ImageView(getApplicationContext());
            }
        });

        Animation aniOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
        Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);

        imageSwitcher.setOutAnimation(aniOut);
        imageSwitcher.setOutAnimation(aniIn);
    }

    //show help information
    public void showHelpDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Help")
                .setMessage("Whisper the password (Hangman's favourite fruit) to save Batman\n\n"
                        + "You only have 8 tries!")
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        })
                .show();
    }
}

Game class
public class Game {

    String secretWord, correctGuess, hiddenWord;

    //Lives remaining by player
    int livesRemaining;

    public int maxLetters;

    public Game(int lives) {
        secretWord = "";
        correctGuess = "";
        hiddenWord = "";
        livesRemaining = lives;
    }
}


text:
Q: What is the third variable in a matrix partial correlation? I believe the below background information is necessary to explain my question...
Background Information:

I have a square 2D matrix of variables that represent the interaction
between any two positions in a protein's sequence. I then compare each
column of interactions using Pearson's correlation and store that
value in a new correlation matrix. This is shown graphically in the
linked image.

The next step in this protocol is to take the partial correlation. For that I use the below equation where Where rxy-1 is the correlation coefficient for a given position (x, y) in the inverted correlation matrix, and rxx-1 and ryy-1 are the corresponding diagonal values.

On to the question itself, I found an alternative way of calculating partial correlations from this kind of data in this paper. It has two equations, shown below. As far as I can tell, the right equation is identical to the pc equation I have been using thus far, except with different notation, and it is shown as being equivalent to the left equation.

My question is: In converting from the right equation to the left equation, where is the third variable, C, coming from. A and B are equivalent to my X and Y position values, so how can I extrapolate a third C dimension from my 2D correlation matrix?
I have very little mathematical background, so don't hesitate to ask me for important information that I have overlooked. Thanks in advance for any help you all can render!!
Edit: Thanks to @GoldenGateBridge 's great explanation I think I now better understand the 3 variable partial correlation equation, at least the version used in the above paper. The right 2 var equation uses inverse covariance as its basis for PC calculation while the 3 var equation is calculated from the correlation matrix. I drew up a graphical representation of my understanding below (the numbers aren't accurate calculations, its just for example).


text:
Q: .NET Core Image not stored in s3 bucket My function is executing successfully, but image is not storing in the s3 bucket. I need your help to understand where I am doing wrong
public IActionResult load([FromForm(Name = "file")] IFormFile file)
{
    var credentials = new EnvironmentVariablesAWSCredentials();
    var client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);

    PutObjectRequest request = new PutObjectRequest
    {
        BucketName = "#######",
        Key = file.FileName,
        InputStream = file.OpenReadStream(),
        ContentType = file.ContentType
    };

    var result = client.PutObjectAsync(request);
    return Ok(result);
}

A: Try this exact .NET Code:
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;

namespace UploadObject
{
    // The following example shows two different methods for uploading data to
    // an Amazon Simple Storage Service (Amazon S3) bucket. The method,
    // UploadObjectFromFileAsync, uploads an existing file to an Amazon S3
    // bucket. The method, UploadObjectFromContentAsync, creates a new
    // file containing the text supplied to the method. The application
    // was created using AWS SDK for .NET 3.5 and .NET 5.0.

    class UploadObject
    {
        private static IAmazonS3 _s3Client;

        private const string BUCKET_NAME = "doc-example-bucket";
        private const string OBJECT_NAME1 = "objectname1.txt";
        private const string OBJECT_NAME2 = "objectname2.txt";

        private static string LOCAL_PATH = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        static async Task Main()
        {
            _s3Client = new AmazonS3Client();

            // The method expects the full path, including the file name.
            var path = $"{LOCAL_PATH}\\{OBJECT_NAME1}";

            await UploadObjectFromFileAsync(_s3Client, BUCKET_NAME, OBJECT_NAME1, path);
            await UploadObjectFromContentAsync(_s3Client, BUCKET_NAME, OBJECT_NAME2, "This is a test...");
        }

        /// <summary>
        /// This method uploads a file to an Amazon S3 bucket. This
        /// example method also adds metadata for the uploaded file.
        /// </summary>
        /// <param name="client">An initialized Amazon S3 client object.</param>
        /// <param name="bucketName">The name of the S3 bucket to upload the
        /// file to.</param>
        /// <param name="objectName">The destination file name.</param>
        /// <param name="filePath">The full path, including file name, to the
        /// file to upload. This doesn't necessarily have to be the same as the
        /// name of the destination file.</param>
        private static async Task UploadObjectFromFileAsync(
            IAmazonS3 client,
            string bucketName,
            string objectName,
            string filePath)
        {
            try
            {
                var putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectName,
                    FilePath = filePath,
                    ContentType = "text/plain"
                };

                putRequest.Metadata.Add("x-amz-meta-title", "someTitle");

                PutObjectResponse response = await client.PutObjectAsync(putRequest);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }

        /// <summary>
        /// This method creates a file in an Amazon S3 bucket that contains the text
        /// passed to the method.
        /// </summary>
        /// <param name="client">An initialized S3 client object.</param>
        /// <param name="bucketName">The name of the bucket where the file will
        /// be created.</param>
        /// <param name="objectName">The name of the file that will be created.</param>
        /// <param name="content">A string containing the content to put in the
        /// file on the destination S3 bucket.</param>
        private static async Task UploadObjectFromContentAsync(IAmazonS3 client,
            string bucketName,
            string objectName,
            string content)
        {
            var putRequest = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectName,
                ContentBody = content
            };

            PutObjectResponse response = await client.PutObjectAsync(putRequest);
        }
    }
}


text:
Q: Show the input[type=file] filename at directive template I'm trying to implement something like the bootstrap-file-uploader in pure angular. This bootstrap extension replaces the default file-upload widget with a consistent alternative (see this jsfiddle).
I'm unable to show the selected filename in another element from the same directive. Tried the following already:

*

*scope.fileName = files[0].name

*ngModel

*scope.$apply.

The event is fired and value is changed, but the change is not reflected in the interface.
angular.module('app', [])
.directive('uploader', function() {
    return {
        restrict: 'E',
        template: '
filename: {{ fileName }}
<input type="file">',
        scope: {},
        link: function(scope, el, attrs) {
            var file = el.find('input');
            scope.fileName = '?';
            file.bind('change', function(ev) {
                var files = event.target.files;
                scope.fileName = files[0].name;
                scope.$apply(function() {
                    scope.fileName = files[0].filename;
                });
                console.log(files, ev);
            });
        }
    };
});

[UPDATE]
Its working now - files[0].filename should be files[0].name.

A: The answer was there, just not implemented in scope.$apply.
Corrected:
scope.$apply(function() {
    scope.fileName = files[0].name;


text:
Q: Matlab dll included in C# project on client pc I'm working on Matlab and C# projects, I've created a DLL file from the Matlab project and run it on the C# project.
My code works fine on my computer and on any Windows 7 x64 bit that I've tested.
The problem is with Windows 8, When I'm trying to run my app on Win 8 PC the app collapsed while calling to the main class that included in the DLL.
I tried to catch the error, but no error occurred, the app just crashed.
I've already installed MCR for the specific Matlab version, but it still doesn't work.
I believe that I'm missing some system configuration, can someone help to do some order what exactly should I do in order to run it?
UPDATE1:
The code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using VisionCameraQA;

using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
namespace VisionCameraQATest
{
    public partial class Form1 : Form
    {
        cls_Main main;
        public Form1()
        {

            InitializeComponent();
             try
        {
            main = new cls_Main();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString())
        }
        }
   }
}

The app crashes while getting to main = new cls_Main();, it is not reached to the catch at all.


text:
Q: Google App Indexing: GSDDeepLink call causes build to fail I'm trying to set up my app for Google App Indexing, following Google's instructions here. As soon as I implemented the GSDDeepLink call in my AppDelegate, I get this error when I try to build:
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_GSDDeepLink", referenced from:
      type metadata accessor for ObjectiveC.GSDDeepLink in AppDelegate.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

When I comment out my GSDDeepLink call, it builds. Does anyone know how to fix this?

A: try change your values in Build Settings->Linking->Other Linker Flags to this.
$(inherited)
-ObjC
-framework
"CoreText"
"GoogleAppIndexing"


text:
Q: Why single CPU core's performance on the same workload different in pthread and OpenCL? I have a very simple task: scan over a char array multiple times (16*1024). I implemented it with pthread with one thread on one CPU core. The time is 23's. Then I use device fission to create a device containing only one CPU Compute Unit (i.e., one CPU core), the time is only 17's. In my opinion, the OpenCL implementation should be slower than pthread (because C is more hardware-close). How come I get this results?

A: The OpenCL kernel language is very close to the hardware. It's a supersubset of C99 (subset as in no function pointers are supported and superset as in you have vector datatypes etc)
The implementations are generally built on top of llvm and the kernels compile to raw X86 functions. In addition due to nature of OpenCL the implementation can do a lot more optimizations than what full C compiler can do, such as way better support for autovectorization. Thus it's not a surprise at all that a code written as OpenCL kernel can easily outperform a naive loop version of the same. One has to do a lot of work to get it approach the OpenCL version.
Currently especially the Intel CPU OpenCL implementation is mostly a marvelous way to write parallel CPU code. Even though in your case you limited it to just single core it's almost certain that it used the full extent of available vector instructions for X86.


text:
Q: How do you store time interval property in neo4j? I wonder whether you can store time interval as property in neo4j, similar to postgresql interval data type. I want to store something like person experience which can range from few months to years. If there is no such data type in neo4j then how do you store this kind of data?

A: You can use the Duration datatype:

Cypher has built-in support for handling temporal values, and the
underlying database supports storing these temporal values as
properties on nodes and relationships.

RETURN duration.between(date('2020-01-01'), date.realtime()) AS `experience`

An example setting properties:
CREATE(p:Person)
SET p.name='John Doe',
    p.startDate = date("2020-01-01");

MATCH(p:Person)
WHERE p.name='John Doe'
    SET p.exp = duration.between(p.startDate, date.realtime())
RETURN p

I don't recommend this approach as the experience value would be accurate only on the day it was created/updated. It is better to calculate such values on the fly, either using the database or the application layer as opposed to hard-coding it in the DB.
Cypher example for the above node would be:
MATCH(p:Person)
WHERE p.name='John Doe'
RETURN p.name AS `Name`,p.startDate as `Start Date`, duration.between(p.startDate, date.realtime()) AS `experience`


text:
Q: Probability density function as number of particles per unit volume? In this book Quantum Mechanics by P.J.E. Peebles pg 365 it hints at the idea of the wave function been the probability of  finding $n$ particles per unit volume. I have looked in other books and on websites, but can't find any more on this view. So in general can we relate the wave function to the number of particles per unit volume and if so how and if not why not?

A: Imagine you stuck a detector in front if the target and it went off a certain number of times per second (on average) per square meter of cross section.
If you then placed it somewhere else at an angle from the forward direction it (the detector) would also go off a certain number of times per second (on average) per square meter of cross section.
Super. That's what you actually measure in the label. A bigger detector and more time gives (on average) more detection events.
A faster beam would make detection events more frequently. But you can normalize that. If it travels at speed v and you have cross section A and you get m detection events in time t then you can consider the volume of volume A(vt) and its highly similar to it having m particles in it. So m detection events in time t with cross section A with particles at speed v gives a relationship like A(vt)n=m where you can think of n as a number of particles per volume.
That's nice, not because there are n particles in some volume somewhere but because you can easily relate n to experimental parameters.
And obviously the wavefunction isn't literally a probability per unit volume (it is complex). But you are use to thinking of $|\psi(x,y,z,t)|^2$ as a probability per unit volume (it isn't). So it's an easier thing to compare with when you compare two things that are probabilities per unit volume.
In reality what you observe is detection events happening at different frequencies. That is always what you measure. Even when you consider $|\psi(x,y,z,t)|^2$ as a probability per unit volume when you look at the experimental data, it is different frequencies of detection events that you end up seeing in the data.


text:
Q: Getting the last record in SQL in WHERE condition and Group by I have similar situation of Getting the last record in SQL in WHERE condition
 examples of table
TESTING
with fields of
SubjectName
TestType
TestDate
ResultIs
Want to return Positive test record if one TestType for that TestDate is Positive, Likewise
want to return Negative test record if all TestTypes for that TestDate are Negative.
I CAN LIVE WITHOUT RETURNING THE Positive results if the code is easier to write without returning records that have any test for that date as positive, because that could be a separate view for a different crystal report "positive.rpt"
So if I need 1 record per date when there are no positive tests, (same as saying I need 1 record per date when all tests are negative)
TESTING (which is really a view).
    SubjectName TestDate ResultIs TestType
    =========== ======== ======== ========
    Alexandaria 20140215 Negative test0001
    Alexandaria 20140215 Positive test0002
    Alexandaria 20140215 Positive test0003
    Alexandaria 20140220 Negative test0002
    Alexandaria 20140220 Negative test0003
    Alexandaria 20140228 Negative test0003
    Alexandaria 20140228 Positive test0004
    Alexandaria 20140228 Positive test0005

TestType does not matter in the selection,  a group by of the first 3 would be perfect, but only when all records for a date are negative. choosing the last record for a date with the ResultIS sinking to the bottom (or Max). Do I need to do a subqquery?
Preferred output of query into a view of this form
 view
    SubjectName TestDate ResultIs TestType
    =========== ======== ======== ========
    Alexandaria 20140215 Positive test0002
    Alexandaria 20140215 Positive test0003
    Alexandaria 20140220 Negative test0003 or test0002 does not matter
    Alexandaria 20140228 Positive test0004
    Alexandaria 20140228 Positive test0005

or just only negative records with no positive for that date.
    SubjectName TestDate ResultIs TestType
    =========== ======== ======== ========
    Alexandaria 20140220 Negative test0003 or test0002 does not matter

furthermore since this last output view that is defined as negative only records for a date, i dont even need the testtype or the Result output, just name, and date
But using a where clause of "negative" would still somehow include dates with Positive results. i dont know a way around that.
    SubjectName TestDate
    =========== ========
    Alexandaria 20140220

Feb 20th is the only negative only date, that is what I would settle for.
DEMOTABLE IS THE LIST OF SUBJECTNAMES
    Alexandria
    Betty
    Tom
    Sue

SELECT SubjectName,TestDate FROM TESTING
inner join Testing to Demotable (if subjectname=subjectname)
where resultIS=Negative
group by subjectName,TestDate


text:
Q: Using webpack with babel and babel-preset-react and babel-preset-es2015 I'm trying to transcompile my react/es6 code and am coming from browserify. I'm struggling to create a webpack build because of the new babel 6 release and the fact that most of the tutorials out there are now outdated.
This works in my .babelrc:
{
  "presets": ["react"]
}

But when I change it to this:
{
  "presets": ["es2015", "react"]
}

it throws this cryptic error:
 ERROR in ./client/App.js
Module build failed: Error: You gave us a visitor for the node type "NumericLiteral" but it's not a valid type
This is my webpack.config.js if that helps at all:
module.exports = {
  entry: "./client/App.js",
  output: {
    filename: "public/bundle.js"
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel'
      }
   ]
  }
};

Is there something obvious I'm missing? I've also swapped the order of the presets and it doesn't seem to make a difference. I have babel-core, babel-loader, babel-preset-es2015, babel-preset-react and webpack in my node modules.

A: I've had the same issue and it seems to have gone away after I removed the node_modules directory and reinstalled all the dependencies.

A: I would start here if I were you. This will give you a very minimal template for React where you can reverse engineer and start learning how to use React inside of a webpack build. React Boilerplate This is very useful for getting started quick and easily, while learning webpack for what you will make use of it. I have always found the webpack documentation hard to figure out for what I need.  I hope this helps.

A: I solved this probleum by nvm even though i reinstalled by npm serveral times useless.
I changed node version to 5+ then it will goes well althogh I already in 5+ node environment.
that's imagine.

A: I had the same issue. It turned out that I was adding a prototype method to the class "Object" that already exist.


text:
Q: I wrote a nice program in linux and I don't want people to steal my work I wrote a nice program in linux and I don't want people to steal my work, is there a way for me to hide the contents of my sh file from other people seeing it when I publish it? And it still has to be functional when I publish it to the public. I won't be posting any of the code because of this.

A: You could consider adding an open source license to your program to protect it:
https://dzone.com/articles/selecting-an-open-source-license-for-your-project

A: One possibility is to compile the shell script to C and ship a binary executable. Compilers for the shell language exist, such as CCsh from Comeau Computing, which is a proprietary product, like yours.


text:
Q: Creating a new Android Application Project I am new to Android Development. I tried to create a new Android Application Project using Eclipse but when I click 'Finish' the windows remains open. When I close it, the folder hierarchy is as follows:

I don't think that this is correct since no AndroidManifest is present
Also, these are the errors that I get in the error log:

A: Sometimes deleting your Debug Certificate would work. This would be located inside your profile folder (In Windows, %USERPROFILE%/.android would be the correct location). Now clean build your android project. It should work.


text:
Q: How to avoid asking for Notification permission in Incognito mode after Chrome 76 update? Notification rejected after how many seconds? I have a use case where I show a black overlay with some helper texts to allow or reject the Web Push Notification.
this.showOverlay();
Notification.requestPermission().then((permission) => {
   ...
   this.hideOverlay();
   ...
})

Earlier I was not executing this code in Incognito mode. But now since Google has closed all the loopholes to detect Incognito mode, I am getting an overlay for few seconds and then its disappearing automatically.
Actually in Incognito, Chrome is not waiting for the User to allow or reject it and rather it is rejecting it by itself but after delay of some second.
So the question is:
1. Can I stop asking for the permission in Incognito mode? (seems not possible)
2. Is there any fixed time duration after which Chrome rejects the permission?
You can see this issue in any websites which shows overlay while asking for Notification permission in Incognito mode. eg., https://www.facebook.com

A: Unfortunately the only way get it working is to cancel using custom popups before the permission is requested. Or do some timing like require permission and show the custom popup if the promise isn't resolved in a couple of seconds.
Browsers aren't interested to let you know you're in incognito so it's a problem indeed.  And it's a problem as e.g. we'd like to explain the user what notifications we're going to send him. As many sites offer news notifications and some worthless updates many users just click 'Block' as soon as they see the permission popup. ...and aren't notified about incoming messages or any other vital info on our site. In this case custom popup delay won't help much but it mostly depends on user. So may be a solution in some limited cases.
As for the time duration I didn't notice any difference: it doesn't resolve the promise instantly but takes time as if the user denied. It may also be affected by different reasons like the user device performance or so.


text:
Q: Hacking and different environments For a long time, I've wanted to become a security expert. In fact, I've always wanted to know everything there is to know about computers in general.
So I did some reading on viruses and the different type of environments you can get. What I found is that viruses affect Windows computers more than UNIX due to less people using UNIX for whatever reason (greater control over what goes on, etc) and Mac computers hardly get hit by viruses at all. From what I understand, this is because Apple keeps the MacOS source under lock and key basically.
What I wanted to know is this:
Black Hats exploit vulnerabilities in Windows and UNIX systems. Obviously because it's intended for more mainstream use, Windows gets exploited most often, but why isn't UNIX exploited more? The source code is freely available, what gives?
With that, we move on to MacOS. Nobody can see the source code unless they're employed by Apple (I guess), and as with any software, it's bound to have vulnerabilities, but, is it more difficult to hack MacOS because of the lack of availability of the code?
Is it even worth it? I also read that Windows is the prime target for viruses and black hats because such a larger percentage of the population use it.
Can anyone point in the direction where I can get some good security white papers?

A: It's mostly a matter of supply and demand - nobody wants to write a botnet which could, maybe, theoretically run on 5% of the computers available worldwide, when it is possible to write one for Windows and it will run on at least 40% of computers (a guess based on Windows market share * percentage of users who will blindly click on anything, especially if it promises them animated smilies).
This is not a matter of "Mac OS/Linux is more secure/has smarter users" - the average end user will bypass any security, if driven by a promise of dancing pigs; and both MacOS and Linux are now usable by the average user. It's just that there are many more average Windows users, because there are more Windows workstations.
In a hypothetical world where Linux would have 90% of the market share, we'd see users following malware's instructions such as "to see dancing pigs, execute chmod +x ./thisevilprogram && sudo ./thisevilprogram", precisely because the userbase would be large enough to make it profitable to write Linux malware. Ease of development or ease of overcoming security measures are rather insignificant, compared to target system's market share.

A: There are less viruses for *NIX systems because people attack them differently. With superuser requirements to make system wide changes and all it becomes harder. However, if there is a vulnerability that an attacker can use then he will most likely use it -- depending on his intentions of course. Most Windows users surf with admin permissions by default due to lacking knowledge.
Regarding Windows, a clear majority are desktop users that know less than a desktop user that would run e.g. Linux. Thus attacking the Windows users where they spend their most time is the best available option, and that's on the web reading emails containing attachments and surfing the web without being too cautious. OS X only has a market share of estimated 4.5%[1]. Spreading a worm designed to exploit vulnerabilities in Windows becomes a lot more lucrative since their market share is 93.90%.
Both Windows and OS X are running proprietary binaries. OS X is not more secure because of it, they can both be reverse engineered by a researcher that is looking for holes. Some Phrack[2] editions contain very interesting issues in OS X.
Then there's also the factor of whom the OS is designed for. Windows is primarily designed to be used by people of less knowledge ("everybody"). Their motto is "it just works". OS X doesn't differ much in that aspect but compared to a PC running Windows a Mac running OS X is a way more expensive. OS X had its main breakthrough amongst professional graphic artists and we still have that dominant opinion today. A Mac simply isn't worth it for most people that require just a browser, Solitaire and MSN.
Statistics about vulnerabilities and virus usage doesn't essentially prove which system is the most vulnerable system by design. They only show which system is being exploited the most, and it's fully logical that the most widespread systems get exploited the most.
[1] http://marketshare.hitslink.com/report.aspx?qprid=8&qptimeframe=M&qpsp=119
[2] http://phrack.org/

A: In some respects malware has similarities with most other types of software.
Portability is difficulty at the best of times. If your software relies on undocumented vulnerabilities, then portability is almost impossible. One can infer then you would target the platform with the highest volume of users (targets).
This is a over-simplified justification as to why Windows has more viruses than the other platforms without going into technical reasons.

A: You may see some sources at http://www.opensource.apple.com/release/mac-os-x-105/
ALso, decompiler & your tools for analyzing binaries are your friends here.
Not much people have seen windows sources, but still it's been hacked pretty well.


text:
Q: Update Spinner items to the database.? i have a spinner that loads items from the SQLite database. it works fine.
then i have a edittext to get the selected spinner item to that edittext. its also woks.
then i want to change the edit text value and update that spinner item to the database.
so how to do that. please any help. thnx

A: You should make sql update query. As you already get spinner items from DB, you should know how to make queries. To make update query, you have to call db.update() method.

A: Lets say,you have populated Spinner spinner with data from database.And you have EditText editText and Button button to update spinner values.Then you can achieve this something like below:
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int position, long arg3) {

                //code to display the selected item in EditText
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
});
selectDate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                 DatabaseCreator dbcreator=new DatabaseCreator(context);
                 SQLiteDatabase sqdb=dbcreator.getWritableDatabase();

                 ContentValues values=new ContentValues();

                 //Update respective fields in database
                 values.put("field_1",newValue1);
                 values.put("field_2",newValue2);

                 long suceess=sqdb.update( "table_name", values, KEY_ID+"='"+id+"'", null);
                 // you can place any condition in place of KEY_ID+"='"+id+"'" as third argument in above statement

                 if(success!=0)
                 {
                      //repopulate spinner here
                 }
        }
});
...

DatabaseCreator.class:
public class DatabaseCreator extends  SQLiteOpenHelper{

    private static final String DB_NAME="db_name";
    private static final int DB_VER=2;

    private static final String TABLE_1="create table table_1(...);"; //complete create query goes here

    public DatabaseCreator(Context context) {
        super(context,DB_NAME, null, DB_VER);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {

        database.execSQL(TABLE_1);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {

            database.execSQL("DROP TABLE IF EXISTS db_name");
        onCreate(database);
    }
}


text:
Q: Relationship between two tables in SQL Server I have two tables in LibraryDB. One is Book_Master and the other is Languages. I have used langid in Book_Master as a Foreign Key and want to make a relationship between these two tables but I've got an error. Picture is given in the description. Help me Programmers..!! Here is the picture  Click to see image

A: Analyze your tables.
select b.LangID
from book_master b
left join Languages L on b.LangID = L.LangID
where L.LangID is null

The result is LangID's in Book_master which don't exist in Languages (and block FK creation).


text:
Q: Crosstab factor scores generated by factor analysis i just wanted to know if i could use factor scores and crosstab it with demographics (i.e. gender, age, etc.)? I have 69 likert-scale variables and run factor analysis on SPSS. It gave me 10 new variables (types of personality. i just wanted to see the demographics of each new variables. Thanks!!!

A: In SPSS, choose Analyze...Descriptive Statistics...Explore.  The factor scores will be your dependents, and a demographic grouping will be your "factor" in this procedure.  I'd choose Plots Only to start with and request boxplots.  You can get either factor levels together or dependents together:  you can experiment.
Later, when you want means and standard deviations and such, I'd use the Summarize command, located in the menus at Analyze...Reports...Case Summaries. You can also experiment with  "means [var list] by [var list]/stat anova."
However, I'd caution you that some of your 10 factors are likely to be marginal ones that have small eigenvalues and explain little of the total item variance.  Maybe consider making your criteria stricter for factor extraction, such as using a subcommand like "/criteria mineigen (1.5)" or 2.0 instead of 1.0 which is so commonly used.  It'll also be a plus to reduce your number of factors when it comes to displaying and explaining your results.


text:
Q: Can I submit my app built with Xcode 12.4? I am building my app on a old Mac wich can only run Xcode 12.4
On Apple's Submit page it says:

Please note, starting April 2023, all iOS and iPadOS apps submitted to the App Store must be built with Xcode 14.1 and the iOS 16.1 SDK.

And on the Apple Developer News page it says:

Starting April 25, 2022, iOS, iPadOS, and watchOS apps submitted to the App Store must be built with Xcode 13, which includes the SDKs for iOS 15, iPadOS 15, and watchOS 8.

Does that mean I have to buy a new mac to build & submit my app?

A: If you're a paid developer, you might get better help directly from Apple, but the minimum SDK train continues to march onwards.
Whether you can virtualize, rent, find another way to comply with the checks Apple puts up depends on your creativity and tolerance to spend time instead of money. The easy solution is a new kit and upgrading to the latest Xcode within 6 months of general release so you don't have to find all the new SDK and Xcode bugs, but also don't get shut out when these deadlines are communicated.
In practice, the new apps tend to get the closest reading of the "rules" and there's some grace period for updates to existing apps and usually a longer one for apps not getting an update, but even an old existing app will eventually need to get work put into it to port / test / rebuild and add the new metadata being requested / required by Apple to sell through their software stores.
I can't see any way you can avoid change and continue to use Xcode 12.4 looking at the Q4 / 2022 situation.


text:
Q: Add commands to the instance manager with association to public method of two clases I want to be able to add commands to the manager instance and associate those commands with invoking public methods from both class A and class B when they're executed. I know that in order to achieve this the class Command should have a pointer to a class member function instead of a regular function (void (T::*Handler)() instead of void(*Handler)() ), but I found myself lost in how exactly I can achieve this. I have the following code:
typedef void (*Handler)();

class Command {
    public:
        Command(char*, Handler);
    private:
        char* name;
        Handler handler;
};

class CommandManager {
    public:
        CommandManager();
        void addCommand(Command*);
        void execute(char* commandName);
    private:
        Command** commands;
}

// implementation, copy constructor and destructor should be ignored at this point since        they do
// not affect directly the question I'm trying to find an answer for.

I have another two classes. Let's say they're class A and class B, both having methods with return type void
and with no params. I also have class C which contains member variables of type pointers to A and B:
class C {
    public:
     // some public stuff here
    private:
     A* a;
     B* b;
     CommandManager* manager;
}

Note: It might be easier to introduce inheritance and abstract class but this is something I am limitted not to use(do not ask why :) ), so is there any way to do what I want?

A: The "best" solution:
typedef std::function<void()> Handler;
//std::function<void()> is the magic bit you were asking about

class Command {
    public:
        Command(const std::string& name, Handler) {}
    private:
        std::string name;
        Handler handler;
};

class CommandManager {
    public:
        CommandManager();
        void addCommand(std::unique_ptr<Command>);
        void execute(const std::string& commandName);
    private:
        std::vector<Command> commands;
};

and then functionoids go like this
struct A {
    void operator()() {std::cout << "A";}
};
Command  ACommand = {"A", A()};
//constructs a temporary A,
//then a temporary std::function<void()> is constructed which stores the A
//then the Command stores this function.

struct B {
    void named_function() {std::cout << "B";}
};
B bobj;
Command  BCommand = {"B", std::bind(&B::named_function, &bobj)};
//bind constructs a functionoid binding the bobj as the "this" of the member function
//then a temporary std::function<void()> is constructed which stores the functionoid
//then the Command stores this function.

A: The problem is the this pointer passed implicitly to every member function. This makes the signature of the functions of A different from those of B.
Without using templates and inheritance, the easiest way would be to declare the functions of A and B as static. Then, there is no this pointer, and the functions can be assigned to the function pointer handler.
Because it's not likely to be powerful enough, here another way, but I must say it's a kludge, it would really be better to use inheritance.
Define
typedef Handler void (*Handler)(void *);

and implement the static command handlers as follows
void A::doit(void *arg)
{
  A *newthis = (A*)arg;
  newthis->UseMembersOfA();
}


text:
Q: Python Log error 'NonType' I' m new to python and would like to ask the following:
I get this error message

bad operand type for unary ~: 'NoneType'

when I'm running a very simple data step as:
df['new_FLAG'] = np.where(~(df.var2.str.contains('Test|Random|Hypo|Sample',case = False)) &
   df.var3.isin(['CLIENT_CURRENT', 'MODEL_CURRENT', 'HYPOTHETICAL']) &
   (df.var1> 4) & (df.var1< 31)
                                 ,'Y','N')

My data frame is like this:
    var1    var2    var3
0   17  AMPF PCA 5.9.18 MODEL_CURRENT
1   17  AMPF PCA 5.9.18 MODEL_CURRENT
2   17  AMPF PCA 5.9.18 MODEL_CURRENT
3   17  AMPF PCA 5.9.18 MODEL_CURRENT
4   17  AMPF PCA 5.9.18 MODEL_CURRENT

Any ideas?

A: It appears you have non-string types in your series. Try setting na=False in pd.Series.str.contains to correct this. The negative of None is not defined, which is what your error is indicating.
Here's a minimal example:
s = pd.Series(['Testing', 'AnotherSTring', 2.5, 'Something Else', np.nan, 'Sampler'])

res1 = s.str.contains('Test|Random|Hypo|Sample', case=False)

# 0     True
# 1    False
# 2      NaN
# 3    False
# 4      NaN
# 5     True
# dtype: object

res2 = s.str.contains('Test|Random|Hypo|Sample', case=False, na=False)

# 0     True
# 1    False
# 2    False
# 3    False
# 4    False
# 5     True
# dtype: bool


text:
Q: Angular Unit Testing: How to unit test subscription which get value from function? I have one subscription inside my ngoninit in ts file.
I want to unit test this subscription how should i can do this?
code.ts
this.generalConfigSubscription = this.generalConfigService.getGeneralConfigState().subscribe((response) => {
      if (response && response.status == 'success') {
        if (response.data && response.data) {
          this.configData = response.data;
          this.calculateNewValues = response.data.calculation_trigger ? response.data.calculation_trigger : [];
          this.valueValidity=response.data.value_validity ? response.data.value_validity : []
        }
      }
    })

generalConfigService.ts
    private initialGeneralConfigState: GeneralConfigState = undefined;
    private generalConfigStateTracker = new BehaviorSubject<GeneralConfigState>(this.initialGeneralConfigState);
                                 .
                                 .
                                 .
    /** Allows subscription to the behavior subject as an observable */
    getGeneralConfigState(): Observable<GeneralConfigState> {
        return this.generalConfigStateTracker.asObservable();
    }

A: Pull the code block within the subscription into it's own function and unit test the function. This way you can skip any potential marble testing for RxJS and do it the old fashion way.
this.generalConfigSubscription = this.generalConfigService.getGeneralConfigState()
    .subscribe((response) => this.parseGeneralConfigStateResponse(response))

// Unit test me like any other non-subscription function
parseGeneralConfigStateResponse(response: Response) {
 if (response && response.status == 'success') {
        if (response.data && response.data) {
          this.configData = response.data;
          this.calculateNewValues = response.data.calculation_trigger ? response.data.calculation_trigger : [];
          this.valueValidity=response.data.value_validity ? response.data.value_validity : []
        }
      }
}


text:
Q: Same Diagonal Dissection Divide a rectangle into smaller rectangles with two criteria:

*

*All sub-rectangles must have different sizes.

*All sub-rectangles must have diagonals with length 1.

What is the smallest possible number of rectangles in a solution?
Here is a solution where a square is divided into 12 rectangles with unit diagonals.  The $x$ values are 0., 0.126115, 0.45009, 0.767632, 1.12506, 1.43832, 1.74608, 1.885, and the $y$ values are 0., 0.04595, 0.783796, 0.992016, 0.990303, 1.73204, 1.885.

Code for 100 digits of accuracy:
NMinimize[{(-1+(x1-x4)^2+y1^2)^2+(-1+(x2-x4)^2+(y1-y2)^2)^2+(-1+(x4-x6)^2+y2^2)^2+(-1+(x1-x2)^2+(y1-y3)^2)^2+(-1+x1^2+y3^2)^2+(-1+(x3-x6)^2+(y2-y4)^2)^2+(-1+(x6-x7)^2+y4^2)^2+(-1+(x2-x3)^2+(y2-y5)^2)^2+(-1+(x3-x5)^2+(y4-y5)^2)^2+(-1+x2^2+(y3-y6)^2)^2+(-1+(x5-x7)^2+(y4-y6)^2)^2+(-1+(x2-x5)^2+(y5-y6)^2)^2, 1/9<x1<x2<x3<x4<x5<x6<x7,0<y1<y2<y3<y5<y6, y2<y4<y5, y6==x7},{x1,x2,x3,x4,x5,x6,x7,y1,y2,y3,y4,y5,y6}, PrecisionGoal->100, AccuracyGoal->100, MaxIterations->100, WorkingPrecision->100]

The below is a earlier, slightly flawed version of the same dissection that was found by hand. The diagonals form two connected sets, colored red and green here.

Is there a solution with a fewer number of rectangles?  Can a rectangle be divided into 11 or fewer different unit-diagonal rectangles?

A: First, I'll show example of such $9$-tiling with more comfortable side lengths:
Tiling:

its pattern:

its sub-rectangles sizes:
$x_1 = 0.884,      y_1 \approx 0.46748690;$
$x_2 \approx 0.84923220, y_2 \approx 0.52801957;$
$x_3 \approx 0.99816622, y_3 \approx 0.06053267;$
$x_4 \approx 0.11416622, y_4 \approx 0.99346166;$
$x_5 \approx 0.85050017, y_5 \approx 0.52597476;$
$x_6 \approx 0.88273202, y_6 \approx 0.46987676;$
$x_7 \approx 0.06482983, y_7 \approx 0.99789633;$
$x_8 \approx 0.94756185, y_8 \approx 0.31957242;$
$x_9 \approx 0.96466638, y_9 \approx 0.26347442.$
(here $x_1=0.884$ is chosen arbitrarily from the $(0.8686, 0.8946)$ $-$ see below).
And note that there are no "fixed"/unique tiling; they exist as $1$-parametric families of tilings:

Now wider description:
It seems there exists "regular" (maybe elegant :) algorithm.
Step 1:
let's call $n$-tiling "irreducible" if any removing (of $1$ or more sub-rectangles) makes this tiling non-rectangular (excluding trivial $n-1$ sub-rectangles removing).
For considered $n$ we'll find all possible "irreducible" tiling patterns, which allow construct all sub-rectangles of different sizes:
$n=5$: 1 possible pattern:

$n=6$: there are no "irreducible" tilings:

$n=7$: $2$ possible patterns:

(Let's focus on $7$-tilings.)
Step 2:
Enumerate sub-rectangles such that
$1$th and $2$nd sub-rectangles are "free", and all further sub-rectangles depend on these two:
let we have $2$ free parameters:
$$
a \in(0,1),\; b\in(0,1);
$$
$7$-tiling A:
running forward, we mark such sides as "free", which would give us more comfort calculations:
$
y_1 = a, \; x_1 = \sqrt{1-a^2};  \\
x_2 = b, \; y_2 = \sqrt{1-b^2};  \\
x_3 = x_1-x_2, \; y_3 = \sqrt{1-x_3^2}; \quad (x_3>0); \\
y_4 = y_2-y_3, \; x_4 = \sqrt{1-y_4^2}; \quad (y_4>0); \\
x_5 = x_3-x_4, \; y_5 = \sqrt{1-x_5^2}; \quad (x_5>0); \\
y_6 = y_4-y_5, \; x_6 = \sqrt{1-y_6^2}; \quad (y_6>0); \\
x_7 = x_6-x_5, \; y_7 = \sqrt{1-x_7^2}; \quad (x_7>0);
$
and close these dependencies by the equation:
$
y_1+y_3+y_5=y_7.
$
Now, we have $16$ variables $a,b,x_1,y_1,\ldots,x_7,y_7$ and $15$ equations.
It describes some $2D$-curve:
$$
F_1(a,b)=0, \;\mbox{ or } b = f_1(a) \mbox{ in our case }, \; \; a\in (a_1,a_2).
$$
for this pattern we'll have
$a_1 = 0, a_2 \approx 0.0732518$.
Plot of the curve (Mathematica):
y1 := a;          x1 := Sqrt[1 - a^2];
x2 := b;          y2 := Sqrt[1 - b^2];
x3 := x1 - x2;    y3 := Sqrt[1 - x3^2];
y4 := y2 - y3;    x4 := Sqrt[1 - y4^2];
x5 := x3 - x4;    y5 := Sqrt[1 - x5^2];
y6 := y4 - y5;    x6 := Sqrt[1 - y6^2];
x7 := x6 - x5;    y7 := Sqrt[1 - x7^2];

ContourPlot[y1 + y3 + y5 == y7, {a, 0.000, 0.08}, {b, 0.000, 0.08},
   GridLines -> {0.01*Range[0, 10], 0.01*Range[0, 10]}]

A few points of this curve:
$
(a,b)\approx (0,    0.004217507); \\
(a,b)\approx (0.01, 0.003927340); \\
(a,b)\approx (0.02, 0.003547516); \\
(a,b)\approx (0.03, 0.003077705); \\
(a,b) \approx (0.0307543, 0.00303861); \mbox{ see Ivan Neretin's answer} \\
(a,b)\approx (0.04, 0.002517544); \\
(a,b)\approx (0.05, 0.001866428); \\
(a,b)\approx (0.06, 0.001124581); \\
(a,b)\approx (0.07, 0.000290911); \\
(a,b)\approx (0.0732518, 0).
$
So this kind of tiling must have shortest sub-rectangle side less than $\approx0.004$.

$7$-tiling B: similar way;
but this pattern gives us tiling with pairs of equivalent sub-rectangles.

$5$-tiling: gives us tiling with pairs of equivalent sub-rectangles.

$8$-tilings:
there are a few patterns with successful tilings, but all them (which I considered) have too small (for viewing) smallest sidelength.

$9$-tilings:
The presented above tiling can be described by the system of equations:
$x_1 = a, \; y_1 = \sqrt{1-x_1^2};$
$x_2 = b, \; y_2 = \sqrt{1-x_2^2};$
$y_3 = y_2-y_1, \; x_3 = \sqrt{1-y_3^2}; \quad (y_3>0);$
$x_4 = x_3-x_1, \; y_4 = \sqrt{1-x_4^2}; \quad (x_4>0);$
$y_5 = y_4-y_1, \; x_5 = \sqrt{1-y_5^2}; \quad (y_5>0);$
$x_6 = x_2+x_3-x_4-x_5, \; y_6 = \sqrt{1-x_6^2}; \quad (x_6\in(0,1)\: );$
$y_7 = y_2+y_6, \; x_7 = \sqrt{1-y_7^2}; \quad (y_7<1);$
$x_8 = x_6+x_7, \; y_8 = \sqrt{1-x_8^2}; \quad (x_8<1);$
$y_9 = y_7+y_8-y_2-y_5, \; x_9 = \sqrt{1-y_9^2}; \quad (y_9\in(0,1)\:);$
and
$x_4+x_5=x_9$,
where $a\in(0,1)$, $b\in(0,1)$, and $(a,b)$
 are linked therefore by certain dependency
$F_2(a,b)=0$, or $b= f_2(a)$ in our case, where $a\in(a_1,a_2)$;
$a_1 \approx 0.868517092, a_2 \approx 0.8946$.
And a few points of the curve:
$
(a,b) \approx (0.868517092, 0.868517091); \\
(a,b) \approx (0.870, 0.86678506); \\
(a,b) \approx (0.875, 0.86073752); \\
(a,b) \approx (0.880, 0.85443240); \\
(a,b) \approx (0.885, 0.84791329); \\
(a,b) \approx (0.890, 0.84122558); \\
(a,b) \approx (0.8946,  0.83497558).
$

A: I believe that a rectangle with certain aspect ratio can be done in as few as 7 parts.

Note that the picture is not entirely accurate, otherwise the 7th rectangle would not be seen at all.
The dimensions of the rectangles (short side first) are:
$$
\begin{array}{l|l}
1& 0.5959136\times0.8030486\\
2& 0.0837313\times0.9964883\\
3& 0.4005748\times0.9162641\\
4& 0.1132155\times0.9935704\\
5& 0.3976568\times0.9175342\\
6& 0.0307543\times0.9995270\\
7& 0.0030386\times0.9999954
\end{array}
$$


text:
Q: Directory Invalid or Specified file not found when starting a process which is elevated I've started my application as a normal user, however sometimes I'll need to start an elevated process which starts another application. The other application, which is started, is in a sub folder called Executables. All users have full access to the files in the the current directory and sub directories.
The code I'm using:
    public bool CreateElevatedProcess(ActionData data, bool log)
    {
        if (!string.IsNullOrEmpty(data.Arguments) && NormalUser.HasCredentials)
        {
            _proc = new Process
            {
                StartInfo =
                {
                    Verb = "runas",
                    FileName = data.Filename,
                    //WorkingDirectory = data.File.DirectoryName,
                    Arguments = data.Arguments,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UserName = NormalUser.Name,
                    Password = GetSecureString(NormalUser.Password),
                    Domain = NormalUser.Domain
                }
            };
            return true;
        }
        return false;
    }

    private bool StartProcess()
    {
        if (_proc != null)
        {
            try
            {
                _proc.Start();

                _proc.WaitForExit();

                return true;
            }
            catch (Win32Exception ex)
            {
                        // throws win32exception due to directory name is invalid or the specified file not found
            }
        }
        return false;
    }

I've tried setting the WorkingDirectory option, but I'm unsure whether it works due to UseShellExecute is set to false.
What I'm experiencing:
When I'm running the my application on the development computer, everything works fine. I've even copied the folder outside of Visual Studio and into a TEMP folder on C:\ without problems. However, on a different computer I'll experience either the directory name is invalid or the specified file is not found error. In all likelyhood it's an user right problem, however, all users have full access ...
How do I properly start an elevated process with a file from a subdirectory?
Adding an example:
The filename property gets: Executables\rc.exe
The argument property gets: 1 lester \mrburns
The filename property only gets a subfolder path instead of the full path, due to the fact that the parent path might be restricted.


text:
Q: how to redirect page in different project in same solution in asp.net i have one solution called : MainProject : - have 6 project in solution,
i want to link 5 project starting page from 6th project aspx , how could  i do that?
from 6th project(as solution starting project) , default.aspx page

Link1 : open 1st project starting page
Link2 : open 2st project starting page
Link3 : open 3rd project starting page
Link4 : open 4th project starting page
Link5 : open 5th project starting page

More explanation : i have lots of small projects in asp.net , i put them in one solution, now from one default.aspx page , i need to see all project starting page

A: *

*Each of your projects is its own web site or web application

*When you publish any/all of them, they will be different web sites/applications

*you can link and/or redirect to any of their pages just like you would between different web sites

If you are asking how to simply run all of your projects while you are developing then you can right click on any page from each project and "view in browser". Note the port that visual studio assigns (`http://localhost:12345) to each page -this is how Visual Studio simulates different web sites.
You can also move all of them to IIS, assign each its own IP and do it that way.
The point is that they are distinct web sites/applications (I don't want to confuse you, but this isn't a hard rule - one of your projects can also be a sub application within some other).


text:
Q: Get error when trying to send new password to e-mail by php I'm a beginner of php and now getting stuck on sending a new password to user e-mail if user requested in android.
ForgetPassword.php
  <?php
require_once('DB_Functions.php');
    $db = new DB_Functions();
    $forgotpassword = $_POST['forgotpassword'];

    $randomcode = $db->random_string();
    if(isset($_POST['forgotpassword'])){
       $hash = $db->hashSSHA($randomcode);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
        $subject = "Password Recovery";
        $message = "Hello User,nnYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.nnRegards,nLearn2Crack Team.";
        $from = "contact@learn2crack.com";
        $headers = "From:" . $from;
     if ($db->isUserExisted($forgotpassword)) {

     $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
      if ($user) {
         $response["success"] = 1;
          mail($forgotpassword,$subject,$message,$headers);
         echo json_encode($response);
        }
        else {
       $response["error"] = 1;
      echo json_encode($response);
        }
     }

            // user is already existed - error response

        }
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}

?>

DB_Functions.php
    <?php
 require_once('dbConnect.php');
class DB_Functions {

    private $db;

    /**
     * Random string which is sent by mail to reset password
     */

public function random_string()
{
    $character_set_array = array();
    $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
    $character_set_array[] = array('count' => 1, 'characters' => '0123456789');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return implode('', $temp_array);
}

  public function isUserExisted($email) {
        $result = mysqli_query($this->db,"SELECT email from users WHERE email = '$email'");
        if($result)
        {
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        }
        }else {
            // user not existed
            return false;
        }
    }

 public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

public function forgotPassword($forgotpassword, $newpassword, $salt){
    $result = mysqli_query("UPDATE `users` SET 'password` = '$newpassword'
                          WHERE `email` = '$forgotpassword'");

if ($result) {

return true;

}
else
{
return false;
}
}
}
?>

dbConnect.php
<?php
    define('HOST','127.0.0.1:3307');
    define('USER','root');
    define('PASS','');
    define('DB','androiddb');

    //Connecting to Database
    $con= mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>

This is what I have tried so far, unfortunately it gives me a bunch of error ! Any help would be appreciated .
I get tutorial from here.
Error(latest)

Notice: Undefined index: forgotpassword in
  C:\xampp\htdocs\Android\CRUD\forgetPassword.php on line 4
  {"error":2,"error_msg":"User not exist"}

A:
Notice: Undefined index: forgotpassword

You have to make sure the index is the same from android & PHP.
Wrap your code around the following check:
if(isset($_POST['forgotpassword'])){//code here}else{//undefined}

Warning: mysqli_query() expects at least 2 parameters, 1 given

As the error says, a param is missing, which is the connection:
$result = mysqli_query($con,"SELECT email from users WHERE email = '$email'");

(Add the connection as a 2nd parameter of your db function)

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
  null given

this is because the query failed.to avoid this error, add more checks:
if($result){
   $no_of_rows = mysqli_num_rows($result);
}else{
   //failed
}


text:
Q: Can't connect to Tomcat via USB tethering
Eclipse logcatil shows like this when I try to connect my phone through USB debugging. When I run my application in emulator using 10.0.2.2, localhost address it works well.
But unfortunately I can't access Tomcat when connecting my phone.

A: *First you should Install Connectifyme Software.After inatalling that open that application and connect your mobile to that.after connected to your mobile just place your cursor on connectify me (opened application) you will get an URL. Instead of localhost just give that ip address in u r mobile.u r tomcat will work in u r mobile.I Hope this will works u. *


text:
Q: What are containers e.g Docker Lately, I've been reading about microservices because I keep hearing about them. But while reading on microservices some articles make  mention of container's and all the resources I've read on container's seems not to help me understand what they're, how they relate to microservices, and what problem does it solve.
Also, is there any book that can be recommended on microservices?

A: They are what host a microservice since microservices is one application made up of many running processes.  This makes your application very modular allowing multiple languages, different frameworks, etc and the ability to add/remove microservices.  A container is basically a kernel level vm that is injected with all of the required dependencies required for your microservice to run.  Completely OS independent.  The has very very little overhead and self contains all the dependencies rather than mucking up a server running multiple services.


text:
Q: Recommend an enjoyable / introductory book on Statistics
Possible Duplicate:
A resource on concepts underlying statistics, not the techniques used in applied stats

I am interested in learning more about Statistics and when I ran a Google / Amazon search that brought up way too many options.
I am hoping to get a recommendation of a statistic book that is beginner's oriented and fun to read / learn.

A: Here are two nice books that I enjoyed

*

*Statistics: A Very Short Introduction This is just about 130 pages of text, that introduces the subject for a general reader. Part of the Very Short Introductions series from OUP.

*Cartoon Guide to Statistics A book that handles the subject with lot of illustrations. Suitable for reader from all walks of life.

Update: A similar query at Quora

A: Slightly OT, but The Lady Tasting Tea is a really fun book about the history of statistics and some of the people who practised it. There's some actual stats in their too, and some of it is really useful in terms of learning stats, e.g. what are parametric statistics?
Oh yeah, and Red State Blue State, by Andrew Gelman, about voter behaviour in the US, is another great one for catching your interest and learning stuff (e.g. the ecological fallacy) along the way. Awesome graphs too. Mmm... graphs (as Homer Simpson never said)

A: I suggest the Statistics 101 course at Udacity
http://www.udacity.com/overview/Course/st101/CourseRev/1
This is not technically a book, but I have found it to be a more useful way to learn statistics, when you are learning on your own.  It is definitely more fun than a book.
It is free, and it starts with the assumption of no previous knowledge of statistics.

A: There is a statistics one course  starting up tomorrow at coursera. I guess it's much like the one at udacity, though I haven't followed that one.
It will be with small assignments throughout the course. 75,000 have already signed up.
It's not a book, but it takes you directly back to the classroom again :-)
Here's the link: https://www.coursera.org/course/stats1

A: I really enjoyed Intuitive Biostatistics.  It covers lots of material, is easy to read, and has very good explanations.  At the end of each topic is a question and answer section for the common (and not so common) problems/concerns for the discussed statistical procedures.  Of course all the examples deal with biology but is still applicable to any field.

A: I got on well with Statistics for Terrified Biologists, though this may be a little focused on biology if you're looking for a more in depth introduction. It covers the absolute basics, which are often overlooked - the importance of standard deviation, and what things really mean.


text:
Q: Find all the solutions of $z^6 = -4$. Why doesn't $arg(z) = \theta = \arctan \left( \frac{\sin(\theta)}{\cos(\theta)} \right)$ work in this case? Find all the solutions of $z^6 = -4$.
I want to convert the complex number into polar form, so I do my usual calculations:
$z = r(\cos(\theta) + i\sin(\theta)) = re^{i\theta}$
$|z|$ = 4 = r
And then I try to find $\theta$:
$arg(z) = \theta = \arctan \left( \dfrac{0}{-4} \right)$ Since $y = \sin(\theta) = 0$ and $x = \cos(\theta) = -4$.
But $\arctan \left( \dfrac{0}{-4} \right) = 0$? The solution says that $\theta = \pi$; which makes sense, since $-4$ represents the negative x-axis $= \pi$.
I would greatly appreciate it if people could please take the time to explain why doesn't the formula $arg(z) = \theta = \arctan \left( \dfrac{\sin(\theta)}{\cos(\theta)} \right)$ work in this case.

A: What you're missing is that you do not have to solve for the equation $\tan\theta=\dfrac yx$, but for the system of trigonometric equations:
\begin{cases}\cos\theta=\dfrac x{\sqrt{x^2+y^2}},\\
\sin\theta=\dfrac y{\sqrt{x^2+y^2}}.\end{cases}
This system implies the equation, but is not equivalent to it. The equation is only a simplified way to find the value of $\theta$. Thus all you can say is
$$\theta\equiv\arctan \frac yx \mod \pi.$$
In the present case, as $x< 0$, $\cos\theta<0$, so $\dfrac\pi2<\theta\le\pi\pmod{2\pi}$, whence the value $\pi$, not $0$.

A: hint
$$-4=4e^{i(2k+1)\pi} =\rho^6e^{6i\theta}$$
thus
$$\rho=4^\frac 16$$
$$arg (z_k)=\theta_k=\frac {2k+1}{6}\pi $$
$$k=0,1,2,3,4,5$$


text:
Q: Create JSON in given format Swift I want to create a JSON in below format.
   {
  "userID": "1234",
  "cart_items": {
    "1": {
      "item_Seq_no": 1,
      "catalog_id": 234,
      "qty": 1,
      "amount": 100
    },
    "2": {
      "item_Seq_no": 2,
      "catalog_id": 45,
      "qty": 3,
      "amount": 300
    },
    "3": {
      "item_Seq_no": 3,
      "catalog_id": 177,
      "qty": 2,
      "amount": 200
    }
  }
}

Code i written in below is not exactly creating in above format.
 let arr:NSMutableArray = []
    for i in 0...KCatalog.catalogValues.count-1
    {
        let seqnum1 = String(i + 1)
        let param2:[String: AnyObject] = [
            seqnum1: [
                "item_Seq_no"  : i+1,
                "catalog_id"    : ((KCatalog.catalogValues[i] as! catalogInfo).catalog_id),
                "qty"    : orderedQuantity[i],
                "amount"    : totalQuantityPrice[i],
            ],
        ]
        arr.addObject(param2)
    }

    print(arr)

    let param1:NSMutableDictionary = [

        "cart_items"  : arr,
        "userID":"asdf",
        ]
    print(param1)
    let data1 = try! NSJSONSerialization.dataWithJSONObject(param1, options: NSJSONWritingOptions.PrettyPrinted)

    let json = String(data: data1, encoding: NSUTF8StringEncoding)
    if let json = json {
        print(json)
    }

I want to whether given format is correct or not. If yes please suggest me to make it in above format
Output i am getting is
{
  "userID": "asdf",
  "cart_items": [
    {
      "1": {
        "item_Seq_no": 1,
        "amount": 10,
        "catalog_id": "1",
        "qty": 1
      }
    },
    {
      "2": {
        "item_Seq_no": 2,
        "amount": 15,
        "catalog_id": "2",
        "qty": 1
      }
    },
    {
      "3": {
        "item_Seq_no": 3,
        "amount": 0,
        "catalog_id": "3",
        "qty": 0
      }
    }
  ]
}

According to samantha answer i got below output
    {
  "userID": "asdf",
  "cart_items": {
    "1": {
      "1": {
        "item_Seq_no": 1,
        "amount": 10,
        "catalog_id": "1",
        "qty": 1
      }
    },
    "2": {
      "2": {
        "item_Seq_no": 2,
        "amount": 15,
        "catalog_id": "2",
        "qty": 1
      }
    },
    "3": {
      "3": {
        "item_Seq_no": 3,
        "amount": 0,
        "catalog_id": "3",
        "qty": 0
      }
    }
  }
}

A: cart_items should be a dictionary rather than an array.
var cartItems = [String: AnyObject]()
for i in 0...KCatalog.catalogValues.count-1
    {
        let seqnum1 = String(i + 1)
        let param2:[String: AnyObject] = [
                "item_Seq_no"  : i+1,
                "catalog_id"    : ((KCatalog.catalogValues[i] as! catalogInfo).catalog_id),
                "qty"    : orderedQuantity[i],
                "amount"    : totalQuantityPrice[i],
        ]
        cartItems[seqnum1] = param2
    }

And then later
let param1:NSMutableDictionary = [
        "cart_items"  : cartItems,
        "userID":"asdf",
        ]

A: Based on @Samantha answer here below is the Swift 3.0 code.
    var cartDictionaryArr = [String: AnyObject]()
    for i in 0...KCatalog.catalogValues.count-1
    {
        let keyValue = String(i + 1)
        let itemsArr :[String: AnyObject] = [
            "item_Seq_no"   : i+1,
            "catalog_id"    : ((KCatalog.catalogValues[i] as! catalogInfo).catalog_id),
            "qty"           : orderedQuantity[i],
            "amount"        : totalQuantityPrice[i]
        ]
        cartDictionaryArr[keyValue] = itemsArr as AnyObject
    }

    print(cartDictionaryArr)

    let finalDict:NSMutableDictionary = [
        "cart_items"  : cartDictionaryArr,
        "userID":"123",
        ]

    print(finalDict)
    let data1 = try! JSONSerialization.data(withJSONObject: finalDict, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = String(data: data1, encoding: String.Encoding.utf8)
    if let json = json {
        print(json)
    }

Here is the Swift 2 working Code -
    var cartDictionaryArr = [String: AnyObject]()
    for i in 0...KCatalog.catalogValues.count-1
        {
            let keyValue = String(i + 1)
            let itemsArr:[String: AnyObject] = [
                    "item_Seq_no"   : i+1,
                    "catalog_id"    : ((KCatalog.catalogValues[i] as! catalogInfo).catalog_id),
                    "qty"           : orderedQuantity[i],
                    "amount"        : totalQuantityPrice[i],
                ]
            cartDictionaryArr[keyValue] = itemsArr as AnyObject
        }

       print(cartDictionaryArr)

       let finalDict:NSMutableDictionary = [
         "cart_items"  : cartDictionaryArr,
         "userID":"123",
       ]
       print(finalDict)

       let data1 = try! NSJSONSerialization.dataWithJSONObject(finalDict, options: NSJSONWritingOptions.PrettyPrinted)

       let json = String(data: data1, encoding: NSUTF8StringEncoding)
       if let json = json {
          print(json)
       }


text:
Q: How to serve same static .html file for all dynamic urls using Play framework and Java?
I am trying to serve a static html file let's call it index.html for all dynamic urls like /tachyon/someId. This someId is generated dynamically. I have tried multiple ways to do this but all failed. This is what all I have tried.

*

*Tried adding controllers.Assets.at(path="/public", file="index.html") for GET url /tachyon/*someId. This failed saying missing parameter someId.

*Tried rendering index.html through render. This also failed since index.html is not a scala.html template.

*Tried returning routes.Assets.at("index.html") through controller. This also failed since I want to return Result but the return type for the method is different.

*Tried returning ok(routes.Assets.at("index.html") through controller. This also failed saying not a valid Call for ok.

It would be better if there is a way to do this through controller and returning Result from method in task helper class to task since I am returning Promise<Result> from method in task class.

A: I think you can use Twirl to generate the page. Since you want a static html, you can ignore the parameter in the body.
so in routes, add:
GET /tachyon/*someId   somecontroller.index(someId)

in the controller's index function, you can return
Ok(views.html.somepage(someId))

And you create a somepage.scala.html Twirl function in views folder, but do not use someId in the body.

A: I got it working. Not sure if it is the correct solution or not. I rendered the index.html by converting it to a byte array and then using ok to render using ByteArrayInputStream. Something like this.
File file = Play.getFile("path to the file", Play.current());
byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
return ok(new ByteArrayInputStream(byteArray)).as("text/html");

Let me know if there is any better way to do this without using scala templating.
Thanks


text:
Q: Block UI not working in I.E 8 i am using block UI .
$('#divab div[name=divname]').click(function() {
         $('#divsecond').block({
            message: '<img src="ajax-loader(2).gif" />',
             css: {
            top:  ($(window).height() - 400) /2 + 'px',
            left: ($(window).width() - 400) /2 + 'px',
            width: '100px',
            border: 'none',

        backgroundColor: 'transparent',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: 0.5,
        color: 'transparent'
        }

        });
    }); `

code is perfectly working in firefox and chrome but not working in i.e 8


text:
Q: How to create an angular template variable I have several buttons that are disabled based on what a function returns. How can I reuse the value returned from isDisabled(product) without calling isDisabled(product) for every single button? The calculations within isDisabled() is long so I don't want to have to repeat it.
Currently the code looks like this:
<div *ngFor="let product of prodList">
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
</div>

A: Try wrapping your controls in ng-container with ngIf like:
<div *ngFor="let product of prodList">
  <ng-container *ngIf="{ disabled: isDisabled(product) } as result">
   <button [disabled]="result.disabled">...</button>
   <button [disabled]="result.disabled">...</button>
   <button [disabled]="result.disabled">...</button>
   ...
  </ng-container>
</div>

See also

*

*How to declare a variable in a template in Angular2


text:
Q: Redirecting back into my website from thirdparty site in laravel I need help here.
I'm trying to integrate a Payment gateway(VoguePay) in my app. Now the sandbox testing tested good on payment but the problem is getting the "success_url" to work. How do I go about this!
<form method="POST" action="https://voguepay.com/pay/">
<input type="hidden" name="v_merchant_id" value="demo"/>
<input type='hidden' name='notify_url' value="{{url('notification')}}" />
<input type='hidden' name='success_url' value="{{url('transaction/successful')}}" />
<input type='hidden' name='fail_url' value="{{url('transaction/fail')}}" />
<input type='submit'  value='Buy now' />
</form>

This what laravel is saying when Voguepay is getting a hand on 'success_url'
 "Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message"
Thank you in advance
Edited
web.php
Route::post('notification','VoguepayController@notify')->name('notification');
    Route::get('transaction/successful','VoguepayController@success')->name('success');
    Route::get('transaction/fail', 'VoguepayController@fail')->name('fail');

A: You must add csrf protection when use form laravel.
You can read documentation laravel or you can read example in laravel 5.1  https://laravel.com/docs/5.1/routing#csrf-protection


text:
Q: List of possible values for particular path variable in Spring MVC Consider three REST resources:
/persons/id/{id}
/persons/code/{code}
/persons/email/{email}

I want to make one method in a Spring MVC controller to handle these requests:
@RequestMapping("/persons/{searchField}/{searchValue}")
public Person search(@PathVariable field, @PathVariable value) {
...
}

The question: is there any elegant way to restrict searchField's variable list of values on the annotation level except just by checking them in the method search?
switch (field) {
  case "id": ...
  case "code": ...
  ...
  default: // not found exception??
}

A: It can be easily done using regular expressions in the mapping:
@RequestMapping("/persons/{searchField:id|code|email}/{searchValue}")

A: You can also use a enum as type for your @PathVariable that will make Spring to limit the accepeted request values to the values of the enum


text:
Q: Prove the integer part of $(1+\sqrt{3})^{2006}$ is odd Prove that the integer part (flooring ) of $(1+\sqrt{3})^{2006}$ is odd.
Here's what I did:
$(1+\sqrt{3})^{2006}=(4+2\sqrt{3})^{1003}={1003\choose 0}4^{1003}+{1003\choose 2}4^{1001}.(2\sqrt{3})^2+\cdots+{1003\choose 1002}4.(2\sqrt{3})^{1002}) + ({1003\choose1}.4^{1002}.2\sqrt{3}+{1003\choose 3}4^{1000}.(2\sqrt{3})^3+\cdots+{1003\choose 1003}(2\sqrt{3})^{1003})$.
It is clear that the expression in the left parentheses is even. So now the task is to prove the floor of the expression in the other parentheses is odd.
I have no idea how to proceed with this.

A: Hint:
Observe that $$(\sqrt3+1)^{2n}+(\sqrt3-1)^{2n}$$ is an even integer
Now $\sqrt3-1=\dfrac{3-1}{\sqrt3+1}<1$
$\implies0<(\sqrt3-1)^{2n}<1$