text:
Q: SQL Server 2008 R2 Mirroring issues I have this very frustrating problem that I've been trying to figure out for almost a week now. I have two SQL Server 2008 R2 STD w/SP3 box running on Windows 2012 R2 with two instances each, Server1 is the PRIMARY and Server2 is the MIRROR. Server2 was purchased for the purpose of mirroring so no live DBs yet. But Server1 is already in production. So here's the complete detailed setup for both.
Created a domain\user account and used it for both Servers' SQLService
Principal Server Configuration

*

*Name: SERVER1.domain.com

*NIC1 : 172.xx.xx.80

*NIC2 : 172.xx.xx.81 (use for mirroring)

*Named Instances: INSTANCE1 and INSTANCE2

Mirror Server Configuration

*

*Name: SERVER2.domain.com

*NIC1 : 172.xx.xx.82

*NIC2 : 172.xx.xx.83 (use for mirroring)

*Named Instances: INSTANCE1 and INSTANCE2

NO WITNESS YET
Static A records in DNS server
172.xx.xx.81 dbm-pri.domain.com and 172.xx.xx.83 dbm-mir.domain.com
Here's what's done on both servers:

*

*checked SQL Server Config Manager and made sure TCP is enabled, then added the ports to be used in IPAll field

*restarted the SQL Service (at one point of despair I restarted the servers itself, yes even the one running on production)

*run netstat and confirmed that the endpoint ports are LISTENING, (sqlserver.exe), also run ping and tracert all tests are good

*from both PRINCIPAL and MIRROR, ran telnet FQDN port, confirmed that I can connect from/to both

*created the endpoints on both servers
PRINCIPAL
    CREATE ENDPOINT INSTANCE1_EndPoint
       STATE=STARTED
       AS TCP (LISTENER_PORT=6025,LISTENER_IP=(172.xx.xx.81))
       FOR DATABASE_MIRRORING (ROLE=PARTNER)

MIRROR
    CREATE ENDPOINT INSTANCE1_EndPoint
       STATE=STARTED
       AS TCP (LISTENER_PORT=6025,LISTENER_IP=(172.xx.xx.83))
       FOR DATABASE_MIRRORING (ROLE=PARTNER)

*granted CONNECT permission to the domain\user account
CREATE LOGIN [domain\user]
FROM WINDOWS
WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO

GRANT CONNECT on ENDPOINT::INSTANCE1_EndPoint TO [domain\user]
GO

*backed up and restored the DB and logs with NO RECOVERY

*ran alter db set partner on the mirror server
ALTER DATABASE DBName SET PARTNER = 'TCP://dbm-pri.domain.com:6025'

*ran alter db set partner on principal server
ALTER DATABASE DBName SET PARTNER = 'TCP://dbm-mir.domain.com:6025'

Error:

Msg 1418, Level 16, State 1, Line 1
  The server network address "TCP://dbm-mir.domain.com:6025" can not be reached or does not exist...

*tested netstat, ping, tracert and telnet on both Servers, all are successful
I've tried re doing this so many times now and I'm lost for ideas

A: Have you tried using an IP address?  I have seen an issue in R2 in the past whereby SQL Server was unable to resolve an FQDN but was fine with an IP address.

A: You may have already attempted this, but I must ask:  Have you attempted to initialize mirroring via the SSMS GUI?
In SSMS on principle server, right-click database --> Mirror --> Configure Security.
I'm curious if the same error message is generated from the GUI.  Can you establish a connection to your mirror server from the principle server via SSMS?

A: Sometime before even I faced the same issue while configuring database mirroring.
Generally SQL Server Database Mirroring Error 1418 occurs due to connection problem between endpoints.
Below checks can be followed in order to fix this issue:

*

*Check TCP/IP port and ensure that it is enabled for both instances.

*Ensure that the system Firewall is not blocking the SQL Server port.

*Ensure that Database Mirroring endpoints/ports are used only by database mirroring process. If another process is listening on the port assigned to database mirroring endpoints, the database mirroring processes cannot communicate with each other.

*Finally check the SQL Server Accounts used to run the SQL Server Service.

*Ensure that the same SQL Server Accounts are used in both instances involved in the database mirroring.

*It is recommended that we use domain accounts for all partners.

*

*Open the SQL Server Configuration Manager or Services.msc

*And ensure that the SQL Server and SQL Server Agent's services are running with the
same credentials.

*Check the credentials used in the mirror database server.

*Ensure that the credentials used in the mirror database server are exactly similar to the principal server.

*If the user is not created then create a new one on the both servers with same credentials.

*Once the user is created on the servers> Login to the principal server > open SQL Server instance and add the new login under Security and map the user with the SQL Login. 7. Once the server user is mapped with the SQL instance; assign Sysadmin role to that login on the SQL Server.

*Follow the step 7 on the mirror server as well.

After all these checks the error 1418 must be resolved.

A: It could be a possibility port number 6025 might be used by another application try changing the port number .

A: I also had the same problem while implementing mirroring to one of my customers, the problem was SQL server Service account for both instances must be a domain name. Once again confirm that.
And try this too.
GRANT CONNECT ON ENDPOINT::Mirroring TO ALL


text:
Q: ES6 Promise then follows catch but catch never gets called I have a question about this Promise code. Why "Foo" is logged? I am confused since 'then' is following 'catch', and 'catch' is never called, why execution flows into 'then'?

let myPromise = new Promise((resolve, reject) => {
  resolve("Foo");
});

myPromise.catch((value) => {
  console.log('inside catch');
}).then((value) => {
  console.log(value);
});

A: Please read the documentation of Promise.
And catch will only be called if the promise is rejected.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
As a side note, and not related to the question:
In most written code then usually comes before catch, although it doesn't have to be.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my username/hostname in the SSH public key? When generating a SSH key i used the cat command on the file id_rsa.pub and noticed the hostname/username of my account was within the file. Why is this there? If I was copying this onto a server wouldn't it make sense for this to not be here or be the hostname/username of the server? And the username to use with SSH? Am I going all about this wrong? My process is this:
mkdir ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
ssh-keygen

And then I write the generated id_rsa.pub to authorized_keys
I finish up by copying over the key to the server.

A: The last field in the ssh public key is a comment. By default it's initialized with the user@host value when the key was generated as a reminder. You can choose to edit it, it won't alter the key. This comment doesn't affect any authentication, it's only here to help manage multiple entries.
The location of the public key on the remote server is what affects it: it will allow access to the account where it was put inside its ~/.ssh/authorized_keys file. Only owning the private key will allow access to the remote account. There's no concept of which user access the account from the point of view of the server: the only relevant thing is that the SSH connection can be successfully established (using ssh key) only from an entity having the private key. If this private key was copied elsewhere (or stolen) it wouldn't make a difference. If you need access by ssh key from different users and/or systems to this account, don't copy the private key, just generate one per different location and add it to the authorized_keys file, it's better security hygiene.
Your method looks fine (you might also have to chmod 700 ~/.ssh) , but if you also have usual password access to the remote account, the easiest way to copy the ssh key is with the ssh-copy-id command. For example to copy the default key to the remoteuser account on remoteserver:
ssh-copy-id remoteuser@remoteserver

which will automatically add the key to the remote account's authorized_keys file (creating it with correct access rights if not existing).


text:
Q: C# - better ways to validate if a string is a number other than int.TryParse()? I find myself often needing to use int.TryParse() to test if a value is an integer. However, when using TryParse, I have to pass a reference variable to the function. So I find myself always needing to create a temp int to be passed in. Usually it looks something like:
int my_temp_integer;
int.TryParse(potential_integer, my_temp_integer);
I find this to be quite cumbersome considering that all I want is a simple true/false response, and I don't care about the actual parsed result. Is there a better way to approach this? Why isn't there an overloaded function where I can just pass the value I want to test and get a true/false response?
Thanks.

A: you could write an extension method:
public static bool IsInt(this string pString)
{
   int value;
   return int.TryParse(pString, out value);
}

then your example becomes:
potential_integer.IsInt();

EDIT:
Lately I have been using a generic form of this.
public delegate bool TryParser<T>(string pString, out T pResult);

public static bool Is<T>(this string pString, TryParser<T> pTryParser)
{
   T val;
   return pTryParser(pString, out val);
}

Can then use it as follows; it's not perfect, but it's more concise than anything I've found:
"1234".Is<int>(int.TryParse);       // true
"asdf123".Is<int>(int.TryParse);    // false
"1.2345".Is<float>(float.TryParse); // true
"1000".Is<byte>(byte.TryParse);     // false

Theoretically, this would also work with custom TryParse methods, as long as you followed the same pattern as the official ones.
Update: If you maintain a static dictionary of TryParse methods by type, you can avoid having to ever directly pass the method. The dictionary can even be populated as needed with reflection.

A: A simple solution is to create an extension method.
public static class StringExtensions {
    public static bool IsInt(this string s) {
        int i;  return Int.TryParse(s, out i);
    }
}

Then you just use it as so:
 string s = "123";

 if (s.IsInt())
     // do something.

A: if you don't want to actually convert the string, only test it, then you can use Regex
something kinda like this (you may need to adjust this to fit your needs):
public bool IsInt(this string inputData)
{
    Regex isNumber = new Regex(@"^\d+$");
    Match m = isNumber.Match(inputData);

    return m.Success;
}

A: You could use
bool isInt = str.TrimEnd( new char[]  {'0','1','2','3','4','5','6','7','8','9'})
                .Length == 0;

A: A shorter alternative to  Muad'Dib above:
bool IsInt(string input)
{
    return new System.Text.RegularExpressions.Regex(@"^\d$").IsMatch(input);
}

/Hans


text:
Q: How can I impersonate a GCP service account for web console access? I want a feature similar to AWS's role switching. In AWS I can switch to a role in the AWS web console- impersonating a "service account" for accessing AWS via the website.
Gcloud has support for impersonating service accounts, but I cannot find examples for how to impersonate a service account for web console access.
There are some users which occasionally require access to production gcp projects. It's more convenient for them to use the web console then the cli sometimes. I don't want to give their user accounts direct access to production, I want to follow best practices and require elevation of privileges. I don't want to create new, additional, user accounts for them for production access either.
In Gcloud it's easy to impersonate a service account, but is this supported for web console access?

A: The service accounts can be impersonated to access the projects resources using gcloud CLI, but they can't be used to access the resources of the project using the console because service accounts are strictly non-human accounts. They are intended for scenarios where your application needs to access resources or perform actions on its own.
If you want to provide access to your users to the web console, configure user accounts:

User accounts are managed as Google Accounts, and they represent a
developer, administrator, or any other person who interacts with
Google Cloud. They are intended for scenarios where your application
needs to access resources on behalf of a human user.

When an application needs to access Google Cloud APIs on behalf of an end
user, the application initiates an OAuth consent flow. After the user
completes the flow, your application receives an access token that
enables your application to call Google Cloud APIs on behalf of the
user.

Here you can find guides about signing in users on the web, using identity platform.
And here you will find more information about using OAuth 2.0 to access Google APIs

A: For Google Cloud, one technique that I implement is groups. Each group has a set of roles. When users require access to cloud resources, they go to a backend app to request access. The backend app attaches their identity to the required group for a period of time and automatically removes the identity.
This concept can be extended to allow the user to select additional IAM roles which the backend app adds to the project's IAM binding with automatic removal. Uses can also click an "I am done" button to have their elevated roles removed.
This does require development but is relatively minor to implement. Users now know that their elevated access is monitored/tracked and with good training only use it when actually required.


text:
Q: How to check when sequence repeats in JavaScript? I am generating a sequence by combining musical rhythms.

Basically, the green is the sound, and the purple is the absence of sound. It moves around the wheel. At each point in the wheel I draw a number (or letter) symbolizing the position of the rotation of the wheel.
Given that I am constructing an array at each step of the beat (where each item in the array is 3 digits), how do I tell once the combination/rhythm fully repeats in the combination of these beats?
That is to say, I want to find when the combination of 3 and 4 (beats 1 and 2 in the visual) repeat, and when 3 and 5 repeat, 4 and 5 repeat, and 3, 4, and 5 together all repeat.
I would like to stop the array from growing once the beat repeats.
Perhaps we can precompute everything so we know when it repeats, but even then, how can it be accomplished, given that we don't necessarily know mentally when it repeats?
I would like to extend this to arbitrary "beats" and alphabets. And doing it differently so that say for example purple = 0 and green = 1, and we draw 101, 111, etc.
I guess there's two questions there. So the first question for this post is, how do I tell when a sequence like the above (rendering the index of each) repeats? Without using fancy math such as telling what the common factor is of these and going from there. As that won't work for other sequences. Basically I just want to know when you can tell the overall "final" sequence repeats.
Here is an example of the code copied/modified to demonstrate how to generate sequences. You can go from there in removing the string output or using the generated data as input for some algorithm.

const alphabet = `abcdefghijklmnopqrstuvwxyz`.split('')

const baseDrum = {
  rhythm: [1, 0, 0],
  position: 2,
}

const hiHat = {
  rhythm: [1, 2, 2, 2],
  position: 3,
}

const flute = {
  rhythm: [1, 0, 1, 0, 0],
  position: 4,
}

const instruments = [flute, baseDrum, hiHat]

const update = () => {
  instruments.forEach(instrument => {
    if (instrument.position == instrument.rhythm.length - 1) {
      instrument.position = 0
    } else {
      instrument.position++
    }
  })
}

const sequence1 = []
const sequence2 = []
const sequence3 = []
const sequence4 = []
const sequence5 = []

function generate() {
  const numbers = [
    baseDrum.position + 1,
    hiHat.position + 1,
    flute.position + 1,
  ]

  const playNumbers = [
    baseDrum.rhythm[baseDrum.position],
    hiHat.rhythm[hiHat.position] - 1,
    flute.rhythm[flute.position],
  ]

  const lettersString = numbers.map(x => alphabet[x]).join('')
  const numbersString = numbers.join('')

  const playNumbersDigit = parseInt(playNumbers.join(''), 2)
  const playLettersString = alphabet[playNumbersDigit]
  const playNumbersString = playNumbers.join('')

  sequence1.push(lettersString)
  sequence2.push(numbersString)
  sequence3.push(playNumbersDigit)
  sequence4.push(playLettersString)
  sequence5.push(playNumbersString)
}

let i = 0

while (i++ < 100) {
  update()
  generate()
}

console.log(JSON.stringify({ sequence1, sequence2, sequence3, sequence4, sequence5 }, null, 2))

A: A barebones string finder is one option:
let out = JSON.stringify(output),
output = JSON.parse(out
          .substr(0, out
            .indexOf(
              JSON.stringify(output[0]),2
            )-1) + "]"
         );

which folds into a zippy little one-liner:
output = JSON.parse(out.substr(0,out.indexOf(JSON.stringify(output[0]),2)-1)+"]") ;

A less efficient loop version is included as an alternate. We just loop through each item, turn it into a string, test to see if we've encountered it before and if not store it. Once we find the repeat, we stop.

const output = [{
    "lettersString": "bbb",
    "numbersString": "111",
    "playNumbersDigit": 5,
    "playLettersString": "f",
    "playNumbersString": "101"
  },
  {
    "lettersString": "ccc",
    "numbersString": "222",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ddd",
    "numbersString": "333",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bee",
    "numbersString": "144",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cbf",
    "numbersString": "215",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcb",
    "numbersString": "321",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bdc",
    "numbersString": "132",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "ced",
    "numbersString": "243",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dbe",
    "numbersString": "314",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "bcf",
    "numbersString": "125",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdb",
    "numbersString": "231",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dec",
    "numbersString": "342",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bbd",
    "numbersString": "113",
    "playNumbersDigit": 5,
    "playLettersString": "f",
    "playNumbersString": "101"
  },
  {
    "lettersString": "cce",
    "numbersString": "224",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ddf",
    "numbersString": "335",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "beb",
    "numbersString": "141",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cbc",
    "numbersString": "212",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcd",
    "numbersString": "323",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bde",
    "numbersString": "134",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cef",
    "numbersString": "245",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "dbb",
    "numbersString": "311",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "bcc",
    "numbersString": "122",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdd",
    "numbersString": "233",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dee",
    "numbersString": "344",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bbf",
    "numbersString": "115",
    "playNumbersDigit": 4,
    "playLettersString": "e",
    "playNumbersString": "100"
  },
  {
    "lettersString": "ccb",
    "numbersString": "221",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "ddc",
    "numbersString": "332",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bed",
    "numbersString": "143",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cbe",
    "numbersString": "214",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcf",
    "numbersString": "325",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bdb",
    "numbersString": "131",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cec",
    "numbersString": "242",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "dbd",
    "numbersString": "313",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "bce",
    "numbersString": "124",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdf",
    "numbersString": "235",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "deb",
    "numbersString": "341",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bbc",
    "numbersString": "112",
    "playNumbersDigit": 4,
    "playLettersString": "e",
    "playNumbersString": "100"
  },
  {
    "lettersString": "ccd",
    "numbersString": "223",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dde",
    "numbersString": "334",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bef",
    "numbersString": "145",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cbb",
    "numbersString": "211",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "dcc",
    "numbersString": "322",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bdd",
    "numbersString": "133",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cee",
    "numbersString": "244",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "dbf",
    "numbersString": "315",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "bcb",
    "numbersString": "121",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cdc",
    "numbersString": "232",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ded",
    "numbersString": "343",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bbe",
    "numbersString": "114",
    "playNumbersDigit": 4,
    "playLettersString": "e",
    "playNumbersString": "100"
  },
  {
    "lettersString": "ccf",
    "numbersString": "225",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ddb",
    "numbersString": "331",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bec",
    "numbersString": "142",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cbd",
    "numbersString": "213",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "dce",
    "numbersString": "324",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bdf",
    "numbersString": "135",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "ceb",
    "numbersString": "241",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dbc",
    "numbersString": "312",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "bcd",
    "numbersString": "123",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cde",
    "numbersString": "234",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "def",
    "numbersString": "345",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bbb",
    "numbersString": "111",
    "playNumbersDigit": 5,
    "playLettersString": "f",
    "playNumbersString": "101"
  },
  {
    "lettersString": "ccc",
    "numbersString": "222",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ddd",
    "numbersString": "333",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bee",
    "numbersString": "144",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cbf",
    "numbersString": "215",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcb",
    "numbersString": "321",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bdc",
    "numbersString": "132",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "ced",
    "numbersString": "243",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dbe",
    "numbersString": "314",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "bcf",
    "numbersString": "125",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdb",
    "numbersString": "231",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dec",
    "numbersString": "342",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bbd",
    "numbersString": "113",
    "playNumbersDigit": 5,
    "playLettersString": "f",
    "playNumbersString": "101"
  },
  {
    "lettersString": "cce",
    "numbersString": "224",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "ddf",
    "numbersString": "335",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "beb",
    "numbersString": "141",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cbc",
    "numbersString": "212",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcd",
    "numbersString": "323",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bde",
    "numbersString": "134",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cef",
    "numbersString": "245",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "dbb",
    "numbersString": "311",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "bcc",
    "numbersString": "122",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdd",
    "numbersString": "233",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dee",
    "numbersString": "344",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bbf",
    "numbersString": "115",
    "playNumbersDigit": 4,
    "playLettersString": "e",
    "playNumbersString": "100"
  },
  {
    "lettersString": "ccb",
    "numbersString": "221",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "ddc",
    "numbersString": "332",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bed",
    "numbersString": "143",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cbe",
    "numbersString": "214",
    "playNumbersDigit": 0,
    "playLettersString": "a",
    "playNumbersString": "000"
  },
  {
    "lettersString": "dcf",
    "numbersString": "325",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bdb",
    "numbersString": "131",
    "playNumbersDigit": 7,
    "playLettersString": "h",
    "playNumbersString": "111"
  },
  {
    "lettersString": "cec",
    "numbersString": "242",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "dbd",
    "numbersString": "313",
    "playNumbersDigit": 1,
    "playLettersString": "b",
    "playNumbersString": "001"
  },
  {
    "lettersString": "bce",
    "numbersString": "124",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  },
  {
    "lettersString": "cdf",
    "numbersString": "235",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "deb",
    "numbersString": "341",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "bbc",
    "numbersString": "112",
    "playNumbersDigit": 4,
    "playLettersString": "e",
    "playNumbersString": "100"
  },
  {
    "lettersString": "ccd",
    "numbersString": "223",
    "playNumbersDigit": 3,
    "playLettersString": "d",
    "playNumbersString": "011"
  },
  {
    "lettersString": "dde",
    "numbersString": "334",
    "playNumbersDigit": 2,
    "playLettersString": "c",
    "playNumbersString": "010"
  },
  {
    "lettersString": "bef",
    "numbersString": "145",
    "playNumbersDigit": 6,
    "playLettersString": "g",
    "playNumbersString": "110"
  }
]

// here's a raw string method
let out = JSON.stringify(output),
  soutput = JSON.parse(out.substr(0, out.indexOf(JSON.stringify(output[0]), 2) - 1) + "]");
console.log(soutput.length, soutput);

// here's a loop method

let ctr = 0,
  rep = false;
let pattern = output.map(o => JSON.stringify(o)).reduce((b, a, i) => {
  if (!rep && b.includes(a)) {
    rep = true;
    ctr = i;
  } else if (!rep) b.push(a)
  return b
}, []).map(o => JSON.parse(o));

console.log('output length', output.length, '/pattern length:', pattern.length, '/pattern:', pattern)


text:
Q: Deserialize JSON in Hack strict mode I have a nested JSON file, consisting of keys and values which are string only. But the structure of the JSON file is not fixed, so sometimes it could be nested 3 levels, sometimes only 2 levels.
I wonder how i could serialize this in strict mode?
  "live" : {
"host" : "localhost",
"somevalue" : "nothing",
"anobject" : {
  "one" : "two",
  "three" : "four",
  "five" : {
    "six" : "seven"
  }
}

}
If i would know the structure of the JSON, i simply would write my own class for it, but since the keys are not fixed, and also the nesting could be into several levels, i really wonder how i cut put such an object into a specific type.
Any help or hints appreciated

A: I think invariants will serve you well here. First off, it might be helpful to know that you can type a keyed tree strictly in Hack:
<?hh // strict
class KeyedTree<+Tk as arraykey, +T> {
  public function __construct(
    private Map<Tk, KeyedTree<Tk, T>> $descendants = Map{},
    private ?T $v = null
  ) {}
}

(It must be a class because cyclic shape definitions are sadly not allowed)
I haven't tried it yet, but type_structures and Fred Emmott's TypeAssert look to also be of interest. If some part of your JSON blob is known to be fixed, then you could isolate the nested, uncertain part and build a tree out of it with invariants. In the limiting case where the whole blob is unknown, then you could excise the TypeAssert since there's no interesting fixed structure to assert:
use FredEmmott\TypeAssert\TypeAssert;
class JSONParser {
    const type Blob = shape(
        'live' => shape(
            'host' => string, // fixed
            'somevalue' => string, // fixed
            'anobject' => KeyedTree<arraykey, mixed> // nested and uncertain
        )
    );
    public static function parse_json(string $json_str): this::Blob {
        $json = json_decode($json_str, true);
        invariant(!array_key_exists('anobject', $json), 'JSON is not properly formatted.');
        $json['anobject'] = self::DFS($json['anobject']);
          // replace the uncertain array with a `KeyedTree`
        return TypeAssert::matchesTypeStructure(
            type_structure(self::class, 'Blob'),
            $json
        );
        return $json;
    }
    public static function DFS(array<arraykey, mixed> $tree): KeyedTree<arraykey, mixed> {
        $descendants = Map{};
        foreach($tree as $k => $v) {
            if(is_array($v))
                $descendants[$k] = self::DFS($v);
            else
                $descendants[$k] = new KeyedTree(Map{}, $v); // leaf node
        }
        return new KeyedTree($descendants);
    }
}

Down the road, you'll still have to supplement containsKey invariants on the KeyedTree, but that's the reality with unstructured data in Hack.


text:
Q: TFS work item query by linked worked items? Let's say I have a bunch of bugs (work items) that are all linked one work item.  How can I right a work item query to fetch the list of all bugs linked to a specific work item?
I can see the list of linked bugs when I look at the specific work item but I'd like to be able to create a query for this.  Thanks!

A: In TFS 2008 you can't do that with a work item query.  TFS 2010 provides this support out the box, along with the ability to view that query in a shiney tree view.  If you fancy having a play with Beta 1 of TFS 2010 then you can download it here
However, don't be tempted to install as a production server just yet as it is still a beta.

A: There may be a way to do this using a low level WIQL API, but through the standard query UI there is no way to do this.


text:
Q: Ionic building an IOS application I have finished building and compiling the Android version of the application from my windows laptop.
But to run it on IOS, am I supposed to copy the application folder to a MAC computer and run "ionic run ios"?

A: Follow these steps.
Check whether Ionic is already installed in Mac by typing ionic -v.

*

*If Ionic is already installed, type the following commands:

*

*ionic platform add ios.

*ionic build ios.

*If Ionic is not installed yet,

*

*First install Node.js in Mac.

*Then install Cordova and Ionic by using this command:
npm install -g cordova ionic

Once done with the installation, use the above commands for adding platform and build.
Then you will able to see Xcode file in platform folder iOS.
Then you can ask iOS developer to generate ipa file for iOS build.

A: You should add ionic ios platform before build
ionic platform add ios

Read this link : Ionic build


text:
Q: Tracked tag badge incorrectly shown as earned Note: I don't seem to have actually been awarded the badge.
I just got this message:

however, I'm still quite a bit away from the reputation requirement:

I didn't get a notification that I earned the badge, nor is it in my badge list. But I cannot select it for tracking anymore:

Not sure if this is related to https://meta.stackexchange.com/a/253516/142802

I did not get the badge awarded, but maybe it's just not that time of the day yet (does the tracking earning notice and the actual awarding occur on different schedules)?


text:
Q: Is it sound to use a regression model to identify excessive medication dosage for individual patients? Let's say I wanted to identify individuals who are taking an excessive amount of the blood clotting drug warfarin relative to their peers. To do this, I'm considering building a regression model that uses patient level data such as sex, age, and health status as factors and their actual drug dosage as the response. After model training, I'd apply the model to new data to generate predicted dosage values and compare those to the actual dosage. Patients who have an actual dosage higher than the predicted dosage would then be flagged as candidates for dose reduction.
Is this a reasonable plan? Essentially I'd be relying on the residuals to identify the patients who should be taking a reduced dosage.

A: I think you can go for one of these approaches:

*

*cluster your data based on the specified features and then you will be able to identify
each group/cluster average, maximum, minimum, ....etc drug dosage. then you can judge any
instance by how far it is from it`s cluster mean(far by n-Standard deviations) then
decide that the instances that fall 3-sd(Standard deviations) are anomaly and need to be
adjusted.

*Use Anomaly detection techniques which will help you detect different/extreme behavior in data.

A: I think you are right: regression (linear or otherwise) may be the way to go. The only exception would be the case is which dosage is limited to a small amount of fixed values, in which case I would consider classification instead
But remember, you model will only be as good as your data, so make sure you have abundant high quality data for the fitting process.
Also, when flagging candidates for dose reduction, take into account the amount of the difference ("actual"-"expected") and how it compares to the standard deviation among your sample population.
I hope this helped!


text:
Q: Simple Elixir / Plug Processes Issue - PID not sticking around I'm just starting out in Elixir and wanted to build a very simple API with Plug. I used this guide to get a very simple API up and running.

Basically, the problem I'm facing is that the process that I registered as :qs doesn't seem to be found (and errors out), whenever I use the send/2 function in queue_service.ex. What I'm trying to achieve is a process that sticks around so that I can have state being maintained across requests.

In my router.ex file, I have:
defmodule SecondQueue.Router do
  use Plug.Router

  alias SecondQueue.Plug.VerifyParams
  alias SecondQueue.QueueService

  plug Plug.Parsers, parsers: [:urlencoded, :multipart]
  plug :match
  plug :dispatch

  get "/receive-message" do
    # gather query parameters from connection
    queue = Map.get(conn.params, "queue")
    message = Map.get(conn.params, "message")

    # handle the params
    QueueService.handle_incoming(queue, message)

    send_resp(conn, 201, "Created")
  end
end

Then inside queue_service.ex, I initiate the queues process, register it to an atom of :qs, and then want to be able to get at that process later via a function that a request calls. I have:
defmodule SecondQueue.QueueService do
  alias SecondQueue.QueueStore
  use Agent

  {:ok, agent_pid} = QueueStore.start_queues_link()
  Process.register(agent_pid, :qs)

  def handle_incoming(queue, message) do
    queue_atom = String.to_atom(queue)
    send(:qs, {:put, queue_atom, "success"})
  end
end

And then finally, in queue_store.ex, I actually define the process that I want to store the state, and run a loop so that it stays alive, and ready to receive messages. I have:
defmodule SecondQueue.QueueStore do
  def start_queues_link() do
    Task.start_link(fn -> queues_loop(%{}) end)
  end

  defp queues_loop(map) do
    receive do
      {:get, key, caller} ->
        send caller, Map.get(map, key)
        queues_loop(map)
      {:put, key, value} ->
        IO.puts("i am here")
        queues_loop(Map.put(map, key, value))
    end
  end
end

Update:
Github repo: https://github.com/qarthandgi/test-second-queue

A: Elixir is a compiled language. The code below gets executed during compilation stage; no process is being started in runtime.
defmodule SecondQueue.QueueService do
  ...
  {:ok, agent_pid} = QueueStore.start_queues_link()
  Process.register(agent_pid, :qs)
  ...
end

Instead, you need to put this code into a function and explicitly call this function to start QueueStore (directly or by plugging it into your app's supervision tree.)


text:
Q: automatic feed from facebook to my website I own the domain name stfu.com and had an idea for a website.
People on Facebook always say "stfu" in their conversations.
Is there a way to create an automatic feed that copies and pastes conversations automatically from Facebook that have the words "stfu" with atleast 5 likes from ALL Facebook accounts automatically to my website stfu.com
For example:  when anyone on Facebook uses the term "stfu" and then gets atleast 5 likes...
this conversation should automatically be copied and pasted on my website stfu.com
is this possible to do?
thank you very much for your help.


text:
Q: shortcut in jbutton tooltip not displaying in other themes apart from matalic We have requirement to display key board shortcuts in Jbutton tooltip, we have added action map and all required code for tooltip but shortcut is only displaying in Metalic look and feel, if we change application look and feel from metalic to system or any other look and feel, short cut is not displaying  in tool tip anymore.
Below is the example program, which shows 2 J buttons with shortcuts, the shortcuts is properly displaying with metalic look and feel, but if i use any other look and feel like system or Motif, shortcuts stopped displaying in J Button tool tip. To test the behaviour of below example in other look and feel please comment Metalic look and feel in example and enable System or Motif look and feel which is commented right now:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        JFrame frame = new JFrame("KeyStroke Sample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JButton buttonA = new JButton("a Button");
        buttonA.setMnemonic('a');
        frame.setVisible(true);
        buttonA.setToolTipText("a Button");
        final JButton buttonB = new JButton("another Button");
        buttonB.setMnemonic('b');
        frame.add(buttonA);
        frame.add(buttonB);
        buttonB.setToolTipText("another Button");
        Action action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().equals(buttonA)) {
                    System.out.println("buttonA");
                }
                if (e.getSource().equals(buttonB)) {
                    System.out.println("buttonB");
                }
            }
        };
        buttonA.addActionListener(action);
        buttonB.addActionListener(action);

        // buttonA ("ALT+A");
        buttonA.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK),
                "left_button_pressed");
        buttonA.getActionMap().put("left_button_pressed", action);

        // buttonB ("CTRL+Shift+A");
        buttonB.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK
                        | InputEvent.SHIFT_MASK), "right_button_pressed");
        buttonB.getActionMap().put("right_button_pressed", action);
        frame.setLayout(new GridLayout(2, 2));

        frame.setSize(400, 200);

    }
}

A: Displaying the accelerator string in the tooltip is something which is implemented only in Metal by default ("only" refers to all the other LAFs I tried). This behavior is defined in the MetalToolTipUI class, which is the class responsible for setting up and displaying the tooltips.
Fortunately the UIManager class allows you to set a ToolTipUI. You can use Metal's for any other LAF:
UIManager.getDefaults().put("ToolTipUI", "javax.swing.plaf.metal.MetalToolTipUI");

For the LAFs that I checked, the tooltip's visual style (background color and font) adapted, but there might be cases in which the looks won't match. In this case, you might want to subclass ToolTipUI or one of its subclasses to suit your own needs.
Also, check that
UIManager.getDefaults().getBoolean("ToolTip.hideAccelerator");

returns false for a LAF. If it doesn't and the tooltip UI used respects this property, then the accelerator won't be displayed. You can set it to true in any case.


text:
Q: How to check if a 3D line segment intersects a cylinder? I have developed a check for a 2D case of a circle intersecting a 2D line segment, however there is a particular case that I can't figure out how to extend to 3D:
If one endpoint on the 3D line segment is inside the 2D projected circle, but above the cylinder, and the other endpoint is outside of the circle, but below the cylinder, how do I check if the line segment crossed the cylinder?

A: Minimize the distance between them and then check to make sure the point is both on the line segment and the cylinder.

A: Let's say that each horizontal cross-section of the cylinder (a circle) has a radius of $r$. That means that on any slice of the cylinder, we have a circle of the form
$$x_c^2+y_c^2=r^2 \text{(Eqn.1)}$$
Now let's write the equation of the line as if we were looking at the whole thing from above (i.e. ignoring it in the z-direction and writing $y_l$ as a function of $x_l$). It would have an apparent equation of the form
$$y_l=mx_l+b \text{(Eqn 2)}$$
Now, if the line crosses the circle at at least one point, then $y_c=y_l$ and $x_c=x_l$. We substitute $y_l$ into $\text {Eqn 1}$ and $x_l$ into $\text {Eqn 1}$, making it
$$x_l^2+(mx_l+b)^2=r^2 \text{(Eqn.3)}$$
Now we can solve for $x_l$. We can plug that into $\text {Eqn 2}$ to find $y_l$, and because we know $y_c=y_l$ and $x_c=x_l$, we can solve for the other variables. If we know the location of $A$ and $B$, we can then find the position of that point in 3-dimensional space.


text:
Q: how to use custom fonts and icons in codeigniter Slam everyone
i want to use custom icons from flaticon.com inside my view
the icons in http://successpermis.com/css/flaticon.html
as html it is working fine , but when i use it inside the view it is not working
i think the problem in loading the font

    @font-face {
    font-family: "Flaticon";
    src: url("http://successpermis.com/css/flaticon.eot");
    src: url("http://successpermis.com/css/flaticon.eot#iefix") format("embedded-opentype"),
    url("http://successpermis.com/css/flaticon.woff") format("woff"),
    url("http://successpermis.com/css/flaticon.ttf") format("truetype"),
    url("http://successpermis.com/css/flaticon.svg") format("svg");
    font-weight: normal;
    font-style: normal;
}

i tried to load fonts from local folders then from online host just like the code above
can you tell me to do it in a right way

A: folder structure
- application
- assets
    - css
    - js
    - images
    - fonts

style.css
  @font-face {
        font-family: "Flaticon";
        src: url("assets/fonts/flaticon.eot");

        -------------
    }

A:

@font-face {
    font-family: "Flaticon";
    src: url("http://successpermis.com/css/flaticon.eot");
    src: url("http://successpermis.com/css/flaticon.eot#iefix") format("embedded-opentype"),
    url("<?php echo base_url('assets/fonts/flaticon.woff')?>") format("woff"),
    url("<?php echo base_url('assets/fonts/flaticon.tff')?>") format("truetype"),
    url("<?php echo base_url('assets/fonts/flaticon.svg')?>") format("svg");
    font-weight: normal;
    font-style: normal;
}


text:
Q: 2D pointer array to 2d array How can I convert
char *s[]={
           "to err is human",
           "but to really mess things up ",
           "one needs to know c!!"
           };

to
char s[3][50]={
           "to err is human",
           "but to really mess things up ",
           "one needs to know c!!"
           };

A: #include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){
    char *s[]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
    };
    int i, size = sizeof(s)/sizeof(*s);
    char ns[size][50];//or use malloc, E.g next line
    //char (*ns)[50] = calloc(size, sizeof(char[50]));
    for(i=0;i<size;++i){
        memset(ns[i], 0, 50);//unnecessary if you use the calloc
        strcpy(ns[i], s[i]);
        //printf("%s\n", ns[i]);
    }
/*
    char ns[3][50]= {
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
    };
*/
    return 0;
}

A: It really already is, just drop the [3] subscript for []:
#include <stdio.h>

int main (void) {

    char s[][50]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
        };

    int i = 0;

    for (i = 0; i < 3; i++)
        printf ("s [%d]  %s\n", i, s[i]);

    return 0;

}

output:
s [0]  to err is human
s [1]  but to really mess things up
s [2]  one needs to know c!!

Your original char *s[]={ will also work.

A: No need to remember Size of array
#include <stdio.h>
#include <string.h>

int main (void) {

char *s[]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!",
        '\0'
        };
    int i = 0;
    char SA[100][100];
    while (s[i]  != '\0') {
        strcpy(SA[i],s[i]);
        i++;
        }
                    SA[i]='\0'
    printf("SA[1][1] : %c\n",SA[1][1])  ;
    return 0;

}

Output
 SA[1][1] : u (as expected)


text:
Q: Get json data from a htttp based web service C# I can't recieve json data from the http web service, because the of data size - i guess - which is 7 MB, i first tried this :
private async Task<string> GetResponse(string url)
{
    HttpResponseMessage response = null;
    HttpClient client = new HttpClient();
    try
    {
        response = await client.GetAsync(url);
    }
    catch (Exception )
    {
        throw;
    }
    return await response.Content.ReadAsStringAsync();
}

but it gives me "Task canceled Exception", after doing some search , i found it might be the request timeout limit probleme, so i implemented the second solution by setting the Timeout limit to two minutes :
HttpClient client = new HttpClient();
client.Timeout = new TimeSpan(0, 2, 0);

when executing, there is no result, no exception and the app blocks at the method
client.GetAsync(url);


text:
Q: Howto read chunk of memory as char in c++ Hello I have a chunk of memory (allocated with malloc()) that contains bits (bit literal), I'd like to read it as an array of char, or, better, I'd like to printout the ASCII value of 8 consecutively bits of the memory.
I have allocated he memory as char *, but I've not been able to take characters out in a better way than evaluating each bit, adding the value to a char and shifting left the value of the char, in a loop, but I was looking for a faster solution.
Thank you
What I've wrote for now is this:
for allocation:
char * bits = (char*) malloc(1);

for writing to mem:
ifstream cleartext;
cleartext.open(sometext);
while(cleartext.good())
{
     c = cleartext.get();
     for(int j = 0; j < 8; j++)
     {  //set(index) and reset(index) set or reset the bit at bits[i]
        (c & 0x80) ? (set(index)):(reset(index));//(*ptr++ = '1'):(*ptr++='0');
         c = c << 1;
     }..
}..

and until now I've not been able to get character back, I only get the bits printed out using:
printf("%s\n" bits);

An example of what I'm trying to do is:
input.txt contains the string "AAAB"
My program would have to write "AAAB" as "01000001010000010100000101000010" to  memory
(it's the ASCII values in bit of AAAB that are 65656566 in bits)
Then I would like that it have a function to rewrite the content of the memory to a file.
So if memory contains again "01000001010000010100000101000010" it would write to the output file "AAAB".

A: int numBytes = 512;
char *pChar = (char *)malloc(numBytes);
for( int i = 0; i < numBytes; i++ ){
   pChar[i] = '8';
}

Since this is C++, you can also use "new":
int numBytes = 512;
char *pChar = new char[numBytes];
for( int i = 0; i < numBytes; i++ ){
   pChar[i] = '8';
}

A: If you want to visit every bit in the memory chunk, it looks like you need std::bitset.
char* pChunk = malloc( n );
// read in pChunk data

// iterate over all the bits.
for( int i = 0; i != n; ++i ){
    std::bitset<8>& bits = *reinterpret_cast< std::bitset<8>* >( pByte );
    for( int iBit = 0; iBit != 8; ++iBit ) {
        std::cout << bits[i];
    }
}

A:
I'd like to printout the ASCII value of 8 consecutively bits of the memory.

The possible value for any bit is either 0 or 1. You probably want at least a byte.

char * bits = (char*) malloc(1);

Allocates 1 byte on the heap. A much more efficient and hassle-free thing would have been to create an object on the stack i.e.:
char bits; // a single character, has CHAR_BIT bits

ifstream cleartext;
cleartext.open(sometext);

The above doesn't write anything to mem. It tries to open a file in input mode.

It has ascii characters and common eof or \n, or things like this, the input would only be a textfile, so I think it should only contain ASCII characters, correct me if I'm wrong.

If your file only has ASCII data you don't have to worry. All you need to do is read in the file contents and write it out. The compiler manages how the data will be stored (i.e. which encoding to use for your characters and how to represent them in binary, the endianness of the system etc). The easiest way to read/write files will be:
// include these on as-needed basis
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>

using namespace std;
// ...

/* read from standard input and write to standard output */
copy((istream_iterator<char>(cin)), (istream_iterator<char>()),
                  (ostream_iterator<char>(cout)));
/*-------------------------------------------------------------*/

/* read from standard input and write to text file */
copy(istream_iterator<char>(cin), istream_iterator<char>(),
         ostream_iterator<char>(ofstream("output.txt"), "\n") );
/*-------------------------------------------------------------*/

/* read from text file and write to text file */
copy(istream_iterator<char>(ifstream("input.txt")), istream_iterator<char>(),
         ostream_iterator<char>(ofstream("output.txt"), "\n") );
/*-------------------------------------------------------------*/

The last remaining question is: Do you want to do something with the binary representation? If not, forget about it. Else, update your question one more time.

E.g: Processing the character array to encrypt it using a block cipher

/* a hash calculator */
struct hash_sha1 {
 unsigned char operator()(unsigned char x) {
    // process
    return rc;
  }
};

/* store house of characters, could've been a vector as well */
basic_string<unsigned char> line;

/* read from text file and write to a string of unsigned chars */
copy(istream_iterator<unsigned char>(ifstream("input.txt")),
                                     istream_iterator<char>(),
                                      back_inserter(line) );

/* Calculate a SHA-1 hash of the input */
basic_string<unsigned char> hashmsg;
transform(line.begin(), line.end(), back_inserter(hashmsg), hash_sha1());

A: Something like this?
char *buffer = (char*)malloc(42);
// ... put something into the buffer ...
printf("%c\n", buffer[0]);

But, since you're using C++, I wonder why you bother with malloc and such...

A: char* ptr = pAddressOfMemoryToRead;

while(ptr < pAddressOfMemoryToRead + blockLength)
{
     char tmp = *ptr;
     // temp now has the char from this spot in memory
     ptr++;
}

A: Is this what you are trying to achieve:
char* p = (char*)malloc(10 * sizeof(char));
char* p1 = p;
memcpy(p,"abcdefghij", 10);

for(int i = 0; i < 10; ++i)
{
    char c = *p1;
    cout<<c<<" ";
    ++p1;
}
cout<<"\n";
free(p);

A: Can you please explain in more detail, perhaps including code?  What you're saying makes no sense unless I'm completely misreading your question.  Are you doing something like this?
char * chunk = (char *)malloc(256);

If so, you can access any character's worth of data by treating chunk as an array: chunk[5] gives you the 5th element, etc.  Of course, these will be characters, which may be what you want, but I can't quite tell from your question... for instance, if chunk[5] is 65, when you print it like cout << chunk[5];, you'll get a letter 'A'.
However, you may be asking how to print out the actual number 65, in which case you want to do cout << int(chunk[5]);.  Casting to int will make it print as an integer value instead of as a character.  If you clarify your question, either I or someone else can help you further.

A: Are you asking how to copy the memory bytes of an arbitrary struct into a char* array?  If so this should do the trick
SomeType t = GetSomeType();
char* ptr = malloc(sizeof(SomeType));
if ( !ptr ) {
  // Handle no memory.  Probably should just crash
}
memcpy(ptr,&t,sizeof(SomeType));

A: I'm not sure I entirely grok what you're trying to do, but a couple of suggestions:
1) use std::vector instead of malloc/free and new/delete. It's safer and doesn't have much overhead.
2) when processing, try doing chunks rather than bytes. Even though streams are buffered, it's usually more efficient grabbing a chunk at a time.
3) there's a lot of different ways to output bits, but again you don't want a stream output for each character. You might want to try something like the following:
void outputbits(char *dest, char source)
{
    dest[8] = 0;
    for(int i=0; i<8; ++i)
        dest[i] = source & (1<<(7-i)) ? '1':'0';
}

Pass it a char[9] output buffer and a char input, and you get a printable bitstring back. Decent compilers produce OK output code for this... how much speed do you need?


text:
Q: Angular link inside link I would like to have a div with class "dialog" so when user click on that div anywhere expert links inside it redirects him to one page. And "links" inside that div should redirect user to another page. And return on previous page browser button should return him on correct page. I saw some examples on javascript but they doesn't work for angular and I always get second page when return back.
I have following snippet of code.

                 ...

                    {{ dialog.adv_name }}

                ....

A: Here is one way you could do it by passing the event object as argument of ng-click function and checking event.target

Then in controller or directive:
$scope.doRedirect = function(event){
     if(!angular.element(event.target).hasClass('msg-heading') ){
          /* not the  tag so put your redirect code here */
     }
}


text:
Q: Symfony 2 - Doctrine : OnetoOne relationship unclear i've been losing my nerves over it and spent a couple of hours searching here and there, unfortunately to no avail.
I've got 2 entities, we'll call them A and B for the sake of simplicity
<?php

namespace System\Main\SystemBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

class A
{
    /**
    * @ORM\OneToOne(targetEntity="B")
    * @ORM\JoinColumn(name="operator_I_id", referencedColumnName="_I_id")
    */
    private $operator = null;

class B
{
    private $_I_id = null;

I'd like to know how I could possibly get the related entity of A (i.e, B).
Here I am with my instance of class A, not knowing how to fetch the related entity (of class B)...I'm stuck here and, to say the least, a bit confused.
Thanks a lot for helping,
S.


text:
Q: Do automorphisms of a finitely generated free module restrict to automorphisms on every invariant submodule? Let $R$ be a (commutative) ring (with 1) and $M$ a free and finitely generated $R$-module. Let $\gamma$ be an $R$-module automorphism of $M$. If $N\subset M$ is a submodule invariant under $\gamma$, then is $\gamma|_N$ an automorphism of $N$?
If this is false, are there reasonable conditions under which it would be true? (e.g., $R$ noetherian...etc?)

A: The answer is yes in all cases, even if $N$ is not finitely generated.
The case where $N$ is finitely generated is settled by Orzech's theorem; see this question. (To reduce to said theorem, pass to $\gamma^{-1}$ instead of $\gamma$, which restricts to a surjective $R$-module homomorphism $N \supseteq \gamma(N) \to N$.) This question was answered by user26857, the very same who already observed that the result holds if $N$ is only assumed to be finitely generated.
The general case is settled by using the Cayley–Hamilton theorem. I follow the approach taken by Darij Grinberg in this writing, which was also linked in his own answer to the aforementioned question regarding Orzech's theorem. The key ingredient to Darij's writing is the following lemma (presented here in my own words):

Lemma 0.5. ($A$ is a commutative ring with unit and $n\in\mathbb{N}_0$ is given.) Let $g : A^n \to A^n$ be an $A$-linear map and let $V \subseteq A^n$ be a submodule satisfying $g^{-1}(V) \subseteq V$. Then we have $g(V) \subseteq V$.
Proof. The case $n = 0$ is trivial, but needs to be considered separately. For the remainder of this proof, we assume $n \geq 1$. By the Cayley–Hamilton theorem, we may choose some $c_0,\ldots,c_n\in A$ with $c_n = 1$ such that
  $$ c_ng^n + c_{n-1}g^{n-1} + \cdots + c_1g + c_0 = 0.\tag*{(1)} $$
  We prove by induction that every $u\in \{0,1,\ldots,n\}$ satisfies
  $$ \big(c_ng^{n - u} + c_{n-1}g^{n - u - 1} + \cdots + c_{u+1}g + c_u\big)(V) \subseteq V.\tag*{(2)} $$

*

*The base case $u = 0$ is clear from $(1)$.

*Let $p \in \{1,\ldots,n\}$ be given and suppose that $(2)$ holds for $u = p - 1$. We must now prove that it also holds for $u = p$. To that end, let $v\in V$ be given. By the induction hypothesis, we have
  $$ \big(c_ng^{n - p + 1} + c_{n-1}g^{n - p} + \cdots + c_pg + c_{p-1}\big)(v) \in V. $$
  Since we also have $c_{p-1}v \in V$, it follows that
  \begin{align*}
     &\: g\Big(\big(c_ng^{n - p} + c_{n-1}g^{n - p - 1} + \cdots + c_{p+1}g + c_p\big)(v)\Big)\\[1ex]
     =& \: \Big(g\big(c_ng^{n - p} + c_{n-1}g^{n - p - 1} + \cdots + c_{p+1}g + c_p\big)\Big)(v)\\[1ex]
     =& \: \big(c_ng^{n - p + 1} + c_{n-1}g^{n - p} + \cdots + c_{p+1}g^2 + c_pg\big)(v) \quad \in V.
    \end{align*}
  Therefore we have
  $$ \big(c_ng^{n - p} + c_{n-1}g^{n - p - 1} + \cdots + c_{p+1}g + c_p\big)(v) \in g^{-1}(V) \subseteq V, $$
  which shows that $(2)$ holds for $u = p$ as well.

  The proof shows that $(2)$ holds for all $u \in \{0,1,\ldots,n\}$, so in particular it holds for $u = n - 1$ (here we use the assumption $n \geq 1$). In other words, we have
  $$ \big(c_ng + c_{n-1}\big)(V) \subseteq V. $$
  Recall that $c_n = 1$ holds; therefore we find $g(V) \subseteq V$.$\quad\blacksquare$

Observe that the lemma cannot be reversed: there are ample examples where $g(V) \subseteq V$ holds but $g^{-1}(V) \not\subseteq V$. (Let $V = \langle x\rangle \subsetneq A$ be a proper principal ideal and let $g : A \to A$ be multiplication with $x$.)
To solve the problem at hand, we apply the above lemma to $g = \gamma^{-1}$ and $V = N$.

A: If $R$ is Noetherian, this is true. Notice that $\gamma(N)\subset N$ implies $N\subset \gamma^{-1} N$. Thus, we get a chain $N\subset\gamma^{-1} N\subset \gamma^{-2} N\subset\cdots$ and by Noetherian hypothesis, we have $\gamma^{-n}(N)=\gamma^{-n-1}(N)$ for some $n$ and then it is easy to see that $N=\gamma(N)$, proving what you need.

A: This alternative solution is a bit simpler than my other answer.
Proposition. Let $R$ be a commutative ring with unit, and let $M$ be a finitely generated $R$-module (not necessarily free). Let $\gamma : M \to M$ be an $R$-module automorphism of $M$, and let $N \subseteq M$ be a submodule invariant under $\gamma$. Then $\gamma$ restricts to an automorphism of $N$.
Proof. By assumption, we have $\gamma[N] \subseteq N$. We show that equality holds.
By Cayley–Hamilton, $\gamma^{-1}$ satisfies a monic polynomial
$$ \gamma^{-n} + a_1 \gamma^{-n+1} + \cdots + a_n \text{id} = 0. $$
Multiplying by $\gamma^n$, we find
$$ \text{id} + a_1 \gamma + \cdots + a_n \gamma^n = 0. $$
To prove $\gamma[N] \supseteq N$, note that for every $x \in N$ we have
$$ x = \text{id}(x) = (-a_1\gamma - \cdots - a_n\gamma^n)(x) \in \gamma[N].\tag*{$\Box$} $$

Acknowledgement: Raymond van Bommel and I found this solution together, a while ago. Thanks Raymond!


text:
Q: How to add non-standardized sql functions in Spring Boot application? My app needs to be portable between Postgres, Mysql and for testing Hsqldb. I've setup Flyway to make some custom functions available on all three, that I now want to use in my SQL/HQL queries.
My current setup is using separate Dialects that I switch between using application-{profile}.yml; which works, but the function declarations need to be duplicated among the various dialects, and it feels suboptimal.
Looking at 15.29. Non-standardized functions in the Hibernate documentation, it says I should be using org.hibernate.cfg.Configuration#addSqlFunction(), which seems more portable and removes the need to extend all three dialects.
My issue is: How do I get access to the Hibernate Configuration class in my Spring Boot (1.3) application? There's no bean to inject by default, and no LocalSessionFactoryBean bean either.
Can anyone point me in the right direction, or at some other way to register my sql functions once?

A: I have rather a hack for the issue.
Hibernate uses org.hibernate.dialect.Dialect.SQLFunctionRegistry to recognize a DB function.
Here is an example of hibernate core 4.3.10.
Internally it consists of two private fields:
/**
 * Defines a registry for SQLFunction instances
 *
 * @author Steve Ebersole
 */
public class SQLFunctionRegistry {
    private final Dialect dialect;
    private final Map<String, SQLFunction> userFunctions;

The first field represents dialect of the database.
Second contains user defined functions which can be filled by org.hibernate.cfg.Configuration#addSqlFunction().
Unfortunately, in my search through hibernate source code I found that configuration object created while initializing hibernate is not exposed in any way.
However, I managed to get access to SQLFunctionRegistry.
One needs to create a local autowired field of type EntityManagerFactory
@Autowired
private EntityManagerFactory emFactory;

and later call the following code:
private void registerMyDbFunctions()
{
    SQLFunctionRegistry registry = this.emFactory.unwrap(org.hibernate.internal.SessionFactoryImpl.class).getSqlFunctionRegistry();
    Field field = ReflectionUtils.findField(SQLFunctionRegistry.class, "userFunctions");
    ReflectionUtils.makeAccessible(field);
    Map<String, SQLFunction> userFunctions = (Map<String, SQLFunction>)ReflectionUtils.getField(field, registry);

    userFunctions.put("my_func", new SQLFunctionTemplate(TextType.INSTANCE, "my_func(?1, ?2)"));
}

Since userFunctions field is private and not exposed in the class, I used ReflectionUtils to get its value. It's usually empty and I just add my DB functions to it.
Since I had to get into SqlFunctionRegistry's internals it's a hack, but I prefer it over creating new DB dialect and messing up with it.


text:
Q: Calling a list of DataFrame index with index key value df = pd.DataFrame([[3,3,3]]*4,index=['a','b','c','d'])

While we can extract a copy of a section of an index via specifying row numbers like below:
    i1=df.index[1:3].copy()
Unfortunately we can't extract a copy of a section of an index via specifying the key (like the case of df.loc method). When I try the below:
i2=df.index['a':'c'].copy()

I get the below error:
TypeError: slice indices must be integers or None or have an __index__ method

Is there any alternative to call a subset of an index based on its keys? Thank you

A: Simpliest is loc with index:
i1 = df.loc['b':'c'].index
print (i1)
Index(['b', 'c'], dtype='object')

Or is possible use get_loc for positions:
i1 = df.index

i1 = i1[i1.get_loc('b') : i1.get_loc('d') + 1]
print (i1)
Index(['b', 'c'], dtype='object')

i1 = i1[i1.get_loc('b') : i1.get_loc('d') + 1]
print (i1)
Index(['b', 'c', 'd'], dtype='object')

Alternative:
i1 = i1[i1.searchsorted('b') : i1.searchsorted('d') + 1]
print (i1)
Index(['b', 'c', 'd'], dtype='object')

A: Try using .loc, see this documentation:
i2 = df.loc['a':'c'].index
print(i2)

Output:
Index(['a', 'b', 'c'], dtype='object')

or
df.loc['a':'c'].index.tolist()

Output:
['a', 'b', 'c']


text:
Q: How to fix error of a button trying to delete an item form a list? Im making a practice app where the main view is a list with a button at the bottom. Pressing the button adds an item to the list. When the item is tapped, it presents the detail view that has a button at the middle of the view.
What Im trying to do is that when the button is pressed, it deletes the item form the list and move me back to the main view. My problem is that I got an error when implementing the delete function to the button.
The error is this one: Cannot convert value of type '(IndexSet) -> ()' to expected argument type '() -> Void'
How can I fix it?
This is the main view:
struct ContentView: View {
    @EnvironmentObject var store: CPStore

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(0..<store.items.count, id:\.self) { index in
                        NavigationLink(destination: Detail(index: index)) {
                            VStack {
                                Text(self.store.items[index].title)
                            }
                        }
                    }
                }
                Spacer()

                Button(action: {
                    self.add()
                }) {
                    ZStack {
                        Circle()
                        .frame(width: 87, height: 87)
                    }
                }
            }
            .navigationBarTitle("Practice")
        }
    }

    func add() {
        withAnimation {
            store.items.append(CPModel(title: "Item \(store.items.count + 1)"))
        }
    }
}

This is the detail view:
struct Detail: View {
    @EnvironmentObject var store: CPStore
    @Environment(\.presentationMode) var presentationMode
    let index: Int

    var body: some View {
        Button(action: removeRecording) { // <- I got the error here
            Image(systemName: "trash")
        }
        .foregroundColor(.blue)
        .font(.system(size: 24))
    }

    func removeRecording(at offsets: IndexSet) {
        withAnimation {
            store.items.remove(atOffsets: offsets)
            self.presentationMode.wrappedValue.dismiss()
        }
    }
}

The model:
struct CPModel: Identifiable {
    var id = UUID()
    var title: String
}

And the ViewModel:
class CPStore: ObservableObject {
    @Published var items = [CPModel]()
}

A: I refer to this post
update your removeRecording function
func removeRecording(at offsets: IndexSet) -> () -> () {
        return {
            withAnimation {
                store.items.remove(atOffsets: offsets)
                self.presentationMode.wrappedValue.dismiss()
            }
        }
    }

and change your button to pass the parameter
Button(action: removeRecording(at: [index]))


text:
Q: Condition for pair of planes in three dimensional geometry We know that the equation $ax^2+by^2+cz^2+2hxy+2fyz+2gzx=0$ represents a pair of planes if and only if $\begin{vmatrix}
a& h& g\\
h&b& f\\
g& f&c
\end{vmatrix}=0.$ I wanted to prove this result. Let the two planes be of the form  $l_1x+m_1y+n_1z=0$ and $l_2x+m_2y+n_2z=0.$ Then we have  $$ax^2+by^2+cz^2+2hxy+2fyz+2gzx=(l_1x+m_1y+n_1z)(l_2x+m_2y+n_2z)=0.$$ On comparing the coefficients of $x, y$ and $z$ both sides we get \begin{align*}
l_1l_2&=a\\
m_1m_2&=b\\
n_1n_2&=c\\
l_1m_2+l_2m_1&=2h\\
l_1n_2+l_2n_1&=2f\\
m_1n_2+m_2n_1&=2g.
\end{align*}
Now we have  six equations in six variables. How to show that these equations have a non-trivial solution if and only if
$\begin{vmatrix}
a& h& g\\
h&b& f\\
g& f&c
\end{vmatrix}=0?$

A: I put material on      solving $P^T M P = D$ diagonal when $M$  is real symmetric at reference for linear algebra books that teach reverse Hermite method for symmetric matrices
The above is just an algorithm for repeated completing the square.
As far as how to do it, we are given a symmetric real matrix, call it $M.$   We may construct  a real matrix $P$   with $\det P = \pm 1$  so that $P^T M P = D$ is diagonal. With determinant $0$  this means as many as two nonzero entries in $D.$   If we take $Q = P^{-1}$   we get $Q^T D Q = M.$ If we name your quadratic form $R(x,y,z)$  we have reached
$$ \color{blue}{  R(x,y,z) = d_1 (a_1x+b_1 y + c_1z)^2  + d_2 (a_2x+b_2 y + c_2z)^2}$$
When $d_1, d_2$  are both positive or both negative, both linear expressions must be zero and the zero set is a single (real) line. When $d_1 d_2 < 0$  we see that $R(x,y,z)$ factors over the reals. One may write $$  A V^2 - B W^2 = (V \sqrt A + W \sqrt B)(V \sqrt A - W \sqrt B) $$


text:
Q: Convert a simple command into an AST in python I would like a function in Python that converts a string command into an AST (Abstract Syntax Tree).
The syntax for the command is as follows:
commandName(3, "hello", 5.0, x::int)

A command can accept any number of comma separated values that can be either

*

*Integers

*Strings

*Floats

*Types

Suppose the function is called convert_to_ast, then
convert_to_ast('commandName(3, "hello", 5.0, x::int)')

Should yield the following AST:
{
  'type': 'command',
  'name': 'commandName',
  'args': [{
    'type': 'int',
    'value': 3
  }, {
    'type': 'str',
    'value': 'Hello'
  }, {
    'type': 'float',
    'value': 5.0
  }, {
    'type': 'var',
    'kind': 'int',
    'name': 'x
  }]

A: Seems like you could just evaluate the string and then pick off the types from there:
>>> items = ast.literal_eval('(404.5, "Hello", 5)')
>>> [{'type': type(item).__name__, 'value': item} for item in items]
[{'type': 'float', 'value': 404.5}, {'type': 'str', 'value': 'Hello'}, {'type': 'int', 'value': 5}]

Of course, if you want to do more interesting things, you can access the AST directly:
>>> ast.dump(ast.parse('(404.5, "Hello", 5)'))
"Module(body=[Expr(value=Tuple(elts=[Num(n=404.5), Str(s='Hello'), Num(n=5)], ctx=Load()))])"
>>> ast.parse('(404.5, "Hello", 5)').body[0].value.elts
[<_ast.Num object at 0x107fa1250>, <_ast.Str object at 0x107fa1290>, <_ast.Num object at 0x107fa12d0>]

For a more general thing than parsing a tuple (as you've added to the question), we still can use python's AST to parse this (as long as your syntax is valid python).  In this case, we'll create an ast.NodeVisitor which will pull out the information that we as it visits each node of the python AST that we care about.  In this case, we care about  Call, Num, Str and Name nodes:
import ast

class Parser(ast.NodeVisitor):

    def __init__(self):
        self.calls = []
        self.current_command = None

    def visit_Call(self, node):
        name = node.func.id
        self.current_command = {
            'type': 'command',
            'name': name,
            'args': []
        }
        self.calls.append(self.current_command)
        for arg in node.args:
            self.visit(arg)
        self.current_command = None

    def visit_Num(self, node):
        if not self.current_command:
            return
        args = self.current_command['args']
        arg = {
            'type': type(node.n).__name__,
            'value': node.n
        }
        args.append(arg)

    def visit_Str(self, node):
        if not self.current_command:
            return
        args = self.current_command['args']
        arg = {
            'type': 'str',
            'value': node.s
        }
        args.append(arg)

    def visit_Name(self, node):
        if not self.current_command:
            return
        args = self.current_command['args']
        arg = {
            'type': 'type',
            'kind': node.id
        }
        args.append(arg)

S = 'commandName(3, "hello", 5.0, int)'

tree = ast.parse(S)
p = Parser()
p.visit(tree)
print p.calls


text:
Q: GetAndDecrement Much Slower than GetAndIncrement. I have found that in Java using AtomicIntegers, GetAndDecrement is much slower than GetAndIncrement. Why does this happen?

A: Whichever one comes second is faster.
AtomicInteger a = new AtomicInteger(1);

long start1 = System.nanoTime();
a.decrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start1));

AtomicInteger b = new AtomicInteger(1);

long start2 = System.nanoTime();
a.incrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start2));

On my machine, this prints:

Time: 49264
Time: 4105

However, if we swap the order of the two operations:
AtomicInteger a = new AtomicInteger(1);

long start1 = System.nanoTime();
a.incrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start1));

AtomicInteger b = new AtomicInteger(1);

long start2 = System.nanoTime();
a.decrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start2));

Then we get:

Time: 43106
Time: 7697

Presumably the JVM or processor or something is doing some runtime optimizations.

A: They look pretty much the same to me --
public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}

public final int getAndDecrement() {
    for (;;) {
        int current = get();
        int next = current - 1;
        if (compareAndSet(current, next))
            return current;
    }
}


text:
Q: While play audio from phone via bluetooth, I need to keep windows (system tray) media play on top of other windows I play music through my pc from my phone via bluetooth.  I am looking for a setting to keep the windows media player on top of all windows.  I am also looking to control player with media keys or ahk script.
Also, is there a specific name for this player as it is not the same theme of windows media player.

A: The Windows Media Player Plus! plug-in adds global hotkey functionality to WMP. It also allows you to configure a hotkey for bringing WMP to the front of all other windows.

A: The program in the below image is the program I am looking to control.
I'm not familiar with the actual name.
Its a remote player for my phone media.  Do you know the actual name?


text:
Q: Convergent or divergent: $\sum_{k=1}^{\infty}\frac{2^{k}\cdot k!}{k^{k}}$
Convergent, absolutely convergent or divergent:
  $$\sum_{k=1}^{\infty}\frac{2^{k}\cdot k!}{k^{k}}$$

I have used ratio test because we got a fraction here and I think I did alright till the end:
$$\lim_{k\rightarrow \infty}\frac{\frac{2^{k+1}\cdot (k+1)!}{(k+1)^{k+1}}}{\frac{2^{k}\cdot k!}{k^{k}}} = \lim_{k\rightarrow \infty}\frac{2^{k+1}\cdot (k+1)! \cdot k^{k}}{(k+1)^{k+1}\cdot 2^{k}\cdot k!} = \lim_{k\rightarrow \infty}\frac{2^{k}\cdot 2^1\cdot k! \cdot (k+1)\cdot k^{k}}{(k+1)^{k}\cdot (k+1)\cdot 2^{k}\cdot k!} = \lim_{k\rightarrow \infty}\frac{2k^{k}}{(k+1)^{k}}$$ $$=2\lim_{k\rightarrow \infty} \left( \frac{k}{k+1}\right)^{k}$$
Now I don't know (without a calculator) to what this would converge / diverge to... In the exam we are not allowed to use a calculator... So what to do?
The denominator will be greater than the enumerator by 1, so dividing each other we got something $<1$. We take exponent $k$ which is $\geq 1$, so we will end up with $<1$ again. Multiply this with 2 we get something $< 1$ but $> 0$ and thus the series is convergent...?
I hope I have described it well? Would you give me full points to this task? :D
Edit: I haven't described it well in the end. See the accepted answer and its comments! Thanks a lot to everyone - from every question I ask here, I always learn new things :-)

A: Hint:
Use that $$\lim_{k\to\infty}\left(1+\frac{1}{k}\right)^k=e$$
So,
$$2\lim_{k\to\infty}\left(\frac{k}{k+1}\right)^k=\frac{2}{e}\lt1$$

A: Observe
\begin{align}
\lim_{k\rightarrow \infty}\left(\frac{k}{k+1} \right)^k = \lim_{k \rightarrow \infty}\left(1-\frac{1}{k+1} \right)^{k+1}\left( 1-\frac{1}{k+1}\right)^{-1} = e^{-1}.
\end{align}


text:
Q: How Can I Set Value To output parameter in sql stored procedure within select statement? I have Stored Procedure in sql server 2008 used to paginating data returned from product table in database. what i want is return total pages count in the same select statement
ALTER PROCEDURE [dbo].[SP_GetProducts]
    @PageSize int = 10,
    @PageNumber int = 1,
    @ProductCode nvarchar(50) = null,
    @ProductName nvarchar(100) = null,
    @TotalPages int = null output
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT TOP (@PageSize) *, @TotalPages = COUNT(*)  FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY ProductId ASC) offset, * FROM (
         SELECT *, count(*) over() AS TotalRows
         FROM Products
        ) myquery
        ) paginator
        WHERE offset >= (((@PageSize * @PageNumber) - @PageSize)) +1 and offset <= (@PageSize * @PageNumber)

A: you cannot retrieve values from a Select statement and assign value to a variable at the same time. In your particular case since you are only assigning the number or rows returned from your select statement you can use a slightly different approach to get what you want.
ALTER PROCEDURE [dbo].[SP_GetProducts]
    @PageSize int = 10,
    @PageNumber int = 1,
    @ProductCode nvarchar(50) = null,
    @ProductName nvarchar(100) = null,
    @TotalPages int = null output
AS
BEGIN
    SET NOCOUNT ON;

    SELECT TOP (@PageSize) *
     FROM (
           SELECT ROW_NUMBER() OVER (ORDER BY ProductId ASC) offset, *
              FROM (
                    SELECT *, count(*) over() AS TotalRows
                    FROM Products
           ) myquery
        ) paginator
        WHERE offset >= (((@PageSize * @PageNumber) - @PageSize)) +1
         AND offset <= (@PageSize * @PageNumber)

    -- here assign value to your output parameter using the following

     SELECT @TotalPages = @@ROWCOUNT;
END

Note
Avoid using SELECT * instead use Column names, only the columns you actually want to retrieve.


text:
Q: Interpret term as type in Coq I am building Integers from Naturals bottom-up and trying to apply a morphism rewrite directly instead of adding it as a setoid morphism because in my case it is hard and unnatural to do it, but a test case is failing with the following error:
The term "x = x" has type "Prop" while it is expected to have type "x = x".

Which is also thrown by the following MRE:
Require Import Setoid.

(* Custom natural Set *)
Parameter CNat : Set.

(* Addition *)
Parameter CAdd : CNat -> CNat -> CNat.
Infix "±" := CAdd (at level 50, left associativity).

(* Addition Morphism *)
Axiom cnat_add_morphism :
  forall (x x' : CNat), x = x' ->
  forall (y y' : CNat), y = y' ->
    x ± y = x' ± y'.

(* Test Example *)
Example cnat_add_inc :
  forall (x y c : CNat), x = y -> x±c = y±c.
Proof.
  intros x y c CH.
  rewrite (@cnat_add_morphism x x (x=x) c c (c=c)). (* #Error *)

Is it possible to tell cnat_add_morphism (which in my code is a theorem instead of an axiom) to interpret the terms x¦x and c¦c as a type to make the morphism work properly, or a different one to be able to apply a manual morphism rewrite instead of adding it as a setoid?

A: The first problem you have is that the term you want to rewrite is not well-typed:
cnat_add_morphism x x (x¦x) c c (c¦c)

You have
cnat_add_morphism x x : x¦x -> forall y y', y¦y' -> x ± y ¦ x ± y'

so you need to provide a proof of x¦x but you're providing x¦x itself.
You actually need to add proofs of reflexivity in your system. Something like
Parameter CRefl : forall (x : CNat), x¦x.

Then you can prove your lemma.
Example cnat_add_inc :
  forall (x y c : CNat),
    x¦y ->
    x ± c ¦ y ± c.
Proof.
  intros x y c CH.
  apply cnat_add_morphism.
  - assumption.
  - apply CRefl.
Qed.

A: There are several problems here.
First of all, the error means you are trying to give cnat_add_morphism a proposition instead of a proof of that proposition. In Coq, proofs are objects of type of the proposition they are the proof of. for example, forall x : CNat, x¦x is a type and you have to build an object of that type to guarantee that the type is true. This is like you have a function f : nat -> nat and you write f nat, you get the following error:
The term "nat" has type "Set" while it is expected to have type "nat".

The error you are receiving is exactly the same. So you need to provide an object of type "x ¦ x" i.e., a proof that guarantees the proposition x ¦ x is true. So you can use the ceq_reflexivity axiom. The term (ceq_reflexivity x) has the type x¦x and you can use it instead of wrong usage of x¦x.
(cnat_add_morphism x x (ceq_reflexivity x))

Second, you need to apply the lemma not rewrite it and use the assumption instead of x¦x (use x and y not x only).
apply (cnat_add_morphism x y CH c c (ceq_reflexivity c)).


text:
Q: angularjs ui-router: find level of current state So I'm using ui-router and stateparams to nest child states, and it works well. I'm now trying to find a way to dictate a css class what state level the app is at. main.route1.section1 would be 3 levels.
Here's some non-working code to help show:

app.run(function($rootScope, $state, $stateParams) {
  $rootScope.$state = $state;
  $rootScope.$stateParams = $stateParams;
  $rootScope.findState = function() {
    var currentName = $state.current.name;
    var currentMatch = currentName.match(/./g);
    $rootScope.currentCount = currentMatch.length;
  };
});

I'm basically looking for a way to take $state.current.name which say equals main.route1.section1 and split it at the dot and count how many are in the array and return that number to the mg-class. Unless you have a better idea... like a regex filter?

A: Take a look of the object $state.$current (instead of $state.current). In particular, the property path : it's an array representing the state hierarchy of the current state.
So what you are looking for is : $state.$current.path.length


text:
Q: Error while calling Matrices Multiplication Function in C# I created this function to do a simple matrix multiplication
 int[] MatrixMul(string[] input, int[,] key)
        {
            int[] result = new int[input.Length];
            for (int row = 0; row < key.GetLength(0); row++)
            {
                for (int col = 0; col < key.GetLength(0); col++)
                {
                   result[row]+= key[row, col] * AtoZ.IndexOf(input[0][col]);

                }

            }
            return result;
        }

However, when I'm trying to call it, it's giving me some errors:
Calling the function:
total=MatrixMul(outPut[i],key);
Error   1   The best overloaded method match for 'Hill_Cipher_CSharp.Hill_Cipher.MatrixMul(string[], int[,])' has some invalid arguments  c:\users\wael\documents\visual studio 2013\Projects\Hill_Cipher_CSharp\Hill_Cipher.cs   34  23  Hill_Cipher_CSharp
Error   2   Argument 1: cannot convert from 'string' to 'string[]'  c:\users\wael\documents\visual studio 2013\Projects\Hill_Cipher_CSharp\Hill_Cipher.cs   34  33  Hill_Cipher_CSharp
The problem is with "outPut", and here is outPut:
IEnumerable<string> output = Enumerable.Range(0, input.Length / key.GetLength(0))
    .Select(x => input.Substring(x * key.GetLength(0), key.GetLength(0)));
            string[] outPut = output.ToArray();

A: Function Should be like:
 int[] MatrixMul(string input, int[,] key)
        {
            int[] result = new int[input.Length];
            for (int row = 0; row < key.GetLength(0); row++)
            {
                for (int col = 0; col < key.GetLength(0); col++)
                {
                   result[row]+= key[row, col] * AtoZ.IndexOf(input[col]);

                }

            }
            return result;
        }

calling function:
for (int i = 0; i < outPut.Length; i++)
            {
                encChars = MatrixMul(outPut[i], key);
            }


text:
Q: Uncaught ReferenceError when Loading a Bookmarklet I am trying to build a simple Bookmarklet that will load some external Javascript into a page, the goal is to add a markdown editor like Stackoverflow has to another site.  I have it working but it requires me to click my Bookmarklet button 2 times instead of 1 time.
The first click gives this error...
Uncaught ReferenceError: Markdown is not defined init.js:46

Line 46 is this...
var converter1 = Markdown.getSanitizingConverter();

Now after clicking my Bookmarklet for the 2nd time then everything runs perfectly but always the first click will give that error and do nothing.
Here is the code for the Bookmarklet file, please help me to fix, my Javascript skills are not too great.
Load external JS and CSS files
function loadScripts(scriptURL) {
    var scriptElem = document.createElement('SCRIPT');
    scriptElem.setAttribute('language', 'JavaScript');
    scriptElem.setAttribute('src', scriptURL);
    void(document.body.appendChild(scriptElem));
}

// Load these 3 Javascript files into the page
// jQuery is already loaded into the page being used so no need to load it
loadScripts('http://codedevelopr.com/labs/javascript/forrst/Markdown.Converter.js');
loadScripts('http://codedevelopr.com/labs/javascript/forrst/Markdown.Sanitizer.js');
loadScripts('http://codedevelopr.com/labs/javascript/forrst/Markdown.Editor.js');

// Load the CSS file into the Page
var head = document.getElementsByTagName('head')[0];
$(document.createElement('link')).attr({
    type: 'text/css',
    href: 'http://codedevelopr.com/labs/javascript/forrst/demo.css',
    rel: 'stylesheet'
}).appendTo(head);

After the files are loaded then we run this...
// Find and replace the curent textarea with the HTML we
// need for our markdown editor to work
$(document).ready(function () {
    var htmlToReplace = ' \

 \

 \
      <textarea class="wmd-input" id="wmd-input" name="description"></textarea> \

 \

';

    $("#description").replaceWith(htmlToReplace);

    //Run the Markdown editor!
    var converter1 = Markdown.getSanitizingConverter();

    var editor1 = new Markdown.Editor(converter1);
    editor1.run();

});

A: Your script files are not loaded yet at the time you're using markdown. You've merely sent the requests. You have to wait until the response is received and parsed.
I've cleaned your code up a bit as well as you're using jQuery:
var urls = [
  'http://codedevelopr.com/labs/javascript/forrst/Markdown.Converter.js',
  'http://codedevelopr.com/labs/javascript/forrst/Markdown.Sanitizer.js',
  'http://codedevelopr.com/labs/javascript/forrst/Markdown.Editor.js'
];

// map urls to getScript calls, and pass them to $.when
$.when.apply($, $.map(urls, $.getScript)).then(function() {
  // use markdown here
});

$("<link>", {
  href: 'http://codedevelopr.com/labs/javascript/forrst/demo.css',
  rel: 'stylesheet'
}).appendTo("head");


text:
Q: Can I use a Quadratic model ax^2+bx+c for nonlinear regression using levenberg? I am working on data fitting. I need to fit a surface. I used two methods.
1) Polynomial regression with two variable. (linear / OSL)
and
2) Quadratic model ax^2+bx+c.
My question is Can I use a Quadratic model ax^2+bx+c for nonlinear regression using levenberg. Since I already implemented it

A: Yes, with two considerations:
1) With linear regression you are mathematically certain to be at the minimum least-squared solution, within the arithmetic resolution of the computer you are using.  This is not certain with non-linear fitting algorithms.
2) Most nonlinear solvers have default initial parameters of all 1.0 if you do not supply initial values yourself.  This can lead to the nonlinear fitting algorithm not reaching a desired minimum least-squared solution, but a local rather than global minimum.  Linear solvers do not need initial parameters.


text:
Q: Function returns only address and not character I'm not so talented with pointers. My function returns only the address and not the word itself.
 char* randstring(){
  char words[20];
  FILE *fp;
  int i = 0, j =0, ran = 0;
  srand(time(NULL));
  fp = fopen("text.txt", "r");

  //get size of the file
  for(; fgets(words , sizeof(words), fp); j++);

  ran = rand() % 10;
  rewind(fp);
  for( i = ran; i < j ; i++){
    fgets(words, sizeof(words), fp);
  }
  return words;
}

The goal of this function is to return a list of words from a text file, after that, I write in a File.
Where exactly is the error with my pointer?


text:
Q: Доступ к приложению на виртуальной машине через браузер хоста В виртуалбоксе запущена ubuntu 18.04, где установлено некое приложение. Как можно достучаться до этого приложения с хоста через браузер. Приложение запускается на порту 8888 и использует протокол HTTP?

A: В общем, переустановил ОС на виртуальной машине, затем включил на первом сетевом адаптере сетевой мост, отключил второй сетевой адаптер. После этих манипуляция смог зайти с браузера другой машины по адресу 192.168.ххх.ххх:8888.


text:
Q: How to convert HEX to NSString in Objective-C j? I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?

A: Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
   NSString *nospaces = [raw stringByReplacingOccurrencesOfString:@" " withString:@""]; // one way to remove the spaces
   const char *cString = [nospaces UTF8String]; // C string
   NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
   NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
   NSString *decoded = attributed.string; // and finally as plain text
   return decoded;
}

That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = @"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(@"%@ -> %@", raw, decoded);

HTH

A: - (NSMutableString *) hextostring:(NSString *) str{
    //ت
    NSMutableString *string = [[NSMutableString alloc]init];

    str = [str stringByReplacingOccurrencesOfString:@"&#" withString:@"0"];
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@"z;"];
    NSArray *arr = [str componentsSeparatedByString:@";"];

    for (int i =0; i<[arr count]; i++) {
        if ([[arr objectAtIndex:i] isEqualToString:@"z"]) {
            [string appendString:@" "];
        } else {
            unsigned x;

            [[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
            [string appendFormat:@"%C",(unichar)x];
        }
    }

    NSLog(@"%@",string);
    return string;
}