text:
Q: I tried to write a function that checks if two arrays are permutation of each other by using counting. It's given that the values of the arrays can be only between 1 and 100. Its seems that my function is not right I dont understand why.
Here is my function:
int CheckPermutation3(int arr1[], int arr2[], int size)
{
    int count1[100], count2[100]; //the size 100 because in that case values are only between 1 and 100//
    int i;

    for(i=0; i<100; i++)
    {
        count1[i]=0;
       count2[i]=0;
    }
    for(i=0;i<size;i++)  //counting the elements of each array//
       count1[arr1[i]]++;
    for(i=0;i<size;i++)
        count2[arr2[i]]++;
    for(i=0;i<100;i++)   //comparison//
        if (count1[i]!= count2[i])
            return 0;
    return 1;
}

A: There is nothing wrong with your implementation: the only reason it wouldn't work is if items were out of range, because this would cause undefined behavior.
You can somewhat simplify the code by using a single array, like this:
int balance[100] = {0}; // Initialize all elements to zero
for (i = 0 ; i < size ; i++) {
    balance[arr1[i]-1]++;
    balance[arr2[i]-1]--;
}
for(i=0;i<100;i++) {
    if (balance[i] != 0) {
        return 0;
    }
}
return 1;

A: There seems to be only 1 problem why it may not work.
You are storing value between 1 and 100 [Inclusive, I guess] in an array with indexes [0-99].
So, if arr1[i] value is 100, it'd break here.
count1[arr1[i]]++;
as you are trying to increment count1[100] which is out of range.
Similarly, if arr2[i] value is 100, it'd break here.
count2[arr2[i]]++;
To fix this:
1. Create an array of 101 size.
2. Iterate from 1 to 100 [inclusive]
for(i=1;i<=100;i++)   //comparison//
        if (count1[i]!= count2[i])
            return 0;
If you want to save some space, let the array be of size 100,
and do this
count1[arr1[i]-1]++;
Similarly, for arr2
count2[arr2[i]-1]++;

This way you are storing each value in it's prev value's place in array. [0th indexing]


text:
Q: Sending Email via MS SMTP Server Fails Because FQDN set to Server Name Some emails sent from our SMTP Server (Windows 2008 running IIS6 SMTP) have begun failing with  some of the following errors:
Action: failed
Status: 5.5.2
Diagnostic-Code: smtp;504 5.5.2 <178867-WWW1>: Helo command rejected: need fully-qualified hostname
Action: failed
Status: 5.5.0
Diagnostic-Code: smtp;550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1)

A: I'm asking and answering in case others run into this issue...
It turns out that after we installed SP2 for Windows 2008, the FQDN set up in the SMTP settings gets reset to the server name rather than the fully qualified domain name that we had set up originally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Quotients of a ring of integers Let $L$ be a number field, let $p$ be a prime number, and let $I$ be a ideal of $\mathcal{O}_L$ containing $p$. I am not assuming that $\mathcal{O}_L$ or that $I$ is prime. The quotient ring $\mathcal{O}_L/I$ has a natural structure of $\mathbb{F}_p$-algebra.
Question. Do we have an isomorphism of $\mathbb{F}_p$-algebras $$\mathcal{O}_L/I\simeq \mathbb{F}_p[X]/(f)$$ for some nonzero monic polynomial $f$ ?
I know that the answer if YES in several cases.
1) For example, it is true if  $\mathcal{O}_L=\mathbb{Z}[\alpha]$ for some $\alpha$.
Indeed, since $I$ contains $p$, evaluation at $\alpha$ induces a morphism of $\mathbb{F}_p$-algebras $\mathbb{F}_p[X]\to \mathcal{O}_L/I$. This morphism is surjective since $\mathcal{O}_L=\mathbb{Z}[\alpha]$ . Its kernel is generated by a monic polynomial. Done.
2) If $L=K_1K_2,$ where $\mathcal{O}_{K_i}=\mathbb{Z}[\alpha_i]$, and  the discriminants of $K_1$ and $K_2$ are coprime, and $p$ is totally ramified in $K_2$, and $I=\mathfrak{p}_2\mathcal{O}_L.$ where $\mathfrak{p}_2$ is the unique prime ideal of $\mathcal{O}_{K_2}$ lygin above $p$. In this case, one may show that $\mathcal{O}_L/I\simeq \mathbb{F}_p[X]/(\overline{\mu}_{\alpha_1,\mathbb{Q}})$.
Nevertheless, I suspect that I am missing obvious counterexamples...
About 2), i wonder if it is a particular case of 1), so there is a side question:
Side question. If $L=K_1K_2,$ where $\mathcal{O}_{K_i}=\mathbb{Z}[\alpha_i]$, and the discriminants of $K_1$ and $K_2$ are coprime, is $\mathcal{O}_L=\mathbb{Z}[\alpha]$ for some $\alpha$ ? For example, is $\alpha=\alpha_1+\alpha_2$ working ?
Any thoughts ?
Greg

A: The answer to your main question is no. Let $I = (p)$ where $p$ splits completely in $L$ and $r := [L:\mathbf Q] > p$. (Example: cubic field in which $p = 2$ splits completely.) Then $\mathcal O_L/(p) \cong \mathbf F_p^r$ but if $\mathcal O_L/(p) \cong \mathbf F_p[X]/(f)$ for monic $f$ in $\mathbf F_p[X]$ then $f$ is a product of $r$ distinct monic linear factors, which is impossible for $r > p$. This proves $\mathcal O_L$ is not $\mathbf Z[\alpha]$ for some $\alpha$ ($L$ is not monogenic).
Dedekind found the first example of this: $L = \mathbf Q(\theta)$ where $\theta$ is a root of $X^3-X^2-2X-8$. This is a cubic field in which $2$ splits completely. Thus $\mathcal O_L/(2) \cong \mathbf F_2^3$ and $\mathcal O_L/(2) \not\cong \mathbf F_2[X]/(f)$ for any $f$ in $\mathbf F_2[X]$. Also $\mathcal O_L \not= \mathbf Z[\alpha]$ for some $\alpha$ in $\mathcal O_L$.


text:
Q: Symfony 3 - routing depending on the host name I'm trying to conditionally use routes with multipe domians.
What I have currently is:
admin_routes:
    host:     "admin.{domain}"
    resource: "@AppBundle/Controller/Admin"
    type: annotation
    requirements:
        domain: domain.local|domain2.local
    defaults: { domain: domain.local }

user_routes:
    host:     "user.{domain}"
    resource: "@AppBundle/Controller/User"
    type: annotation
    requirements:
        domain: domain3.local|domain4.local
    defaults: { domain: domain3.local }

Controllers in both folders have same route names as this is how the app is built.
The above is not working as the app is still loading both routes. For user domain urls from admin are built.
Is what I'm trying to achieve possible at all or am I doing this wrong way completely?
Ultimatelly what I'd like is to set of controllers is only "visible" for given hostname.

A: The routes need to have unique name. If there are 2 routes with same name the one will override another. As for host specification, this only affects if the route is matched or not. Similar to route requirements.
Solution to your problem is to name routes in both Controllers differently. One thing how to achieve this is by route name prefixes in Controller class annotation.
/**
 * @Route("/path", name="admin_")
 */

and
/**
 * @Route("/path", name="user_")
 */

https://symfony.com/blog/new-in-symfony-3-4-prefix-all-controller-route-names
Routes can have same /path prefix but their name needs to differ. This way they can match same path with different conditions.


text:
Q: If $x \in W$ and $x \in W^\perp$, then $x=0$ Let $E=\{e_1,...,e_n\}$ be basis for $W$ and $P=\{p_1,...,p_n\}$ be a basis for $W^\perp$. Since $x$ is in both of these spaces $$x=a_1e_1 + ... +a_ne_n$$ $$x=b_1p_1 + ... + b_np_n$$
multiply $x$ by $x$ $$x \cdot x = a_1b_1(e_1p_1)+...+a_nb_n(e_np_n)$$
Now if $x\neq 0$, that would imply $e_ip_i \neq 0$, which would contradict the fact that they are from orthogonal sets, and their product must by definition be $0$. Thus $x$ must equal zero. Is this correct? Also, does this equivalently show that $W \cap W^\perp = \{0\}$?

A: The idea of your proof seems correct.
Here's a simpler proof. Suppose $x \in W$ and $x \in W^\perp$, i.e. $x \in W\cap W^\perp$. Since $x \in W^\perp$, for any $y \in W$ we know that $\langle x, y \rangle = 0$. In particular, $x \in W$, so $\langle x, x \rangle = 0$. So $\|x\|^2 = \langle x,x \rangle = 0$, which implies that $x = 0$. Hence $W \cap W^\perp = \{0\}$.

A: We can do it without a basis too:
$x \in W^\perp$ means that $\forall y \in W: (x|y)=0 $. But if $x \in W$ as well, then we have that $(x|x)=0$, i.e. $x=0$.


text:
Q: How do I debug routing problems from a virtual tun0 device? I have a program (written by me) that creates a tun0 device and sets
up a route so that packets destined for the 172.16.1.0/24 subnet can
be read from this device. I'm trying to go in the other direction now
and write packets to the tun device that can be received by
My first effort, just changing the source and destination address and
ports worked fine. I can run the following:
nc -u -s MY_IP -p 4001 172.16.1.3 4000

and my input gets echoed.
My second effort, actually generating output packets from scratch, is
currently failing.
I can run tcpdump -i tun0 and see the packets that I've written:
11:30:14.433489 IP (tos 0x0, ttl 32, id 0, offset 0, flags [none], proto UDP (17), length 56) 172.16.1.2.54167 > Ubuntu-dbacher.local.4011: [udp sum ok] UDP, length 28

But my listener (nc -l -u -s MY_IP -p 4011) doesn't see anything.
I suspect there's something wrong that's preventing the tun0 device
from routing its packets out, but I don't know how to get visibility
into where the packets are being dropped.
$ ifconfig tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:172.16.1.1  P-t-P:172.16.1.1  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.16.1.0      172.16.1.1      255.255.255.0   UG    0      0        0 tun0
10.10.48.0      0.0.0.0         255.255.255.0   U     1      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth0
0.0.0.0         10.10.48.1      0.0.0.0         UG    0      0        0 eth0

$ cat /proc/sys/net/ipv4/ip_forward
1

How do I debug where the tun packets are being dropped?
(BTW, all packets are UDP.)

A: just a hunch - does linux allow packet routing?
run cat /proc/sys/net/ipv4/ip_forward - you expect to see 1. if it's 0 run:
echo 1 > /proc/sys/net/ipv4/ip_forward

also check your iptables - at the beginning you probably want to have ACCEPT for FORWARD chain:
iptables -P FORWARD ACCEPT
iptables -F FORWARD

when troubleshooting routing / firewalls i most often use tcpdump [ which you've mentioned ].

A: Maybe this helps:
ip route get 198.51.100.1

or:
ip route get to 198.51.100.1 from 192.168.0.2 iif eth0

Source of this: http://www.microhowto.info/troubleshooting/troubleshooting_the_routing_table.html


text:
Q: Can't push or fetch with git I can pull but I can't push or fetch using git version 1.9.5. It suddenly started giving me the following error. Any ideas as to how to fix it?
$ git fetch
fatal: unable to access 'https://arubygit@github.com/webpeak/wp-cla-dcs.git/':error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version

A: You are likely running into an incompatibility with GitHub's deprecation of weak encryption protocols.  You can see list of incompatible clients and potential solutions here:
https://githubengineering.com/crypto-removal-notice/


text:
Q: PhpStorm option to not insert a line break after an in-line comment I'm trying to adjust the code formatter in PhpStorm and I can't find what rule is causing a certain re-formatting to happen.  In general, if there's some way to know which rules/settings caused a certain change to happen, that would be great for debugging my setup.
The specific issue I'm trying to address is that the formatter is forcing a line break after an in-line comment.
For example, the following code:
array_search($needle, $haystack, /*strict=*/true);

Is being turned into:
array_search($needle, $haystack, /*strict=*/
             true);

And I can't find the setting that controls this.  Anyone know which setting controls this, or more generally, how to see a log of which rules are being applied so I can debug behaviors like this?
(I'm running PhpStorm 2018.3.5)

A: As Olga Strizhenko commented, I've confirmed this issue is fixed in version 2019.1.


text:
Q: mysql select problem I have like follow table.
And I want to select match this-> "Tip-1 = 225 and Tip-2 = 65 and Tip3 = 16" product.
There are 1 products that match the query. The product ID 2.
But I do not know how to do please help me.
id  product_id  option_id   name    label   value
44  1                   4   Tip-5   Tip 5   Dört Mevsim
42  1                   2   Tip-2   Tip 2   65
48  2                   4   Tip-5   Tip 5   Dört Mevsim
47  2                   3   Tip-3   Tip 3   16
46  2                   2   Tip-2   Tip 2   65
45  2                   1   Tip-1   Tip 1   225
52  3                   4   Tip-5   Tip 5   Dört Mevsim
51  3                   3   Tip-3   Tip 3   16
50  3                   2   Tip-2   Tip 2   75
49  3                   1   Tip-1   Tip 1   215
60  4                   4   Tip-5   Tip 5   Dört Mevsim
58  4                   2   Tip-2   Tip 2   75
64  5                   4   Tip-5   Tip 5   Dört Mevsim
63  5                   3   Tip-3   Tip 3   12
62  5                   2   Tip-2   Tip 2   85
61  5                   1   Tip-1   Tip 1   155
59  4                   3   Tip-3   Tip 3   16
43  1                   3   Tip-3   Tip 3   16
41  1                   1   Tip-1   Tip 1   205
57  4                   1   Tip-1   Tip 1   205
72  6                   4   Tip-5   Tip 5   Dört Mev

A: Try this:
SELECT product_id
FROM yourtable
WHERE (name, value) IN (('Tip-1', '225'), ('Tip-2', '65'), ('Tip-3', '16'))
GROUP BY product_id
HAVING COUNT(*) = 3

This assumes that (product_id, name) is unique. If not, use COUNT(DISTINCT name) instead.

A: It would be better to have own table for product details but to do your select try this
SELECT * FROM table_name WHERE (name = "Tip-1" AND value = 225) AND (name = "Tip-2" AND value = 65) AND (name = "Tip-3" AND value = 16) GROUP BY product_id

This might work but the table structure is really terrible, you should chane it if it's possible..

A: First of all, unless you have a very specific need, this is a horrible database design. That said,
SELECT T1.product_id
FROM mytable T1
JOIN mytable T2 ON T1.product_id = T2.product_id
JOIN mytable T3 ON T1.product_id = T3.product_id
WHERE T1.name = 'Tip-1' AND T1.value = '255'
  AND T2.name = 'Tip-2' AND T2.value = '65'
  AND T3.name = 'Tip-3' AND T3.value = '16'

A: A regular group by with OR clauses and HAVING should do it
SELECT   product_id
FROM     yourtable
WHERE    (name = 'Tip-1' and value = '225')
   OR    (name = 'Tip-2' and value = '65')
   OR    (name = 'Tip-3' and value = '16')
GROUP BY product_id
HAVING   COUNT(distinct value) = 3


text:
Q: Trying to extract specific data with split i have this txt file name contacts.txt that contains this:
kate|female|kathryn bailey beckinsale|26-jul-1973|#23 underworld drive|(621) 142-7827|kate@lycans.net
jessica|female|jessica claire biel|03-mar-1982|27 texas avenue|(53)2344223|jbiel@yahoo.com
johnny|male|john christopher depp ii|09-jun-1963|711 pirate road|(773) 476-6634|jspaw@piratebay.org

my script is this:
function syncText() {
var xhr = new XMLHttpRequest();
xhr.open("get", "data/contacts.txt", false);
xhr.send(null);

  if (xhr.status == 200) {
    var data = xhr.responseText;
    var items = data.split("|");
    items.sort();
    var div = document.getElementById("header2");

  for (var i = 0; i < items.length; i++) {
    var p = document.createElement("p");
    var text = document.createTextNode(items[i]);
    p.appendChild(text);
    div.appendChild(p);
  }
  } else {
    alert("data retrieval failed...");
  }
}

The HTML is this:
<div id="header2">
  <button onclick="syncText()">Load</button>
</div>`

i only want to retreive kat, jessica, johnny.. please help me

A: That should do the trick to get only names :
var items = data.split("\n"); // build an array with each lines
// \n or \n\r considering that it is separated with line jumps
// warning: it may also contain an empty value at the end if there's an ending line jump

var names=[];

for (var i=0;i<items.length;i++) {
    names.push( items[i].split("|")[0] ); // read the first value before | and insert it
}

// ...
// whatever is needed to be done with names
// ...


text:
Q: Performance of the same MySQL database is different on different servers I have two servers:

*

*Server A: AMD Epyc 7371 - 16c / 32t - 3.1 GHz / 3.8 GHz 256 GB ECC 2400 MHz 2 × 960 GB NVMe SSD MySql 8.0.26

*Server B: Dual Intel Xeon Gold 6242R - 20c / 40t - 3.1 GHz / 4.1 GHz 384 GB ECC 2933 MHz 6 × 3.84 TB NVMe SSD 2 × 480 GB SATA SSD

On server A, despite it being smaller, the database works well and transactions are very fast with over 200 concurrent users.
On the much larger server B this happens to me: up to 50 concurrent users is not a problem and the database works well, but after the number of users to go beyond 50, the database starts to slow down.
Both servers have the same database, same tables, same stored procedure, same applications, in practice they are a copy of each other.
How can I figure out where the problem lies?
This is the configuration file:
[client]
pipe=
socket=MYSQL
port=3306
[mysql] no-beep
default-character-set=
server_type=1
[mysqld]
port=3306
datadir=E:/ProgramData/MySQL/MySQL Server 8.0\Data
character-set-server=
default-storage-engine=INNODB
sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"
log-output=FILE
general-log=0
general_log_file="NS31525947.log"
slow-query-log=1
slow_query_log_file="NS31525947-slow.log"
long_query_time=10
log-error="NS31525947.err"
log-bin="NS31525947-bin"
server-id=1
lower_case_table_names=1
secure-file-priv="C:/ProgramData/MySQL/MySQL Server 8.0/Uploads"
max_connections = 500
table_open_cache=3G
tmp_table_size=3G
thread_cache_size=100
myisam_max_sort_file_size=10G
myisam_sort_buffer_size=68G
key_buffer_size=61M
read_buffer_size=23M
read_rnd_buffer_size=256K
innodb_flush_log_at_trx_commit=0
innodb_log_buffer_size=512M
innodb_buffer_pool_size=10G
innodb_log_file_size=1G
innodb_thread_concurrency=0
innodb_autoextend_increment=64
innodb_buffer_pool_instances=8
innodb_concurrency_tickets=5000
innodb_old_blocks_time=1000
innodb_stats_on_metadata=0
innodb_file_per_table=1
innodb_checksum_algorithm=0
back_log=80
flush_time=0
join_buffer_size=256K
max_allowed_packet=4M
max_connect_errors=100
open_files_limit=10000
sort_buffer_size=256K
table_definition_cache=1400
binlog_row_event_max_size=8K
sync_relay_log=10000
sync_relay_log_info=10000
loose_mysqlx_port=33060
default_authentication_plugin = mysql_native_password

I also tried to put the my.ini from server A on server B, but nothing changed.

I entered the database status references
Right now

A: The one word that grabs my attention is SATA. SATA is slower than SSD
There is a webpage entitled Types of hard drives: SATA vs. SSD vs. NVMe
It says in part

SSD stands for Solid State Drive. These disks don't have any moving parts. Instead, all of the data is stored on non-volatile flash memory. That means that there isn't a needle that has to move to read or write data and that they are significantly faster than SATA drives. It's difficult to find an exact speed because it varies by manufacturer and form factor, but even the lower-performing drives are comparable to SATA drives.

I would suggest putting everything on SSDs. I mentioned getting away from SATA in my old post MySQL/Percona Server is taking long and I'd prefer to skip all this waiting even if it means data loss
I would also suggest splitting the redo logs away from the data using separate disks (See my old post MySQL on SSD - what are the disadvantages?)
I would also set innodb_thread_concurrency to 64 (See my old post MariaDB 10.1.22 to use more RAM rather than CPU)

A: table_open_cache=3G  -- NO! That's files, not bytes!  Drop to a few thousand
innodb_buffer_pool_size=10G  -- increase to about 70% of RAM

No more than 1% of available RAM (each):
tmp_table_size=3G            --> 200M
max_heap_table_size          --> 200M
myisam_sort_buffer_size=68G  --> 200M

If you would like further analysis of settings, see http://mysql.rjweb.org/doc.php/mysql_analysis#tuning
That analysis will include discovering whether you are I/O-bound, hence confirming that SATA vs NVMe is a big issue.
Speeding up queries is another way to scale; let's analyze the SlowLog
The Answer talking about SSDs leads to the need to speed up "slow" queries.  Note that the slowlog measures elapsed time, hence captures disk I/O.  Be sure to set long_query_time = 1.0 (or lower).
More
Buffer_pool of 10G; data folder with 13.8GB...  When a server is first started, nothing is in the buffer_pool and queries run slower than they will eventually.  This is due to I/O.  (And as already discussed the machines have different I/O speeds.)
Eventually the buffer_pool will fill up and further actions may (or may not, depending on the "working set size") lead to thrashing -- I/O to bump out stuff in the cache in order to load new things.  This I/O will be especially problematic if queries are doing full table scans.
Since you have lots of RAM, you should increase innodb_buffer_pool_size.  However, if your data size continues to grow, you may eventually hit the sluggishness again.  You should locate any "slow" queries and consider how to avoid "full table scans" (or whatever is making them slow).


text:
Q: tuned-adm set how to set default power profile using RHEL/CentOS 7.9 I know how to do tuned-adm profile   latency-performance
However after reboot it is back to throughput-performance.
How, or where, does tuned specify the default power profile and what is the correct way to modify things such that after reboot the power profile is always what I want it to be?


text:
Q: download file from web via R Console I'd like to download a log-file with R via a download link, but I get only the un-evaluated html.
this is what I tried, without any success:
url = "http://statcounter.com/p7447608/csv/download_log_file?ufrom=1323783441&uto=1323860282"

# SSL-certificate:
CAINFO = paste(system.file(package="RCurl"), "/CurlSSL/ca-bundle.crt", sep = "")

curlH = getCurlHandle(
    header = FALSE,
    verbose = TRUE,
    netrc = TRUE,
    maxredirs = as.integer(20),
    followlocation = TRUE,
    userpwd = "me:mypassw",
    ssl.verifypeer = TRUE)

setwd(tempdir())
destfile = "log.csv"
x = getBinaryURL(url, curl = curlH,
                 cainfo = CAINFO)

shell.exec(dir())

A: Here are two ways of downloading the file.
It seems when renaming the file to log.html and opening it, that we have an invalid login. This is why you get the html structure. You need to add the login credentials to the URL.
You can get the name value pairs from the html source code:
Username:
<input type="text" id="username2" name="form_user" value="" size="12" maxlength="64" class="large">

Password:
<input type="password" name="form_pass" id="password2" value="" size="12" maxlength="64" class="large">

As you can see the name value pair for the username is called form_user=USERNAME and the name value pair for the password is called form_pass=PASSWORD.
This is why the curl userpwd setting doesn't work, it doesn't recognize the ids or the names.
 ## Url for downloading - Does not contain login credentials.
 url <- "http://statcounter.com/p7447608/csv/download_log_file?ufrom=1323783441&uto=1323860282"

 USERNAME = 'your username'
 PASSWORD = 'your password'

 ## Url for downloading - Does contain login credentials. Use this one!!
 url <- paste( 'http://statcounter.com/p7447608/csv/download_log_file?ufrom=1323783441&uto=1323860282&form_user=', USERNAME, '&form_pass=', PASSWORD, sep = '')

 ## method one, using download file
 download.file(url, destfile = "log.csv" )

 csv.data <- read.csv("log.csv" )
 head(csv.data)

 ## method 2 using curl
 CAINFO = paste(system.file(package="RCurl"), "/CurlSSL/ca-bundle.crt", sep = "")

 cookie = 'cookiefile.txt'
 curlH = getCurlHandle(
 cookiefile = cookie,
 useragent =  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en - US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6",
     header = FALSE,
     verbose = TRUE,
     netrc = TRUE,
     maxredirs = as.integer(20),
     followlocation = TRUE,
     ssl.verifypeer = TRUE)

 destfile = "log2.csv"
 content = getBinaryURL(url, curl = curlH, cainfo = CAINFO)
 ## write to file
 writeBin(content, destfile)
 ## read from binary object
 csv.data2 <- read.csv(textConnection(rawToChar(content)))
 head(csv.data2)
 csv.data2 == csv.data

A: You don't seem to need SSL certificates etc since the url is http:, not https:... So maybe download.file(url, "log.csv") would work fine in this case?
I'd first make sure the url and its response is correct outside of R.
...I used Chrome to access the URL and got a downloaded file "StatCounter-Log-7447608.csv". It contains a csv header and HTML?!
"Date and Time","IP Address","IP Address Label","Browser","Version","OS","Resolution","Country","Region","City","Postal Code","ISP","Returning Count","Page URL","Page Title","Came From","SE Name","SE Host","SE Term"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Author" content="StatCounter">
...


text:
Q: How many external style-sheets are required for cross browser compatibility? I have just started web development after a few years. Mostly in the past I would specify a style-sheet dedicated to IE6. Now, Chrome and Safari seem to be rendering elements better, over FireFox.
What is standard procedure for external style-sheets these days? IE6 (STILL?) - IE8? FF even?
It would be greatly appreciated if anyone has advice specifically catered to marketplace development, ie XHTML / Wordpress development.

A: There is no specified number of stylesheets. Usually it is one for IE and one for rest of the browsers. Note that there exist solutions such as ie7.js or CSS3 Pie to make IE behave like standard-compliant browser.

A: I personally use 2 stylesheets. One core one, and one for IE6.
Most of the modern browsers simply ignore anything that they don't support, and dont have quite the sheer number of behaviours that require hacks.

A: Given that a stylesheet isn't required at all, the answer is none. I would still say you need only 1 though. (If you've created your css properly and used a proper doctype). Technically you shouldn't need to have browser specific styles at all. And for the few times you might, you can use Star Hacks for IE...

A: I think question you're asking relates back to the much bigger topic of how best to handle cross-browser issues.
It's a wide and varied topic, but to help you with you're specific question about CSS branching (forking)... you may be interested in the following article from "A List Apart"
"Stop Forking with CSS3" http://www.alistapart.com/articles/stop-forking-with-css3/
Cheers.


text:
Q: Starting a task in a certain time I'm using the following code in order to perform a task every 5 minute.
this.timer.schedule(new Send(), new Date(), TEN_SECONDS*6*5);

My question is, how can I start my task in this kind of time: xx:00, xx:05, xx:10, xx:15 - in jump of 5 minutes, so I would like to start my task from the nearest 5 minute jump.

A: you can use quartz.
it is open-source and has cron-like functionality.
http://quartz-scheduler.org/documentation/quartz-2.1.x/examples/Example3

A: It wasn't that hard, really simple math.
d1.setMinutes(d1.getMinutes() + 5 - d1.getMinutes()%5);


text:
Q: In Magento2, how to get checked checkboxes values in uicomponent grid in frontend? I have added grid using uicomponent in Magento 2 frontend, to list related products. grid is showing fine but now i want to get checked checkboxes values (in any hidden input if possible) to send that with form data.
Screenshot below:


text:
Q: Unwanted blank pages before and after a chapter I use Xelatex, and the class Report
I have a document that follows this simple architecture :
\part (thee)

\chapter (nine chapters and two chapters* (for introduction and conclusion)

\section (fourty-one)

When I do the compilation, I get two blank pages before and after the chapter 5, although I have no others blank pages for the other chapters. Does anyone how can I remove this bug ? Or is it a least a bug ?I was thinking that maybe the titles of my chapters and sections are sometimes too long


text:
Q: Bitwise NOT of Java BigInteger is Negative I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).
BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));

This results in the following, if I output it using base 2:
11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000
I am trying to flip/reverse all the bits using a bitwise not.
System.out.println(b.not().toString(2));

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:
-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000
This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?
UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.
Based on the responses, I think the following should work:
E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?
BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}

A: As others have pointed out, it's the sign bit that is giving you the result that you don't want.
There are a couple of ways that you can get the inverted bits.  For both of them you will need a 128 bit mask value:
private static final BigInteger MASK_128 =
    BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);

Then you can either mask the sign bit:
BigInteger b = BigInteger.valueOf(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(MASK_128.andNot(b).toString(2));

Or invert directly using xor:
System.out.println(b.xor(MASK_128).toString(2));

I expect the mask value will be useful elsewhere once you start fleshing things out also.

A: signed byte 64  = 01000000
Invert it
and we get signed byte -65 = 10111111
Sign "minus" is the "not" operator itself:
-1000000 = 0111111
Type this and you see that the values are equal (+1) in absolute
System.out.println(b.toString());
System.out.println(b.not().toString());

A: Your answer is perfectly correct ,In java everything is in two's compliment:
Convert Decimal to Two's Complement
Convert the number to binary (ignore the sign for now) e.g. 5 is 0101 and -5 is 0101
If the number is a positive number then you are done. e.g. 5 is 0101 in binary using twos complement notation.
Here goes your solution.
If the number is negative then

3.1 find the complement (invert 0's and 1's) e.g. -5 is 0101 so finding the complement is 1010

3.2 Add 1 to the complement 1010 + 1 = 1011. Therefore, -5 in two's complement is 1011.

So, what if you wanted to do 2 + (-3) in binary? 2 + (-3) is -1. What would you have to do if you were using sign magnitude to add these numbers? 0010 + 1101 = ?
Using two's complement consider how easy it would be.
2  =  0010
-3 =  1101
+

-1 =  1111
Converting Two's Complement to Decimal
Converting 1111 to decimal:
The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000.
Add 1 to 0000, and we obtain 0001.
Convert 0001 to decimal, which is 1.
Apply the sign = -1.
In your case
when you do b.not().toString(2) , you will get the response :
-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000001

with 1 at the last bit.
Now do the two's compliment and you will get the right answer.
e.g; Flip all the 1's by 0's and vice-versa. after doing that add one to the solution and you will get the solution that you are seeking.
Final solution
00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111

A: Use
VALUE = 0xFFFFFFFFFFFFFFFF0000000000000000 - this is patern for bit 1...10...0
VALUE = 0x0000000000000000FFFFFFFFFFFFFFFF - this is patern for bit 0...01...1
Just type by hand 16 x "F" and "0" and remember to add "0x"before each pattern.
Define this values as final.
If You want to generate such values you must do
value += 0x1;
value << 1;
For n times. In your case n is 64.


text:
Q: clicking a marker opening a image next to map I have a leaflet map which has lots of markers and what I would like is to open a image next to the map which is linked to certain marker on marker click. All I know that I need javascript/jquery and ajax to make this work.
Here is an example what it could look like: http://www.washingtonpost.com/wp-srv/special/local/14th-street-businesses/
Any hints/tips/tutorials appreciated.
Thanks in advance!

A: Here is a solution to your problem: http://franceimage.github.io/leaflet/10/
var selectedMarker = false;

var geojsonMarkerOptions = {
        radius: 8,
        fillColor: "#ff7800",
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8
    };

L.geoJson(fi_markers, {
    pointToLayer: function (feature, latlng) {
        var marker = L.circleMarker(latlng, geojsonMarkerOptions);

        marker.on('click', function (e) {
            var feature = e.target.feature;
            var content = '
' + feature.properties.popupContent + '
' + feature.properties.thumbnail + '';
            document.getElementById("events").innerHTML = content;

            if(selectedMarker != false) {
                selectedMarker.setStyle({ fillColor: "#ff7800"});
            }
            marker.setStyle({ fillColor: "#000000"});
            selectedMarker = marker;
        });

        return marker;
    }
}).addTo(map);

This a way you can do it (there are plenty others)
In this example:

*

*There are no ajax calls (and no jquery either). Data is loaded from a geoJson structure (look at http://franceimage.github.io/leaflet/10/data.geojson)

*The html content of the popup is created using the properties of the geojson feature

*I have used CircleMarker so that changing the color is a piece of cake
I hope this will help


text:
Q: Is there a way to get audio file length Python Pyglet I am working with pyglet and was wondering if there was a way to get full audio file length? The only way of getting the time that I am aware of is the player.time function.
Code:
import pyglet

player = pyglet.media.Player()
sound = pyglet.media.load("My Movie.wav", streaming=False)
player.queue(sound)
player.play()

A: You can use the .duration property:
sound.duration

The length of the source, in seconds.
Not all source durations can be determined; in this case the value is
  None.


text:
Q: NVIDIA Proprietary driver not working properly I have a Lenovo Z40-70 laptop which was running Ubuntu 14.04 with a HDD. After upgrading to SSD (OCZ 240GB) and installing a fresh copy of Ubuntu I came across few issues with drivers for Broadcom and Nvidia graphic card. I think now the Broadcom driver works fine, but still the Nvidia causes some problems.
I always had problems with Suspend and Resume with this driver since the SSD upgrade. Most of the time it freezes at the resumption. However I had no issues when I was running Ubuntu with HDD. To solve this I changed my Ubuntu version to 15.04. I installed quite a few drivers for nvidia, finally with the following sequence of commands I was able to solve Suspend/resume issue.
sudo apt-get remove nvidia*
sudo apt-get clean
sudo apt-get update
sudo apt-get install nvidia-current
However even with this, additional drivers section of Software & Updates shows the driver is using X.org X server-Nouveau driver. This image shows the working driver configuration .
At this moment Suspend/resume is working fine, but I noticed some jitter in playing videos.
Then I changed my driver in additional driver section to NVIDIA proprietary driver, version 340.96 (proprietary,tested). This caused the resume problem again.
This time, going back to Nouveau driver didn't solve the problem.
However following above sequence of commands again I was able to successfully solve the suspend/resume issue.
How can I make the NVIDIA driver work ? Does it have to do anything with SSD upgrade ?
(Maybe this problem was there even with HDD but I didn't notice since I was using the Nouveau driver always. I didn't really care about graphics driver at that time since it looked working fine.)


text:
Q: How to sanitize inputs in nodejs to prevent sql injection? i have this sanitize function
    sanitizeXSS: string => {
      const map = {
          '&': '&',
          '<': '<',
          '>': '>',
          '"': '"',
          "'": ''',
          "/": '/',
      };
      const reg = /[&<>"'/]/ig;
      return string.replace(reg, (match)=>(map[match]));
    }

And this sanitize function is being used here
addOrUpdateAddress : function (request, resolve)
    {

        const customerKey = sanitizeXSS(decrypt_key(request.customer_key));
        const lat = sanitizeXSS(decrypt_key(request.lat));
        const lng = sanitizeXSS(decrypt_key(request.lng));
        const line1 = sanitizeXSS(decrypt_key(request.line1));
        const line2 = sanitizeXSS(decrypt_key(request.line2));
        const city = sanitizeXSS(decrypt_key(request.city));
        const pincode = sanitizeXSS(decrypt_key(request.pincode));
        const state = sanitizeXSS(decrypt_key(request.state));

        const contact = sanitizeXSS(decrypt_key(request.contact));
        const landmark = request.landmark?sanitizeXSS(decrypt_key(request.landmark)):null;
        let req=request;
        if(req.name && req.email)
        {

            updateUser(req,function(err,result)
            {
                console.log(err);
                console.log(result);
            });
        }
        let addressId = (!req.address_id || req.address_id == null || req.address_id == '')
                ? -1 : req.address_id;
        console.log(addressId);
        async.auto({
            serviceability : function (cb)
            {
                searchServiceArea(req,function(err,result)
                {
                    if(err)
                    {
                        resolve(null, {'errorMessage':'Address selected not serviceble'}, 203, 'error');
                    }
                    else
                    {
                       if(!result.hub_id)
                       {
                          resolve(null, {'errorMessage':'Address selected not serviceble'}, 203, 'error');
                       }
                       if(addressId == -1)
                       {
                           let s=mysql.write('customer_address').insert({customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss")}).then(function(res)

                           {
                            if(res.length > 0)
                            {
                                cb(null,{address_id:res[0],customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss"),'hub_id':result.hub_id})
                            }
                            else
                            {
                                cb(true,{'errorMessage':'Unable to add address try again'})
                            }

                           });
                       }
                       else
                       {
                            let s=mysql.write('customer_address').update({line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss")}).where({customer_key:customerKey, address_id:addressId}).then(function(res)
                           {
                                console.log(res)
                                if(res == 1)
                                {
                                    cb(null,{address_id:addressId,customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss"),'hub_id':result.hub_id})
                                }
                                else
                                {
                                    cb(true,{'errorMessage':'Unable to update address try again'})
                                }

            },
        },
   );

    }

So while inserting the address I'm identifying sql injection. I checked everywhere the possible solutions i was not able to solve it. Please do check the sql query also which i have mentioned.
How to solve this?
That would be a lot of help. Thanks in advance

A: I'd just use a standard library that already provides sanitization, like node-mysql.
https://github.com/mysqljs/mysql#escaping-query-values
const mysql      = require('mysql');
const connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});
const post  = {title: 'Hello MySQL', 'content': '...'};

connection.query(
  'insert into posts (title, content, updated_at, created_at) values (?, ?, ?, ?);',
  [
    connection.escape(post.title),
    connection.escape(post.content),
    connection.escape(new Date()),
    connection.escape(new Date())
  ]
).then((err, res, fields) => {
  //do stuff
})


text:
Q: Proving a certain set in a compact metric space is open The question is:
Let $(X,d)$ be a compact metric space. Let $f : X \rightarrow X$ be continuous. Fix a point $x_0 \in X$, and assume that $d(f(x), x_0)\geq1$ whenever $x\in X$ is such that $d(x,x_0)=1$. Prove that $U\setminus f(U)$ is an open set in $X$, where $U=\{ x\in X: d(x,x_0) <1\}$.
This is one of the analysis qual question. (I am going to sit for one in two days time)
I am having problem visualize the set in the question, whenever I have this sort of feeling, I will have great difficulties answering the question. Any suggestion? Thanks.

A: Hint: The thing to notice here is that all elements $x\in \partial U$ satisfy $d(x,x_0) = 1$. So by assumption $f(x)\notin U$ for all $x\in \partial U$.
This then implies that $f(\overline U) \cap U = f(U) \cap U$.
In general, if you read the condition "$X$ compact, Hausdorff", a thing on your mind should be that all continuous maps are automatically closed.


text:
Q: Why does the object get stuck in the wall when repelled? I made the endless movement of the object and its repulsion from the walls, but it does not always work correctly. At rounded corners (sometimes even at a straight wall), it just gets stuck and stops moving altogether, or moves slowly to the point where it stops moving. What can this be related to and how can it be fixed?
private void FixedUpdate() {
  rb.velocity = direction * normalSpeed;
  lastDirection = direction;
}

private void OnCollisionEnter2D(Collision2D collision) {
  //Repulsion from objects.
  direction = Vector3.Reflect(lastDirection.normalized, collision.GetContact(0).normal);
}

There is a small distance between the objects, but the circle seems to stick to the wall and moves with it until it collides with another collider:
Example
there are objects under the circle that also have colliders, but the collision between them is not considered, since they have the same layer (in the settings, I disabled the collision for objects on the same layer). What can be done to fix this error and what can it be related to?
The object in the general scale:
Example
I tried to increase the size of the wall collider, tried to change polygon collider to box collider, connect composite collider, changed the mechanics of the object movement (in these cases, the movement could work incorrectly), but the result was always the same - the jams (sticking to the wall) continued.

A: It is difficult to answer your question without having more information, but I can suggest if you are using physics to move your objects - utilize physic materials and remove code that changes direction manually in OnCollisionEnter. Using physic materials you can easily make your object bounce from colliders of your choice without losing velocity.


text:
Q: F# CSVProvider only reports first column data
While using CSVprovider on any csv file, I used the below:
http://spatialkeydocs.s3.amazonaws.com/FL_insurance_sample.csv.zip
    type statsProvider = CsvProvider<"../../FL_insurance_sample.csv",",">

    let stats = statsProvider.Load("../../FL_insurance_sample.csv")

    let firstRow = stats.Rows |> Seq.head

The CSVProvider only returns the data from the first column.   It does identify the columns (18) correctly and the name of the columns correctly, yet when you look at the type of rows, they're only type string, not a tuple or a structure...
see in the screenshot the type of firstRow should be a specific type e.g. tuple or structure not a string.
What am I doing wrong?  Using Visual studio 2017, FSharp 4.1, .net 4.5.2 and FSharp.Data 2.3.3
Note: this happens with several at least 3 more csv files. I picked this particular csv for demonstration only.

A: I can't reproduce your problem: the sample CSV file you provided worked just fine for me. But then, I'm using VS Code, not Visual Studio; it's possible that the source of the problem is somewhere in Visual Studio 2017 rather than in FSharp.Data. Here's what I did:

*

*Create a new, empty project folder.

*Copy the Paket bootstrapper into it, in .paket/paket.bootstrapper.exe.

*Run paket init.

*Edit the paket.dependencies file to add FSharp.Data.

*Run paket install.

*Run paket generate-load-scripts, which created a bunch of scripts in the .paket/load folder to load all the dependencies at once. (I love this feature for scripting!)

*Created script.fsx with the following content:
#load ".paket/load/net452/FSharp.Data.fsx"
open FSharp.Data

type Csv = CsvProvider<"/home/rmunn/Downloads/tmp/csv/FL_insurance_sample.csv">
let data = Csv.GetSample()

printfn "%A" data.Headers

let firstRow = data.Rows |> Seq.head
printfn "%A" firstRow

*In VS Code, selected the entire script file and pressed Alt+Enter to send it to the F# Interactive window.
Here's the output I got:
F# Interactive for F# 4.1
Freely distributed under the Apache 2.0 Open Source License

For help type #help;;
> # silentCd @"/home/rmunn/code/fsharp/tmp/foo";;
- # 1 @"/home/rmunn/code/fsharp/tmp/foo/script.fsx"
- ;;

(snip the copy of my script that F# Interactive echoed)

[Loading /home/rmunn/code/fsharp/tmp/foo/.paket/load/net452/Zlib.Portable.fsx
 Loading /home/rmunn/code/fsharp/tmp/foo/.paket/load/net452/FSharp.Data.fsx]
namespace FSI_0002.Zlib

namespace FSI_0002.FSharp

Some
  [|"policyID"; "statecode"; "county"; "eq_site_limit"; "hu_site_limit";
    "fl_site_limit"; "fr_site_limit"; "tiv_2011"; "tiv_2012";
    "eq_site_deductible"; "hu_site_deductible"; "fl_site_deductible";
    "fr_site_deductible"; "point_latitude"; "point_longitude"; "line";
    "construction"; "point_granularity"|]
(119736, "FL", "CLAY COUNTY", 498960M, 498960M, 498960M, 498960M, 498960M,
 792148.9M, 0M, 9979.2M, 0, 0, 30.102261M, -81.711777M, "Residential", "Masonry",
 1)
type Csv = FSharp.Data.CsvProvider<...>
val data : FSharp.Data.CsvProvider<...>
val firstRow : FSharp.Data.CsvProvider<...>.Row =
  (119736, "FL", "CLAY COUNTY", 498960M, 498960M, 498960M, 498960M, 498960M,
   792148.9M, 0M, 9979.2M, 0, 0, 30.102261M, -81.711777M, "Residential",
   "Masonry", 1)
val it : unit = ()

However, all did not go entirely smoothly. When I then tried to process every row, I got the following exception:

System.Exception: Couldn't parse row 2439 according to schema: Expecting Int32 in fl_site_deductible, got 68817.6

(I've omitted the traceback because it won't be particularly helpful to you to know which line number in FSharp.Data threw that exception).
The cause of this problem can be seen in the CsvProvider documentation, in the "Controlling the column types" section, which reads:

By default, the CSV type provider checks the first 1000 rows to infer the types, but you can customize it by specifying the InferRows static parameter of CsvProvider. If you specify 0 the entire file will be used.

There are two ways you can solve the "Inferred int but should have been decimal" problem. One would be to add InferRows=0 to your CsvProvider type definition. The other way would be to specify an explicit schema to tell the CsvProvider which rows it's going to get wrong by looking only at the first 1,000. (If your data set is huge, this is far preferable since looking through all the rows to infer data types would take far too long). See the documentation for examples, but you'd do something like Schema="fl_site_deductible=decimal".
So if you can't get your code to work in Visual Studio, see if VS Code (with the Ionide-Paket, Ionide-FSharp, and Ionide-FAKE extensions) works for you instead.


text:
Q: Restore Bacpac File in SSMS Using Powershell or Command Line in Windows I have to restore bacpac file into SSMS in local machine using a script or a command line,
Can someone please help me with this?


text:
Q: MatchQ failing in some cases with Hold Could someone clarify why the first of these MatchQ finds a match whereas the second does not?  (I'm using version 10.0, in case that matters.)
MatchQ[Hold[x + 2 y], Hold[x + 2 _]]
(*True*)
MatchQ[Hold[x + 2 y + 0], Hold[x + 2 _ + 0]]
(*False*)

EDIT: The conclusion below is that when encountering an Orderless function (here Plus), the pattern matcher does not test for all possible orderings of arguments but rather sorts the pattern's constant arguments and allows blanks _ to appear in arbitrary places within that list.  This reordering disregards Hold.  On the other hand Hold does keep the order of the arguments of the expression fixed, so Hold[x+2y+0] is compared (with fixed argument order) to Hold[0+x+2_], Hold[0+2_+x] and Hold[2_+0+x], none of which match.

A: UPDATE
That question is by the essence an exact duplicate of this one. The explanation given by Mr.Wizard means that the pattern-matcher is NOT capable to handle situations when an unevaluated function with Orderless attribute is wrapped by Hold. So this is indeed a gedanken functionality.
The pattern-matcher works on the base of the assumption that Orderless attribute is already applied and the arguments are sorted in the canonical order:
ClearAll[o]
SetAttributes[o, Orderless]
MatchQ[Hold[o[y, x, a]], Hold[o[_, x, a]]]
MatchQ[Hold[Evaluate@o[y, x, a]], Hold[o[_, x, a]]]

False

True

In the light of this the Documentation statement

In matching patterns with Orderless functions, all possible orders of
  arguments are tried.

means that actually only all possible positions of the Blanks in the pattern are tried but other arguments in the pattern are preliminarily sorted in the fixed canonical order. This is evident from the following:
MatchQ[Hold[o[y, a, x]], Hold[o[_, x, a]]]
MatchQ[Hold[o[y, x, a]], Hold[o[_, x, a]]]
MatchQ[Hold[o[y, a, x]], Hold[o[x, _, a]]]
MatchQ[Hold[o[y, a, x]], Hold[o[x, a, _]]]

True

False

True

True

In the other words, Hold prevents applying Orderless attribute in the sense that it prevents sorting of the arguments in the canonical order, but it does not prevent action of this attribute in the pattern (i.e. all possible positions of the Blanks are indeed tried).

Original answer
This behavior is definitely comes from the Orderless attribute of Plus and reproduces for arbitrary function having this attribute. As can be seen from the following, without Hold the pattern matches regardless of the order of the arguments due to Orderless attribute of o:
ClearAll[o]
SetAttributes[o, Orderless]
MatchQ[o[y, x, a], o[_, x, a]]
MatchQ[o[y, a, x], o[_, a, x]]
MatchQ[o[y, x, a], o[_, a, x]]

True

True

True

But when we wrap the expressions by Hold something breaks - now it does not match even when the order of the arguments is identical:
MatchQ[Hold[o[y, x, a]], Hold[o[_, x, a]]]

False

Surprisingly, it does match if we reorder arguments in the both expressions:
MatchQ[Hold[o[y, a, x]], Hold[o[_, a, x]]]

True

I suspect that we have a bug in the pattern matcher because this behavior cannot be explained by the documented meaning of the Orderless attribute.

A: You can put a Verbatim on the Plus:
MatchQ[Hold[x + 2 y + 0], Hold[Verbatim[Plus][x, 2 _, 0]]] (* True *)

Another way:
expr = Inactivate[x + 2 y + 1];
form = Inactivate[x + 2 _ + 1];
MatchQ[expr, IgnoringInactive@form] (* True *)


text:
Q: How can I reset a JsonReader instance instead of calling JToken.CreateReader? I have a large JSON file that I'm deserializing using Newtonsoft.Json - and I'm experiencing performance issues, esp. regarding one specific detail:
While deserializing I need to use an IOC ("Inversion Of Control") Container to create the required instances.
Inspired by https://skrift.io/issues/bulletproof-interface-deserialization-in-jsonnet/ and other sources I implemented a custom JsonConverter that overrides ReadJson. The method signature includes Type objectType, but e.g. in the case of arrays, this may well only be some common interface and not a specific class type.
I serialized the data using the option TypeNameHandling.Objects, which includes a "$type" token for each class.
If I detect that the type is not sufficient, I do something like the following:
JObject o = JObject.Load(reader);

var typeName = o["$type"].ToString();

if (!tryGetBindingByName(typeName, out var detectedBinding))
    throw new SpecificBindingNotFoundBinderException(typeName, binding);

result = detectedBinding.DeserializeType;

//"reset" reader, because due to `JObject.Load(reader)` call above the reader's current position has changed
reader = o.CreateReader();

I think the performance critical part - esp. regarding heap allocations - is where I manually read the JSON object - and then the need to call reader = o.CreateReader().
My question: can an existing JTokenReader be "reset" so that I can continue using it, instead of creating a new instance all the time?

A: No.  Neither JTokenReader, nor the abstract JsonReader on which it is based, provide a means to "reset" or go backward to an earlier point.  They are forward-only readers by design.
However, it sounds like the problem you are really trying to solve is just getting Json.Net to use your IOC container to create concrete instances of your classes in a performant manner.  For that, I think you might be using the wrong tool for the job.  Instead of a JsonConverter, try using a custom ContractResolver.  You can supply your own DefaultCreator function to handle the instantiation for each Type, as shown below.
class CustomResolver : DefaultContractResolver
{
    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        JsonObjectContract contract = base.CreateObjectContract(objectType);
        contract.DefaultCreator = () =>
        {
            // Change this to use your IOC container to create the instance.
            var instance = Activator.CreateInstance(objectType);

            return instance;
        };
        return contract;
    }
}

To use the resolver, you just need to add it to the JsonSerializerSettings alongside the TypeNameHandling.Objects option you are already using:
var settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Objects,
    ContractResolver = new CustomResolver(),
};

Here is a round-trip demo: https://dotnetfiddle.net/eHcLMb

If you also need to customize the type names that are written into the JSON, you can implement a custom SerializationBinder to do that part.
Here is a contrived example to demonstrate the concept.  The CustomSerializationBinder below uses some hardcoded dictionaries to map some known types to an "alias", which is just a unique string I chose to represent that type.  The "known types" here are the same ones from the "Bulletproof Interface Deserialization in Json.Net" article you linked to in your question.  You can replace the dictionaries with whatever type lookup mechanism you require.  Note that I'm not using the assemblyName in the example below just to keep the JSON simple.
class CustomSerializationBinder : ISerializationBinder
{
    Dictionary<string, Type> AliasToTypeMapping { get; set; }
    Dictionary<Type, string> TypeToAliasMapping { get; set; }

    public CustomSerializationBinder()
    {
        TypeToAliasMapping = new Dictionary<Type, string>
        {
            { typeof(Person), "Peep" },
            { typeof(Programming), "Coder" },
            { typeof(Writing), "Wordsmith" }
        };

        AliasToTypeMapping = new Dictionary<string, Type>(
            TypeToAliasMapping.Select(kvp => new KeyValuePair<string, Type>(kvp.Value, kvp.Key))
        );
    }

    public void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        if (TypeToAliasMapping.TryGetValue(serializedType, out string alias))
        {
            assemblyName = null;  // I don't care about the assembly name for this example
            typeName = alias;
            return;
        };
        throw new Exception($"Type {serializedType.Name} is not mapped to an alias");
    }

    public Type BindToType(string assemblyName, string typeName)
    {
        if (AliasToTypeMapping.TryGetValue(typeName, out Type type))
        {
            return type;
        }
        throw new Exception("No type was found matching the alias {typeName}");
    }
}

To use the custom binder, you guessed it, just add it to the settings with the other stuff:
var settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Objects,
    ContractResolver = new CustomResolver(),
    SerializationBinder = new CustomSerializationBinder()
};

Here is the same round-trip demo with the binder: https://dotnetfiddle.net/YC9IAT


text:
Q: ASPNet Identity Authentication MVC5 Client web site->Auth Server-> Web API server I'm a newbie for ASPnet identity services and we require a following requirement.
Following is the architecture setup
1. Appserver
Appsever having
a. Entity Framework
b. ASP.Net Web API2 Odata services
c. Authorization server
2. Webserver
ASP.Net MVC 5 application (Client which access the App server)
The flow needs to be

*

*MVC5 Cleint application having a login / Register form

*While register / login the information needs to send to  the authorization server int he app server, Authorize and creating the claims using Identity Services.

*Once the Identity has been created in the Authorization server, the client application should logged in

*I'm aware of getting bearer token from authentication server and that will be used as header information to access the API service
All we are lacking is the MVC client application should use the same identity claims that have created in the Authorization server.
Is there any way to access the claims which are created in the auth server.
I have got some samples about how to authenticate in the auth server and receiving token though OWIN and from this token we can access the API securely but I need of the client web application needs to sign in based on the token
I have gone through the following links
http://blogs.msdn.com/b/webdev/archive/2013/09/20/understanding-security-features-in-spa-template.aspx
Also, I require to add claims when ever it requires after login as well

A: I have resolve this issue as follows, but I'm not sure this is the effective method

*

*Once log-in and retrieve the bearer token (this token should assigned with claims identity already such as username, role .. etc)

*In the web api AccountController, need to create a method to retrieve the default claims which requires for client web application. Please check the follows
[Authorize]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
    var firstname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("FirstName")).SingleOrDefault();
    var lastname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("LastName")).SingleOrDefault();

    var IsApproved = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("IsApproved")).SingleOrDefault();

    var userinfo = new UserInfoViewModel
    {
        UserName = User.Identity.GetUserName(),
        FirstName = firstname.Value.ToString(),
        LastName = lastname.Value.ToString(),
        UserApproved = Convert.ToBoolean(IsApproved.Value.ToString()),
        HasRegistered = externalLogin == null,
        LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
    };

    return userinfo;
}

*From the client, this actin will be called through the token as a header.

*Once we have got the information (is in Json string format) needs to serialize with the UserInfoViewModel class (user defined viewmodel is based on the info we require and send from webapi account) with javascript serializer

*Using these viewmodel information, assign them to local storage and using (cookies for my case) as a identity at local

*keep logout webapi too when ever you logs out from web app.
Please let me know if you need more info or code


text:
Q: PyQt dynamic stopwatch timer is slow because of slow updates I am creating a "stopwatch" for a competition. A participants starts doing something, i star the program, and the participant can see his own placement which is updated dynamically with the watch. I have a fully functional code below:
import sys
from PyQt4 import QtGui, QtCore

class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ms = 0
        self.s = 0
        self.m = 0
        self.data_list = {
            "asd": "00:02:01",
            "bsd": "00:07:01",
            "csd": "00:01:01",
            "rrsd": "00:04:01",
            "fghsd": "00:01:41",
            "tzu": "00:09:01",
            "azud": "00:02:01",
            "cvb": "00:01:41",
            "jkl": "00:01:06",
            "aertt": "00:11:01"
        }
        self.next_comp = ""
        self.timer_state = False
        self.table_rows = 9
        self.table_cols = 3
        self.participants_above = 6
        self.initUI()

    def initUI(self):

        centralwidget = QtGui.QWidget(self)

        self.lcd = QtGui.QLCDNumber(self)
        time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms)
        self.lcd.setDigitCount(len(time))
        self.lcd.display(time)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.Time)

        self.start = QtGui.QPushButton("Start/Stop", self)
        self.start.clicked.connect(self.Start)

        self.reset = QtGui.QPushButton("Reset", self)
        self.reset.clicked.connect(self.Reset)

        self.le_name = QtGui.QLineEdit()

        self.table = QtGui.QTableWidget()
        self.table.setStyleSheet('QTableWidget { font-size: 24pt; padding: 10px; }')
        self.table.setRowCount(self.table_rows)
        self.table.setColumnCount(self.table_cols)
        self.table.setShowGrid(False)
        self.table.verticalHeader().setDefaultSectionSize(60)
        self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.table.verticalHeader().setVisible(False)
        self.table.horizontalHeader().setVisible(False)
        self.update_table()

        grid = QtGui.QGridLayout()

        grid.addWidget(self.start, 1, 0)
        grid.addWidget(self.reset, 1, 2)
        grid.addWidget(self.lcd, 2, 0, 1, 3)
        grid.addWidget(self.le_name, 3, 0, 1, 3)
        grid.addWidget(self.table, 4, 0, 1, 3)
        grid.setRowMinimumHeight(2, 100)

        centralwidget.setLayout(grid)

        self.setCentralWidget(centralwidget)

        # ---------Window settings --------------------------------

        self.setGeometry(300, 300, 380, 370)
        # self.showFullScreen()

    def update_table(self, new_entry=""):
        local_data = self.data_list
        local_data.update(new_entry)
        local_data = [(v, k) for k, v in local_data.items()]
        local_data.sort(reverse=True)
        if new_entry:
            pos = local_data.index(tuple([(v, k) for k, v in new_entry.items()])[0])
        else:
            pos = len(local_data) - 1
        local_data = [(i, k) for i, k in enumerate(local_data)]
        if pos > self.participants_above:
            local_data = local_data[pos - self.participants_above:]

        for i, j in enumerate(local_data):
            self.a = QtGui.QTableWidgetItem(str(j[0] + 1))
            self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
            self.table.setItem(i, 0, self.a)
            if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]:
                self.table.item(i, 0).setBackground(QtGui.QColor("red"))

            self.a = QtGui.QTableWidgetItem(j[1][0])
            self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignCenter)
            self.table.setItem(i, 1, self.a)
            if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]:
                self.table.item(i, 1).setBackground(QtGui.QColor("red"))

            self.a = QtGui.QTableWidgetItem(j[1][1])
            self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft)
            self.table.setItem(i, 2, self.a)
            if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]:
                self.table.item(i, 2).setBackground(QtGui.QColor("red"))

    def clear_table(self):
        for i in range(self.table_rows):
            for j in range(self.table_cols):
                self.table.setItem(i, j, QtGui.QTableWidgetItem(""))

    def Reset(self):
        self.timer.stop()
        self.clear_table()
        self.update_table()
        self.timer_state = False
        self.s = 0
        self.m = 0
        self.ms = 0

        time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms)

        self.lcd.setDigitCount(len(time))
        self.lcd.display(time)

    def Start(self):
        if not self.timer_state:
            self.timer_state = True
            self.timer.start(10)
        else:
            self.timer_state = False
            self.timer.stop()

    def Time(self):

        if self.ms < 99:
            self.ms += 1
        else:
            if self.s < 59:
                self.ms = 0
                self.s += 1
            elif self.s == 59 and self.m < 99:
                self.m += 1
                self.ms = 0
                self.s = 0
            else:
                self.timer.stop()
        time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms)
        self.update_table({self.le_name.text(): time})
        self.lcd.setDigitCount(len(time))
        self.lcd.display(time)

app = QtGui.QApplication(sys.argv)
main = Main()
main.show()

sys.exit(app.exec_())

As you can see the timer points to the Time function, and fires it every milisec. Inside the timer i update the list, so the participant and the viewers can see his placement all the time.  The problem is that the timer is slower with every participant.
I assume its because the computer is slow, and cant update the graphical table this fast, however i am struggling to come up with a better idea to make the clock work as a real clock, and maintain the dynamic update of the list as well.
Any help would be appreciated!


text:
Q: Selecting content between [] I have HTML code like this:

Some text

Lorem Ipsum:

  [423A18K5][R68A18K5]

Some other text

Lorem Ipsum:

  [9903A1K5][P095GR31]

What i need to do: i must select all codes between [ and ] with jQuery (and to pass them to ajax later).
NOTE: Instead of [] i can use some other symbols, but i cant use HTML tags.
Do you have any sugestions?

A: Not sure if all of the divs you're trying to grab the data from has a common class or if they're all unique as in your example. Also you give a very specific format for the contents of the div above. I.e.:

 ... [#s][#s]...

The code below works assuming that what you grab is in the same format. Basically it selects the div you want, gets the text inside, then drops leading or ending spaces, drops anything before the first '[', then gets rid of the first [ and last ], then creates the array, splitting on ']['.
    var codes = $('.inside').text().trim().replace(/^[^\[]*/,'').replace(/^\[/,'').replace(/\]$/,'').split('][');

The regex could probably be cleaned up a bit, but it's simple and it works.


text:
Q: My computer wakes up at 5:59:39 every morning. How do I stop that from happening? For some reason my 2017 iMac running macOS 10.14.6 keeps waking up from sleep at exactly 5:59:39 AM every morning. If I look at the logs using pmset -g log at this time it consistently reports:
2019-11-07 05:59:39 -0500 Assertions            PID 77(powerd) Created UserIsActive "com.apple.powermanagement.wakeschedule" 00:00:00  id:0x0x900009fac [System: PrevIdle PrevDisp DeclUser kDisp]
2019-11-07 05:59:39 -0500 Assertions            Kernel Idle sleep preventers: IODisplayWrangler
2019-11-07 05:59:39 -0500 Notification          Display is turned on
2019-11-07 05:59:40 -0500 Assertions            PID 77(powerd) Created UserIsActive "com.apple.powermanagement.wakeschedule" 00:00:00  id:0x0x900009faf [System: PrevIdle PrevDisp DeclUser kDisp]
2019-11-07 05:59:41 -0500 Assertions            PID 77(powerd) TimedOut UserIsActive "com.apple.powermanagement.wakeschedule" 00:00:02  id:0x0x900009fac [System: PrevIdle PrevDisp DeclUser kDisp]
2019-11-07 05:59:41 -0500 Assertions            PID 77(powerd) TimedOut UserIsActive "com.apple.powermanagement.wakeschedule" 00:00:01  id:0x0x900009faf [System: PrevIdle PrevDisp DeclUser kDisp]

I don't understand what those log entries mean and searching for the terms in them hasn't yielded anything revealing so far.
In the Energy Saver system preferences, I have the following options enabled:

*

*Prevent Computer from sleeping automatically when the display is off

*Wake for network access

*Enable Power Nap

In the "Schedule" settings the "Start up or wake" setting is disabled.
Why is my computer waking up? And what can I do to stop it?

A: You should use the Terminal command pmset -g sched to determine if there is any repeated wake from sleep scheduled or some other app/system service which has set a wake event.


text:
Q: Get the ID of a function(this) td element I send a TD through a function but I can't interact with the ID.
HTML:

JS:
function move(td) {
    //I want the ID of this td that I've captured by "this"
    var tdId = td.id; //<--- This doesn't works

    var tds = document.getElementsByTagName('td');
    for (var td in tds) {
            if (tds[td].innerHTML == "last") {
                tdFinal = tds[td];
            }
    }
    alert(tdFinal.id); //<---- This works fine
}

A: strong textFor me it works just fine :)
Here is a fiddle: http://jsfiddle.net/4P3jF/
var move = function(td) {
//I want the ID of this td that I've captured by "this"
var tdId = td.id; //<--- This doesn't works

alert(tdId);

}

A: Let's start with a jsbin.com demo. People love demos.

A couple of things that should be addressed:
1. HTML ids should start with a letter
This is is no longer a requirement in HTML 5, but you should still do it. Read more about the id attribute here
If you want to attach data to an element, you should use a data-* attribute. Read more about data-* attributes here

2. Unobtrusive JavaScript
I removed the onclick attributes in favor of taking a more unobtrusive approach. I attached a simple id to the table element to make it easy to target the specific td elements we care about.
// our move function
function move(elem) {
  console.log(elem.getAttribute("data-id"));
}

// our click listener
function onClick(event) {
  move(this);
  event.preventDefault();
}

// get our table's td elements
var table = document.getElementById("my-table");
var tds   = table.getElementsByTagName("td");

// loop through each td and add a click listener
for (var i=0, len=tds.length; i<len; i++) {
  tds[i].addEventListener("click", onClick);
}

Add a dash of CSS to make the td elements appear clickable
#my-table td {
  cursor: pointer;
}

A: Your first statement works fine!
I've made a fiddle with an example:
http://jsfiddle.net/8tgVq/2/
(check your console for the output!)
The HTML:

        a
        b
        c

The JS:
function move(td) {
    console.log(td.id);
}

The output:
1
2
3


text:
Q: AccountManager: when to set result? Context
My app only stores user/pass. No tokens are used.
Question 1
Methods setAccountAuthenticatorResult(Bundle) and onResult(Bundle) are meant to notify the AbstractAccountAuthenticator about the outcome, but I have a project working without them, what are they for ?
Question 2
What is onRequestContinued() for ?
Question 3
When addAccount is finished and the account created, should onActivityResult be called on the Activity that triggered it?
Question 4
If an Intent is returned with key AccountManager.KEY_INTENT in addAccount implementation, the AbstractAccountAuthenticator will start the Intent. I have noticed that many developers add extras. Who gets them ?
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException
{
    Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);

    intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_TYPE, accountType);     // <-- this
    intent.putExtra(AuthenticatorActivity.ARG_AUTH_TYPE, authTokenType);      // <-- this
    intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true);   // <-- this

    Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);

    return bundle;
}

Asnwers
kris larson:
Thanks for the answer. I think we might be using the AccountManager wrong to be honest.
We want to share some credentials across our apps, so we have a Service to hold the custom account type. Since apps know the account type and share the signing certificate, they have access to the Account.
When each app is started, they try to get the Account. If no Account exists, they trigger the login page in our Service by calling AccountManager.addAccount(...).
Once the login (through web services) is successfull, we make it available to other apps with AccountManager.addAccountExplicitly(...). Not setting an outcome after it, does not impact the outcome.
How does it affect the AccountManager ? Is this approach correct ?

A: EDIT: I'll just describe how — after much agony — I implemented the authentication service for our app.
You said you have a Service for the authenticator.  I'll assume you did that in the prescribed way: declare a service in your manifest that references your class, which subclasses android.accounts.AbstractAccountAuthenticator.  The manifest entry also references an XML file with the account-authenticator tag that declares your account type, plus a name and icons to be used by the Settings | Accounts page.  That stuff is all documented.
For our app, I wanted the last signed in user to sign in automatically until they selected "Sign Out" on the navigation drawer.  To accomplish this, the username would be persisted in SharedPreferences for the app.
So if the SharedPreferences did not have a username, the app calls AccountManager.newChooseAccountIntent() for our custom account type, then calls startActivityForResult with intent that was returned.  If the user selects "Add new account", then addAccount() will be invoked on the authenticator as described below.
Our authentication activity not only has UI for username/password login but also password reset and new trial account creation, so there are a lot of moving parts.  When the user enters the username/password and presses the Sign In button, the app authenticates against our server.  If successful, the app calls AccountManager.addAccountExplicitly() for that username.
The AccountManager Choose Account activity will call onActivityResult() when this is all finished.  If we get RESULT_OK the app persists the username for the next sign in operation.
If the SharedPreferences has a username, and the Account Manager has an account registered for it, we don't need to select anything and just skip to this next phase.
With the account selected/known, now the app can authenticate.  It calls peekAuthToken() to see if a token was registered, and invalidateAuthToken() if it was.  This is done so that when the app calls getAuthToken() on the account manager, it forces the account manager to call getAuthToken() on the app's authenticator to authenticate with the server.  Since the server is not returning tokens, we are using dummy tokens and that is why they are invalidated every time.
Now the interesting part about all this is that if the user selects an account that was already registered, it won't be authenticated, whereas if they selected Add New Account and that operation was successful, the new account will be authenticated.  So just be aware that if you notice that signing into a new account causes two round trips to your authentication server, now you know why.  (I have some logic in there using setUserData() on the account to indicate pre-authenticated, but it looks like I forgot to finish that feature.  Hmmm.)

Let's start with some background to clarify things.
You have some subclass of AbstractAccountAuthenticator.  You have created this class to respond to authentication requests for the account type it was registered for.  The thing to keep in mind about this class is that the platform AccountManager is always the component your app will interact with; your app will never interact directly with this class.  So in a sense the AccountManager is a client of your authentication service.  The work that the authenticator performs is stuff that will be in a background thread.
Now part of the work the authentication service must do is interact with the user, asking for user account names, passwords, fingerprint IDs, smart cards, etc.  So let's assume you have an AuthenticatorActivity that does that work.  Typically you will subclass android.accounts.AccountAuthenticatorActivity for this.  This activity class is really nothing special.  The only thing it does is to expect a reference to an AccountAuthenticatorResponse when it starts, then to call that response's onResult() method when the activity exits.
The app I work on is similar to yours in that there is no token returned from the authentication service.  I still implemented getAuthToken for two reasons:

*

*to stay consistent to the workflow that Google has mandated.

*to make it easy to return a real token if/when we enhance our authentication service to return a token.

So let's follow the bouncing ball to understand how everything fits together.

*

*Your app activity has implemented the AccountManagerCallback interface in order to get asynchronous messages from the AccountManager.

*Let's assume your app has persisted a user name for authentication.  Your app creates an Account object with this username.

*Optionally your app can call AccountManager.getAccountsByType() to ensure that the account exists.

*Your app calls AccountManager.getAuthToken() for the account.

*The AccountManager sees that your authenticator is registered for that account type and calls authenticator's getAuthToken method.

*The getAuthToken method will contact your authentication server and get a response.

*If successful, your authenticator returns the (dummy) auth token.

If the login fails, then things get interesting.

*

*Since your authenticator is not returning an auth token, it must return an intent to start your AuthenticatorActivity so that the user can re-authenticate.

*The AccountManager uses your intent to start your AuthenticatorActivity. As part of the request, it will get a reference to an AccountAuthenticatorResponse it will need later.

*Your AuthenticatorActivity interacts with the user, gets username/password, contacts your server, gets a response.  Let's say the authentication succeeds.

*Your activity will finish, calling the onResult method of the AccountAuthenticatorResponse it was given.

*The AccountManager on getting notification from the response object will invoke the callback method with the results.

So with that we can answer your questions:

Methods setAccountAuthenticatorResult(Bundle) and onResult(Bundle) are meant to notify the AbstractAccountAuthenticator about the outcome, but I have a project working without them, what are they for ?

More correctly, they are meant to notify the AccountManager about the outcome.
 Are you sure it's working?  Have you tried logging in with an invalid username/password?  AccountManager will assume authentication has been cancelled unless it gets notified otherwise.

What is onRequestContinued() for ?

I don't have an exact answer. My guess is that it's to keep the AccountManager in sync somehow with what is happening with the UI in regards to authentication.

If an Intent is returned with key AccountManager.KEY_INTENT in addAccount implementation, the AbstractAccountAuthenticator will start the Intent. I have noticed that many developers add extras. Who gets them ?

The answer is:  You do.  This intent will go the AuthenticatorActivity that you have created to handle authentication, so any data your activity needs to perform authentication needs to be passed in with these extras.

When addAccount is finished and the account created, should onActivityResult be called on the Activity that triggered it?

The use case for this is when your app calls AccountManager.newChooseAccountIntent() then calls startActivityForResult() with the resulting intent.  The AccountManager's "choose account" activity is then started.
Now since "add new account" is an option on the "choose account" UI, the AccountManager will call your authenticator's addAccount() method when that option is selected.  Your authenticator then returns a Bundle as described in the AbstractAccountAuthenticator docs back to AccountManager.  After this the "choose account" activity will finish and call onActivityResult() on your activity.
Hopefully you're starting to see that the AccountManager acts as a broker between your app and your authenticator components.  To make this clearer, consider that you could package up those components in a way that other apps could use them to authenticate to your service without knowing any details.  If you created your own custom account type, you can invoke your authentication directly from the Settings | Accounts page of the device.  This is a good test to see if your addAccount() method is implemented correctly.

A:
Methods setAccountAuthenticatorResult(Bundle) and onResult(Bundle) are meant to notify the AbstractAccountAuthenticator about the outcome, but I have a project working without them, what are they for ?

Those methods (as well as onError) are to pass back a result to whoever might wait for one, e.g. have a look at AccountManager.getAuthToken(...) and many others that let you specify a AccountManagerCallback<Bundle>. This is where your result will be passed to. null is valid for the callback, so unless you structure your app around the result, it will work without it.
AccountAuthenticatorResponse.onResult(Bundle) and onError(...) are much more important if you implement getAuthToken where this is how you can return an access token from an asynchronous backend call (e.g. token refresh).

What is onRequestContinued() for ?

There is very little information (reads: none) available. The only time it gets used that I could find was in AccountManagerService where it's but a counter that gets increased for logging purposes. I don't think it does anything at the moment.

When addAccount is finished and the account created, should onActivityResult be called on the Activity that triggered it?

Should work as long as you use startActivityForResult(..)

If an Intent is returned with key AccountManager.KEY_INTENT in addAccount implementation, the AbstractAccountAuthenticator will start the Intent. I have noticed that many developers add extras. Who gets them ?

As already mentioned by kris, you can return an Intent that starts your Activity and pass any extras that you might need.

On an unrelated note: You should really try not to store any passwords in plain text. Even though the AccountManager says setPassword() it is not protected and thus not secure.


text:
Q: How to decode a JSON into a pandas dataframe? I am trying to decode a JSON I get from a RESTful API into a pandas dataframe. Here is snippet of how the JSON looks like:
{
   "success":true,
   "data":[
      {
         "id":26,
         "name":"A",
         "comment":"",
         "start_time_plan":null,
         "start_time_actual":"2016-09-13 00:00:00",
         "start_time_delta":null,
         "start_time_score":null,
         "start_time_score_achievement":null,
         "start_time_traffic_light":null,
         "end_time_plan":null,
         "end_time_actual":"2016-09-13 00:00:00",
         "end_time_delta":null,
         "end_time_score":null,
         "end_time_score_achievement":null,
         "end_time_traffic_light":null,
         "status":0,
         "measure_schedule_revision_id":63,
         "responsible_user_id":3,
         "created_time":"2016-09-13 11:29:14",
         "created_user_id":3,
         "modified_time":"2016-09-21 16:33:41",
         "modified_user_id":3,
         "model":"Activity"
      },
      {
         "id":27,
         "name":"B",
         "comment":"",
         "start_time_plan":null,
         "start_time_actual":"2016-09-13 00:00:00",
         "start_time_delta":null,
         "start_time_score":null,
         "start_time_score_achievement":null,
         "start_time_traffic_light":null,
         "end_time_plan":null,
         "end_time_actual":"2016-09-13 00:00:00",
         "end_time_delta":null,
         "end_time_score":null,
         "end_time_score_achievement":null,
         "end_time_traffic_light":null,
         "status":0,
         "measure_schedule_revision_id":63,
         "responsible_user_id":3,
         "created_time":"2016-09-13 11:29:48",
         "created_user_id":3,
         "modified_time":"2016-10-16 18:14:36",
         "modified_user_id":1,
         "model":"Activity"
      }
   ]
}

My goal is to get a dataframe with two columns consisting of end_time_delta and start_time_delta and to build a simple scatterplot from it.
Here is what I do:
u = 'https://myurl.com'

# urllib3 + poolmanager for requests
import urllib3
http = urllib3.PoolManager()

# get the JSON
import json
r = http.request('GET', u)
result = json.loads(r.data.decode('utf-8'))

for item in result['data']:
    print(item['end_time_delta'])

for item in result['data']:
    print(item['start_time_delta'])

# decode JSON to pandas dataframe
import pandas as pd

df = pd.read_json( result, orient='values')

I manage to get the JSON and forloop through it. But I can't decode it to a pandas dataframe. How does that work?
(I tried myself out with pandas read_json. But I am not sure, it is a smart idea. It is not working anyhow.)

A: try:
df = pd.DataFrame(json.loads(j)['data'])

get the columns you want
df[['start_time_delta', 'end_time_delta']]

scatter plot with
df[['start_time_delta', 'end_time_delta']].plot.scatter(0, 1)

setup
import json

j = """{
   "success":true,
   "data":[
      {
         "id":26,
         "name":"A",
         "comment":"",
         "start_time_plan":null,
         "start_time_actual":"2016-09-13 00:00:00",
         "start_time_delta":null,
         "start_time_score":null,
         "start_time_score_achievement":null,
         "start_time_traffic_light":null,
         "end_time_plan":null,
         "end_time_actual":"2016-09-13 00:00:00",
         "end_time_delta":null,
         "end_time_score":null,
         "end_time_score_achievement":null,
         "end_time_traffic_light":null,
         "status":0,
         "measure_schedule_revision_id":63,
         "responsible_user_id":3,
         "created_time":"2016-09-13 11:29:14",
         "created_user_id":3,
         "modified_time":"2016-09-21 16:33:41",
         "modified_user_id":3,
         "model":"Activity"
      },
      {
         "id":27,
         "name":"B",
         "comment":"",
         "start_time_plan":null,
         "start_time_actual":"2016-09-13 00:00:00",
         "start_time_delta":null,
         "start_time_score":null,
         "start_time_score_achievement":null,
         "start_time_traffic_light":null,
         "end_time_plan":null,
         "end_time_actual":"2016-09-13 00:00:00",
         "end_time_delta":null,
         "end_time_score":null,
         "end_time_score_achievement":null,
         "end_time_traffic_light":null,
         "status":0,
         "measure_schedule_revision_id":63,
         "responsible_user_id":3,
         "created_time":"2016-09-13 11:29:48",
         "created_user_id":3,
         "modified_time":"2016-10-16 18:14:36",
         "modified_user_id":1,
         "model":"Activity"
      }
   ]
}"""


text:
Q: Getting postmeta value I am currently creating a wordpress plugin that retrieves the value of the custom fields after insertion into the database.
I use p2theme and I add a text box (for the value of the custom fields) on the form in frontend.
post is added and the value of custom fields as well in postmeta.
But the problem is that in my plugins there's no value.
function recupere($post_id) {

  echo 'POST = ' . $post_id . ' / ';

  if (wp_is_post_revision($post_id)) {
    return;
  }

  $post = get_post($post_id);

  $meta_values = get_post_meta($post_id, 'destinataire', true);

  echo 'meta = ' . $meta_values . ' <br />';
}
add_action('save_post', 'recupere');


text:
Q: Why backlight an LCD display with AMOLED? Can IPS terminology apply to AMOLED? I've been reading about IPS LCD and LED/OLED display technology in general, and am a bit confused about the following product:
HP Spectre x360 2-in-1 Laptop: 15.6" 4K, i7-8705G, 16GB DDR4, 512 SSD, Vega M GL
In the specs it says:
15.6" diagonal 4K IPS anti-glare micro-edge AMOLED-backlit (3840 x 2160)
What actually is this?
Based on reading the wikipedia articles on IPS and AMOLED I have two ideas:
 1. That they are backlighting an IPS LCD screen with AMOLED.
 2. That they are using the IPS terminology to refer to the active matrix part of the OLED.
As for hypothesis (1) Why would you do this though? Isn't the point of the the AMOLED that the OLED is managed by pixel addressing with an active matrix? What benefit do you get from mixing the two technologies in the same screen?
As for hypothesis (2), I see an enormous number of articles arguing for AMOLED or IPS being better technologies, so could they be marketing this as a hybrid so that buyers say "this has both!". Since AMOLED stands for active matrix OLED and IPS is technically an active matrix, could it be that HP or Samsung is using the term to describe the thin film transistor matrix that addresses the OLEDs. Am I overthinking this?
What actually is going on with this product?

A: Click through to the HP page, it says
15.6" diagonal 4K IPS BrightView micro-edge WLED-backlit touch screen
so it's likely an error.

A: OLED and AMOLED displays do not use backlights as they are light emitting. IPS specifically is used for LCD displays only, as far as I know.
I'd say it's either a mistake or they are using AMOLEDs to produce the backlight, which seems strange to me. My bet is on the former.


text:
Q: Dynamically Loading Data Into Django Modal I've been trying to implement a way to dynamically load information into a modal in order to do a quick preview for my ecommerce site. Any help would be appreciated, I'm not sure which direction I should head in. I tried to play with Javascript and creating an onclick function to refresh the div, but I have had no success so far. Please comment if any part of my question is unclear.
attached is a screenshot as to what is rendering on my end to get an idea of what I am trying to do.
https://gyazo.com/e0168c6d41a19071a95e8cecf84e37a9
store.html
    {% extends 'main.html' %}
    {% load static %}
    <!DOCTYPE html>

        <link rel="stylesheet" href="{% static 'css/store.css' %}">

    {% block content %}

Store

                Welcome to our online shop, where our shipping quotes are listed below

                We ship a variety of items to fit your needs including cars, car parts, heavy duty boxes, clothes, canned goods and food, furniture, household items, freight containers and more.

                Click here to learn more

        {% for product in products %}

{{product.name}}

                <button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#myModal">View Details</button>

{{product.name}}

                        <button type="button" class="close" data-dismiss="modal">×</button>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                {% if user.is_authenticated %}
                {% if product.specialObject == 0 %}
                <button  data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

${{product.price|floatformat:2}}

                {% endif %}
                {% endif %}

        {% endfor %}

    {% endblock content %}

models.py
class Product(models.Model):
    name = models.CharField(max_length=150, null=True)
    price = models.FloatField()
    image = models.ImageField(null=True, blank=True)
    specialObject = models.BooleanField(default=False)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

A: You could assign an id to the h6, img and button tags respectively then use javascript to update the modal by retrieving the necessary ids.
For example:
{% for product in products %}
     ...
     # Here you can use the product id to mark each tags within the iteration

     # Applying the same concept as above to the h6 and button tags

{{ product.name }}

          # Can use the onclick event here on the button and pass the button's id which is the product's id itself to be dealt with in js.
          <button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#myModal" id="{{ product.id }}" onclick="updateModal(this.id)">View Details</button>
          ...

     ...
{% endfor %}

# I'd suggest moving the modal outside of the forloop as well...

...

      ...

  # Leave here blank...
      ...
           # Assign an id here as well.
      ...
...

# Javascript