text:
Q: LearnPress creating template for course content - different flow Is it possible to create a course flow like this:

$(document).ready(function() {
    $("div.bhoechie-tab-menu>div.list-group>a").click(function(e) {
        e.preventDefault();
        $(this).siblings('a.active').removeClass("active");
        $(this).addClass("active");
        var index = $(this).index();
        $("div.bhoechie-tab>div.bhoechie-tab-content").removeClass("active");
        $("div.bhoechie-tab>div.bhoechie-tab-content").eq(index).addClass("active");
    });
});
/*  bhoechie tab */
div.bhoechie-tab-container{
  z-index: 10;
  background-color: #ffffff;
  padding: 0 !important;
  border-radius: 4px;
  -moz-border-radius: 4px;
  border:1px solid #ddd;
  margin-top: 20px;
  margin-left: 50px;
  -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
  box-shadow: 0 6px 12px rgba(0,0,0,.175);
  -moz-box-shadow: 0 6px 12px rgba(0,0,0,.175);
  background-clip: padding-box;
  opacity: 0.97;
  filter: alpha(opacity=97);
}
div.bhoechie-tab-menu{
  padding-right: 0;
  padding-left: 0;
  padding-bottom: 0;
}
div.bhoechie-tab-menu div.list-group{
  margin-bottom: 0;
}
div.bhoechie-tab-menu div.list-group>a{
  margin-bottom: 0;
}
div.bhoechie-tab-menu div.list-group>a .glyphicon,
div.bhoechie-tab-menu div.list-group>a .fa {
  color: #5A55A3;
}
div.bhoechie-tab-menu div.list-group>a:first-child{
  border-top-right-radius: 0;
  -moz-border-top-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a:last-child{
  border-bottom-right-radius: 0;
  -moz-border-bottom-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a.active,
div.bhoechie-tab-menu div.list-group>a.active .glyphicon,
div.bhoechie-tab-menu div.list-group>a.active .fa{
  background-color: #5A55A3;
  background-image: #5A55A3;
  color: #ffffff;
}
div.bhoechie-tab-menu div.list-group>a.active:after{
  content: '';
  position: absolute;
  left: 100%;
  top: 50%;
  margin-top: -13px;
  border-left: 0;
  border-bottom: 13px solid transparent;
  border-top: 13px solid transparent;
  border-left: 10px solid #5A55A3;
}

div.bhoechie-tab-content{
  background-color: #ffffff;
  /* border: 1px solid #eeeeee; */
  padding-left: 20px;
  padding-top: 10px;
}

div.bhoechie-tab div.bhoechie-tab-content:not(.active){
  display: none;
}
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

Lesson 1

Lesson 2

Lesson 3

Lesson 4

Lesson 5

Lesson 1 Heading</h2

Lesson 1 Content

                      <button style="margin-top: 0;color:#55518a">Complete Lesson</button>
                      </button>

Lesson 2 Heading</h2

Lesson 2 Content

                      <button style="margin-top: 0;color:#55518a">Complete Lesson</button>
                      </button>

Lesson 3 Heading</h2

Lesson 3 Content

                      <button style="margin-top: 0;color:#55518a">Complete Lesson</button>
                      </button>

Lesson 4 Heading</h2

Lesson 4 Content

                      <button style="margin-top: 0;color:#55518a">Complete Lesson</button>
                      </button>

Lesson 5 Heading</h2

Lesson 5 Content

                      <button style="margin-top: 0;color:#55518a">Complete Lesson</button>
                      </button>

If that's possible could you help me with references to how to pull all the courses data ( course preview, lessons and all their content )? I can do it using get_posts but i'm not sure that's a good way to go about it since LearnPress has a lot of those safety checks functions and course progression etc.
For example, i'm trying to put these in my custom content-learning.php in my child theme:
$user          = LP_Global::user();
$course_item   = LP_Global::course_item();
$course        = LP_Global::course();
$can_view_item = $user->can_view_item( $course_item->get_id(), $course->get_id() );

echo '
';var_dump( $course_item );echo '
';

var_dump( $course_items ); returns null but when I switch to the default theme it works, what kind of "dependency" does it need? why is it not working?
Thanks.


text:
Q: Use read as a prompt inside a while loop driven by read? I have a use case where I need to read in multiple variables at the start of each iteration and read in an input from the user into the loop.
Possible paths to solution which I do not know how to explore --

*

*For assignment use another filehandle instead of stdin

*Use a for loop instead of ... | while read ... ... I do not know how to assign multiple variables inside a for loop
echo -e "1 2 3\n4 5 6" |\
while read a b c;
do
  echo "$a -> $b -> $c";
  echo "Enter a number:";
  read d ;
  echo "This number is $d" ;
done

A: There is only one /dev/stdin, read will read from it anywhere where it is used (by default).
The solution is to use some other file descriptor instead of 1 (/dev/stdin).
From code equivalent (in bash) to what you posted [1] (look below)
just add 0</dev/tty (for example) to read from the "real" tty:
while read a b c
do    read -p "Enter a number: " d  0</dev/tty   # 0<&2 is also valid
      echo "$a -> $b -> $c and ++> $d"
done  <<<"$(echo -e '1 2 3\n4 5 6')"

On execution:
$ ./script
Enter a number: 789
1 -> 2 -> 3 and ++> 789
Enter a number: 333
4 -> 5 -> 6 and ++> 333

Other alternative is to use 0<&2 (which might seem odd, but is valid).
Note that the read from /dev/tty (also 0<&2) will bypass the stdin of the script, this will not read the values from the echo:
$ echo -e "33\n44" | ./script

Other solutions
What is needed is to redirect one input to some other fd (file descriptor).
Valid in ksh, bash and zsh:
while read -u 7 a b c
do    printf "Enter a number: "
      read d
      echo "$a -> $b -> $c and ++> $d"
done  7<<<"$(echo -e '1 2 3\n4 5 6')"

Or, with exec:
exec 7<<<"$(echo -e '1 2 3\n4 5 6')"

while read -u 7 a b c
do    printf "Enter a number: "
      read d
      echo "$a -> $b -> $c and ++> $d"
done

exec 7>&-

A solution that works in sh (<<< doesn't work):
exec 7<<-\_EOT_
1 2 3
4 5 6
_EOT_

while read a b c  <&7
do    printf "Enter a number: "
      read d
      echo "$a -> $b -> $c and ++> $d"
done

exec 7>&-

But this is probably easier to understand:
while read a b c  0<&7
do    printf "Enter a number: "
      read d
      echo "$a -> $b -> $c and ++> $d"
done  7<<-\_EOT_
1 2 3
4 5 6
_EOT_

1 Simpler code
Your code is:
echo -e "1 2 3\n4 5 6" |\
while read a b c;
do
  echo "$a -> $b -> $c";
  echo "Enter a number: ";
  read d ;
  echo "This number is $d" ;
done

A simplified code (in bash) is:
while read a b c
do    #0</dev/tty
      read -p "Enter a number: " d ;
      echo "$a -> $b -> $c and ++> $d";
done  <<<"$(echo -e '1 2 3\n4 5 6')"

Which, if executed, prints:
$ ./script
1 -> 2 -> 3 and ++> 4 5 6

Which is just showing that the var d is being read from the same /dev/stdin.

A: With zsh, you can write it instead:
for a b c (
  1 2 3
  4 5 6
  'more complex' $'\n\n' '*** values ***'
) {
  read 'd?Enter a number: '
  do-something-with $a $b $c $d
}

For 2D arrays, see also the ksh93 shell:
a=(
  (1 2 3)
  (4 5 6)
  ('more complex' $'\n\n' '*** values ***')
)
for i in "${!a[@]}"; do
  read 'd?Enter a number: '
  do-something-with "${a[i][0]}" "${a[i][1]}" "${a[i][2]}" "$d"
done

A: If I got this right, I think you want to basically loop over lists of values, and then read another within the loop.
Here's a few options, 1 and 2 are probably the sanest.
1. Emulate arrays with strings
Having 2D arrays would be nice, but not really possible in Bash. If your values don't have whitespace, one workaround to approximate that is to stick each set of three numbers into a string, and split the strings inside the loop:
for x in "1 2 3" "4 5 6"; do
  read a b c <<< "$x";
  read -p "Enter a number: " d
  echo "$a - $b - $c - $d ";
done

Of course you could use some other separator too, e.g. for x in 1:2:3 ... and  IFS=: read a b c <<< "$x".

2. Replace the pipe with another redirection to free stdin
Another possibility is to have the read a b c read from another fd and direct the input to that (this should work in a standard shell):
while read a b c <&3; do
    printf "Enter a number: "
    read d
    echo "$a - $b - $c - $d ";
done 3<<EOF
1 2 3
4 5 6
EOF

And here you can also use a process substitution if you want to get the data from a command: while read a b c <&3; ...done 3< <(echo $'1 2 3\n4 5 6') (process substitution is a bash/ksh/zsh feature)

3. Take user input from stderr instead
Or, the other way around, using a pipe like in your example, but have the user input read from stderr (fd 2) instead of stdin where the pipe comes from:
echo $'1 2 3\n4 5 6' |
while read a b c; do
    read -u 2 -p "Enter a number: " d
    echo "$a - $b - $c - $d ";
done

Reading from stderr is a bit odd, but actually often works in an interactive session. (You could also explicitly open /dev/tty, assuming you want to actually bypass any redirections, that's what stuff like less uses to get the user's input even when the data is piped to it.)
Though using stderr like that might not work in all cases, and if you're using some external command instead of read, you'd at least need to add a bunch of redirections to the command.
Also, see Why is my variable local in one 'while read' loop, but not in another seemingly similar loop? for some issues regarding ... | while.

4. Slice parts of an array as needed
I suppose you could also approximate a 2D-ish array by copying slices of a regular one-dimensional one:
data=(1 2 3
      4 5 6)

n=3
for ((i=0; i < "${#data[@]}"; i += n)); do
    a=( "${data[@]:i:n}" )
    read -p "Enter a number: " d
    echo "${a[0]} - ${a[1]} - ${a[2]} - $d "
done

You could also assign ${a[0]} etc. to a, b etc if you want names for the variables, but Zsh would do that much more nicely.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ofstream issue: writing data stops if the file has been externally opened I suppose my issue is quite stupid but I'm not a professional programmer.
I've customized an already existing software for machine and process control for the company where I'm currently employed.
In particular, I wrote some code to obtain a log file containing the most important information about the producion process.
I'm using C++ and MFC libraries. I've used the ofstream class, and its functions. In particular I create the data file once in the creator of the class, and the I use the .open (filename, ios::out | ios::app); function in order to append information to it.
The code works well, but if I copy the log file before the end of the execution of the program (for example at the half of our production process, when I'd like to know the state of the system), it ends to writing and updating the data. Can you give me an axplanation of this and a possible solution for my issue?
Thank you so much


text:
Q: passwordless ssh not working between machines I am trying to set up passwordless SSH between 4 machines. I was able to get it done for all of them except for one Ubuntu 12.04 machine where I cannot log into it passwordlessly. Here is the sshd_config
# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile  %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication yes
# similar for protocol version 2
HostbasedAuthentication yes
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

What might the issue be? How can I go about diagnosing this?
ssh -vvv gives the following output
OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 192.168.4.36 [192.168.4.36] port 22.
debug1: Connection established.
debug1: identity file /home/farhat/.ssh/identity type -1
debug3: Not a RSA1 key file /home/farhat/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /home/farhat/.ssh/id_rsa type 1
debug1: identity file /home/farhat/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug3: Wrote 792 bytes for a total of 813
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug3: Wrote 24 bytes for a total of 837
debug2: dh_gen_key: priv key bits set: 123/256
debug2: bits set: 524/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug3: Wrote 144 bytes for a total of 981
debug3: check_host_in_hostfile: filename /home/farhat/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 1
debug1: Host '192.168.4.36' is known and matches the RSA host key.
debug1: Found key in /home/farhat/.ssh/known_hosts:1
debug2: bits set: 518/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: Wrote 16 bytes for a total of 997
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug3: Wrote 48 bytes for a total of 1045
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/farhat/.ssh/identity ((nil))
debug2: key: /home/farhat/.ssh/id_rsa (0x7fa3a4639000)
debug2: key: /home/farhat/.ssh/id_dsa ((nil))
debug3: Wrote 64 bytes for a total of 1109
debug1: Authentications that can continue: publickey,password,hostbased
debug3: start over, passed a different list publickey,password,hostbased
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/farhat/.ssh/identity
debug3: no such identity: /home/farhat/.ssh/identity
debug1: Offering public key: /home/farhat/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug3: Wrote 368 bytes for a total of 1477
debug1: Authentications that can continue: publickey,password,hostbased
debug1: Trying private key: /home/farhat/.ssh/id_dsa
debug3: no such identity: /home/farhat/.ssh/id_dsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password

Thanks,

A: On the server side, change LogLevel INFO to LogLevel DEBUG, restart the server and check the logs on the server during an access attempt.
Also, given that you have StrictModes yes and AuthorizedKeysFile  %h/.ssh/authorized_keys
 in your config, I'd check the permissions on the $HOME directory, the ~/.ssh directory, and the files in it.
For the former, it should not be group or world writable. For the latter, ensure group nor world have any permissions, i.e. chmod -R go= ~/.ssh.


text:
Q: Standard Object- Too many custom fields At the current implementation, that standard objects are customized heavily especially Account and Opportunity objects. I see many custom fields are added(about 30-40) to these objects. I was wondering is it a good a practice to add that many custom fields to an object OR add a child object to capture the custom fields?
Just wanted to get your thoughts and how you would design this..

A: This is a pretty complex answer, and can often depend on your implementation goals. But here are a few reasons why you might pick to add more fields or new objects:
Object Limits
I big reason why customers avoid creating a new child object is the limit to the number of allowed custom objects. This is often tied to your salesforce contract or edition, so optimizing how many objects is often a design-time decision.
Fat Objects Efficiency
Record storage is calculated on a per row basis. Apart from a few standard objects a single record counts as 2k of storage against your org's limit. This makes for some very simple math to determine how many records you can store. For example, a DE org comes with 5MB of data storage. So you will be able to store approximately 2500 records. This is the same whether your object has 2 fields, or 200 fields. So sometimes the "fat object" strategy is employed purely for the purpose of saving record storage space.
I've had to do this where I was storing sensor measurements on a 15 minute basis. In order to conserve space, I made each row a day, and each column the 15 minute period where the measurement was observed. This would have been really weird in any other data source, but it allowed me to optimize my space in this unusual instance.
The Emergent Org
There are plenty of times where the number of fields in an object is purely down to bad change management procedures and lack of governance, awareness or documentation as to what has been built before. Someone says they need some data about their account records. They tell the person with the keys to the data model. That person builds it. Requestor is happy. Another user makes a same or similar request and the process is repeated. This unhappy circumstance is not just limited to fields on objects but can also lead to a blob-like org in many ways (too many sharing rules, roles, profiles, reports, to name a few).
Normalize Where Possible
As a general rule you want to follow good data design practices. Attempt to normalize where possible. Make compromises where you must. But try to avoid the emergent org problem.


text:
Q: Interpreting [R] Greatest Common Divisor (GCD) (and LCM) Function in {numbers} package I don't have background in programming (except from wrestling with R to get things done), and I'm trying to verbalize what the formula for the greater common divisor in the R {numbers} package is trying to do at each step. I need help with understanding the flow of steps within the function:
function (n, m)
{
    stopifnot(is.numeric(n), is.numeric(m))
    if (length(n) != 1 || floor(n) != ceiling(n) || length(m) !=
        1 || floor(m) != ceiling(m))
        stop("Arguments 'n', 'm' must be integer scalars.")
    if (n == 0 && m == 0)
        return(0)
    n <- abs(n)
    m <- abs(m)
    if (m > n) {
        t <- n
        n <- m
        m <- t
    }
    while (m > 0) {
        t <- n
        n <- m
        m <- t%%m
    }
    return(n)
}
<environment: namespace:numbers>

For instance, in the if (m > n) {} part the n becomes t and ultimately it becomes m? I'm afraid to ask, because it may be painfully obvious, but I don't know what is going on. The same apply to, I guess, he else part of the equation with %% being perhaps modulo.

A: What it says is:
Stop if either m or n are not numeric, more than one number, or have decimals, and return the message, "Arguments 'n', 'm' must be integer scalars."
If they both are zero, return zero.
Using absolute values from now on.
Make sure that n > m because of the algorithm we'll end up applying in the next step. If this is not the case flip them: initially place n in a temporary variable "t", and assign m to n, so that now the larger number is at the beginning of the (n, m) expression. At this point both the initial (n, m) values contain m. Finish it up by retrieving the value in the temporary variable and assigning it to m.
Now they apply the modified Euclidean algorithm to find the GCD - a more efficient version of the algorithm that shortcuts the multiple subtractions, instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two.
The smaller number at the beginning of the algorithm will end up being the larger after the first iteration, therefore we'll assign it to n to get ready for the second iteration. To do so, though, we need to get the current n out of the way by assigning it to the temporary variable t. After that we get the modulo resulting from dividing the original larger number (n), which now is stored in t, by the smaller number m. The result will replace the number stored in m.
As long as there is a remainder (modulo) the process will go on, this time with the initial smaller number, m playing the role of the big guy. When there is no remainder, the smaller of the numbers in that particular iteration is returned.
ADDENDUM:
Now that I know how to read this function, I see that it is limited to two numbers in the input to the function. So I entertained myself putting together a function that can work with three integers in the input:
require(numbers)

GCF <- function(x,y,z){
    tab.x <- tabulate(primeFactors(x))
    tab.y <- tabulate(primeFactors(y))
    tab.z <- tabulate(primeFactors(z))

    max.len <- max(length(tab.x), length(tab.y), length(tab.z))
    tab_x = c(tab.x, rep(0, max.len - length(tab.x)))
    tab_y = c(tab.y, rep(0, max.len - length(tab.y)))
    tab_z = c(tab.z, rep(0, max.len - length(tab.z)))

    GCD_elem <- numeric()
    for(i in 1:max.len){
        GCD_elem[i] <- min(tab_x[i], tab_y[i], tab_z[i]) * i
    }
    GCD_elem <- GCD_elem[!GCD_elem==0]
    GrCD <- prod(GCD_elem)
    print(GrCD)
}

Also for the LCM:
LCM <- function(x,y,z){
    tab.x <- tabulate(primeFactors(x))
    tab.y <- tabulate(primeFactors(y))
    tab.z <- tabulate(primeFactors(z))

    max.len <- max(length(tab.x), length(tab.y), length(tab.z))
    tab_x = c(tab.x, rep(0, max.len - length(tab.x)))
    tab_y = c(tab.y, rep(0, max.len - length(tab.y)))
    tab_z = c(tab.z, rep(0, max.len - length(tab.z)))

    LCM_elem <- numeric()
    for(i in 1:max.len){
        LCM_elem[i] <- i^(max(tab_x[i], tab_y[i], tab_z[i]))
    }
    LCM_elem <- LCM_elem[!LCM_elem==0]
    LCM <- prod(LCM_elem)
    print(LCM)
}


text:
Q: Unable to start windows service in Services window This is the story of a windows service that has been running for years on multiple servers, but for one reason or another will not start on one specific 2012 Windows Server any longer.  It worked fine on this server also until it suddenly did not (June 26th 2019).
The error message it gives is the generic Error 1053: The service did not respond to the start or control request in a timely fashion.  This could mean almost anything.  I have followed advice from other SO questions:

*

*I have set ServicePipeTimeout in Registry to several minutes and restarted the service.  Note that the error message comes immediately when I try to start the service manually in the Services window, not after the expected time.

*I have uninstalled and reinstalled the service.

*I have put a try-catch around the entry point trying to log any exception to the EventLog.  No such message.  Note again that the error message comes immediately.

*I have checked for Windows Updates, but see none that matches when the service stopped.

*I have checked which .Net Framework is installed.  The service is 4.6.1, while it seems that everything up to and included 4.7.1 is installed.

*I have tried to swicth Log On credentials to an admin user.

*I have tried to set Allow service to interact with desktop for the Local Service as described here (as this fits my scenario except for that being a 2003 Server): Link to similar 2003 Server problem

*windbg is not installed on the server.

I can, however, double click the exe-file.  This actually works as long as I don't close the command window that opens.  In the Services window the windows service there is still not running, but now the program is running as long as I don't close the command window or the logged in session.  This is of course not a good solution.
Here is the startup code, by the way:
using System;
using System.Diagnostics;
using Topshelf;

namespace Blabla.Endpoint
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                HostFactory.Run(x =>
                {
                    x.Service<EndpointConfiguration>(s =>
                    {
                        s.ConstructUsing(name => new EndpointConfiguration());
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc => tc.Stop());
                    });
                    x.RunAsLocalSystem();
                    x.SetDescription("Handles events for Blabla.Endpoint");
                    x.SetDisplayName("Blabla.Endpoint");
                    x.SetServiceName("Blabla.Endpoint");
                });
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
                throw;
            }
        }
    }
}

Any ideas what I should try next?
Update 1
I have not been able to research this as much as I would have liked to since the post, but I have found by looking more closely at the EventLog (thanks, @Rhizzakanizza) that the last thing that happened before the service stopped working was that the server was restarted by C:\WINDOWS\CCM\CcmExec.exe.
Google says: "The process ccmexec.exe (Microsoft SMS Agent Host ) is part of the Microsoft SMS (Systems Management Server) suite, which is mainly used to distribute software patches to the machines on a network." (reference link)
Is there anywhere to see what this might have installed around or just before June 26th 2019?  There are no Windows Update patches around that date, but clearly the server was restarted by this process in conjunction with some update.

A: Some thoughts,
Add a call to EventLog.WriteEntry(); as the first line in main. It's possible for some faults to bomb straight through a try-catch, although rare. Regardless, I think it'd be more definitive in showing that there's a new configuration issue.
Check the security logs for activity during service startup. There are some differences, but they key symptoms you are describing were the same as I encountered recently. That turned out to be the "log on as" settings I was trying to use. Just to note, I'm also using TopShelf.
Finally, how far back from June 26th have you looked in the logs? It may not be a Windows Update but maybe you can find some evidence of a configuration change. If you want to cast even a wider net, search the file system to see if you can identify any interesting changes based on modification times that might correlate to your symptoms.


text:
Q: What guarantee does concurrencyLevel argument of ConcurrentHashMap give us? From the Javadocs of ConcurrentHashMap :

The allowed concurrency among update operations is guided by the
  optional concurrencyLevel constructor argument (default 16), which is
  used as a hint for internal sizing.

I do not understand the part that says "which is used as a hint for internal sizing." . What does this mean ? What is the best practice for setting this value and what guarantee does it give us ?

A: Take a look at the very next sentences in the Javadoc:

The table is internally partitioned to try to permit the indicated
   number of concurrent updates without contention. Because placement
   in hash tables is essentially random, the actual concurrency will
   vary.  Ideally, you should choose a value to accommodate as many
   threads as will ever concurrently modify the table. Using a
   significantly higher value than you need can waste space and time,
   and a significantly lower value can lead to thread contention. But
   overestimates and underestimates within an order of magnitude do
   not usually have much noticeable impact. A value of one is
   appropriate when it is known that only one thread will modify and
   all others will only read. Also, resizing this or any other kind of
   hash table is a relatively slow operation, so, when possible, it is
   a good idea to provide estimates of expected table sizes in
   constructors.

So in other words, a concurencyLevel of 16 means that the ConcurrentHashMap internally creates 16 separate hashtables in which to store data. Operations that modify data in one hashtable do not require locking the other hashtables, which allows somewhat-concurrent access to the overall Map.
You might want to try reading the source of ConcurrentHashMap.

A: Concurrency level is around equal how many operations on map can be invoked concurrently without using internal locking mechanism. As maat b is saying that ConcurrentHashMap will have N internal hashtables and thus operations which are working on different hashtables  doesn't require additional locking - otherwise if operations are working on the same internal hashtable then ConcurrenyHashMap uses additional internal locking on them.


text:
Q: Dragon age Inquisition not responding with controller? I'm using a PS3 controller plugged into my computer with an emulator to let me play it as a Xbox controller. It's all fine and dandy on other games, but the moment I switch to controller on Dragon Age Inquisition, the game crashes. I open it again and the controller lets me click start, moves me to the home screen, and just doesn't let me do anything. It makes a noise when I move my joystick, but nothing changes. I press ctrlaltdel and the screen advances to the character creation screen, but it's glitchy.
Before you ask, no I do not have two different controllers plugged in, no I don't have anything razer on my computer at all, and no I don't have any FPS tracking software or origin overlay on or anything like that. I've tried everything I've found and nothing is working; the funny thing is, my controller worked perfectly before I updated my game. Please help.


text:
Q: Magento after Onepage checkout adding new products to cart i would like to add some Products after the Checkout
I have an observer and it's listening on 'checkout_onepage_controller_success_action'
when i try
$this->_getCart()->addProduct($product, $params);
and save the cart the success page will be loaded but no new products in the cart.
Any idea what's wrong?

A: It's working if you know that you must do a new
$cart = Mage::getSingleton('checkout/cart');
before you can go one


text:
Q: invoke and wait which interacts with a sub class I have found many fine examples of invoke later and invoke and wait across the site.
However the issue that I have is that the I would like to get a response from a class which is called by the main method
Could any one provide some code that a main method calls a sub method to see how this is constructed with an invoe and wait method?
Thanks in advance

A: SwingUtilities#invokeAndWait or invokeLater take a Runnable as an argument so you can not get a result back.
Look into SwingWorkers where you can do an action in a background thread and get back the result to update the UI inside the EDT


text:
Q: breezejs update cache with changes from server I am using breezejs in a offline first manner, executing query's initially against a server and stashing the entities in local storage where I query the entity manager cache.
When data changes on the server (by means of another app changing it using breeze) the client app synchronizes by just getting a new copy of the entities from the server.
This works great but I am wondering if there is a way that I can get only the changes from the server, I was thinking maybe set a revision GUID or timestamp on each record and then checking the metadata if it needs updating but I really have no idea on how to proceed.
So my question is can breeze be tweaked to allow for such a use case?
And is there maybe a beter way that I am overlooking?

A: I think your direction is correct .If you had a column with a TimeDate in every table e.g "LastModified" and that column would get updated on every record update. then you could add a filter to every breeze query after the first that says that that date must be later than the last time you did this "rebase" query or the initial loading. so It's not supported out of the box, but you can get it to work yourself. the guid per version will not really be a good idea, as you will have to send all these guids on every request, and then check all of them. time stamp makes more sense.


text:
Q: Understanding where the continuity equation comes from Suppose we have a random variable $X$ taking values in $\mathbb{R}^k$ and that this random variable has a smooth density $p(x)$ over all of $\mathbb{R}^k$. Suppose further that I have a smooth vector field $\mathbf{g} : \mathbb{R}^k\to\mathbb{R}^k$ and let $\phi_t(x)$ denote the flow of this vector field to time $t$ starting from initial position $\phi_0(x) = x$. It seems to be a result that if I transform $X_t\overset{\text{def.}}{=} \phi_t(X)$ then the density of $X_t$ obeys a continuity equations:
$$
\frac{\partial}{\partial t} p_t(x) = -\text{div}(p_t \mathbf{g})
$$
How does one prove this result?
I actually know this result to be a special case of the Fokker-Planck equation governing stochastic differential equations. The proof I know for Fokker-Planck requires Dynkin's formula, stopping times, infinitesimal generators for diffusions, and operator adjoints. I have a feeling that a simpler proof should exist for the case wherein the diffusion coefficient is zero, as I have described.

A: BOTTOM LINE UP FRONT: You can apply the Reynolds Transport Theorem to the scalar field $p$.
Fix $A\subset\mathbb{R}^k$. This set evolves according to the flow $\phi_t$: at time $t$, the "material points" that "occupied" $A$ at time 0, occupy the set $\phi_t(A)$. The integral of $p$ over $\phi_t(A)$ is
\begin{equation}
\int_{\phi_t(A)}p(t,x)dV.
\end{equation}
The Reynolds Transport Theorem shows that
\begin{equation}
\frac{d}{dt}\int_{\phi_t(A)}p(t,x)dV = \int_{\phi_t(A)}\frac{\partial p}{\partial t}(t,x)dV + \int_{\partial\phi_t(A)}p(t,x)\mathbf{g}(x)\cdot\mathbf{n}(x)dS,
\end{equation}
where $\partial\phi_t(A)$ is the boundary of $\phi_t(A)$, $\mathbf{n}(x)$ is the outward-facing unit normal vector at $x\in\partial\phi_t(A)$, and $dS$ is the differential area on $\partial\phi_t(A)$.
By the Divergence Theorem,
\begin{equation}
\int_{\partial\phi_t(A)}p(t,x)\mathbf{g}(x)\cdot\mathbf{n}(x)dS = \int_{\phi_t(A)}\textrm{div}(p(t,x)\mathbf{g}(x))dV.
\end{equation}
So far we have
\begin{equation}
\frac{d}{dt}\int_{\phi_t(A)}p(t,x)dV = \int_{\phi_t(A)}\left[\frac{\partial p}{\partial t}(t,x) + \textrm{div}(p(t,x)\mathbf{g}(x))\right]dV.
\end{equation}
If the probability attached to each evolving set is constant, then the time derivative on the left-hand side is zero for all (well-behaved) sets $A$. The only way this can be true for such a wide class of sets is if the integrand is identically zero (or zero almost everywhere, if you're into that sort of thing).

The Reynolds Transport Theorem

We can express the integral over $\phi_t(A)$ as an integral over $A$ as follows:
\begin{equation}
\int_{\phi_t(A)}p(t,\tilde{x})dV(\tilde{x}) = \int_{A}p(t,\phi_t(x))J(t,x)dV(x),
\end{equation}
where $dV(\tilde{x})$ it the volume measure on $\phi_t(A)$, $dV(x)$ is volume measure on $A$, and $J$ is the Jacobian determinant of the map $x\mapsto\phi_t(x)$.
\begin{equation}
\frac{d}{dt}\int_{A}p(t,\phi_t(x))J(t,x)dV(x) = \int_{A}\frac{d}{dt}\left[p(t,\phi_t(x))J(t,x)\right]dV(x)
\end{equation}

Let $y(t,x) = \phi_t(x)$.
\begin{equation}
\begin{split}
\frac{d}{dt}p(t,\phi_t(x)) &=~ \frac{d}{dt}p(t,y(t,x))\\
&=~ \frac{\partial p}{\partial t}(t,y(t,x)) + \sum_{i=1}^{k}\frac{\partial p}{\partial x_i}(t,y(t,x))\frac{\partial y_i}{\partial t}(t,x)\\
&=~ \frac{\partial p}{\partial t} + (\nabla p)\cdot\mathbf{g},
\end{split}
\end{equation}
where the spatial argument of each term in the last line is $y(t,x) = \phi_t(x)$.

\begin{equation}
\begin{split}
\frac{d}{dt}J(t,x) &=~ \frac{d}{dt}\det\left(\textrm{grad}~\phi_t(x)\right)\\
&=~ \frac{d}{dt}\det\left(\textrm{grad}~y(t,x)\right)\\
&=~ \textrm{div}\left(\frac{\partial y}{\partial t}(t,x)\right)J(t,x)\\
&=~ \textrm{div}\left(\mathbf{g}(y(t,x))\right)J(t,x)
\end{split}
\end{equation}

When we put these terms together, the integrand over $A$ is seen to be
\begin{equation}
\begin{split}
\frac{d}{dt}\left[p(t,y(t,x))J(t,x)\right] &=~ J(t,x)\frac{d}{dt}p(t,y(t,x)) + p(t,y(t,x))\frac{d}{dt}J(t,x)\\
&=~ J\left(\frac{\partial p}{\partial t} + (\nabla p)\cdot\mathbf{g}\right) + pJ~\textrm{div}(\mathbf{g})\\
&=~ J\left(\frac{\partial p}{\partial t} + (\nabla p)\cdot\mathbf{g} + p~\textrm{div}(\mathbf{g})\right)\\
&=~ J\left(\frac{\partial p}{\partial t} + \textrm{div}\left(p\mathbf{g}\right)\right).
\end{split}
\end{equation}

In summary,
\begin{equation}
\begin{split}
\frac{d}{dt}\int_{\phi_t(A)}p(t,\tilde{x})dV(\tilde{x}) &=~ \frac{d}{dt}\int_{A}p(t,\phi_t(x))J(t,x)dV(x)\\
&=~ \int_{A}\left(\frac{\partial p}{\partial t}(t,\phi_t(x)) + \textrm{div}\left(p(t,\phi_t(x))\mathbf{g}(\phi_t(x))\right)\right)J(t,x)dV(x)\\
&=~ \int_{\phi_t(A)}\left(\frac{\partial p}{\partial t}(t,\tilde{x}) + \textrm{div}\left(p(t,\tilde{x})\mathbf{g}(\tilde{x})\right)\right)dV(\tilde{x})
\end{split}
\end{equation}


text:
Q: Convergence of $ \int_0^{1/2}\frac{1}{\sin x\ln x}\, dx $
Does the following integral converge or diverge?
  $$ \int_0^{1/2}\frac{1}{\sin x\ln x}\, dx $$

When $x \in [0,1/2] , \sin x>0$ and $\ln x<0$. Therefore $-1/(\sin x\ln x)>0$, which means I can use the comparision test.
$$ \int_0^{1/2} \frac{1}{\sin x\ln x}dx  <  \int_0^{1/2} \frac{1}{\ln x}dx $$
I don't know what to do next in order to prove convergence (which I think is the answer). Hints will be appreciated.

A: Hint: Note that $\frac2\pi x\le\sin(x)\le x$ for $0\le x\le\frac\pi2$. Therefore,
$$
\frac{\pi}{2}\int_0^{1/2}\frac1{x\log(x)}\,\mathrm{d}x\le\int_0^{1/2}\frac1{\sin(x)\log(x)}\,\mathrm{d}x\le\int_0^{1/2}\frac1{x\log(x)}\,\mathrm{d}x.
$$


text:
Q: Not an ARRAY reference when trying to trying to update old Perl code. Hash to Array issue? I am trying to update an outdated perl plugin to Google's new API (They changed their search call). I'm new to Perl so I'm not sure how to correctly update the code. I'm pretty sure I'm trying to read a hash when it's supposed to be an array?
Data Structure Dumped:
$VAR1 = {
          'station_hits' => bless( do{\(my $o = 1726698624)}, 'Inline::Python::Object' ),
          'album_hits' => bless( do{\(my $o = 1726698288)}, 'Inline::Python::Object' ),
          'artist_hits' => bless( do{\(my $o = 1726698336)}, 'Inline::Python::Object' ),
          'situation_hits' => bless( do{\(my $o = 1726698384)}, 'Inline::Python::Object' ),
          'song_hits' => bless( do{\(my $o = 1726698432)}, 'Inline::Python::Object' ),
          'playlist_hits' => bless( do{\(my $o = 1726698480)}, 'Inline::Python::Object' ),
          'video_hits' => bless( do{\(my $o = 1726698528)}, 'Inline::Python::Object' )
        };

Code Block:
# Search All Access
sub search {
        my $query = shift;

        return unless $prefs->get('all_access_enabled');

        my $uri = 'googlemusic:search:' . $query;

        if (my $result = $cache->get($uri)) {
                return $result;
        }

        my $googleResult;
        my $result = {
                tracks => [],
                albums => [],
                artists => [],
        };

        eval {
                $googleResult = $googleapi->search($query, $prefs->get('max_search_items'));
        };

        if ($@) {
                $log->error("Not able to search All Access for \"$query\": $@");
                return;
        }
        #My Attempt
        for my $hit (%@{$googleResult->{song_hits}}) {
                push @{$result->{tracks}}, to_slim_track($hit->{track});
        }
        #How it was originally
        for my $hit (@{$googleResult->{album_hits}}) {
                push @{$result->{albums}}, album_to_slim_album($hit->{album});
        }

I'm getting this error after making only a name change:
Not an ARRAY reference at [LINE#]
Changed search_all_access to search
Line in question:
for my $hit (@{$googleResult->{song_hits}}) {

I tried researching and added a % in front, but now I am getting an error on the following line.
'newlist' object has no attribute 'track' at [LINE#+1]
 push @{$result->{tracks}}, to_slim_track($hit->{track});

EDIT:
After making the changes after explaining well how referencing a hash is supposed to work, I get this:
 [16-05-23 10:22:36.7283] Slim::Networking::IO::Select::__ANON__ (131) Error: Select task failed calling Slim::Web::HTTP::processHTTP: Can't locate object method "FIRSTKEY" via package "Inline::Python::Object::Data" at /usr/lib/arm-linux-gnueabihf/perl/5.20/Data/Dumper.pm line 224.
; fh=Slim::Web::HTTP::ClientConn=GLOB(0x1007a188)

I'm not sure if there was an existing error in their code or that Google is returning the API data in a different structure after this latest error.

A: These objects seem to be abstracted away. You can read the Inline::Python documentation, but there's nothing about it. In the code for the Inline::Python::Object however, there is a hint.
Two lines down, there is this (omission mine).

use overload '%{}' => \&__data__, # [...]

If it has an overload for when it's used with a hash dereference we can be pretty sure it will return a hash ref in that case.
Now all we need to do is fix your syntax error that you introduced. You did %@{}, which is not valid syntax. Instead of the array deref @{}, you need %{}.
for my $hit (%{ $googleResult->{song_hits} }) {
        push @{$result->{tracks}}, to_slim_track($hit->{track});
}

But because hashes in Perl are essentially lists, you will now iterate over both the keys and the values. That's hardly ever a good idea. Instead, you should iterate over the keys, and then work with that. Or more likely, there is only one key in each of them that you are interested in. If there is an API description, I suggest you check it. It might be helpful here.
If not, Dumper it like this.
print Dumper \%{ $googleResult->{song_hits} };

That dereferences it first, making sure that overload is called. Because Data::Dumper doesn't understand lists as data structures, you are passing it a reference to the returned hash, so you get $VAR1={} instead of $VAR1='foo'; $VAR2='bar' and so on.

A: If you use Data::Dumper to print out those data structures you will soon see what form they are in.Then you won't have to guess. Also don't mistake the object oriented calling style with hash access. , they are they same because that's how Perl5 objects are made.
use data::dumper;
print "variable is :" + Dumper(@variable)

A: I don't see what is the intended "update", what needs to be changed. But here are a few comments.
First: the syntax is invalid -- one cannot have %@{...}. You can dereference a reference to either a hash, %{$hashref}, or to an array, @{$arrayref} (or to scalar, $$scalarref).

Your data structure is interesting.  First, it is a hash reference. (Or, rather, an anonymous hash.)  You can either dereference it altogether to create a hash, or can pull values for specific keys as
my $href = { 'k1' => 'val1', 'k2' => 'val2' };
my $value_of_k1_key = $href->{'k1'};            # will be == val1

Next, the 'value' in your code is formally an object. The bless function associates a reference to a data structure (usually a hashref) with a class, making it an object of that class (which it returns).
So you really have
$href = { 'station_hits' => $object, ... }

After you query (any of) the keys, you are getting back that object.
$object = $googleResult->{song_hits}

According to code shown under "# How it was originally" (which I presume works), the object's data structure is a reference to an array, not a hash, since it dereferences an array. That's OK.  The odd part is that it dereferences it directly, seeking its data/attributes. In terminology of some other languages, it is accessing (presumably) private members.  In Perl that is legal and will retrieve a value but it is generally considered as bad as if it were banned.


text:
Q: Send server information to client Last semester we had to develop the game Ludo in JavaScript and HTML/CSS. That was pretty easy. Now we have to develop a backend with GWT (Java) to create a multiplayer game. Sadly, we haven't got much information on how to develop with GWT and the exercise is quite difficult at the beginning.
At the moment I am trying to create a kind of lobby where different players can join.
My idea was to use some input fields, where the player could enter his name and join the lobby. But I don't know how to give the other clients the information that a new player has joined.
I created an asynchronous interfaces (RPC) where a player could submit his name to the server (Like this example). This works ok. But how should I share this information? Our docent said we should use JSON to share information's, but I don't know how this should help in this situation.
Is there a way to send information's to the clients? I read a lot and just find to use additional libraries as gwt-comet.
I have really now clue how I could go on. I'm thankful for every help and information!
Greetz

A: You have two options: push and pull.
"Pull" option:
Other players get required information when they join the lobby and/or do something else. You can also schedule to pull this information periodically (like once every 10 minutes).  You can use the same RPC mechanism to get data from server to a client. "Pull" means that a client initiates the request and server responds with the information.
"Push" option:
When a new player joins, the server pushes this new data to all other players. The best solution depends on your game implementation. Comet is a good option, as Jean-Michel mentioned, but it's more complicated and "expensive" from resources point of view. You should use this option if you need real-time status updates for your game.

A: I would suggest Errai and ErraiBus in particular. From Java perspective you are only sending some events via event bus (observer GoF pattern) and all the magic with Ajax Push is happening behind the scenes.


text:
Q: Найти наибольший элемент массива и его порядковый номер Нужно найти наибольший элемент массива и его порядковый номер на C#, с полноценным разбором

A: Для нахождения большего элемента в массиве(Предположим int, в вопросе не сказан тип данных) нужно сделать примерно так:
int maxValue = yourList.Max<int>();

А для определнения его индекса можно использовать IndexOf:
int index = Array.IndexOf(yourList, maxValue);


text:
Q: Spark RDD - Error while sending iterator So, I'm just trying to iterate over a Spark RDD and perform an action on each row, like so:
for row in df.rdd.toLocalIterator():
    print(row)

But I get a weird exception:
ERROR PythonRDD:91 - Error while sending iterator
java.lang.IllegalArgumentException
    at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
    at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
    at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
    at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432)
    at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103)
    at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230)
    at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40)
    at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103)
    at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732)
    at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432)
    at org.apache.xbean.asm5.ClassReader.a(Unknown Source)
    at org.apache.xbean.asm5.ClassReader.b(Unknown Source)
    at org.apache.xbean.asm5.ClassReader.accept(Unknown Source)
    at org.apache.xbean.asm5.ClassReader.accept(Unknown Source)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:261)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:159)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2292)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2066)
    at org.apache.spark.rdd.RDD$$anonfun$toLocalIterator$1.org$apache$spark$rdd$RDD$$anonfun$$collectPartition$1(RDD.scala:954)
    at org.apache.spark.rdd.RDD$$anonfun$toLocalIterator$1$$anonfun$apply$30.apply(RDD.scala:956)
    at org.apache.spark.rdd.RDD$$anonfun$toLocalIterator$1$$anonfun$apply$30.apply(RDD.scala:956)
    at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$class.foreach(Iterator.scala:893)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
    at org.apache.spark.api.python.PythonRDD$.writeIteratorToStream(PythonRDD.scala:204)
    at org.apache.spark.api.python.PythonRDD$$anon$1$$anonfun$run$1.apply$mcV$sp(PythonRDD.scala:400)
    at org.apache.spark.api.python.PythonRDD$$anon$1$$anonfun$run$1.apply(PythonRDD.scala:400)
    at org.apache.spark.api.python.PythonRDD$$anon$1$$anonfun$run$1.apply(PythonRDD.scala:400)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1377)
    at org.apache.spark.api.python.PythonRDD$$anon$1.run(PythonRDD.scala:401)

Seems oddly dev-ops-y to me, and I'm wondering if I botched a pip installation or something. Any suggestions?
Thanks!


text:
Q: Does using Dynamic DNS or port forwarding to set up a website blocks other people in the network from doing the same? So, I've been reading around about dynamic DNS and portforwarding, among others here:
Portforwarding to multiple computers
If I gather correctly, this is the scenerio that will unfold in real life: Let's say I want to setup a webserver on my local machine, but I don't want but a dedicated server, so I decide I will use dynamic DNS service with port forwarding, so that each time my current IP allocated by my ISP to me (and to many other users) will direct to my website.
Does that mean that it is impossible for another website of some user that is in the same ISP and is for the current moment behind the same NAT as me, to be reachable at the same time as my website? Because at that situation, we will share the same IP:PORT until one of us will get a new IP from our ISP.
If that's true, that just seems pretty impractical to me. Am I missing something here? Are there no ways to overcome this possible issue?
Hopefully I've made myself clear, as English isn't my native language.

A: Yes, technically you would be correct – but in practice, if you're behind ISP-controlled NAT, then you generally cannot set up port forwarding in the first place.
When you're behind a CGNAT and share the address with other customers, it doesn't matter if you configure some port-forwarding rules on your own router; they will have no effect on the ISP's routers which actually 'own' the public address – only the ISP can provide port-forwarding. And in most cases, the ISP will refuse to do it.
So yes, it's impractical, and that's why in practice it isn't done in the first place.

When people actually use port forwarding, it's used with ISPs which don't implement CGNAT yet – they assign a public IP address directly to a single customer. Yes, the IP:port can still be forwarded to one device only, no matter where NAT happens... but the problem isn't nearly as significant because there's no sharing between customers – only between devices belonging to the same LAN.
(In the case of HTTP, it's even less significant because the customer can set up a reverse proxy and route HTTP requests to different devices based on the domain name.)

Finally, note that Dynamic DNS is completely unrelated to this. All it does here – well, all that regular DNS does – is assign a name to the IP address, but the actual traffic doesn't know the difference. When a browser tries to set up a connection to your webserver, the IP and TCP packets look exactly the same whether DNS was used or not.


text:
Q: selecting row with highest value and a join Ho can i only fetch the rows with the highest cvID value?
current code
SELECT
  CollectionVersionBlocks.cID,
  CollectionVersionBlocks.cbDisplayOrder,
  CollectionVersionBlocks.cvID,
  btContentLocal.bID,
  btContentLocal.content
FROM
  CollectionVersionBlocks
  INNER JOIN btContentLocal
    ON CollectionVersionBlocks.bID = btContentLocal.bID
WHERE (CollectionVersionBlocks.cID = 259)
  AND CollectionVersionBlocks.isOriginal = 1
  AND CollectionVersionBlocks.arHandle = 'main'
  AND btContentLocal.content != ''

I want to get the row at the bottom (where the cvID value is 10).
This is a test statement for a bigger result set -
I will eventually need a set of results from perset cIDs (CollectionVersionBlocks.cID = 259 OR CollectionVersionBlocks.cID = 260... upto 800)

updated screenshots
1) too few results
2) un grouped results

A: To get the highest row per group (from your question i assume cID as a single group) you can do so by using a self join on the maxima of your desired column by using additional condition in in your third join i.e ON(c.cID=cc.cID AND c.cvID=cc.cvID)
SELECT
  c.cID,
  c.cbDisplayOrder,
  c.cvID,
  b.bID,
  b.content
FROM
  CollectionVersionBlocks  c
  INNER JOIN btContentLocal b
    ON (c.bID = b.bID)
  INNER JOIN
  (SELECT cID, MAX(cvID) cvID FROM CollectionVersionBlocks GROUP BY cID) cc
  ON(c.cID=cc.cID AND c.cvID=cc.cvID)
WHERE (c.cID = 259)
  AND c.isOriginal = 1
  AND c.arHandle = 'main'
  AND b.content != ''

and for multiple groups you can just use WHERE c.cID  IN(259,....800)

A: Try below Query:
SELECT CollectionVersionBlocks.cID,CollectionVersionBlocks.cbDisplayOrder,        CollectionVersionBlocks.cvID ,  btContentLocal.bID , btContentLocal.content
FROM CollectionVersionBlocks
INNER JOIN btContentLocal
ON CollectionVersionBlocks.bID=btContentLocal.bID
WHERE (CollectionVersionBlocks.cID = 259)
AND CollectionVersionBlocks.isOriginal=1 AND CollectionVersionBlocks.arHandle ='main'            AND           btContentLocal.content !='' and CollectionVersionBlocks.cID in
(

    SELECT Max(CollectionVersionBlocks.cID)
    FROM CollectionVersionBlocks
    INNER JOIN btContentLocal
    ON CollectionVersionBlocks.bID=btContentLocal.bID
    WHERE (CollectionVersionBlocks.cID = 259)
    AND CollectionVersionBlocks.isOriginal=1 AND CollectionVersionBlocks.arHandle   ='main' AND btContentLocal.content !='' )


text:
Q: Validate a user requests between servers Background: I am creating a file server. I am using Tomcat behind Nginx reverse proxy. I have a main server which host the UI and lots of edge servers where I hope to store user uploaded files and serve them back. It's a private file storage so only the file uploader should be able to download their uploaded files.
Problem: I authenticate users on the main server when they login to their account by creating a session and keep it to validate further requests from users (regular stuff). This information is not propergated to edge servers, edge servers serve files to any request. That's not what I want. I want to authorize downloads only to file owner.
Now, here I am trying to avoid Tomcat clustering where edges and main servers configure as a cluster that has sessions distributed. Site is SSL supported. Is there a way to validate a user's login status when a file download request reach an edge server from a user who is already logged in(created a session) the main server?

A: I see several approaches you could use
You can use a form of "claim based authentication" or resource access token.
Claim based authentication - you could use e.g. a JWT token, which should contain some necessary information (user id, account id, authorization, expiration, ..) and is signed by a shared secret (between the main server and file servers) or by a private key from the main server.
Advantage is, that the edge server can validate the token based on the hash or signature without contacting the main server. Disadvantage is, that there must be logic to decide whether the user has access to the requested resource.
see: https://jwt.io/
Resource access token - this approach that is used some cloud  storage providers (AWS S3, IBM Object Storage, ...) - the main site will return a resource URL with some extra parameters - e.g. account, nonce, expiration, signature. The resource (edge) server must check the expiration and signature and provide or deny the resource
Advantage is, that the edge server doesn't care about any authentication and the authentication and authorization is completely in scope of the main server. Disadvantage is, that the provided resource URL must have limited expiration time.
see: http://s3-expiry.50projects.com/
Note:

*

*placing the condition that the resource server may not communicate with the main server effectively you're unable to check if the user is logged in, except using SAML SSO with SLO (single logout) or OIDC with session management


text:
Q: How to debug speechSynthesis that isn't making any sound I am using the SpeechSynthesis API in its simplest form, basically
var msg = new SpeechSynthesisUtterance();
msg.text = 'Saying something'
window.speechSynthesis.speak(msg)

Even if I run this in the console I hear no sound. How do I debug something like this? I know the code is working but I get no audio output from any browser I try.


text:
Q: Why is the group operation $A\cdot \{v_1,...,v_n\}:=\{Av_1,...,Av_n\}$ transitive?
*

*$\mathcal{O}=\{\{v_1,...,v_n\}\subset \mathbb{R}^n \mid\{v_1,...,v_n\} \text{ is  an orthonormal Basis of } \mathbb{R}^n\}$

*$\mathcal{S}^{n-1}=\{x\in \mathbb{R}^n \mid \| x\|=1\}$
I have to prove that $\operatorname{O}(n)\times \mathcal{O}\to \mathcal{O}, (A,\{v_1,...,v_n\})\mapsto A\boldsymbol{\cdot} \{v_1,...,v_n\}=\{Av_1,...,Av_n\}$ is a transitive group operation, hence for two elements $\{a_1,...,a_n\},\{b_1,...,b_n\}$ there has to be a $A\in \operatorname{O}(n)$ such that $A\{a_1,...,a_n\}=\{Aa_1,...,Aa_n\}=\{b_1,...,b_n\}$
I don't really know what to prove here. Since $A$ is orthogonal matrix, we know that $|\det(A)|=1\neq 0$ and thus there will be an inverse $A^{-1}$. Isn't this basically a system of equations $Aa_1=b_1,...,Aa_n=b_n$?

A: Hint:
You want to show for any two orthonormal bases $\{ a_1, \ldots, a_n \}$ and
$\{ b_1, \ldots, b_n \}$ there is an orthogonal matrix going from one basis to the other.
That is, $A a_k = b_k$ for each $k$.
Of course, since the $\{ a_k \}$ form a basis, you've now defined a map on a basis. So this extends to a linear map in a unique way. Do you know how to find the matrix associated to a linear map? Once you have this matrix in hand, can you show it's orgthogonal? This will amount to checking that each $b_i \cdot b_j = \begin{cases} 1 & i = j \\ 0 & i \neq j \end{cases}$ (do you see why?), which will be true because of the orthonormal-ness of the $\{ b_k \}$ basis.

I hope this helps ^_^


text:
Q: JQuery shrink fixed menu animation speed based on scroll speed? I managed to get a fixed menu, that shrinks on scroll, using the following code: http://jsfiddle.net/JJ8Jc/913/
But I would like the animation / shrink speed to follow the scroll speed pixel by pixel, just like you see in the WP Enfold theme: http://www.kriesi.at/themes/enfold/ So when a user only scrolls down 5 pixels from the top, the menu shrinks 5 pixels. And when a user scrolls up 5 pixels, the menu increases 5 pixels in height.
Is that even possible with the animation code I'm currently using? Or does it require a different approach?
Code I'm currently using:
$(function(){
    $('#header_nav').data('size','big');
});

$(window).scroll(function(){
if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
{
    if($('#header_nav').data('size') == 'small')
    {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
    }
}
});

A: Ok, I was able to get the exact same fixed menu effect, as seen in the Unfold theme, by modding some jQuery code meant to resize a div through scrolling. And adding a min-height CSS value to the #header_nav class.
Here's the fiddle link showing the code in action: http://jsfiddle.net/JJ8Jc/919/
TIP re menu transparency: In case you'd like to recreate the transparency of the Unfold menu, simply use a repeat 1px*1px PNG (with a transparency around 90%-95%) as #header_nav background image. Using CSS for this is also possible, but that'll also make your logo and menu items transparent.
In case someone knows of a better solution, I'd still like to hear about it :)
The jQuery:
$(document).ready(function(){
    $(window).scroll(function() {
        var $myDiv = $('#header_nav');
        var OriginalHeight = '100';
        var st = $(this).scrollTop();
        $myDiv.height( OriginalHeight - st );
    }).scroll();
});

The CSS:
body {
    height:1000px;
    width:100%;
    background-color:#F0F0F0;
}

#header_nav {
    width:100%;
    height:100px;
    min-height:40px;
    background-color:#666;
    position:fixed;
    top:0;
    left:0;
}
#header_nav img {
    height:100%;
}

#content_wrapper {
    width:100%;
    height:500px;
    padding-top:100px;
}

Example HTML used:

Just some content.


text:
Q: JavaFX Maven Plugin Failed to execute goal (missing parameters) I use below pom.xml file to package my JavaFX 8 application. When I run through NetBeans I get following error:

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project CoperativeERP: The parameters 'executable' for goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec are missing or invalid -> [Help 1]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>re.iprocu</groupId>
<artifactId>CoperativeERP</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>CoperativeERP</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mainClass>re.iprocu.coperativeerp.MainApp</mainClass>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<organization>
    <!-- Used as the 'Vendor' for JNLP generation -->
    <name>Your Organisation</name>
</organization>
<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>8.1.4</version>
                <configuration>
                        <mainClass></mainClass>
                </configuration>
                <executions>
                        <execution>
                                <id>create-jfxjar</id>
                                <phase>package</phase>
                                <goals>
                                        <goal>build-jar</goal>
                                </goals>
                        </execution>
                </executions>
        </plugin>
    </plugins>
</build>

I am using jdk 1.8.0_77 with NetBean IDE 8.1.
I am new to Maven and JavaFX packaging, so am expecting something easy to use and understand.

A: Look at:
<configuration>
   <mainClass></mainClass>
</configuration>

It is empty. There you main class fully specified name (example com.myproject.Main) should be written.
Looking at documentation whole plug-in configuration should looks like this:
<plugin>
   <groupId>com.zenjava</groupId>
   <artifactId>javafx-maven-plugin</artifactId>
   <version>8.5.0</version>
   <configuration>
       <vendor>YourCompany</vendor>
       <mainClass>your.package.with.Launcher</mainClass>
   </configuration>
</plugin>

Make sure that your <mainClass> contains main method (apps entry point) and tat you are using newest version possible. Also try first build the project by mvn clean package without the javafx-maven-plugin.


text:
Q: How to programmatically link a contact number? I want to develop contact application with basic CRUD operations with Contacts, and Mostly Link Contact Numbers using Android.

A: Try this it works for me :
public class MyActivity extends Activity {

private static final String TAG = MyActivity.class.getSimpleName();
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID;     // contacts unique ID

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public void onClickSelectContact(View btnSelectContact) {

    // using native contacts selection
    // Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
    startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
        Log.d(TAG, "Response: " + data.toString());
        uriContact = data.getData();

        retrieveContactName();
        retrieveContactNumber();
        retrieveContactPhoto();

    }
}

private void retrieveContactPhoto() {

    Bitmap photo = null;

    try {
        InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
                ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));

        if (inputStream != null) {
            photo = BitmapFactory.decodeStream(inputStream);
            ImageView imageView = (ImageView) findViewById(R.id.img_contact);
            imageView.setImageBitmap(photo);
        }

        assert inputStream != null;
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void retrieveContactNumber() {

    String contactNumber = null;

    // getting contacts ID
    Cursor cursorID = getContentResolver().query(uriContact,
            new String[]{ContactsContract.Contacts._ID},
            null, null, null);

    if (cursorID.moveToFirst()) {

        contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
    }

    cursorID.close();

    Log.d(TAG, "Contact ID: " + contactID);

    // Using the contact ID now we will get contact phone number
    Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                    ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

            new String[]{contactID},
            null);

    if (cursorPhone.moveToFirst()) {
        contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    }

    cursorPhone.close();

    Log.d(TAG, "Contact Phone Number: " + contactNumber);
}

private void retrieveContactName() {

    String contactName = null;

    // querying contact data store
    Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

    if (cursor.moveToFirst()) {

        // DISPLAY_NAME = The display name for the contact.
        // HAS_PHONE_NUMBER =   An indicator of whether this contact has at least one phone number.

        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    }
    cursor.close();
    Log.d(TAG, "Contact Name: " + contactName);
}
}

main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" >

<Button android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select a Contact"
        android:onClick="onClickSelectContact" />

<ImageView android:id="@+id/img_contact"
           android:layout_height="wrap_content"
           android:layout_width="match_parent"
           android:adjustViewBounds="true"
           android:contentDescription="Contacts Image"
            />

and add this to menifest file :
  <uses-permission android:name="android.permission.READ_CONTACTS" />


text:
Q: Connecting ADFS to Flutter App using ASP.NET Core MVC I am trying to connect ADFS for SSO in a Flutter app. I decided to use ASP.NET core MVC to connect the flutter app and the ADFS together because I didn't find any packages for connecting ADFS to Flutter directly. However, resources for connecting ADFS to Asp.Net core MVC are very few.
I have ADFS configured and flutter app working. When the user presses the button in the flutter app for SSO it should take the user to a browser where they sign in and if successful should go back to the app and open the user's account.

*

*Is connecting through ASP.NET core MVC the correct approach?

*If yes, how can I do it?

*If not, what is the best approach?


text:
Q: Unable to connect database schema hibernate, gradle I'm unable to get spring boot to automatically load my database schema when I start it up.
I follow this example: https://spring.io/guides/gs/accessing-data-mysql/#scratch
Here is my application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/sakila
spring.datasource.username=root
spring.datasource.password=root1

sakila it is a default database included in mysql
enter image description here
Error:
Unable to create initial connections of pool


text:
Q: JavaFX: Setting Drag Done Currently I am developing a program which transfers a list item into another list. It works well with setOnDragExited,if I drag it to another component with the setOnDragExited, it will be dropped. (Which I think the program is rightbecause that is the function of setOnDragExited. But I need the program to only drop the list item when I release the button).
So I have the source which is fieldList and the target which is mainTable
Here is the code for the source, which I have no problem with.
fieldList.setOnDragDetected(new EventHandler<MouseEvent>() {
         public void handle(MouseEvent event) {
                /* drag was detected, start a drag-and-drop gesture*/
                /* allow any transfer mode */
                Dragboard db =fieldList.startDragAndDrop(TransferMode.ANY);
                /* Put a string on a dragboard */
                ClipboardContent content = new ClipboardContent();
                content.putString(fieldList.getSelectionModel().getSelectedItem());
                db.setContent(content);

                event.consume();
         }
    });

And here is the code which doesn't work with setOnDragDropped but works with setOnDragExited
mainTable.setOnDragDropped(new EventHandler<DragEvent>() {
             public void handle(DragEvent event) {
                 /* data dropped */
                    System.out.println("onDragDropped");
                    /* if there is a string data on dragboard, read it and use it */
                    Dragboard db = event.getDragboard();
                    boolean success = false;
                    if (db.hasString()) {
                        ObservableList<String> ls = FXCollections.observableArrayList();

                        try {
                            columnLS.add(Resources.getgBCon().getActualName(tableList.getSelectionModel().getSelectedItem())+"."+db.getString());
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        success = true;
                        String base= "";
                       if(!columnLS.isEmpty()){
                            for(int i = 0; i<= columnLS.size()-1 ;i++){
                                if(i == 0){
                                    base = columnLS.get(i);
                                }else{
                                    base = base + ", " + columnLS.get(i);
                                }
                            }
                        }
                        columnQuery = base;
                        me.refreshSQLQuery(columnQuery,getTableQuery(),filterQuery,groupQuery,sortQuery);
                    }
                    /* let the source know whether the string was successfully
                     * transferred and used */
                    event.setDropCompleted(true);

                    event.consume();
             }
        });

So far I didn't find anything that relates to my problem, on those that are remotely related I found, I have tried but to no avail.
Thank you Stack Overflow.
I have added setOnDragEntered. It seems it still didn't work. Is there a difference between setOnDrag and setOnMouseDrag?
mainTable.setOnDragEntered(new EventHandler<DragEvent>() {
             public void handle(DragEvent event) {
                     System.out.println("onDragEntered");
                    event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
             }
        });

I have also tried TransferMode.ANY but to no avail.
Solution:
Used  mainTable.setOnDragOver instead of mainTable.setOnDragEntered


text:
Q: Drupal Template Variables Something that has been bothering me since I started using drupal is how exactly does the php engine know which $node/$classes/$attributes you are referring to in template files. these variables are never declared as globals, so how does the php engine figure out what "$node" you are referring to??

A: See http://drupal.org/node/223430 which states

The main role of the preprocessor is to set up variables to be placed
  within the template (.tpl.php) files. From Drupal 7 they apply to
  templates and functions, whereas in Drupal 6 preprocess functions only
  apply to theming hooks implemented as templates. Plain theme functions
  do not interact with preprocessors.

Look at the template_preprocess* and the template_process referred to in the API.  These functions show you the code that set up the various variables that you can access in your node template.
In a similar manner, you can also add your own preprocess code in a theme function to add to the variables available in your tpl.php file like so:
/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_node(&$variables) {
   $variables['hello'] = 'Look at me now!';
}

After this, you can reference $hello in your node.tpl.php file.

A: These variables are set by Drupal's templating engine.


text:
Q: I am getting the following error while trying to use the library function fminunc in octave error: 'cholupdate' undefined near line 209 column 14
error: called from
fminunc at line 209 column 12
ex2 at line 86 column 13

A: My C drive had run out of space so the installation probably didn't succeed properly.
Reinstalling Octave after clearing space has fixed the issue.
Thanks for your help.


text:
Q: Dealing with label noise (Regression, NLP) For my school project, my group is tackling this Kaggle challenge (assign reading level based on passage).
commonlitreadabilityprize
However, it seems there is some label noise (examples below, lower score means more difficult)

https://imgur.com/VQJYRqA

https://imgur.com/4JQDp2F

https://imgur.com/SxIgiin
What are some good ways with identifying and/or correcting mislabeled regression scores for textual data?
Since this is for a Deep Learning course, deep methods would be preferred.

A: There are a lot more prior works on noisy labels than noisy regression values; we could adapt some ideas from them.
Some of the easier categories of techniques (and some ways to use them) are:

*

*Robust architecture

*

*We take the regression value and corrupt it (e.g. sample from Gaussian distribution with the given regression value and the standard deviation). Then on top of the base model you already have, we add an additional layer that takes in the input from the base model and predicts the noisy value. The loss function will be the difference between the generated noisy value and the predictions. When evaluating, we will use the prediction of the base model.

*Robust regularization

*

*We can conduct data augmentation by augmenting our training data to harder and easier versions and include them in our training data. This is usually based on heuristics which would require you to have some knowledge in linguistic (or if you are lucky, there might be prior works that you can use easily).

*A similar idea would be to source for additional datasets. e.g. if you believe that classic literature works (e.g. Shakespeares) use harder-to-read sentence structures and vocabularies, you can include them in your datasets as hard examples. Conversely, you could do the same by including children's books as easy examples. By doing so, you are hoping to bais the NN to capture different styles of sentence structures and vocabularies and use them in the prediction.

*Loss adjustment

*

*You can try to reweight the losses by the standard deviation of the regression to account for the uncertainty around the target. More specifically, data points with higher standard deviation should have smaller loss values (e.g. multiply by 1/std.dev - do play around with different weighting functions).

*Sample selection

*

*You can try to do co-teaching. Train 2 NN simultaneously, at each mini-batch, for each network, sample the data points with a smaller loss. You will end up with 2 sets of data containing the smaller loss instances. You will calculate the gradient for a model using the data sampled from the other model.


text:
Q: Функция cos() выдаёт неправильный результат #include "stdafx.h"
#include <cmath>
#include <iostream>

int main()
{
   double d = 50.879840;
   std::cout << cos(d) << std::endl;
   return 0;
}

Программа выдает результат 0.817144, хотя на любом инженерном калькуляторе результат равен 0.630948, и это правильно. В чём ошибка?

A: Функции cos, sin и подобные принимают параметр в радианах, а не в градусах.
Переводите значение из градусов в радианы, и всё будет правильно:
double d = 50.879840;
std::cout << cos(d / 180 * Pi) << std::endl;


text:
Q: Subring such that all products are zero Suppose I have a ring $R$, and I want to find a subset $J \subset R$ such that
$$xy = 0 : x,y \in J$$
(and hopefully, find the 'maximal' such subset $J$). Is there a name for such subsets $J$, or are they all just trivial?

A: Take $R=\mathbb{Z}/4$, represented by $0,1,2,3$. Then $J=\{0,2\}$ is such a set. The sets
$$
\mathrm {Ann} _{R}(S)=\{r\in R\mid \forall s\in S,rs=0\}
$$
are called (left) annihilator sets.


text:
Q: Searching with Panda based on specific categorization in Python Dears,
I have a csv file with below content, There are several Teams with members and Team, Now I want to select a captain and the another person who is the replace of Captian in an NBA Basketball team.
Different team exists, so I categorized them to TEAMA, TEAMB,TEAMC.
SiteCode          Name    Type      NO
TEAMA       Al Horford      A       20
TEAMA       Tiago Splitter  B       19
TEAMA       Walter Tavares  C       18
TEAMA       Kris Humphries  D       17
TEAMA       Paul Millsap    E       16
TEAMB       Mike Muscala    A       20
TEAMB       Mike Scott      B       20
TEAMB       Dennis Schroder C       18
TEAMC       Jeff Teague     A       20
TEAMC       Kent Bazemore   B       19

*

*If Type=A Captian is A, If B exists A will be Captian of B and If Any other members exist B will be the Captian of any other member:
I should add No of Captian and ReplaceCaptian to other columns, I don't know how to search based on team and find the NO of Captian and put it in CaptianNo fields.
(I think I should go ahead and solve this by adding a for loop and search based on team.)

Code:
    import pandas as pd
    import numpy as np
    df = pd.read_csv("C:\\Users\\Desktop\\P.csv")
    df["Captian"] = ["A" if x=="A" or x=="B" else "B" for x in df["Type"]]
    df["CaptianNO"] = ["A" if x=="A" or x=="B" else "A" for x in df["NO"]]
    df["ReplaceCaptain"] = ["A" if x=="A" else x for x in df["Type"]]
    df["ReplaceCaptainNO"] = ["A" if x=="A" else x for x in df["NO"]]
    print(df)
    df.head(3)
    df.to_csv('C:\\Users\\Desktop\\Captian.csv')

Actual Result of code which CatianNO is A and not the NO value it's relative Captian .
ID  SiteCode    Name        Type    NO  Captian CaptianNO   ReplaceCaptain  ReplaceCaptainNO
0   TEAMA   Al Horford      A       20     A        A                A                20
1   TEAMA   Tiago Splitter  B       19     A        A                B                19
2   TEAMA   Walter Tavares  C       18     B        A                C                18
3   TEAMA   Kris Humphries  D       17     B        A                D                17
4   TEAMA   Paul Millsap    E       16     B        A                E                16
5   TEAMB   Mike Muscala    A       20     A        A                A                20
6   TEAMB   Mike Scott      B       19     A        A                B                19
7   TEAMB   Dennis Schroder C       18     B        A                C                18
8   TEAMA   Jeff Teague     A       20     A        A                A                20
9   TEAMA   Kent Bazemore   B       19     A        A                B                19

Expected Result:
ID  SiteCode    Name       Type NO  Captian CaptianNO   ReplaceCaptain  ReplaceCaptainNO
0   TEAMA   Al Horford      A   20      A       20              A               20
1   TEAMA   Tiago Splitter  B   19      A       20              B               19
2   TEAMA   Walter Tavares  C   18      B       19              C               18
3   TEAMA   Kris Humphries  D   17      B       19              D               17
4   TEAMA   Paul Millsap    E   16      B       19              E               16
5   TEAMB   Mike Muscala    A   20      A       20              A               20
6   TEAMB   Mike Scott      B   19      A       20              B               20
7   TEAMB   Dennis Schroder C   18      B       19              C               18
8   TEAMA   Jeff Teague     A   20      A       20              A               20
9   TEAMA   Kent Bazemore   B   19      A       20              B               19

A: For column CaptianNO use DataFrame.join or DataFrame.merge with left join:
df["Captian"] = np.where(df["Type"].isin(['A','B']), "A", "B")
df = df.join(df.set_index(['SiteCode','Type'])['NO'].rename('CaptianNO'),
             on=['SiteCode','Captian'])

Alternative:
d = {'NO': 'CaptianNO', 'Type':'Captian'}
df = df.merge(df[['SiteCode','Type','NO']].rename(columns=d),
              on=['SiteCode','Captian'], how='left')

df["ReplaceCaptain"] = df["Type"]
df["ReplaceCaptainNO"] = df["NO"]

print (df)
  SiteCode             Name Type  NO Captian  CaptianNO ReplaceCaptain  \
0    TEAMA       Al Horford    A  20       A         20              A
1    TEAMA   Tiago Splitter    B  19       A         20              B
2    TEAMA   Walter Tavares    C  18       B         19              C
3    TEAMA   Kris Humphries    D  17       B         19              D
4    TEAMA     Paul Millsap    E  16       B         19              E
5    TEAMB     Mike Muscala    A  20       A         20              A
6    TEAMB       Mike Scott    B  19       A         20              B
7    TEAMB  Dennis Schroder    C  18       B         19              C
8    TEAMC      Jeff Teague    A  20       A         20              A
9    TEAMC    Kent Bazemore    B  19       A         20              B

   ReplaceCaptainNO
0                20
1                19
2                18
3                17
4                16
5                20
6                19
7                18
8                20
9                19


text:
Q: How to toggle show and hide password for multiple field in React I want to toggle the show and hide password for the input fields.
It can work on single input, but I don't know how to do it for multiple input field
I want that on clicking input icon it will toggle for the show/hide password
It should work individually for each input field.
for example if I click on current password input field icon then it will only show/hide password for this input field.
const App = () => {
  const [values, setValues] = React.useState({
    password: "",
    showPassword: false,
  });

  const handleClickShowPassword = () => {
    setValues({ ...values, showPassword: !values.showPassword });
  };

  const handlePasswordChange = (prop) => (event) => {
    setValues({ ...values, [prop]: event.target.value });
  };

  return (

Change your password

      <InputLabel htmlFor="standard-adornment-password">
        Current password
      </InputLabel>
      <Input
        type={values.showPassword ? "text" : "password"}
        onChange={handlePasswordChange("password")}
        value={values.password}
        endAdornment={
          <InputAdornment position="end">
            <IconButton
              onClick={handleClickShowPassword}
            >
              {values.showPassword ? <Visibility /> : <VisibilityOff />}
            </IconButton>
          </InputAdornment>
        }
        <InputLabel htmlFor="standard-adornment-password">
            New password
        </InputLabel>
        <Input
            type={values.showPassword ? "text" : "password"}
            onChange={handlePasswordChange("password")}
            value={values.password}
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  onClick={handleClickShowPassword}
                >
                  {values.showPassword ? <Visibility /> : <VisibilityOff />}
                </IconButton>
          </InputAdornment>
        }
        <InputLabel htmlFor="standard-adornment-password">
            Confirm password
        </InputLabel>
        <Input
            type={values.showPassword ? "text" : "password"}
            onChange={handlePasswordChange("password")}
            value={values.password}
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  onClick={handleClickShowPassword}
                >
                  {values.showPassword ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
        }
      />

  );
};

A: Could you do something like that ?

const Input = (props) => {
  const [showPassword, setShowPassword] = React.useState(false)

  return (

      <input type={showPassword ? "text" : "password"} {...props} />
      <button onMouseDown={(e) => {
        e.preventDefault()
        setShowPassword(!showPassword)
      }}>{showPassword ? 'Hide' : 'Show'} password</button>

  )
}

const reducer = (state, changes) => {
  return {
    ...state,
    ...changes
  }
}

const App = () => {
  const [values, setValues] = React.useReducer(reducer, {
    currentPassword: "",
    newPassword: "",
    confirmPassword: ""
  });

  return (

Change your password

      Current password
      <Input id="password-input" onChange={({target}) => {
        return setValues({currentPassword: target.value})
      }} />

      New password
      <Input id="new-password" onChange={({target}) => {
        return setValues({newPassword: target.value})
      }} />

      Confirm password
      <Input id="confirm-password" onChange={({target}) => {
        return setValues({confirmPassword: target.value})
      }} />

Form content

currentPassword : {values.currentPassword}

newPassword : {values.newPassword}

confirmPassword : {values.confirmPassword}

  );
};

ReactDOM.render(<App />, document.querySelector("#app"))

A: Because you are using one boolean to check 3 fields password. To fix, you just update showPassword to store string like this:
  const handleClickShowPassword = (fieldName) => {
    setValues({ ...values, showPassword: fieldName === values.showPassword ? "" : fieldName});
  };

...
type={values.showPassword === "currentPassword" ? "text" : "password"}
onClick={() => handleClickShowPassword("currentPassword")}
{values.showPassword === "currentPassword" ? <Visibility /> : <VisibilityOff />}
...

...
type={values.showPassword === "newPassword" ? "text" : "password"}
onClick={() => handleClickShowPassword("newPassword")}
{values.showPassword === "newPassword" ? <Visibility /> : <VisibilityOff />}
...

...
type={values.showPassword === "confirmPassword" ? "text" : "password"}
onClick={() => handleClickShowPassword("confirmPassword")}
{values.showPassword === "confirmPassword" ? <Visibility /> : <VisibilityOff />}
...

A: I was able to come up with this. Let me know if it helps
const App = () => {
  const [values, setValues] = React.useState({
    currentPassword:{show:false,password:'' "},
    newPassword:{show:false,password:'' "},
    confirmPassword{show:false,password:'' "}
  });

const handleClickShowPassword = (prop) =>{
    Input = values[props]
    setValues({ ...values, [prop]: {show:!Input.show, password:Input.password} });
  };

  const handlePasswordChange = (prop,value) =>  {
    Input = values[props]
    setValues({ ...values, [prop]: {show:Input.show,
    password:value} });
  };

  return (

Change your password

      <InputLabel htmlFor="standard-adornment-password">
        Current password
      </InputLabel>
      <Input
        type={values.currentPassword.show ? "text" : "password"}
        onChange={({target})=>handlePasswordChange("currentPassword",target.value)}
        value={values.currentPassword.password}
        endAdornment={
          <InputAdornment position="end">
            <IconButton
              onClick={handleClickShowPassword}
            >
              {values.currentPassword.show ? <Visibility /> : <VisibilityOff />}
            </IconButton>
          </InputAdornment>
        }
        <InputLabel htmlFor="standard-adornment-password">
            New password
        </InputLabel>
        <Input
            type={values.newPassword.show ? "text" : "password"}
            onChange={({target})=>handlePasswordChange("newPassword",target.value)}
            value={values.newPassword.password}
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  onClick={handleClickShowPassword}
                >
                  {values.newPassword.show ? <Visibility /> : <VisibilityOff />}
                </IconButton>
          </InputAdornment>
        }
        <InputLabel htmlFor="standard-adornment-password">
            Confirm password
        </InputLabel>
        <Input
            type={values.confirmPassword.show ? "text" : "password"}
            onChange={({target})=>handlePasswordChange("confirmPassword",target.value)}
            value={values.confirmPassword.password}
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  onClick={handleClickShowPassword}
                >
                  {values.confirmPassword.show ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
        }
      />

  );
};