text:
Q: Password masking console application I tried the following code...
string pass = "";
Console.Write("Enter your password: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);

    // Backspace Should Not Work
    if (key.Key != ConsoleKey.Backspace)
    {
        pass += key.KeyChar;
        Console.Write("*");
    }
    else
    {
        Console.Write("\b");
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Password You entered is : " + pass);

But this way the backspace functionality doesn't work while typing the password.
Any suggestion?

A: I found a bug in shermy's vanilla C# 3.5 .NET solution which otherwise works a charm. I have also incorporated Damian Leszczyński - Vash's SecureString idea here but you can use an ordinary string if you prefer.
THE BUG: If you press backspace during the password prompt and the current length of the password is 0 then an asterisk is incorrectly inserted in the password mask. To fix this bug modify the following method.
    public static string ReadPassword(char mask)
    {
        const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127;
        int[] FILTERED = { 0, 27, 9, 10 /*, 32 space, if you care */ }; // const

        SecureString securePass = new SecureString();

        char chr = (char)0;

        while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER)
        {
            if (((chr == BACKSP) || (chr == CTRLBACKSP))
                && (securePass.Length > 0))
            {
                System.Console.Write("\b \b");
                securePass.RemoveAt(securePass.Length - 1);

            }
            // Don't append * when length is 0 and backspace is selected
            else if (((chr == BACKSP) || (chr == CTRLBACKSP)) && (securePass.Length == 0))
            {
            }

            // Don't append when a filtered char is detected
            else if (FILTERED.Count(x => chr == x) > 0)
            {
            }

            // Append and write * mask
            else
            {
                securePass.AppendChar(chr);
                System.Console.Write(mask);
            }
        }

        System.Console.WriteLine();
        IntPtr ptr = new IntPtr();
        ptr = Marshal.SecureStringToBSTR(securePass);
        string plainPass = Marshal.PtrToStringBSTR(ptr);
        Marshal.ZeroFreeBSTR(ptr);
        return plainPass;
    }

A: (My) nuget package to do this, based on the top answer:
install-package PanoramicData.ConsoleExtensions
Usage:
using PanoramicData.ConsoleExtensions;

...

Console.Write("Password: ");
var password = ConsolePlus.ReadPassword();
Console.WriteLine();

Project URL: https://github.com/panoramicdata/PanoramicData.ConsoleExtensions
Pull requests welcome.

A: Here's a version that adds support for the Escape key (which returns a null string)
public static string ReadPassword()
{
    string password = "";
    while (true)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.Escape:
                return null;
            case ConsoleKey.Enter:
                return password;
            case ConsoleKey.Backspace:
                if (password.Length > 0)
                {
                    password = password.Substring(0, (password.Length - 1));
                    Console.Write("\b \b");
                }
                break;
            default:
                password += key.KeyChar;
                Console.Write("*");
                break;
        }
    }
}

A: Complete solution, vanilla C# .net 3.5+
Cut & Paste
:)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleReadPasswords
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Write("Password:");

                string password = Orb.App.Console.ReadPassword();

                Console.WriteLine("Sorry - I just can't keep a secret!");
                Console.WriteLine("Your password was:\n<Password>{0}</Password>", password);

                Console.ReadLine();
            }
        }
    }

    namespace Orb.App
    {
        /// <summary>
        /// Adds some nice help to the console. Static extension methods don't exist (probably for a good reason) so the next best thing is congruent naming.
        /// </summary>
        static public class Console
        {
            /// <summary>
            /// Like System.Console.ReadLine(), only with a mask.
            /// </summary>
            /// <param name="mask">a <c>char</c> representing your choice of console mask</param>
            /// <returns>the string the user typed in </returns>
            public static string ReadPassword(char mask)
            {
                const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127;
                int[] FILTERED = { 0, 27, 9, 10 /*, 32 space, if you care */ }; // const

                var pass = new Stack<char>();
                char chr = (char)0;

                while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER)
                {
                    if (chr == BACKSP)
                    {
                        if (pass.Count > 0)
                        {
                            System.Console.Write("\b \b");
                            pass.Pop();
                        }
                    }
                    else if (chr == CTRLBACKSP)
                    {
                        while (pass.Count > 0)
                        {
                            System.Console.Write("\b \b");
                            pass.Pop();
                        }
                    }
                    else if (FILTERED.Count(x => chr == x) > 0) { }
                    else
                    {
                        pass.Push((char)chr);
                        System.Console.Write(mask);
                    }
                }

                System.Console.WriteLine();

                return new string(pass.Reverse().ToArray());
            }

            /// <summary>
            /// Like System.Console.ReadLine(), only with a mask.
            /// </summary>
            /// <returns>the string the user typed in </returns>
            public static string ReadPassword()
            {
                return Orb.App.Console.ReadPassword('*');
            }
        }
    }

A: Console.Write("\b \b"); will delete the asterisk character from the screen, but you do not have any code within your else block that removes the previously entered character from your pass string variable.
Here's the relevant working code that should do what you require:
var pass = string.Empty;
ConsoleKey key;
do
{
    var keyInfo = Console.ReadKey(intercept: true);
    key = keyInfo.Key;

    if (key == ConsoleKey.Backspace && pass.Length > 0)
    {
        Console.Write("\b \b");
        pass = pass[0..^1];
    }
    else if (!char.IsControl(keyInfo.KeyChar))
    {
        Console.Write("*");
        pass += keyInfo.KeyChar;
    }
} while (key != ConsoleKey.Enter);

A: Taking the top answer, as well as the suggestions from its comments, and modifying it to use SecureString instead of String, test for all control keys, and not error or write an extra "*" to the screen when the password length is 0, my solution is:
public static SecureString getPasswordFromConsole(String displayMessage) {
    SecureString pass = new SecureString();
    Console.Write(displayMessage);
    ConsoleKeyInfo key;

    do {
        key = Console.ReadKey(true);

        // Backspace Should Not Work
        if (!char.IsControl(key.KeyChar)) {
            pass.AppendChar(key.KeyChar);
            Console.Write("*");
        } else {
            if (key.Key == ConsoleKey.Backspace && pass.Length > 0) {
                pass.RemoveAt(pass.Length - 1);
                Console.Write("\b \b");
            }
        }
    }
    // Stops Receving Keys Once Enter is Pressed
    while (key.Key != ConsoleKey.Enter);
    return pass;
}

A: Jeez guys
    static string ReadPasswordLine()
    {
        string pass = "";
        ConsoleKeyInfo key;
        do
        {
            key = Console.ReadKey(true);
            if (key.Key != ConsoleKey.Enter)
            {
                if (!(key.KeyChar < ' '))
                {
                    pass += key.KeyChar;
                    Console.Write("*");
                }
                else if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                {
                    Console.Write(Convert.ToChar(ConsoleKey.Backspace));
                    pass = pass.Remove(pass.Length - 1);
                    Console.Write(" ");
                    Console.Write(Convert.ToChar(ConsoleKey.Backspace));
                }
            }
        } while (key.Key != ConsoleKey.Enter);
        return pass;
    }

A: Mine ignores control characters and handles line wrapping:
public static string ReadLineMasked(char mask = '*')
{
    var sb = new StringBuilder();
    ConsoleKeyInfo keyInfo;
    while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
    {
        if (!char.IsControl(keyInfo.KeyChar))
        {
            sb.Append(keyInfo.KeyChar);
            Console.Write(mask);
        }
        else if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);

            if (Console.CursorLeft == 0)
            {
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                Console.Write(' ');
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
            }
            else Console.Write("\b \b");
        }
    }
    Console.WriteLine();
    return sb.ToString();
}

A: This masks the password with a red square, then reverts back to the original colours once the password has been entered.
It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.
Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;

Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;

string Password = Console.ReadLine(); // read the password

Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;

A: Reading console input is hard, you need to handle special keys like Ctrl, Alt, also cursor keys and Backspace/Delete. On some keyboard layouts, like Swedish Ctrl is even needed to enter keys that exist directly on US keyboard. I believe that trying to handle this using the "low-level" Console.ReadKey(true) is just very hard, so the easiest and most robust way is to just to disable "console input echo" during entering password using a bit of WINAPI.
The sample below is based on answer to Read a password from std::cin question.
    private enum StdHandle
    {
        Input = -10,
        Output = -11,
        Error = -12,
    }

    private enum ConsoleMode
    {
        ENABLE_ECHO_INPUT = 4
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr GetStdHandle(StdHandle nStdHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int lpMode);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetConsoleMode(IntPtr hConsoleHandle, int dwMode);

    public static string ReadPassword()
    {
        IntPtr stdInputHandle = GetStdHandle(StdHandle.Input);
        if (stdInputHandle == IntPtr.Zero)
        {
            throw new InvalidOperationException("No console input");
        }

        int previousConsoleMode;
        if (!GetConsoleMode(stdInputHandle , out previousConsoleMode))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get console mode.");
        }

        // disable console input echo
        if (!SetConsoleMode(stdInputHandle , previousConsoleMode & ~(int)ConsoleMode.ENABLE_ECHO_INPUT))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not disable console input echo.");
        }

        // just read the password using standard Console.ReadLine()
        string password = Console.ReadLine();

        // reset console mode to previous
        if (!SetConsoleMode(stdInputHandle , previousConsoleMode))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not reset console mode.");
        }

        return password;
    }

A: For this you should use the System.Security.SecureString
public SecureString GetPassword()
{
    var pwd = new SecureString();
    while (true)
    {
        ConsoleKeyInfo i = Console.ReadKey(true);
        if (i.Key == ConsoleKey.Enter)
        {
            break;
        }
        else if (i.Key == ConsoleKey.Backspace)
        {
            if (pwd.Length > 0)
            {
                pwd.RemoveAt(pwd.Length - 1);
                Console.Write("\b \b");
            }
        }
        else if (i.KeyChar != '\u0000' ) // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
        {
            pwd.AppendChar(i.KeyChar);
            Console.Write("*");
        }
    }
    return pwd;
}

A: You could append your keys to an accumulating linked list.
When a backspace key is received, remove the last key from the list.
When you receive the enter key, collapse your list into a string and do the rest of your work.

A: I made some changes for backspace
        string pass = "";
        Console.Write("Enter your password: ");
        ConsoleKeyInfo key;

        do
        {
            key = Console.ReadKey(true);

            // Backspace Should Not Work
            if (key.Key != ConsoleKey.Backspace)
            {
                pass += key.KeyChar;
                Console.Write("*");
            }
            else
            {
                pass = pass.Remove(pass.Length - 1);
                Console.Write("\b \b");
            }
        }
        // Stops Receving Keys Once Enter is Pressed
        while (key.Key != ConsoleKey.Enter);

        Console.WriteLine();
        Console.WriteLine("The Password You entered is : " + pass);

A: I have updated Ronnie's version after spending way too much time trying to enter a password only to find out that I had my CAPS LOCK on!
With this version what ever the message is in _CapsLockMessage will "float" at the end of the typing area and will be displayed in red.
This version takes a bit more code and does require a polling loop. On my computer CPU usage about 3% to 4%, but one could always add a small Sleep() value to decrease CPU usage if needed.
    private const string _CapsLockMessage = " CAPS LOCK";

    /// <summary>
    /// Like System.Console.ReadLine(), only with a mask.
    /// </summary>
    /// <param name="mask">a <c>char</c> representing your choice of console mask</param>
    /// <returns>the string the user typed in</returns>
    public static string ReadLineMasked(char mask = '*')
    {
        // Taken from http://stackoverflow.com/a/19770778/486660
        var consoleLine = new StringBuilder();
        ConsoleKeyInfo keyInfo;
        bool isDone;
        bool isAlreadyLocked;
        bool isCapsLockOn;
        int cursorLeft;
        int cursorTop;
        ConsoleColor originalForegroundColor;

        isDone = false;
        isAlreadyLocked = Console.CapsLock;

        while (isDone == false)
        {
            isCapsLockOn = Console.CapsLock;
            if (isCapsLockOn != isAlreadyLocked)
            {
                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                    Console.ForegroundColor = originalForegroundColor;
                }
                else
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    Console.Write("{0}", string.Empty.PadRight(_CapsLockMessage.Length));
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                }
                isAlreadyLocked = isCapsLockOn;
            }

            if (Console.KeyAvailable)
            {
                keyInfo = Console.ReadKey(intercept: true);

                if (keyInfo.Key == ConsoleKey.Enter)
                {
                    isDone = true;
                    continue;
                }

                if (!char.IsControl(keyInfo.KeyChar))
                {
                    consoleLine.Append(keyInfo.KeyChar);
                    Console.Write(mask);
                }
                else if (keyInfo.Key == ConsoleKey.Backspace && consoleLine.Length > 0)
                {
                    consoleLine.Remove(consoleLine.Length - 1, 1);

                    if (Console.CursorLeft == 0)
                    {
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                        Console.Write(' ');
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                    }
                    else
                    {
                        Console.Write("\b \b");
                    }
                }

                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.CursorLeft = cursorLeft;
                    Console.CursorTop = cursorTop;
                    Console.ForegroundColor = originalForegroundColor;
                }
            }
        }

        Console.WriteLine();

        return consoleLine.ToString();
    }

A: Here is my simple version.
Every time you hit a key, delete all from console and draw as many '*' as the length of password string is.
int chr = 0;
string pass = "";
const int ENTER = 13;
const int BS = 8;

do
{
   chr = Console.ReadKey().KeyChar;
   Console.Clear(); //imediately clear the char you printed

   //if the char is not 'return' or 'backspace' add it to pass string
   if (chr != ENTER && chr != BS) pass += (char)chr;

   //if you hit backspace remove last char from pass string
   if (chr == BS) pass = pass.Remove(pass.Length-1, 1);

   for (int i = 0; i < pass.Length; i++)
   {
      Console.Write('*');
   }
}
 while (chr != ENTER);

Console.Write("\n");
Console.Write(pass);

Console.Read(); //just to see the pass

A: If I understand this correctly, you're trying to make backspace delete both the visible * character on screen and the cached character in your pass variable?
If so, then just change your else block to this:
            else
            {
                Console.Write("\b");
                pass = pass.Remove(pass.Length -1);
            }

A: I just improve code from ask I simple and just work
    string pass = ""; //create empty password string
    Console.Write("Enter your password: ");
    ConsoleKeyInfo key;
    int passLen = 0; // base password length

    do
    {
        key = Console.ReadKey(true); //reading keyboard key

        if (key.Key == ConsoleKey.Escape) Environment.Exit(0); // If key is escape console will close (optional)

        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) // on key with is not bacspase and enter
        {
            pass += key.KeyChar; //password string add key value
            Console.Write("*"); // and print star as masked char
            passLen++; // upgrading password length
        }
        else if (passLen > 0 && key.Key == ConsoleKey.Backspace) //if password have a any symbol and u press Backspace
        {
                Console.Write("\b \b"); //Backspace delete star symbol and coursor back in line
                passLen--; // password length is one less
                pass = pass[0..^1]; // new string passowrd is string without last charter
        }
    }
    while (key.Key != ConsoleKey.Enter); // if you press enter this stop execute with your password

    Console.WriteLine();
    Console.WriteLine("The Password You entered is : " + pass);

A:  string pass = "";
 Console.WriteLine("Enter your password: ");
 ConsoleKeyInfo key;

 do {
  key = Console.ReadKey(true);

  if (key.Key != ConsoleKey.Backspace) {
   pass += key.KeyChar;
   Console.Write("*");
  } else {
   Console.Write("\b \b");
   char[] pas = pass.ToCharArray();
   string temp = "";
   for (int i = 0; i < pass.Length - 1; i++) {
    temp += pas[i];
   }
   pass = temp;
  }
 }
 // Stops Receving Keys Once Enter is Pressed
 while (key.Key != ConsoleKey.Enter);

 Console.WriteLine();
 Console.WriteLine("The Password You entered is : " + pass);


text:
Q: How to use if statement with characters in C So here is my code of a simple calculator I'm trying to build in C (I'm learning C):
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main()
{
    char Operation;
    printf("Welcome to Double-Figure Calculator!\n\n");
    Sleep(1000);
    printf("What operation would you like to do? (+, -, *, /,) \n");
    Sleep(1000);
    scanf("%c\n\n", Operation);
    Sleep(1000);

    if (Operation == '+'){

        int FirstNumber;
        int SecondNumber;

            printf("Please enter your first number\n");
            scanf("%s\n\n", &FirstNumber);

            printf("Please enter your second number\n");
            scanf("%s\n\n", &SecondNumber);
            Sleep(1000);

            printf("Calculating");

            Sleep(1000);
            printf(".");

            Sleep(1000);
            printf(".");

            Sleep(1000);
            printf(".\n\n");

            printf("Your calculation is %d\n\n", FirstNumber + SecondNumber);

            system("Pause");

    }

    if (Operation == '-'){

        int OneFirstNumber;
        int OneSecondNumber;

        printf("Please enter your first number\n");
        scanf("%s\n\n", &OneFirstNumber);

        printf("Please enter your second number\n");
        scanf("%s\n\n", &OneSecondNumber);
        Sleep(1000);

        printf("Calculating");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".\n\n");

        printf("Your calculation is %d\n\n", OneFirstNumber - OneSecondNumber);

        system("Pause");

    }

    if (Operation == '*'){

        int TwoFirstNumber;
        int TwoSecondNumber;

        printf("Please enter your first number\n");
        scanf("%s\n\n", &TwoFirstNumber);

        printf("Please enter your second number\n");
        scanf("%s\n\n", &TwoSecondNumber);
        Sleep(1000);

        printf("Calculating");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".\n\n");

        printf("Your calculation is %d\n\n", TwoFirstNumber * TwoSecondNumber);

        system("Pause");

    }

    if (Operation == '/'){

        int ThreeFirstNumber;
        int ThreeSecondNumber;

        printf("Please enter your first number\n");
        scanf("%s\n\n", &ThreeFirstNumber);

        printf("Please enter your second number\n");
        scanf("%s\n\n", &ThreeSecondNumber);
        Sleep(1000);

        printf("Calculating");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".");

        Sleep(1000);
        printf(".\n\n");

        printf("Your calculation is %d\n\n", ThreeFirstNumber / ThreeSecondNumber);

        system("Pause");

    }

    system("pause");
    return 0;

}

The problem is whenever I run the code, and enter an operation, so +,-,*, or /, and then press enter, nothing happens, even though I have if statements there to carry out the rest of the program. I can't figure out what I'm doing wrong here. Any help? (Sorry, I'm new to programming, and am in the early stages of learning C).

A: You have some mistakes in your code that you could improve.
The first one, when you use scanf, you must pass the variable address to store the data, for example:
scanf("%c", &Operation);

Avoid using "\n\n" in scanf, it tells that you expect an char and two returns from user input. If the user don't do that, your code will not work properly.
I could notice you are using scanf wrong in the most cases regarding data type. If you want to get an integer value from user with scanf, you must use the corresponding conversion %d to get an integer value, for example:
scanf("%d\n", &secondNumber);

When you use %s, you are telling that you expect an string from user's input, it can crash your code if you store an string into an integer variable.
Another point is related to use if statement to switch the user's input, it would be better to use switch-case statements, for example:
switch(operation) {
case '+':
    // do add operation
    break;
case '-':
    // do sub operation
    break;
default:
    // return some error message.
}

In switch-case statement, the "default" is a routine that you want to perform if none of the cases don't match with what you expect.
I thing this is all you need to do to get your code working.

A: scanf("%c\n\n", &Operation);

To scan into the value, you need to give scanf an address.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Terraform: azurerm_lb_rule should be type list, got type string I'm trying to create an azure lb rule using element and here's the error message and the code listed below.
What should I be changing within my main.tf file or variables.tf file to get the element to work. However, when I provide ports directly (which are commented) the code executes without any issues.

1 error(s) occurred:

*

*azurerm_lb_rule.test: 1 error(s) occurred:

*azurerm_lb_rule.test: At column 3, line 1: element: argument 1 should be type list, got type string in:
${element(var.lb_port["${element(keys(var.lb_port), count.index)}"],
  2)}

main.tf

resource "azurerm_lb_rule" "test" {
  resource_group_name            = "${azurerm_resource_group.test.name}"
  loadbalancer_id                = "${azurerm_lb.lb.id}"
  name                           = "LBRule"
  protocol                       = "Tcp"
  #frontend_port                  = 3389
  #backend_port                   = 3389
 protocol                       = "${element(var.lb_port["${element(keys(var.lb_port), count.index)}"], 0)}"
 frontend_port                  = "${element(var.lb_port["${element(keys(var.lb_port), count.index)}"], 1)}"
 backend_port                   = "${element(var.lb_port["${element(keys(var.lb_port), count.index)}"], 2)}"
  frontend_ip_configuration_name = "${var.frontend_name}"
}

variables.tf

variable "lb_port" {
  description = "Protocols to be used for lb health probes and rules."
  default     = {"var1" = "tcp,3389,3389"}
}

A: According to your requirement, you could define variable lb_port as a map type, then use the lookup function to retrieve the value of a single element from a map given its key.
For example,
variable "lb_port" {
  description = "Protocols to be used for lb health probes and rules."
   default = {
    "protocol" = "TCP"
    "frontend_port" = "3389"
    "backend_port" = "3389"
  }
}
...

resource "azurerm_lb_rule" "test" {
  resource_group_name            = "${azurerm_resource_group.test.name}"
  loadbalancer_id                = "${azurerm_lb.lb.id}"
  name                = "LBRule"
  #protocol            = "Tcp"
  #frontend_port                  = 3389
  #backend_port                   = 3389
  protocol                       = "${lookup(var.lb_port, "protocol" )}"
  frontend_port                  = "${lookup(var.lb_port, "frontend_port" )}"
  backend_port                   = "${lookup(var.lb_port, "backend_port" )}"
  frontend_ip_configuration_name = "${var.frontend_name}"
  ...
}

More example references here.


text:
Q: is there anyway to detect recursive method in javascript/jQuery? I am working on small part of calculation code. I need to identify whenever recursive occur in javascript/jQuery and i need to terminate that recursive.
Is there any api to support this in javascript/jQuery?

A: You could implement your own recursive protection.  There is nothing built into jQuery that would natively support preventing recursion.
function myFunc(arg) {
    // if this function already executing and this is recursive call
    // then just return (don't allow recursive call)
    if (myFunc.in) {
        return;
    }

    // set flag that we're in this function
    myFunc.in = true;

    // put your function's code here

    // clear flag that we're in this function
    myFunc.in = false;

}

myFunc.in = false;

You could also turn the boolean into a counter and allow recursion only up to a certain number of levels.
FYI, because JS is single threaded, this should only be an issue that might need protection if your function takes some sort of callback from code that isn't yours.  If it's all your own code, then you should just make sure your own code won't cause this sort of problem.

Here's a little more foolproof version that protects the counter in a closure so it can't be manipulated outside the function:
 var myFunc = (function() {
     var inCntr = 0;
     return function(args) {
         // protect against recursion
         if (inCntr !== 0) {
             return;
         }
         ++inCntr;

         try {

             // put your function's code here

         } finally {
             --inCntr;
         }

     }
 })();

Note: this uses a try/finally block so even if your code or any code you call throws an exception the counter is still cleared (so it never gets stuck).

A: Another dodgy trick. If you use something like .bind(this) for recursion or if you use arrow function, it won't work.

boom();

function boom () {
  if(arguments.callee === arguments.callee.caller) {
    console.log('no recursion will happen');
    return;
  }
  boom();
}

Simple solution could be a flag in a parameter

boom2();

function boom2 (calledRecursively) {
  if(calledRecursively) {
    console.log('no recursion will happen');
    return;
  }
  boom2(true);
}


text:
Q: Need to Insert Identity MasterId into 2 tables #tblUniqueKeys and #tblChild I have 2 tables "#tblData1" and "#tblData2" link with "Id" column. Table "#tblData2" may or may not data for the same "Id" of "#tblData1".
Create Table #tblData1 (Id int, Details VARCHAR(10),  UniqueKey VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
insert into #tblData1 values (1, 'DT1', 'uq1', '01/15/2016', 'abc'), (2, 'DT2', 'uq2', '01/16/2016', 'xyz');

Create Table #tblData2 (Id int, Details VARCHAR(10), DetectDate DATE);
insert into #tblData2 values (1, 'DT11', '01/16/2016'), (1, 'DT12', '01/17/2016')

Now, I need to insert data into below 3 tables "#tblUniqueKeys", "#tblMaster" and "#tblChild".

*

*Same Identity "MasterId" into both tables "#tblUniqueKeys" and "#tblChild".

*Data from  "#tblData1" into 2 tables "#tblUniqueKeys" and  "#tblMaster".

*Data from "#tblData2" into table ""#tblChild".
create Table #tblMaster (MasterId INT IDENTITY(101,1), Details VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
create Table #tblUniqueKeys (UqId INT IDENTITY(10,1), MasterId INT, UniqueKey VARCHAR(10), DetectDate DATE);
create Table #tblChild (ChildId INT IDENTITY(201,1), MasterId INT, Details VARCHAR(10), DetectDate DATE);
Using below "Merge" sql query, I'm able to insert records into 2 table "#tblUniqueKeys" and  "#tblMaster".
Question, How to insert records into the 3rd table "#tblChild"? Can we insert record into 3rd table along with "MasterId" within same Merge query? Thanks!!!
MERGE INTO #tblMaster AS Dest
USING
(
SELECT UniqueKey, Details, DetectDate, UpdateBy
FROM #tblData1
) AS Src
ON (1 = 0)
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
Details
,DetectDate
,UpdateBy)
VALUES
(Src.Details
,Src.DetectDate
,Src.UpdateBy)
 OUTPUT inserted.MasterId, Src.UniqueKey, Src.DetectDate
 INTO #tblUniqueKeys(MasterId, UniqueKey, DetectDate);

select * from #tblMaster
select * from #tblUniqueKeys

DROP TABLE #tblData1;
drop table #tblData2;
DROP TABLE #tblMaster;
drop table #tblChild
DROP TABLE #tblUniqueKeys;


text:
Q: Bing Search API in PHP - missing webPages property in json response I am trying to get search results as per the api documentation
Here is what I wrote in PHP
    require_once 'HTTP/Request2.php';

    $api_key = 'my_bing_search_api_key';
    $url_encoded_keyword = urlencode('animation concepts and tutorials');

    $request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
    $headers = [
        'Ocp-Apim-Subscription-Key' => $api_key
    ];
    $request->setHeader($headers);

    $url = $request->getUrl();

    $parameters = [
        'q' => $url_encoded_keyword,
        'count' => '10',
        'offset' => '0',
        'safesearch' => 'Strict',
    );

    $url->setQueryVariables($parameters);

    $request->setMethod(\HTTP_Request2::METHOD_GET);

    $request->setBody("{body}");

    $search_result = null;
    try {
        $response = $request->send();
        $search_results = json_decode($response->getBody(), true);
        return $search_results;
    } catch (HttpException $ex) {
        return [];
    }

I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only.
I tested the same request in the api console. There I am getting the webPages property in the json response.
Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?

A: From the code snippet, you are passing the keyword to Bing web search API after encoding it.
    $url_encoded_keyword = urlencode('animation concepts and tutorials');
$parameters = [
    'q' => $url_encoded_keyword,
    'count' => '10',
    'offset' => '0',
    'safesearch' => 'Strict',
);

Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as

https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation
  concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate


text:
Q: Custom Post Type vs Shortcode: Which one is more performant? I am designing a Wordpress blog where I will have two types of posts:
a. Normal posts; regular posts with a number of text paragraphs

b. Posts with table content, where the table structure will be more or less like http://click.apache.org/docs/user-guide/html/images/introduction/simple-table.png
Knowing that normal posts will be the regular Posts > Add New from the admin area. I came up with two solutions for the table-type posts:
Solution A
A custom post type. My knowledge of custom post types is very limited but I believe I would need to create the custom post type, a template for it as well as any custom fields I may need
Solution B
Shortcodes, where I treat posts with table content just like regular posts only that where I want to place the table I will use a string such as:
[PEOPLETABLE]231|Albert Master|albert.master@gmail.com|Bonds
210|Alfred Alan|aalan@gmail.com|Stocks
256|Alison Smart|asmart@biztalk.com|Residential Property[/PEOPLETABLE]

The html in the post will then be rendered by passing this string to a shortcode where the parsing will take place and the HTML generated.
Am I right in saying that Solution B is faster as it does not involve custom templates and custom fields?

A: If the posts with tables are part of "normal" blogging flow and appear with rest of the posts, there is probably little reason to separate them out into CPT. Shortcode bit is irrelevant, you'll have to deal with tables regardless of native or custom post type.
The use cases for CPTs loosely start for content that no longer belongs in stream of blog posts (or arbitrary purpose pages).


text:
Q: Which user's password does `sudo` asks for? $ ls -l /usr/bin/sudo
-rwsr-xr-x 1 root root 136808 Jul  4  2017 /usr/bin/sudo

so sudo is runnable by any user, and any user who runs sudo will have root as the effective user ID of the process because the set-user-id bit of /usr/bin/sudo is set.
From https://unix.stackexchange.com/a/11287/674

the most visible difference between sudo and su is that sudo requires the user's password and su requires root's password.

*

*Which user's password does sudo asks for? Is it the user represented by the real user ID of the process?
If yes, doesn't any user can gain the superuser privilege by running sudo and then providing their own password? Can Linux restrict that on some users?

*Is it correct thatsudo asks for the password after execve() starts to execute main() of /usr/bin/sudo?
Since the euid of the process has been changed to root (because the set-user-id bit of /usr/bin/sudo is set), what is the point of sudo asking for password later?
Thanks.
I have read https://unix.stackexchange.com/a/80350/674, but it doesn't answer the questions above.

A: From the first line(s) of man sudo:

DESCRIPTION
  sudo allows a permitted user to execute a command as the superuser or another user, as specified by the security policy.  The invoking user's real (not effective) user ID is used to determine the user name with which to query the security policy.

So:

*

*The invoking user's real (not effective) user ID is used ...

*Yes, any (permitted) user can gain the superuser (or other) additional privilege(s) by running sudo and then providing the (configured) authentication required. Both permitted and configured are set in sudoers file(s).

*Can Linux restrict that on some users?
Yes, it can, but it doesn't. Linux is set to allow the sudo binary to make the decision based on the set of rules (security policy) inside the sudo program and inside the file /etc/sudoers. Usually, other files (also/instead) may be used.
From man setresuid:

DESCRIPTION
         setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the calling process.

*The only way to gain superuser permissions granted by the kernel is to run a program suid. It can not be otherwise. It is the way Linux has selected to grant superuser permissions.

*After the kernel has loaded an executable that can not be modified by any other user (file and directory owned by root and writable only by root) the executable itself (sudo) authenticates the user by asking for its password (or something else as configured) and decides if and which permissions to grant.

A: *

*In its most common configuration, sudo asks for the password of the user running sudo (as you say, the user corresponding to the process' real user id). The point of sudo is to grant extra privileges to specific users (as determined by the configuration in sudoers), without those users having to provide any other authentication than their own. However, sudo does check that the user running sudo really is who they claim to be, and it does that by asking for their password (or whatever authentication mechanism is set up for sudo, usually using PAM — so this could involve a fingerprint, or two-factor authentication etc.).
sudo doesn't necessarily grant the right to become root, it can grant a variety of privileges. Any user allowed to become root by sudoers can do so using only their own authentication; but a user not allowed to, can't (at least, not by using sudo). This isn't enforced by Linux itself, but by sudo (and its authentication setup).

*sudo does indeed ask for the password after it's started running; it can't do otherwise (i.e. it can't do anything before it starts running). The point of sudo asking for the password, even though it's root, is to verify the running user's identity (in its typical configuration).

A: sudo usually asks for the password of the user running it, though this can be configured:

Unlike su(1), when
       sudoers requires authentication, it validates the invoking user's credentials, not the target user's (or root's) credentials.  This can be changed via
       the rootpw, targetpw and runaspw flags, described later.

Setting rootpw has sudo always ask for root's password, targetpw asks for the password of the user sudo will eventually run the program as, and runaspw asks for the password of the user set in runas_default.
A sudo binary set up like that can indeed be started with root privilege by any user. Assuming sudo doesn't have any bugs with its authentication code, that in itself won't matter much.
Somewhat similarly, any process can also execute code in kernel mode, by calling any system call, say open(). (that's not the same as userspace code as root.) As long as the kernel doesn't have bugs, they won't be able to run arbitrary code, though.

A: Additional to other good answers about sudo:
su allows you to effectively become a different user.  On my own computer I don't run as an administrator for everyday use -- which means, among other things, I can't (directly) use sudo.  If I do want to use sudo, I can use su to "become" the Administrator user, and then in that role use sudo.  In that situation I end up entering the Admin account's password twice -- once when I run su, and once when I run sudo.


text:
Q: JSON Array of strings (no objects), extracting data I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
    ["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]

I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?

A: this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}

A: Maybe this post can help you out:
JSON Array iteration in Android/Java
  HashMap<String, String> applicationSettings = new HashMap<String,String>();
    for(int i = 0; i < settings.length(); i++){
        String value = settings.getJSONObject(i).getString("value");
        String name = settings.getJSONObject(i).getString("name");
        applicationSettings.put(name, value);
    }

 JSONArray names= json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i = 0 ; i < values.length(); i++){
        if(names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if(names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString));
        }
        else if(names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if(names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if(names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if(names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }

A: Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
    int pipeIndex = element_strings.indexOf("|");
    elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}

Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html

A: If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.json.JSONArray;

public class JsonArrayTest {

    public static void main(String[] args) {
        System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
        System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
    }

    private static String getValue(String input) {
        JSONArray jsonArray = new JSONArray(input);

        return IntStream
                .range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
                .filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
                .map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
    }

}

Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.


text:
Q: Google Analytics API v3 : Unknown metric(s): ga:adsenseAdsViewed, ga:adsenseAdsClicks, ga:adsenseRevenue, ga:adsenseAdUnitsViewed It seems that something has changed last thursday/friday with the following metrics : ga:adsenseAdsViewed, ga:adsenseAdsClicks, ga:adsenseRevenue, ga:adsenseAdUnitsViewed
I was able to pull these metrics before and since a while and I'm no longer able to have these metrics since last friday.
I'm hit by : Unknown metric(s): ga:adsenseAdsViewed, ga:adsenseAdsClicks, ga:adsenseRevenue, ga:adsenseAdUnitsViewed
I went to the API change logs, no changes since 2016-10-12. These metrics also are still showing available in the documentation.
In the past, this already happened and a quick retry fixed the issue - but this is no longer the case right now.
Does someone has already got the same issue? Are these field removed? Something else?
Thank you a lot for any feedback

A: This issue has been fixed in the latest release, see changelog for details.
AdSense dimensions and metrics
This release fixes an issue which started on 1/7/2017 in which querying for AdSense dimensions and metrics
  would return an Unknown Metric error for non-AdSense linked views.
Coming changes
On or after 1/31/2017 non-AdSense linked views will be restricted from
  querying for AdSense dimensions and metrics. Querying for these dimensions
  and metrics with a non-AdSense linked views will result in an error.
Update your code
If possible link the views with the AdSense account when needed otherwise you should check the error messages and have your client respond accordingly.


text:
Q: jquery $(this).find not working for me okay so in php tags i have this:
<?php
echo "
";
echo "
 WELCOME ".$_SESSION['username']."!

link1

";
echo "
";
?>

i am trying to make it so it will show the link1 on hover. so i am using jquery and my code for that is:
</style>

        <?php
            echo "
";
            echo "
 WELCOME ".$_SESSION['username']."!

hello

";
            echo "
";
        ?>

that is named welcome.php
i have another file named index.php where i include that into my php.

A: hide your li containing the link, then toggle it .

$(document).ready(function() {
  $('#lis').hover(function() {
    $(this).find('ul>li').fadeToggle(400);
  });
});

WELCOME ".$_SESSION['username']."!

link1

A: Add a class that hides the link on render.
Then target the a and toggle that.
In your case it would not work if you hide the li as there is no element to hover if you hide the li
JS
$('li').hover(function() {
  $(this).find('ul > li > a').fadeToggle(400);
});

HTML
link1

CSS
.hide {
  display: none;
}

jsFiddle

A: Because your $('li') select ALL
s in the document, include the
link1
, try to use #id selector instead:
$(document).ready(function(){
    $('#lis').hover(function(){
        $(this).find('ul>li').fadeToggle(400);
    });
});


text:
Q: How should I design a relationship table for friendship? If A is a friend of B, then should I store both values AB and BA, or one is enough? What are the advantages and disadvantages of both methods.
Here is my observation:

*

*If I keep both then I have to update both when receive a request from a friend.

*If I don't keep both, then I found it difficult when having to do multiple JOIN with this table.

Currently, I keep the relationship one way.

So what should I do in this case? Any advice?

A: Assuming a "friendship" is always two-way/mutual, I'd probably handle it something like this.
CREATE TABLE person (
    person_id int IDENTITY(1,1) PRIMARY KEY,
    ...other columns...
)

CREATE TABLE friendship (
    friendship_id int IDENTITY(1,1) PRIMARY KEY,
    ...other columns, if any...
)

CREATE TABLE person_friendship (
    person_id int NOT NULL,
    friendship_id int NOT NULL
    PRIMARY KEY (person_id, friendship_id)
)

The result is that you change it from a many-to-many join from "person" to "person", to a many-to-many join from "person" to "friendship". This will simplify joins and constraints, but has the side effect of allowing more than two people in a single "friendship" (though maybe the additional flexibility would be a potential advantage).

A: You may need to define indexes around friendships instead of doubling the number of rows:
CREATE TABLE person
(
    person_id INT NOT NULL AUTO_INCREMENT,
    ...
    PRIMARY KEY (person_id)
);
CREATE TABLE friendship
(
    friend_of INT NOT NULL,
    friend_to INT NOT NULL,
    PRIMARY KEY (friend_of,friend_to),
    UNIQUE KEY friend_to (friend_to,friend_of)
);

This way, you double the storage for indexes but not for the table data. As a result, this should be a 25% savings on diskspace. The MySQL Query Optimizer will choose perform index range scans only, which is why the concept of covering indexes works well here.
Here are some nice links on Covering Indexes:

*

*http://peter-zaitsev.livejournal.com/6949.html

*http://www.mysqlperformanceblog.com/2006/11/23/covering-index-and-prefix-indexes/

*http://ronaldbradford.com/blog/tag/covering-index/
CAVEAT
If friendship is not mutual, you have the basis for another type of relationship : FOLLOWER
If friend_to is not a friend of friend_of, you can simply leave that relationship out of the table.
If you want to define relationships for all types, whether they are mutual or not, you could probably use the following table layout:
CREATE TABLE person
(
    person_id INT NOT NULL AUTO_INCREMENT,
    ...
    PRIMARY KEY (person_id)
);
CREATE TABLE relationship
(
    rel_id INT NOT NULL AUTO_INCREMENT,
    person_id1 INT NOT NULL,
    person_id2 INT NOT NULL,
    reltype_id TINYINT,
    PRIMARY KEY (rel_id),
    UNIQUE KEY outer_affinity (reltype_id,person_id1,person_id2),
    UNIQUE KEY inner_affinity (reltype_id,person_id2,person_id1),
    KEY has_relationship_to (person1_id,reltype_id),
    KEY has_relationship_by (person2_id,reltype_id)
);
CREATE TABLE relation
(
    reltype_id TINYINT NOT NULL AUTO_INCREMENT,
    rel_name VARCHAR(20),
    PRIMARY KEY (reltype_id),
    UNIQUE KEY (rel_name)
);
INSERT INTO relation (relation_name) VALUES
('friend'),('follower'),('foe'),
('forgotabout'),('forsaken'),('fixed');

From the relation table, you could arrange the relationships to include the following:

*

*Friends should be mutual

*Foes could be mutual or not

*Followers could be mutual or not

*The other relationships would be subject to interpretation (by the forgotten or forsaken or the recipient of revenge (fixed))

*Possibie relationships can be further extended

This should be more robust for all relationships, whether the relationship is mutual or not.

A: I would store AB and BA.  A friendship is really a two-way relationship, each entity is linked to another.  Even though intuitively we think of the "friendship" as one link between two people, from a relational point of view it is more like "A has a friend B" and "B has a friend A".  Two relationships, two records.

A: If friendship is intended to be symmetrical (i.e. it is not possible for A  to be friends with B but not vice-versa) then I would just store the one way relationship with a check constraint ensuring that each relationship can only be represented one way.
Also I would ditch the surrogate id and have a composite PK instead (and possibly a composite unique index also on the reversed columns).
CREATE TABLE Friends
  (
     UserID1 INT NOT NULL REFERENCES Users(UserID),
     UserID2 INT NOT NULL REFERENCES Users(UserID),
     CONSTRAINT CheckOneWay CHECK (UserID1 < UserID2),
     CONSTRAINT PK_Friends_UserID1_UserID2 PRIMARY KEY (UserID1, UserID2),
     CONSTRAINT UQ_Friends_UserID2_UserID1 UNIQUE (UserID2, UserID1)
  )

You don't say the queries that this makes difficult but you can always create a View
CREATE VIEW Foo
AS
SELECT UserID1,UserID2
FROM Friends
UNION ALL
SELECT UserID2,UserID1
FROM Friends

A: If you can control within the application that id of A is always lower than id of B ( pre order the A,B elements ids ) you can leverage of asking without an OR ( select where id_A = a AND id_B = b, instead of asking (id_A = a AND id_B = b) OR (id_A = b AND id_B = a) ), and also maintain half of the records you'll need with the other's approximations. Then you should use another field to maintain the state of the relationship ( are-friends, a-solicited-to-b, b-solicited-to-a, exfriends-a, exfriends-b ), and you're done.
This is the way I've managed my friendship system, and this simplifies the system and uses half the rows you'll need with other systems, only saying A is equals to the lower id value in code.


text:
Q: Concurrency and memory models I'm watching this video by Herb Sutter on GPGPU and the new C++ AMP library.  He is talking about memory models and mentions Weak Memory Models and then Strong Memory Models and I think he's referring to read/write ordering etc, but I am however not sure.
Google turns up some interesting results (mostly science papers) on memory models, but can someone explain what is a Weak Memory Model and what is a Strong Memory Model and their relation to concurrency?

A: The two terms aren't clearly defined, and it's not a black/white thing.
Memory models can be extremely weak, extremely strong, or anywhere in between.
It basically refers to the guarantees offered about concurrent memory accesses.
Naively, you would expect a write made on one thread, to be immediately visible to all other threads. And you would expect events to appear in the same order on all threads as well.
But in a weaker memory model, neither of those may hold.
Sequential consistency is the term for a memory model which guarantees that events are seen in the same order across all threads. So a memory model which ensures sequential consistency is pretty strong.
A weaker guarantee is causal consistency: the guarantee that events are observed after the events they depend on.
In other words, if you first write a value x to some address A, and then write a second value y to the same address, then no thread will ever read the value y after reading the x value. Because the two writes are to the same address, it would violate causal consistency if not all threads observed the same order.
But this says nothing about what should happen to unrelated events. The result of writing a third value to a different memory address could be observed at absolutely any time by other threads (so different threads may observe events in a different order, unlike under sequential consistency)
There are plenty other such levels of "consistency", some stronger, some weaker, and offering all sorts of subtle guarantees about what you can rely on.
Fundamentally, a stronger memory model is going to offer more guarantees about the order in which events are observed, and will normally guarantee behavior closer to what you'd intuitively expect.
But a weaker model allows more room for optimization, and especially, it scales better with more cores (because less synchronization is required)
Sequential consistency is basically free on a single-core CPU, is doable on a quad-core, but would be prohibitively expensive on a 32-core system, or a system with 4 physical CPUs. Or a shared-memory system between multiple physical machines.
The more cores you have, and the further apart they are, the harder it is to ensure that they all observe events in the same order. So compromises are made, and you settle for a weaker memory model which makes looser guarantees.

A: Yes, you are right - the difference between Weak and Strong memory models is a difference in what optimizations are available (order of reads/write and related fences).

You can specify a memory model by starting with a sequentially consistent model (the most restrictive, or strongest model), and then specify how reads and writes from a single thread can be introduced, removed, or moved with respect to one another
In this model (sequentially consistent) the memory is independent of any of the processors (threads) that use it. The memory is connected to each of the threads by a controller that feeds read and write requests from each thread. The reads and writes from a single thread reach memory in exactly the order specified by the thread, but they might be interleaved with reads and writes from other threads in an unspecified way

Understand the Impact of Low-Lock Techniques in Multithreaded Apps
However there's no exact bound between strong and weak memory models, unless you consider sequentilly consistent model vs others. Some of them are just stronger/weaker and therefore more open to optimizations by reordering than others. For example, memory model in .NET 2.0 for x86 allows a bit more optimizations that the verison in .NET 1.1 so it can be considered as a weaker model.

A:
Google turns up some interesting results (mostly science papers) on memory models, but can someone explain what is a Weak Memory Model and what is a Strong Memory Model and their relation to concurrency?

A strong memory model is one where, from the point of view of other cores, reads and writes appear to happen as they appear in the program and, in particular, in the order in which they appear in the program. This is known as sequential consistency.
A weak memory model is one where memory executions may be changed by the CPU, e.g. reordered. All practical CPU architectures allow instructions to be reordered.
Note that Herb Sutter uses "strong memory model" to mean one where atomic intrinsics are not reordered. This is not the commonly accepted definition.

A: In terms of concurrency, a memory model specifies the constraints on data accesses, and the conditions under which data written by one thread/core/processor becomes visible to another.
The terms weak and strong are somewhat ambiguous, but the basic premise is that a strong memory model places a lot of constraints on the hardware to ensure that writes by one thread/core/processor are visible to other threads/cores/processors in clearly-defined orders, whilst allowing the programmer maximum freedom of data access.
On the other hand, a weak model places very little constraints on the hardware, but instead places the responsibility of ensuring visibility in the hands of the programmer.
The strongest memory model is Sequential Consistency: all operations to all data by all processors form a single total order agreed on by all processors, which is consistent with the order of operations on each processor individually. This is essentially an interleaving of the operations of each processor.
The weakest memory model will not impose any restrictions on the order that processors see each other's writes. Different processors in the same system may see writes in different orders, and some processors may use "stale" data from their own cache for a long time after a write to the same memory address by another processor. Sometimes, whole cache lines are treated as a single unit, so a write to one variable on a cache line will cause writes from other processors to other variables on that cache line that are not yet visible to the first processor to be effectively discarded, as the stale values are written over the top when it eventually writes the cache line to memory. Under such a scheme, extreme care must be taken to ensure that data is transferred to other processors in the correct order, using explicit synchronization instructions.
For example, the Intel x86 memory model is generally considered to be on the stronger end, as there are strict rules about the order in which writes become visible to other processors, whereas the DEC Alpha and ARM processors are generally considered to have weak memory models, as writes from one processor are only required to be visible to other processors in a particular order if you explicitly put ordering instructions (memory fences or barriers) in your code.
Some systems have memory that is only accessible by particular processors. Transferring data between these processors therefore requires explicit data transfer instructions. This is the case with the Cell processors, and is often the case with GPUs as well. This can be viewed as an extreme of a weak memory model --- data is only visible to other processors if you explicitly invoke the data transfer.
Programming languages usually impose their own memory models on top of whatever is provided by the underlying processors. For example, C++0x specifies a complete set of ordering constraints ranging from completely relaxed to full sequential consistency, so you can specify in code what you require. On the other hand, Java has a very specific set of ordering constraints that must be adhered to and cannot be varied. In both cases the compiler must translate the desired constraints into the relevant instructions for the underlying processor, which may be quite involved if you request sequential consistency on a weakly ordered machine.


text:
Q: Orient OpenLayers 6 labels along longest side of a polygon I'm using OpenLayers with the EPSG 3857 Coordinate System and I want my polygon labels to be orientated along the longest side of the polygon.
The labels in OpenLayers are aligned horizontally by default but I can rotate them by passing a radian value. It goes clockwise on positive and counterclockwise on negative radian.
So I need to calculate the correct radians.
First I iterate the points of a polygon and calculate the longest side. Then I determine my vector from one point to another by subtracting the x and y values and the unit vector in the direction of the x-axis.
Now I calculate the scalar product and if it's zero then I know I have to rotate my labels by 90 degree or PI/2 for radian. This works fine I just add PI to flip the text so I can read it easier.
With if/else at the end I'm messing around to get the right angle but I'm not sure at this point because it works for the most polygons but not all of them.
What I'm missing here?
My math looks like this for each polygon:
var arrPoints = feature.getGeometry().getFlatCoordinates();

if (arrPoints.length >= 6) {

    var x = 0;
    var y = 1;

    var longestSide = 0;
    var longestSidePointFrom;
    var longestSidePointTo;

    for (var i = 4; i <= arrPoints.length; i += 2) {
        var pointFrom = [arrPoints[i - 4], arrPoints[i - 3]];
        var pointTo = [arrPoints[i - 2], arrPoints[i - 1]];

        const xDiff = arrPoints[i - 4] - arrPoints[i - 2];
        const yDiff = arrPoints[i - 3] - arrPoints[i - 1];

        var distance = Math.sqrt(xDiff * xDiff + yDiff * yDiff);

        if (distance > longestSide) {
            longestSide = distance;

            longestSidePointFrom = pointFrom;
            longestSidePointTo = pointTo;
        }
    }

    var vector = [longestSidePointFrom[x] - longestSidePointTo[x], longestSidePointFrom[y] - longestSidePointTo[y]];

    var scalarProduct = vector[x] * 1 + vector[y] * 0;

    if (scalarProduct == 0) {
        return Math.PI + (Math.PI / 2);
    } else {
        var sumA = Math.pow(vector[x], 2) + Math.pow(vector[y], 2);
        var sumB = Math.pow(1, 2) + Math.pow(0, 2);

        var cosine = scalarProduct / (Math.sqrt(sumA) * Math.sqrt(sumB));

        var radian = Math.acos(cosine);

        if (radian > (Math.PI / 2)) {
            radian = radian * -1 + (Math.PI)
        } else {
            radian = radian + 2 * Math.PI;
        }

        return radian;
    }
}

EDIT:
Here are 4 Polygons. The green line indicates the longest side. As you can see the angle for number 1 is not correct:

Here are the coordinates for the shown polygons:
1)
0: 44.7879
1: 313.8661
2: 42.1537
3: 317.1012
4: 45.4705
5: 319.8012
6: 48.1048
7: 316.5661
8: 44.7879
9: 313.8661
2)
0: 42.458
1: 311.9045
2: 39.7923
3: 315.1779
4: 42.1537
5: 317.1012
6: 44.7879
7: 313.8661
8: 42.458
9: 311.9045
3)
0: 37.2561
1: 307.6731
2: 34.5923
3: 310.9445
4: 36.9185
5: 312.8382
6: 39.5832
7: 309.5648
8: 37.2561
9: 307.6731
4)
0: 29.4927
1: 301.3244
2: 26.8156
3: 304.6124
4: 30.0662
5: 307.259
6: 32.7309
7: 303.9856
8: 29.4927
9: 301.3244
If I remove my if statements then it looks like this:

A: Using Math.atan is the easiest way to get the angle.  It is also much simpler to work which coordinates from getCoordinates() instead of flat coordinates.  https://codesandbox.io/s/great-babbage-800do?file=/main.js
The relevant code:
var vectorLayer = new VectorLayer({
  source: new VectorSource({
    features: features
  }),
  style: function (feature) {
    var arrPoints = feature.getGeometry().getCoordinates()[0];

    var sqLongestSide = 0;
    var longestSideXDiff;
    var longestSideYDiff;

    for (var i = 1; i < arrPoints.length; i++) {
      var pointFrom = arrPoints[i - 1];
      var pointTo = arrPoints[i];

      const xDiff = pointFrom[0] - pointTo[0];
      const yDiff = pointFrom[1] - pointTo[1];

      var sqDistance = xDiff * xDiff + yDiff * yDiff;

      if (sqDistance > sqLongestSide) {
        sqLongestSide = sqDistance;
        longestSideXDiff = xDiff;
        longestSideYDiff = yDiff;
      }
    }

    var radian = Math.atan(-longestSideYDiff / longestSideXDiff);
    style.getText().setText("OpenLayers");
    style.getText().setRotation(radian);
    return style;
  }
});


text:
Q: I am using odoo 8. when I install my module called Asterisk it will shows Error Odoo Warning
Error
Unable to install module "asterisk_click2dial" because an external dependency is not met: No module named Asterisk
Ok

A: This error appears when you declare Asterisk as an python external dependency in __openerp__.py but the python module is not installed or does not exist.
Please look for something like this in your __openerp__.py:
'external_dependencies': {
    'python': [
        'Asterisk',
    ],
},

Either remove this code if you don't need it, or install the Asterisk module in your server if you need it.

If you are actually talking about the OCA's asterisk_click2dial module that is available here, then what you need is to install the py-Asterisk module on your server by running:
pip install py-Asterisk
Or if you already downloaded the code from Github:
pip install -r requirements.txt
Remember to use sudo if your user does not have sufficient access rights.


text:
Q: New control button doesn't have the correct Windows ID I have a Window form application in C++.
I added a new button and linked it to a function called ChangeTitle.
But when I run the application and I press the button, it doesn't call the function.
I checked and I noticed that when I click the button and check the Window ID of the button (wmId), which I set it to be 110 (IDM_CHANGE_TITLE), it is with the value of 1.
I am not sure what is the problem, maybe it is related to the resource file?
Reproduce:
Open Visual Studio and
Create new project Visual C++ -> Windows Desktop Application.
Set it with the name WindowsProject1.
Code of WindowsProject1.cpp
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK ChangeTitle(HWND hWnd);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            // Parse the menu selections:
            switch (wmId)
            {
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            case IDM_CHANGE_TITLE:
                ChangeTitle(hWnd);
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_CREATE:
        CreateWindowW(L"button", L"Change Title",
            WS_VISIBLE | WS_CHILD,
            20, 50, 95, 25, hWnd, (HMENU)1, (HINSTANCE)ChangeTitle(hWnd), NULL);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK ChangeTitle(HWND hWnd)
{
   SetWindowText(hWnd, L"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
   return TRUE;
}

Part code of Resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by WindowsProject1.rc

#define IDM_ABOUT               104
#define IDM_CHANGE_TITLE                110

Part code of WindowsProject1.rc
IDC_WINDOWSPROJECT1 MENU
BEGIN
    BEGIN
        MENUITEM "&About ...",           IDM_ABOUT
    END
END

IDC_WINDOWSPROJECT1 ACCELERATORS
BEGIN
    "?",            IDM_ABOUT,              ASCII,  ALT
    "/",            IDM_ABOUT,              ASCII,  ALT
END

A: I solved it. The problem was that I created the button control with hMenu set to 1.
I changed it to #define IDM_CHANGE_TITLE   110 and now it works.
Here is the fixed code:
CreateWindowW(L"button", L"Change Title",
    WS_VISIBLE | WS_CHILD,
    20, 50, 95, 25, hWnd, (HMENU)IDM_CHANGE_TITLE, NULL, NULL);


text:
Q: How to dynamically loop through Key Value Pairs in powershell/azure cli I wanted to change the azure webapp settings and i was able to do it through the following powershell code. As you can see there are variables and their values, I want to dynamically call the Variables and their values and loop through it and by using the command only once. Is there a way to achieve it
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings ApplicationInsightsAgent_EXTENSION_VERSION="~2"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings APPINSIGHTS_PROFILERFEATURE_VERSION="1.0.0"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings APPINSIGHTS_SNAPSHOTFEATURE_VERSION="1.0.0"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings XDT_MicrosoftApplicationInsights_BaseExtensions="disabled"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings XDT_MicrosoftApplicationInsights_Mode="recommended"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings DiagnosticServices_EXTENSION_VERSION="~3"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings SnapshotDebugger_EXTENSION_VERSION="disabled"
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings InstrumentationEngine_EXTENSION_VERSION="disabled"

A: *

*The az CLI accepts multiple key-value pairs as arguments to its  --settings parameter.

*PowerShell lets you pass the elements of an array as individual arguments to an external program (such as the az CLI).
# Define the settings as an array of key-value pairs
# as strings in format
#   "<key>=<value"
# Use variable references inside the expandable strings ("...") as needed.
$settings =
  "ApplicationInsightsAgent_EXTENSION_VERSION=~2",
  "APPINSIGHTS_PROFILERFEATURE_VERSION=1.0.0",
  "APPINSIGHTS_SNAPSHOTFEATURE_VERSION=1.0.0",
  "XDT_MicrosoftApplicationInsights_BaseExtensions=disabled",
  "XDT_MicrosoftApplicationInsights_Mode=recommended",
  "DiagnosticServices_EXTENSION_VERSION=~3",
  "SnapshotDebugger_EXTENSION_VERSION=disabled",
  "InstrumentationEngine_EXTENSION_VERSION=disabled"

# Pass the array to --settings-names
az webapp config appsettings set -g $resourceGroup -n $webAppName --settings $settings

Caveat: CLI az is implemented as az.cmd, i.e. a batch file (which calls Python), so arguments passed to it may require escaping to satisfy cmd.exe's syntax requirements.

A: simplest way of doing this with powershell + az cli:
'ApplicationInsightsAgent_EXTENSION_VERSION="~2"',xxx,'InstrumentationEngine_EXTENSION_VERSION="disabled"' | Foreach-Object {
    az webapp config appsettings set -g $resourceGroup -n $webAppName --settings $_
}

you can also achieve the same without powershell with xargs


text:
Q: "Recent values to use" in Toloka quality control Can the "Recent values to use" for control tasks be set to a larger value than the current pool size to include older pools?

A: Yes, you can put a larger value than the current pool size. The rule will be spread to the other pools where you indicate "recent values to use" for control tasks. To make a calculation based on control task responses from all project pools, fill in the field in the rule for each pool.
In other words, image you have 3 pools. In each pool you have control tasks rule. In 1st and 3rd pool you set "Recent values to use" = 10. In the 2nd pool you did not indicate any values for "Recent values to use". So the performer's "control tasks history" will include only 1st and 3rd pools.


text:
Q: Symfony3 forms not showing input fields when using CollectionType I'm having problem with displaying form when using CollectionType. It doesn't show newOrderCustomerType inputs, just label "Customer Id". Whats wrong?

newOrderCustomerType
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class newOrderCustomerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
        add('firstname', TextType::class,array('label'=>'Firstname'))->
        add('lastname', TextType::class,array('label'=>'Lastname'))->
        add('email', TextType::class,array('label'=>'Email'))->
        add('login', TextType::class,array('label'=>'Login'));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Customer',
        ));
    }

    public function getName()
    {
        return 'app_bundlenew_order_customer_type';
    }
}

newOrderType
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class newOrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('customerId',CollectionType::class,array(
                'entry_type'=>newOrderCustomerType::class,
                'allow_add'    => true,
                'by_reference' => false,
                'data_class' => 'AppBundle\Entity\Customer',
            ))
            ->add('shopOrderId')
            ->add('orderDate')
            ->add('postBuyFormMsg')
            ->add('invoice')
            ->add('payType')
            ->add('shipmentType')
            ->add('payStatus')
            ->add('save',SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {

    }

    public function getName()
    {
        return 'app_bundlenew_order_type';
    }
}

And in TWIG template
{{ form_start(orderForm) }}
    {{ form_widget(orderForm) }}
{{ form_end(orderForm) }}

How to make it show all input fields?

A: If you have an active "allow_add" option, it is possible to render this input throught the 'prototype' option:
 $builder
        ->add('customerId',CollectionType::class,array(
            'entry_type'=>newOrderCustomerType::class,
            'allow_add'    => true,
            'by_reference' => false,
            'data_class' => 'AppBundle\Entity\Customer',
            'prototype'     => true,
        ))

and then in the form:
{{ form_row(orderForm.customerId.vars.prototype}) }}

It should work.
For more, see the Symfony documentation of prototype option

A: Try removing 'data_class', I don't think that's part of CollectionType:
->add('customerId',CollectionType::class,array(
     'entry_type'=>newOrderCustomerType::class,
     'allow_add'    => true,
     'by_reference' => false,
))

See if that works.


text:
Q: Epplus add one value over a range How can I add one text value of a range of cells?  Currently, I have the following code snippet:
ExcelRange oRngheader1 = oSheet.Cells["A2:B2"];
oSheet.Cells["A2:B2"].Value= "Division Budgets";

Which places the value 'Division Budgets' in both cell A2 and Cell B2; however, I wish this value to span both A2 to B2.

A: ExcelRange oRngheader1 = oSheet.Cells["A2:B2"];
oSheet.Cells["A2"].Value= "Division Budgets";
oRngheader1.Merge = true;

It's important to put the value in the top-left-most cell to ensure that it's not lost when you merge.


text:
Q: Highcharts loaded via ajax, issue to dynamically create yAxis I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>

        <form method="post" action="">
            <select id="f" name="f[]" multiple>
                <option value="rss1" select>1RSS(dB)</option>
                <option value="rss2">2RSS(dB)</option>
                <option value="rqly">RQly(%)</option>
                <option value="rsnr">RSNR(dB)</option>
            </select>
        </form>

No selection

Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();

// Include config file
require_once "config.php";

$jsonObject = array();
$yaxis = 0;

foreach($_POST["f"] as $v) {

    $data = array();
    $sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
    $result = $link->query($sql);

    while($row = $result->fetch_row()) {
        $data[] = $row[0];
    }

    $jsonObject[] = array(
            "name" => $v,
            "data" => $data,
            "yAxis"=>$yaxis
        );
    $yaxis++;
}

$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;

// Close connection
mysqli_close($link);
?>

When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
    at Object.a.error (highcharts.src.js:498)
    at highcharts.src.js:32669
    at Array.forEach (<anonymous>)
    at r.<anonymous> (highcharts.src.js:32621)
    at a.fireEvent (highcharts.src.js:2635)
    at r.bindAxes (highcharts.src.js:32618)
    at r.init (highcharts.src.js:32482)
    at a.Chart.initSeries (highcharts.src.js:26913)
    at highcharts.src.js:28765
    at Array.forEach (<anonymous>)

I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.

A: I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
    var updateChart = function(json) {
        //console.log(json)
        var options = {
            chart: {
                renderTo: 'graph',
                type: 'line',
                zoomType: 'x'
            },
            title: { text: null },
            yAxis:[],
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'bottom'
            },
            plotOptions: {
                series: {
                    label: {
                        connectorAllowed: false
                    },
                    pointStart: 0
                }
            },
            series: [],
            tooltip: { shared: true }
        }

        var chart = new Highcharts.Chart(options);

        // update axis and series
        for (i=0; i<json.length; i++) {
            // add axis
            chart.addAxis({ title: { text: json[i].name } });

            // add serie
            var a = chart.series.length;
            var seriesOptions = {
                name: json[i].name,
                data: json[i].data,
                yAxis: a
            }
            chart.addSeries(seriesOptions,true);
            chart.options.series.push(seriesOptions);
        }
    }

    $(document).ready(function() {
        $('#f').change(function() {
            var requestParams = { f: $('#f').val() };
            $.post('analysisajax.php', requestParams, updateChart);
            //return false;
        });
    });


text:
Q: How to call multiple arrays from a function in PHP 5.6? I have a php file, say A.php, where I have defined a function log_campaign_activity, which is returning 2-arrays, as shown below:
function log_campaign_activity($identifier, $activity, $update=true, $clicked_url_key=null) {

$return_array = array();

$db = DBManagerFactory::getInstance();

 //check to see if the identifier has been replaced with Banner string
if($identifier == 'BANNER' && isset($clicked_url_key)  && !empty($clicked_url_key))
{
    // create md5 encrypted string using the client ip, this will be used for tracker id purposes
    $enc_id = 'BNR'.md5($_SERVER['REMOTE_ADDR']);

    //default the identifier to ip address
    $identifier = $enc_id;

    //if user has chosen to not use this mode of id generation, then replace identifier with plain guid.
    //difference is that guid will generate a new campaign log for EACH CLICK!!
    //encrypted generation will generate 1 campaign log and update the hit counter for each click
    if(isset($sugar_config['campaign_banner_id_generation'])  && $sugar_config['campaign_banner_id_generation'] != 'md5'){
        $identifier = create_guid();
    }

    //retrieve campaign log.
    $trkr_query = "select * from campaign_log where target_tracker_key='$identifier' and related_id = '$clicked_url_key'";
    $current_trkr=$db->query($trkr_query);
    $row=$db->fetchByAssoc($current_trkr);

    //if campaign log is not retrieved (this is a new ip address or we have chosen to create
    //unique entries for each click
    if($row==null  || empty($row)){

            //retrieve campaign id
            $trkr_query = "select ct.campaign_id from campaign_trkrs ct, campaigns c where c.id = ct.campaign_id and ct.id = '$clicked_url_key'";
            $current_trkr=$db->query($trkr_query);
            $row=$db->fetchByAssoc($current_trkr);

            //create new campaign log with minimal info.  Note that we are creating new unique id
            //as target id, since we do not link banner/web campaigns to any users

            $data['target_id']="'" . create_guid() . "'";
            $data['target_type']= "'Prospects'";
            $data['id']="'" . create_guid() . "'";
            $data['campaign_id']="'" . $row['campaign_id'] . "'";
            $data['target_tracker_key']="'" . $identifier . "'";
            $data['activity_type']="'" .  $activity . "'";
            $data['activity_date']="'" . TimeDate::getInstance()->nowDb() . "'";
            $data['hits']=1;
            $data['deleted']=0;
            if (!empty($clicked_url_key)) {
                $data['related_id']="'".$clicked_url_key."'";
                $data['related_type']="'".'CampaignTrackers'."'";
            }

            //values for return array..
            $return_array['target_id']=$data['target_id'];
            $return_array['target_type']=$data['target_type'];

            //create insert query for new campaign log
            $insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")";
            $insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")";
            $db->query($insert_query);
        }else{

            //campaign log already exists, so just set the return array and update hits column
            $return_array['target_id']= $row['target_id'];
            $return_array['target_type']= $row['target_type'];
            $query1="update campaign_log set hits=hits+1 where id='{$row['id']}'";
            $current=$db->query($query1);

       }

    //return array and exit
    return $return_array;

}

You can observe that in the end, it is returning 2-arrays:

*

*$return_array['target_id']= $row['target_id'];

*$return_array['target_type']= $row['target_type'];

I want to call this function and store these values in 2-variables of another php-file, say B.php:

*

*$targetID

*$targetType

How can I do this? What is better method?
With thanks,
RK

A: In B.php
//Require A.php, so you can call your function
require_once("A.php");

//Call your function with needed parameters
$result = log_campaign_activity($param1, $param2, $param3...);

//Save result into vars
$targetID = $result["target_id"];
$targetType = $result["target_type"];


text:
Q: Any smartform control that lets me select Page Layouts? In the smart form controls, my choices are link selector and resource selector. The link will only allow me to enter one by hand or select from the library. The resource selector only allows me to select content blocks, but page layout pages are not listed.
Is there any smart form control that will let me select a page layout page?
Thanks all

A: You could make the page layout a template and then make it the template for the smart form. The other option is reverse the link, and use a resource selector on the page layout to link to the smart form (assuming that your relationships are 1 to 1).

A: Bill Cava came up with the answer over at Ektron. There is a filter in the render that needs to be modified.
http://developer.ektron.com/Forums/?v=t&t=880


text:
Q: Recursively add digits in Java BigInteger Below is what I have so far but compiler states method needs to return BigInteger.
private static BigInteger recSum(BigInteger val, BigInteger moddiv, BigInteger result){
    if(moddiv.compareTo(val) == 1){
        return result;
    }else{
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
    }
}

I'm basically looking to pass an argument to this method through val and find the sum of all the digits of that number. Just for practice it seemed recursion could work here, opposed to say converting it to a string and parsing out each character to a value and adding.
Basically if starting with 1524, 1+5+2+4
Writing it out I figured it looked like this:
(1524%10)+([1524-(1524%10)]%100)+([1524-([1524-(1524%10)]%100)]%1000)...
Writing it out like that I see my current code will stop short, but also there is something missing regardless.
Oh and I guess if my code would work it would probably do something like
1000+500+20+4
I could easily rearrange things and divide by the moddiv before incrementing it to the next power. The thing is at some point it isn't returning a BigInteger.
Any advice?

A: Your function has no return statement is the else clause. You should return result there too.
Or better yet, rearrange your code to have a single return statement :
private static BigInteger recSum (BigInteger val, BigInteger moddiv, BigInteger result)
{
    if (moddiv.compareTo(val) != 1){
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
    }

    return result;
}

A: You forgot the return statement:
private static BigInteger recSum(BigInteger val, BigInteger moddiv, BigInteger result){
    if(moddiv.compareTo(val) == 1){
        return result;
    }else{
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
        return result; // <-- need return statement here
    }
}


text:
Q: browser local storage, tied to the domain AND that only live as long as the browser window Does browser local storage with the following characteristics exists :

*

*lives only as long as the browser window

*is tied to the domain (JS code from other domains cannot access it), OR is erased when the page reloads with a URL from another domain

*is stored only in RAM (not on the disk)

*is not sent to the server (excludes cookies)
I beleive the answer is no, but I'd like to be surprised !
storing data in window.name comes close, but does not satisfy (2)

A: I think you say sessionStorage, let see what developer.mozilla.org says:

The sessionStorage property allows you to access a session Storage
  object. sessionStorage is similar to localStorage, the only difference
  is while data stored in localStorage has no expiration set, data
  stored in sessionStorage gets cleared when the page session ends. A
  page session lasts for as long as the browser is open and survives
  over page reloads and restores. Opening a page in a new tab or window
  will cause a new session to be initiated, which differs from how
  session cookies work.

Then, there is an example too:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');

If you close the browser or change the domain, the sessionStorage item is erased.


text:
Q: Reuse nested loops without copy and paste Suppose I've this nested loop
for (int a=1; a<MAX_A; ++a)
  for (int b=1; b<MAX_B; ++b)
    for (int c=1; c<MAX_C; ++c)
    {
       do_something(a, b ,c);
    }

and I reuse this loop in various part of my code, changing the function do_something. It's quite boring to rewrite every time the first three lines. In python for example I would created a generator to return an iterator (1, 1, 1), (1, 1, 2), ... or something like itertools.product.
In c++ the only solution I've in mind is to define a macro. Something better?e

A: Make a helper loop function:
template<typename Work>
void loop(Work work) {
  for (int a=1; a<MAX_A; ++a)
    for (int b=1; b<MAX_B; ++b)
      for (int c=1; c<MAX_C; ++c)
      {
        work(a, b ,c);
      }
}

Define the work to be done:
void some_work(int a, int b, int c) {
}

Then use:
loop(some_work);

Note that now you don't need to use only function, but you can use a function object (object for which an operator() is overloaded).

A: Use templates:
template<typename Func>
inline void do_something_loop(Func f)
{
    for (int a=1; a<MAX_A; ++a)
      for (int b=1; b<MAX_B; ++b)
        for (int c=1; c<MAX_C; ++c)
        {
           f(a, b ,c);
        }
}

This can be called with any function pointer or function object that matches the signature, e.g.:
void do_something(int a, int b, int c) { /* stuff */ }

do_something_loop(do_something);

Or with a function object:
struct do_something
{
    void operator()(int a, int b, int c) { /* stuff */ }
};

do_something_loop(do_something());

Or if your compiler supports C++11, even with a lambda:
do_something_loop([](int a, int b, int c) { /* stuff */ });

Note that you could also declare the f parameter as a function pointer with the signature void(*f)(int,int,int) instead of using a template, but that's less flexible (it won't work on function objects (including the result of std::bind) or lambdas).


text:
Q: eBay API: how to use outputSelector in HTTP get request I'm using URLs like this in my application
http://svcs.ebay.com/services/search/FindingService/v1
?OPERATION-NAME=findItemsAdvanced
&SERVICE-VERSION=1.0.0
&SECURITY-APPNAME=MYAPPID
&RESPONSE-DATA-FORMAT=XML
&REST-PAYLOAD&GLOBAL-ID=EBAY-IT
&categoryId=CATEGORYID
&descriptionSearch=true
&keywords=KEYWORDS

I get the XML response, but I need more fields using outputSelector.
But I don't understand how to use it in my request.
I tried to add a field like
&outputSelector=searchResult.item.listingInfo.buyItNowAvailable, but it doesn't add anything to the response.

A: Got it!

outputSelector only has few fields, itemFilter workes instead.
&itemFilter.name=ListingType
&itemFilter.value=AuctionWithBIN
http://developer.ebay.com/Devzone/finding/CallRef/extra/fndItmsAdvncdRqst.tmFltr.nm.html

A: Also be sure to set your SERVICE-VERSION to be current. Usually it doesn't make a difference, but I've seen cases where it did. Change it to 1.12.0 and you're set. (Actually 1.11.0 may be better -- sometimes when it's TOO new there are quirks, believe it or not.)


text:
Q: Codeigniter site_url Начал осваивать codeigniter по туториалу, подскажите в чем проблема, код вьюхи:
<a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article

Генерирую url для ссылки, он получается верный, функция site_url как и положено ей возвратит sitename.ru/index.php/news/slug1. В ссылке же, href равен sitename.ru/index.php/sitename.ru/index.php/news/slug1. Само собой такого роута у меня нет

A: Чтобы функция site_url() работала корректно, нужно задать бэйс_урл в конфиг файле application/config/config.php
$config['base_url'] = 'http://твой-хост/';
Там же, чуть ниже, можно выкинуть index.php из УРЛа:
$config['index_page'] = '';

A: Я site_url не использую пишу просто
<a href="news/<?= $news_item['slug']; ?>">View article


text:
Q: Why the same Access Token works for Media but doesn't work for Feed? I'm using InstaSharp to get all medias from my account. This code works without any error:
 var user = new InstaSharp.Endpoints.Media.Authenticated(config, authInfo);
 var media = user.Popular();

Now if I do the same with Users:
var user = new InstaSharp.Endpoints.Users.Authenticated(config, authInfo);
var feed = user.Feed("self");

This returns:

OAuthParameterException: The access_token provided is invalid.

Why the same access token works in one place but doesn't work in another?

Note: I'm passing all scopes (basic, comments, likes, relationships) while getting the access token.I have also tried with default (basic) and it didn't work either.
Note2: Since I'm trying this in a ConsoleApplication, the way I'm getting the access token is, generate the link, copy/paste to the browser, confirm the authorization and get it from url. I'm not sure it makes any difference but it's worth noting...

A: I figure out the problem. It seems that the generated link was requesting code, not access_token.So that's why it was invalid.
And I realized that I was using older version of InstaSharp even though I downloaded it from it's website. First, I installed the latest version via NuGet. Then, I get the access token and the media like this:
var config = new InstagramConfig(clientId, clientSecret);
var AuthLink = OAuth.AuthLink(config.OAuthUri + "/authorize",
                              config.ClientId,
                              config.RedirectUri,
                              scopes,
                              OAuth.ResponseType.Code);

var authInfo = new OAuth(config);

// get the code from the link then pass it to RequestToken
var response = await authInfo.RequestToken(code);
var user = new Users(config, response);
var media = await user.RecentSelf(count: 30);

And all worked very well.


text:
Q: Set custom header when using res.render I'm using express.js's res.render function and I met some issue to set custom headers, I'm tried 4 kind of method and all failed
here is my code
Method 1
app.get('/login', function(req, res, next) {
  res.writeHead(200, {'Content-Type':'text/plain; charset=utf-8'});
  next()
});

app.get('/login', function(req, res) {
  res.locals.text="hello";
  res.render('index');
});

It has a error log with this code: Error: Can't set headers after they are sent.

Method 2 (example from here)
app.get('/login', function(req, res, next) {
  res.header(200, {'Content-Type':'text/plain; charset=utf-8'});
  next()
});

app.get('/login', function(req, res) {
  res.locals.text="hello";
  res.render('index');
});

the code comes with the error: TypeError: field.toLowerCase is not a function

Method 3
app.get('/login', function(req, res) {
  res.writeHead(200, {'Content-Type': 'application/xhtml+xml; charset=utf-8'});
  res.locals.text="hello";
  res.render('index');
});

the code also has error: Error: Can't set headers after they are sent.

That's all the ways I can thought and find but still can't resolve, is there any ways to set custom header (especially encoding type) with res.render?

A: To set custom response header with res.render, you can use res.set(). Here is an example code:
app.get('/login', function(req, res) {
  res.set({'Content-Type': 'application/xhtml+xml; charset=utf-8'});
  res.locals.text="hello";
  res.render('index');
});

Please check Express document for more details about res.set()

A: If you want to set an header for your response, you can use setHeader method on http.ServerResponse object.
var server = require('http').createServer(function(req, res) {
    res.setHeader('content-type', 'application/json');
    res.write(headerStr);
    res.end();
});