text:
Q: How to know if equation adds more info to a set of equations? I'm looking for a formalized way to be able to know whether adding an equation to a set of linear equations adds new information or not, does anyone know of a way?
For a really simple case, let's say I have these equations:
$A = 3\\
B+C = 4\\
D = 8
$
Obviously, the equation below doesn't add any new information:
$-A = -3$
But it gets less obvious when adding an equation like this:
$B + D = 6$
Or:
$C = 2$
When the list of equations is longer, it gets a lot less obvious to me as well:
$
A=3\\
B+C=4\\
D=8\\
C=4\\
F=3\\
E=12\\
F+G=4\\
H=1
$
If I want to add a new equation:
$D+E=7$
I can see that $D$ and $E$ are already fully specified, so this doesn't really add any new information, but a more complex expression would be harder for me to rule out.
Is there a formalized way to see whether or not adding a new equation will add more information?  Possibly by looking at the matrix form of the equations?
Here is the last group of equations:
$
\begin{bmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{bmatrix}
*
\begin{bmatrix}
A \\
B \\
C \\
D \\
E \\
F \\
G \\
H \\
\end{bmatrix}
=
\begin{bmatrix}
3 \\
4 \\
8 \\
4 \\
3 \\
12 \\
4 \\
1 \\
\end{bmatrix}
$
And here is the equation I wanted to add to the set:
$
\begin{bmatrix}
0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\
\end{bmatrix}
*
\begin{bmatrix}
A \\
B \\
C \\
D \\
E \\
F \\
G \\
H \\
\end{bmatrix}
=
7
$
Thanks for any help you can provide!

A: Let's say you have a set of $n$ equations in $m$ variables.  You already know how to represent this set of equations as an $n \times m$ matrix $A$.
Now you want to augment that set of equations with one more.  This new, larger set of equations can be represented by an $(n+1) \times m$ matrix, $B$.
The question "Does my last equation add any information to the collection?" is equivalent to "Is the rank of $B$ larger than the rank of $A$?".  To answer this question, you need to:

*

*Perform row reduction on $A$ and count the number of pivots;

*Perform row reduction on $B$ and count the number of pivots;

*Compare one number to the other.

A: Given a set of equations,
$$
\begin{cases}
    A+B = 5\\
    2D = 3\\
    A + B + C + 3D = 10,
\end{cases}
$$
You can identify it with a matrix like this,
$$
\begin{bmatrix}
1 & 1 & 0 & 0 &  5 \\
0 & 0 & 0 & 2 &  3 \\
1 & 1 & 1 & 3 &  10 \\
\end{bmatrix}
$$
Notice that each column of the matrix corresponds to each variable A, B, C and D in order, the last column corresponds to the result of the equation, and each number in the rows (except for the results of the equations) correspond to the integer coefficient that is next to each variable. For example the first row corresponds to the equation $A+B = 5$ that is the same as $A + B + 0C + 0D = 5$ so we should write in the first row 1 1 0 0 5.
This association is very useful because the matrix has the same properties as the system of equations when you want to add equations is the same as adding rows, so you already know that when two equations have the same "information" then the can "cancel each other out". For example,
\begin{cases}
    Z+Y = 1\\
    -5Z-5Y=-5,\\
\end{cases}
Divide the second equation by 5,
\begin{cases}
    Z+Y = 1\\
    -Z-Y=-1\\
\end{cases}
Sum the first one to the last one,
\begin{cases}
    Z+Y = 1\\
    -Z-Y + Z+ Y=-1 + 1\\
\end{cases}
We get,
\begin{cases}
    Z+Y = 1\\
    0=0\\
\end{cases}
And we already know that so we end with,
\begin{cases}
    Z+Y = 1\\
\end{cases}
But this method also works with matrices,
We associate a matrix to the system of equations and do the same "operations",
\begin{cases}
    Z+Y = 1\\
    -5Z-5Y=-5,\\
\end{cases}
$\hspace{87 mm} \equiv$
\begin{bmatrix}
1 & 1 & 1 \\
-5 & -5 & -5 \\
\end{bmatrix}
We divide the last row by 5,
\begin{bmatrix}
1 & 1 & 1 \\
-1 & -1 & -1 \\
\end{bmatrix}
the we sum the first row to the last row,
\begin{bmatrix}
1 & 1 & 1 \\
-1 + 1 & -1 + 1& -1 + 1\\
\end{bmatrix}
is the same as,
\begin{bmatrix}
1 & 1 & 1 \\
0 & 0& 0\\
\end{bmatrix}
then we just have that the associated system of equation is the 1x1 matrix:
\begin{bmatrix}
1 & 1 & 1 \\
\end{bmatrix}
We showed that the last equation wasn't adding "new information" because we ended up with
\begin{cases}
    Z+Y = 1\\
\end{cases}
Finally, what we have done with the associated matrix is to check if its rows are linearly independent, then two equations have "different information" if and only if their "correspondent rows" are linearly independent in their associated matrix.


text:
Q: VBA excel issue with textbox i have been tasked with creating a simpple sign in and out book for vistors but i am not sure on the corect code to use to get the time out to link with the correct name,
what i would like if its possibe is when the vistors go to sign out the enter their name and the time get  added to their data from when they signed in.
 for example the vistors name is in column A row 2 i would like for the time to go to column G row 2 and so on for how many people sign in.
thanks

A: The following will insert the current date time into Column G based on the last used row for that column:
Sub InsertTime()

Dim lRow As Long
lRow = Cells(Rows.Count, 7).End(xlUp).Row + 1
Cells(lRow, 7).Value = Now()

End Sub

Edit:
To do this on the command of a button press you could do this:
Private Sub CommandButton1_Click()

Dim Name As String
Dim lRow As Long

Name = TextBox1.Value
lRow = Cells(Rows.Count, 7).End(xlUp).Row + 1
Cells(lRow, 7).Value = Now()
Cells(lRow, 1).Value = Name

'Reset TextBox For Next Entry
TextBox1.Value = ""

End Sub

You will just need a TextBox and a command button on the form:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract innerText of "Who was your first employer? into Excel from the given HTML

    Who was your first employer?

My code was
Set htmlsecurityquestion = htmldoc.getElementById("dnn_ctr1854_ChallengeQuestion_ChallengeQuestionCmnTextBox_ControlLabel")
Range("A1").Value = htmlsecurityquestion.innerText

but it is not working

A: You access this value through attributes collection, not through innerText. Your second line should be:
Range("A1").Value = htmlsecurityquestion.Attributes["title"].Value;


text:
Q: CSS help positioning divs inline I need help with a recurring problem that happens a lot.  I want to create a header that consists of 3 sections which are positioned inline.  I display them inline using the following css code:  display: inline & float: leftThe problem is that when I resize my browser window the last div is pushed down and isn't displayed inline.  I know it sounds like I'm being picky, but I don't want the design to distort as the visitor change's the monitor screen.  I have provided the html and css code below that I am working with below.  Hopefully I have explained this well enough.  Thanks in advance.
HTML

CSS
#Header {
  display: block;
  width: 100%;
  height: 80px;
  background: #C0C0C0;
}
.masthead-wrapper {
  display: inline;
  float: left;
  width: 200px;
  height: 80px;
  background: #3b5998;
}
.searchbar-wrapper {
  display: inline;
  float: left;
  width: 560px;
  height: 80px;
  background: #FF0000;
}
.profile-menu-wrapper {
  display: inline;
  float: left;
  width: 200px;
  height: 80px;
  background: #00FF00;
}

A:
display them inline using the following css code: display: inline & float: left

Aside... You are actually floating the element, not displaying it inline. The display:inline rule is irrelevant here since floated elements are implicitly displayed as block.
But anyway, your problem is that your sections are all of a fixed width (200 + 560 + 200 = 960px), so when the browser window reduces to near this width (960px plus a bit more for your page margins) the design is going to break - your containers wrap.
If you still want these containers to be fixed width and to simply be cropped on a smaller browser window then you could perhaps add overflow:hidden to your #Header. At least then it won't push the #Header height down beyond 80px (which is a problem you seem to be experiencing). But content will be hidden on the smaller screen.
Or, make all your column containers dynamic and give them percentage widths, so that they flex with the available width. eg. 20%, 60% and 20% respectively. Although this might make the widths too small or too large at some window sizes. You could add a min-width and max-width (with an absolute amount) to limit this. But at narrow widths height:80px is not going to be enough, so min-height:80px would perhaps be more appropriate, if your design allows for your #Header to be flexible?

A: With the percentage, be sure to no have padding on your columns. The padding will be add some width. For your header, you can use the position:fixed, and for IE6 and 7 use position: absolute ( the position :fixed ) doesn't work for them.
For the columns, you can add the clearfix method who can help you for placing without problem the rest of the content.
Your HTML can be something like this :

Column 01

Column 02

Colunm 03

And the CSS :
    #header {
    position: fixed;
    height:80px;
    width:100%;
    }

    #col01,
    #col02,
    #col03 {
    float:left;
    }
    #col01,
    #col03 {
    width:20%;
    }
    #col02 {
    width:60%;
    }
    .clearfix:after {
        content: ".";
        display: block;
        clear: both;
        visibility: hidden;
        line-height: 0;
        height: 0;
    }

    .clearfix {
        display: inline-block;
    }

    html[xmlns] .clearfix {
        display: block;
    }

* html .clearfix {
    height: 1%;
}

Hope it's helping you :-)


text:
Q: PCRE version of subRegex I need to make a version of the function subRegex which works with Text.Regex.PCRE.
The version of subRegex provided in the Text.Regex module is this:
{- | Replaces every occurance of the given regexp with the replacement string.

In the replacement string, @\"\\1\"@ refers to the first substring;
@\"\\2\"@ to the second, etc; and @\"\\0\"@ to the entire match.
@\"\\\\\\\\\"@ will insert a literal backslash.

This does not advance if the regex matches an empty string.  This
misfeature is here to match the behavior of the the original
Text.Regex API.
-}

subRegex :: Regex                          -- ^ Search pattern
         -> String                         -- ^ Input string
         -> String                         -- ^ Replacement text
         -> String                         -- ^ Output string
subRegex _ "" _ = ""
subRegex regexp inp repl =
  let compile _i str [] = \ _m ->  (str++)
      compile i str (("\\",(off,len)):rest) =
        let i' = off+len
            pre = take (off-i) str
            str' = drop (i'-i) str
        in if null str' then \ _m -> (pre ++) . ('\\':)
             else \  m -> (pre ++) . ('\\' :) . compile i' str' rest m
      compile i str ((xstr,(off,len)):rest) =
        let i' = off+len
            pre = take (off-i) str
            str' = drop (i'-i) str
            x = read xstr
        in if null str' then \ m -> (pre++) . ((fst (m!x))++)
             else \ m -> (pre++) . ((fst (m!x))++) . compile i' str' rest m
      compiled :: MatchText String -> String -> String
      compiled = compile 0 repl findrefs where
        -- bre matches a backslash then capture either a backslash or some digits
        bre = mkRegex "\\\\(\\\\|[0-9]+)"
        findrefs = map (\m -> (fst (m!1),snd (m!0))) (matchAllText bre repl)
      go _i str [] = str
      go i str (m:ms) =
        let (_,(off,len)) = m!0
            i' = off+len
            pre = take (off-i) str
            str' = drop (i'-i) str
        in if null str' then pre ++ (compiled m "")
             else pre ++ (compiled m (go i' str' ms))
  in go 0 inp (matchAllText regexp inp)

When I run this with Text.Regex.PCRE imported, I get

Not in scope: 'mkRegex'

There is a function called makeRegex in the RegexLike module but it has a different type and this is where I'm stuck.
Edit - Solution
Create new mkRegex function like so:
-- | Makes a regular expression with the default options
mkRegex :: String -> Regex
mkRegex s = makeRegexOpts opt defaultExecOpt s
  where opt = (defaultCompOpt + compCaseless) -- or other options

A: mkRegex is defined in Text.Regex in the regex-compat package. You could try just copying its source. I'd be surprised if it worked completely without change, but perhaps not too much is necessary.


text:
Q: How to correctly disable systemd-resolved on port 53 for avoiding clash with dnsmasq in Ubuntu 20.04…? I'm trying to use dnsmasq on Ubuntu 20.04 and I get a port clash on port 53 with systemd-resolved. So I've found a few suggestions on solutions, but they seem to be dated or not applicable to my case.
If I disable systemd-resolved, everything comes to a crawl because I seem to be waiting for a timeout on:
sudo: unable to resolve host ubuntu: Temporary failure in name resolution

So basically any command I type takes 20 seconds or so.
I guess I need something like the suggestion to put dns=default in
/etc/NetworkManager/NetworkManager.conf like suggestion in https://askubuntu.com/a/907249. However, this file doesn't exist and is not part of the package anymore:
$ dpkg -S /etc/NetworkManager/NetworkManager.conf
dpkg-query: no path found matching pattern /etc/NetworkManager/NetworkManager.conf

So I post this as a 20.04-titled question instead of adding to 20+ comments there…
If I disable systemd-resolve I can start dnsmasq but everything still comes to a crawl with that "Temporary failure in name resolution" error and if I look at dnsmasq status it seems it has problems too:
ubuntu@ubuntu:~$ sudo systemctl status dnsmasq.service
sudo: unable to resolve host ubuntu: Temporary failure in name resolution
● dnsmasq.service - dnsmasq - A lightweight DHCP and caching DNS server
     Loaded: loaded (/lib/systemd/system/dnsmasq.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2020-10-22 11:20:35 UTC; 1min 8s ago
    Process: 36231 ExecStartPre=/usr/sbin/dnsmasq --test (code=exited, status=0/SUCCESS)
    Process: 36232 ExecStart=/etc/init.d/dnsmasq systemd-exec (code=exited, status=0/SUCCESS)
    Process: 36241 ExecStartPost=/etc/init.d/dnsmasq systemd-start-resolvconf (code=exited, status=0/S>
   Main PID: 36240 (dnsmasq)
      Tasks: 1 (limit: 9024)
     CGroup: /system.slice/dnsmasq.service
             └─36240 /usr/sbin/dnsmasq -x /run/dnsmasq/dnsmasq.pid -u dnsmasq -7 /etc/dnsmasq.d,.dpkg->

Oct 22 11:20:35 ubuntu dnsmasq[36240]: using nameserver 127.0.0.53#53
Oct 22 11:20:35 ubuntu dnsmasq[36240]: read /etc/hosts - 7 addresses
Oct 22 11:20:35 ubuntu systemd[1]: Started dnsmasq - A lightweight DHCP and caching DNS server.
Oct 22 11:20:37 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:20:48 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:20:57 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:21:07 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:21:17 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:21:27 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)
Oct 22 11:21:37 ubuntu dnsmasq[36240]: Maximum number of concurrent DNS queries reached (max: 150)

Is it so that dnsmasq now delegates to non-running 127.0.0.53:53 according to above logs?
With systemd-resolved running I had:
$ sudo ss -lp "sport = :domain"
Netid     State      Recv-Q      Send-Q           Local Address:Port             Peer Address:Port     Process
udp       UNCONN     0           0                127.0.0.53%lo:domain                0.0.0.0:*         users:(("systemd-resolve",pid=36111,fd=12))
tcp       LISTEN     0           4096             127.0.0.53%lo:domain                0.0.0.0:*         users:(("systemd-resolve",pid=36111,fd=13))

And with systemd-resolved disabled but dnsmasq running I have:
sudo ss -lp "sport = :domain"
sudo: unable to resolve host ubuntu: Temporary failure in name resolution
Netid State  Recv-Q Send-Q Local Address:Port    Peer Address:Port Process
udp   UNCONN 18432  0            0.0.0.0:domain       0.0.0.0:*     users:(("dnsmasq",pid=36240,fd=4))
udp   UNCONN 0      0               [::]:domain          [::]:*     users:(("dnsmasq",pid=36240,fd=6))
tcp   LISTEN 0      32           0.0.0.0:domain       0.0.0.0:*     users:(("dnsmasq",pid=36240,fd=5))
tcp   LISTEN 0      32              [::]:domain          [::]:*     users:(("dnsmasq",pid=36240,fd=7))

I have:
$ cat /etc/resolv.conf | grep nameserver
nameserver 127.0.0.53

A: By default, systemd-resolved provides a "validating DNS/DNSSEC stub resolver" on "IP address 127.0.0.53", port 53. You can verify this:
$ sudo netstat -tulpn | grep LISTEN

tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      787/systemd-resolve
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      787/systemd-resolve
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      923/sshd: /usr/sbin
tcp6       0      0 :::5355                 :::*                    LISTEN      787/systemd-resolve
tcp6       0      0 :::22                   :::*                    LISTEN      923/sshd: /usr/sbin

Since port 53 is the default for DNS traffic, as you've pointed out that's where your conflict exists.
systemd-resolved can be configured to work in a few different ways, and the stub resolver can even be disabled entirely.
/etc/systemd/resolved.conf.d is one of those handy directories that allow you to break up configuration in to multiple files. On some distributions this directory may not yet exist, so:
[ -d /etc/systemd/resolved.conf.d ] || mkdir -p /etc/systemd/resolved.conf.d

Next we create the file /etc/systemd/resolved.conf.d/10-make-dns-work.conf in which we'll override the default configuration in /etc/systemd/resolved.conf:
printf "%s\n%s\n" '[Resolve]' 'DNSStubListener=no' | sudo tee /etc/systemd/resolved.conf.d/10-make-dns-work.conf

Now we have:
$ cat /etc/systemd/resolved.conf.d/10-make-dns-work.conf

[Resolve]
DNSStubListener=no

After changing config, we need to restart systemd-resolved:
$ sudo systemctl restart systemd-resolved

Now take a look at where systemd-resolved is listening:
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      2494/sshd
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      8033/systemd-resolv
tcp6       0      0 :::22                   :::*                    LISTEN      2494/sshd
tcp6       0      0 :::5355                 :::*                    LISTEN      8033/systemd-resolv

dnsmasq should now be able to listen on port 53.
If you want to revert these changes, just delete the config file you added:
sudo rm /etc/systemd/resolved.conf.d/10-make-dns-work.conf
sudo systemctl restart systemd-resolved

A: You really don't need to mess with systemd-resolved.
Add 'bind-dynamic' or 'bind-interfaces' to dnsmasq.conf. This way you can leave systemd-resolved alone and running along-side dnsmasq. The dnsmasq man page suggests bind-dymanic for any Linux system that supports it, which Ubuntu does. In use, I can't see any difference they both work.
...just watch out for any 'listen-address=' directives stopping dnsmasq on reboot. In my case, on a pi4 running Ubuntu 20.04 the local IP address of the pi and openVpn server address (different subnet same machine) don't exist when dnsmasq tries to start. I solved this by editing the dnsmasq service file to start after the openVpn service to make sure the IP address was available to bind to by dnsmasq on startup.


text:
Q: Why the channel in the example code of tokio::sync::Notify is a mpsc? I'm learning the synchronizing primitive of tokio. From the example code of Notify, I found it is confused to understand why Channel<T> is mpsc.
use tokio::sync::Notify;

use std::collections::VecDeque;
use std::sync::Mutex;

struct Channel<T> {
    values: Mutex<VecDeque<T>>,
    notify: Notify,
}

impl<T> Channel<T> {
    pub fn send(&self, value: T) {
        self.values.lock().unwrap()
            .push_back(value);

        // Notify the consumer a value is available
        self.notify.notify_one();
    }

    // This is a single-consumer channel, so several concurrent calls to
    // `recv` are not allowed.
    pub async fn recv(&self) -> T {
        loop {
            // Drain values
            if let Some(value) = self.values.lock().unwrap().pop_front() {
                return value;
            }

            // Wait for values to be available
            self.notify.notified().await;
        }
    }
}

*

*If there are elements in values, the consumer tasks will take it away

*If there is no element in values, the consumer tasks will yield until the producer nitify it

But after I writen some test code, I found in no case the consumer will lose the notice from producer.
Could some one give me test code to prove the above Channel<T> fail to work well as a mpmc?

The following code shows why it is unsafe to use the above channel as mpmc.
use std::sync::Arc;
#[tokio::main]
async fn main() {
    let mut i = 0;
    loop{
        let ch = Arc::new(Channel {
            values: Mutex::new(VecDeque::new()),
            notify: Notify::new(),
        });

        let mut handles = vec![];

        for i in 0..100{
            if  i % 2 == 1{
                for _ in 0..2{
                    let sender = ch.clone();
                    tokio::spawn(async move{
                        sender.send(1);
                    });
                }
            }else{
                for _ in 0..2{
                    let receiver = ch.clone();
                    let handle = tokio::spawn(async move{
                        receiver.recv().await;
                    });
                    handles.push(handle);
                }
            }
        }

        futures::future::join_all(handles).await;
        i += 1;
        println!("No.{i} loop finished.");
    }
}

Not running the next loop means that there are consumer tasks not finishing, and consumer tasks miss a notify.

A: Quote from the documentation you linked:

If you have two calls to recv and two calls to send in parallel, the following could happen:

*

*Both calls to try_recv return None.

*Both new elements are added to the vector.

*The notify_one method is called twice, adding only a single permit to the Notify.

*Both calls to recv reach the Notified future. One of them consumes the permit, and the other sleeps forever.

Replace try_recv with self.values.lock().unwrap().pop_front() in our case; the rest of the explanation stays identical.
The third point is the important one: Multiple calls to notify_one only result in a single token if no thread is waiting yet. And there is a short time window where it is possible that multiple threads already checked for the existance of an item but aren't waiting yet.


text:
Q: Doctrine : query not happening with where clause I don't understand my mistake here,
I'm doing a doctrine query in Symfony, which is supposed to find results from a search and order them at the same time.
When checking the page, I get no results and the query isn't in the profiler.
If I only use order by, I get a result and the query in profiler.
Here's my query :
public function getVehiclesbySearchAndSort($sort, $search)
{
    $query = $this->createQueryBuilder('v')
    ->where('v.model like :re')//commenting these lines makes the sorting query happen
    ->setParameter('re', $search)//but with the where clause, no query is happening
    ->orderBy('v.price', $sort)
    ->getQuery()
    ->getResult()
    ;

    return $query;
}

A: While I still didn't figure why I wasn't getting the query in the profiler, it was in the logs.
Now for the dummy mistake :
I forgot to use the '%' to wrap around the like input, as Cid figured too.
->setParameter('re', '%' . $search . '%')


text:
Q: Pad outgoing messages I can't quite figure out how to pad a message that I send. Basically.. I want to pad the message to the max 512 chars as defined in the RFC.
I understand that a message being sent by the user will contain user!user@hostname privmsg #chan (or other_user): text text text \r\n.
Thanks in advance.

A: To pad a string you can use the functions ljust, center or rjust, respectively:
print "Hello, " + "world".ljust(10) + "!"
print "Hello, " + "world".center(10) + "!"
print "Hello, " + "world".rjust(10) + "!"

Output (Try it):
Hello, world     !
Hello,   world   !
Hello,      world!

All three functions have an optional second argument fillchar which lets you specify the character that is used to fill up the additional space.


text:
Q: Non-homeomorphic connected $T_2$-spaces with isomorphic topology poset What are examples of non-homeomorphic connected $T_2$-spaces $(X_i,\tau_i)$ for $i=1,2$ such that the posets $(\tau_1, \subseteq)$ and $(\tau_2,\subseteq)$ are order-isomorphic?

A: Here's an answer without familiarity with locales, which I started after reading Todd Trimble's answer (so his answer is the right one to accept).
Let $X$ be a $\mathsf{T}_1$ topological space, $\tau_X$ the lattice of open subsets, and $\Phi_X$ the opposite lattice, which identifies to the lattice of closed subsets. Let's reconstruct $X$ from $\Phi_X$.
Denote by $0$ "zero" the unique minimal element in $\Phi_X$. Let $\Phi_X^\min$ be the set of minimal elements in $\Phi_X\smallsetminus\{0\}$. Let $i$ be the map $x\mapsto\{x\}$. Since $X$ is $\mathsf{T}_1$, $i$ is a well-defined injective map $X\to\Phi_X$, and its image is exactly $\Phi_X^\min$. (This already retrieves the cardinal of $X$.)
Now we wish to retrieve the topology. Namely, I claim that for $K\subset\Phi_X^\min$, $i^{-1}(K)$ is closed if and only if there exists $F\in\Phi_X$ such that $K=\{Z\in\Phi_X^\min\,:\,Z\le F\}$.
Indeed, suppose that $i^{-1}(K)$ is closed: define $F_K=i^{-1}(K)$ (so $K=i(F_K)$): then $\{Z\in\Phi_X:Z\le F_K\}=\{\{z\}:z\in F_K\}=i(F_K)=K$. Conversely, suppose $K=\{Z\in\Phi_X:Z\le F\}$ for some $F\in\Phi_X$. So $K=\{\{z\}:z\in F\}=i(F)$, so $i^{-1}(K)=F$ is closed.
Hence, for any $\mathsf{T}_1$ topological spaces $X,Y$, every isomorphism $\tau_X\to\tau_Y$ is induced by a unique homeomorphism $X\to Y$.
This also shows that the automorphism group of $\Phi_X$ is canonically isomorphic to the self-homeomorphism group of $X$.
This works without assuming $X$ to be sober. For example, it applies for the cofinite topology, $\Phi_X$ consisting of $X$ and its finite subsets, which is non-sober as soon as $X$ is infinite. (Todd's answer also encompasses non-bijective maps, which I didn't address; soberness is then probably important. Also, there are non-$\mathsf{T}_1$ sober spaces.)

A: There aren't any. Hausdorff spaces are sober spaces. If $X, Y$ are sober, then every frame map $\mathcal{O}(Y) \to \mathcal{O}(X)$, i.e., every poset map between their topologies that preserves finite meets and arbitrary joins, arises from a uniquely determined continuous map $X \to Y$. It follows that a poset isomorphism $\mathcal{O}(X) \cong \mathcal{O}(Y)$, being a frame isomorphism, arises from a homeomorphism between the spaces.
(Just to give slightly more detail: for a sober space $X$, the points of $X$ are in natural bijection with frame maps $\mathcal{O}(X) \to \mathcal{O}(1)$ where the codomain is the topology on a one-point space. Thus a frame map $\phi: \mathcal{O}(Y) \to \mathcal{O}(X)$ induces, via composition with frame maps $\mathcal{O}(X) \to \mathcal{O}(1)$, a function $f: X \to Y$, and is itself of the form $\phi(V) = f^{-1}(V)$.)


text:
Q: `Unexpected element '\' in format string` in code written for MS Fortran I am trying to compile a old Fortran application, original written for Microsoft Fortran (v3.3 1985, F77) using GNU Fortran.

The bigger question: What is the easiest way to compile a  Microsoft Fortran DOS application compiling to a binary for Windows?

I get a large number of errors if I try to compile this code using f77, mainly in printing output (to screen/file). How can I fix?
   110 FORMAT(/,10X,'    Enter action : '\)
                                         1
Error: Unexpected element '\' in format string at (1)
APP1.FOR:107:20:

   120 WRITE(*,'(1X,2A\)')CH,'[2J'
                    1
Error: Unexpected element '\' in format string at (1)
APP1.FOR:121:44:

What is the syntax of WRITE?
   120 WRITE(*,100)
                 1
Error: FORMAT label 100 at (1) not defined


text:
Q: Javascript slideshow web application get really slow I have a Tizen TV Web application, which is basically just a regular web application with Javascript and HTML5. The app must display pictures one by one as a slideshow. The pictures are rather large, about 3000px x 2000px png files, and there are about 300 of them.
I load them as they are needed, not all at once.
Problem being that the application is super fast when it starts, but get progressively slower as time goes on. Eventually, it completely freeze as the TV most likely runs out of memory. Also, this app should be running 24/7, but right now we need to restart the TV at least once a day.
I feel like the cache is being filled and is never cleared. I far a I know, there is no way to clear the cache in Javascript. Is there any solutions to this problem ?


text:
Q: For Einstein's equation $E= mc^2$ is it energy that increases or mass as the velocity increases? I will be surprised if no one asked this before and I would be happy if it is answered already although I haven't located it just yet!
From Einstein's original paper "Does The Inertia of a Body Depend on it's Energy Content" 1905. I am wondering if maybe my original thinking is not right. I always thought that energy increased as velocity increased. End of story.
But as I hear videos and read books the mantra seems to be  mass increases as velocity increases. So which is right I wonder. I know I left gamma out of the equation in the question. Assume it is there thank you.


text:
Q: Toggle the state value with a click in React I'm displaying a certain div when a user clicks a button(really an image)
<img src={notification} className="search_bar_icons" onClick={this.props.open_notifications}/>

When the user clicks this image i'm changing the state of the div i want to show to 'true'
open_notification() {
    this.setState({
        showNotification: true,
    });
}

This is working correctly. But i want to set state as 'false', if the user clicks the image again. How can i do this?

A: You can toggle your value with
this.setState({ showNotification: !this.state.showNotification });

Update. For now, a better approach of using previous state inside of the setState is:
this.setState(prevState => ({ showNotification: !prevState.showNotification }));


text:
Q: Change text color in shape on touch of button How to change color text in button when the user touches this button?
Here is my shape.xml code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:state_pressed="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33"
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item android:state_focused="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33"
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item >
<shape android:shape="rectangle">
  <gradient android:startColor="#333333"
    android:endColor="#333333"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

</selector>

A: Use color selector, something like this
src/color/button_text.xml
 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true" android:color="#000000" />
     <item android:state_focused="true" android:color="#000000" />
     <item android:color="#FFFFFF" />
 </selector>

Then in the button you do this
<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/text"
   android:textColor="@color/button_text" />

A: Your probably going to want to do other stuff once you have pressed the button so why not just create a normal button and set its background to your shape and then in java create an onTouch event for the button
    Button.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                // do other stuff
                Button.setTextColor(Color.parseColor("#000000"));
            }
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {
                Button.setTextColor(Color.parseColor("#FFFFFF"));
            }
            return false;
        }
    });


text:
Q: Graphics2D - Rotating Shapes on a Graphics2D object I have a Graphics2D object which I use to draw on my Canvas. I draw multiple shapes on the Canvas and want to transform only one (or part) of them.
I'll try to keep this simple:
void render(Graphics2D g) {
    ... // Draw shape 1
    ... // Draw shape 2
    ... // Draw shape 3
}

How would I go about rotating shape 2 while leaving shape 1 and 3 intact? By "rotate" I mean rotating around its center point, which we can define as x and y for example.
I've been looking for a way to do this for a while now, but couldn't find anything that works the way I want it to.
Is there any simple way to do this?

A: Rather than rotating the shape around it's centre point, rotate and then translate the canvas. To rotate around the centre of the shape at (x, y), first translate the canvas by (-x, -y) and then rotate the canvas -d degrees and draw the shape as normal at (0,0).
When you're done, rotate back then translate back (note that with these geometric transformations the order is important, translating and then rotating will give you a completely different outcome).
This means that you can still draw an object at any rotation without having to recalculate the coordinates yourself.

A:     AffineTransform afx = new AffineTransform();
    afx.rotate(angleRad, s.getCenter().x, s.getCenter().y);
    //afx.rotate(angleRad);
    java.awt.Shape ss = afx.createTransformedShape(s.getPrimativeShape());
    return ss;

s is my wrapper class for java.awt.Shape and does some stuff with it.... But what you want is in line 2.
afx.rotate(Angle,xAnchorPoint,yAnchorPoint);
afx.rotate rotates the object about the point (xAnchorPoint;yAnchorPoint).
Hope this is what you wanted

A: In order to rotate a shape, use one of the Graphics2D.rotate methods.
Cache the transform used for both shape 1 and shape 3. Before drawing shape 3, ensure that you reset the transform to the cached one, since using rotate for shape 2 will alter the current transform coordinates.
Steps:

*

*Cache current transform

*Draw shape 1

*Rotate

*Draw shape 2

*Set transform to cached one

*Draw shape 3


text:
Q: How to get conditional weighted means for several columns For the following dataframe:
eu <- structure(list(land = structure(c(1L, 4L, 5L, 12L, 9L, 13L, 16L, 18L, 27L, 10L, 25L, 21L, 28L, 19L, 8L, 26L, 6L, 3L, 15L, 14L, 11L, 17L, 20L, 23L, 24L, 2L, 22L, 7L), .Label = c("Belgie", "Bulgarije", "Cyprus", "Denemarken", "Duitsland", "Estland", "Europese Unie", "Finland", "Frankrijk", "Griekenland", "Hongarije", "Ierland", "Italie", "Letland", "Litouwen", "Luxemburg", "Malta", "Nederland", "Oostenrijk", "Polen", "Portugal", "Roemenie", "Slovenie", "Slowakije", "Spanje", "Tsjechie", "Verenigd Koninkrijk", "Zweden"), class = "factor"), `1979` = c(91.36, 47.82, 65.73, 63.61, 60.71, 85.65, 88.91, 58.12, 32.35, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 61.99), `1981` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 81.48, NA, NA, NA, NA, NA, NA, NA,  NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `1984` = c(92.09, 52.38, 56.76, 47.56, 56.72, 82.47, 88.79, 50.88, 32.57, 80.59, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 58.98), `1987` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 68.52, 72.42, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `1989` = c(90.73, 46.17, 62.28, 68.28, 48.8, 81.07, 87.39, 47.48, 36.37, 80.03, 54.71, 51.1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 58.41), `1994` = c(90.66, 52.92, 60.02, 43.98, 52.71, 73.6, 88.55, 35.69, 36.43, 73.18, 59.14, 35.54, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 56.67), `1995` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 41.63, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `1996` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 67.73, 57.6, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `1999` = c(91.05, 50.46, 45.19, 50.21, 46.76, 69.76, 87.27, 30.02, 24, 70.25, 63.05, 39.93, 38.84, 49.4, 30.14, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 49.51), `2004` = c(90.81, 47.89, 43, 58.58, 42.76, 71.72, 91.35, 39.26, 38.52, 63.22, 45.14, 38.6, 37.85, 42.43, 39.43, 28.3, 26.83, 72.5, 48.38, 41.34, 38.5, 82.39, 20.87, 28.35, 16.97, NA, NA, 45.47), `2007` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 29.22, 29.47, NA), `2009` = c(90.39, 59.54, 43.3, 58.64, 40.63, 65.05, 90.75, 36.75, 34.7, 52.61, 44.9, 36.78, 45.53, 45.97, 40.3, 28.2, 43.9, 59.4, 20.98, 53.7, 36.31, 78.79, 24.53, 28.33, 19.64, 38.99, 27.67, 43), inwoners = c(11161642, 5602628, 80523746, 4591087, 65578819, 59685227, 537039, 16779575, 63896071, 11062508, 46727890, 10487289, 9555893, 8451860, 5426674, 10516125, 1320174, 865878, 2971905, 2023825, 9908798, 421364, 38533299, 2058821, 5410836, 7284552, 20020074, 501403599), plicht = structure(c(1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("ja", "nee"), class = "factor")), .Names = c("land", "1979", "1981", "1984", "1987", "1989", "1994", "1995", "1996", "1999", "2004", "2007", "2009", "inwoners", "plicht"), row.names = c(NA, -28L), class = "data.frame")

I need conditional column means. I can do that with:
verplicht <- c("Europese Unie (stemplicht)", colMeans(eu[eu$plicht=="ja",c(2:13)], na.rm=TRUE), NA)
vrij <- c("Europese Unie (geen stemplicht)", colMeans(eu[eu$plicht=="nee",c(2:13)], na.rm=TRUE), NA)
eu2 <- rbind(eu, verplicht, vrij)

However, I need weighted column means with country population (the inwoners column) as the weights. I tried to that with:
verplicht <- c("Europese Unie (stemplicht)", lapply(eu[eu$plicht=="ja",c(2:13)], weighted.mean(x, eu[eu$plicht=="ja",14], na.rm=TRUE)), NA)

but that resulted in the following error:
Error in weighted.mean.default(x, eu[eu$plicht == "ja", 14], na.rm = TRUE) :
  'x' and 'w' must have the same length

I understand what the error-message is saying, but don't know how to solve this. Any suggestions?

A: The problem is with how you're using lapply. Here's the correct code:
lapply(eu[eu$plicht=='ja',2:13], weighted.mean, eu[eu$plicht=='ja','inwoners'], na.rm=TRUE)
lapply(eu[eu$plicht=='nee',2:13], weighted.mean, eu[eu$plicht=='nee','inwoners'], na.rm=TRUE)

Notice how weighted.mean is used as an argument, rather than inside an anonymous function with x as an argument. You could equivalently do:
lapply(eu[eu$plicht=='ja',2:13], function(x) weighted.mean(x, eu[eu$plicht=='ja','inwoners'], na.rm=TRUE))
lapply(eu[eu$plicht=='nee',2:13], function(x) weighted.mean(x, eu[eu$plicht=='nee','inwoners'], na.rm=TRUE))

But you're currently kind of mixing the two different ways of using lapply.

A: If inwoners is the population, then
> (weights <- with(eu, inwoners/sum(inwoners)))
#  [1] 0.0111303968 0.0055869443 0.0802983327 0.0045782350 0.0653952416
#  [6] 0.0595181478 0.0005355356 0.0167326033 0.0637172042 0.0110315403
# [11] 0.0465970828 0.0104579315 0.0095291428 0.0084282004 0.0054114829
# [16] 0.0104866868 0.0013164784 0.0008634541 0.0029635856 0.0020181596
# [21] 0.0098810599 0.0004201845 0.0384254312 0.0020530577 0.0053956892
# [26] 0.0072641601 0.0199640310 0.5000000000

and the weighted mean of the 2004 column, for example, is
> weighted.mean(eu$`2004`, w = weights, na.rm = TRUE)
# [1] 45.31782

To get the weighted mean of each of the year columns for when plicht == 'ja',
> s <- subset(eu, plicht == "ja")
> w2 <- weights[as.numeric(rownames(s))]
> newDF <- do.call(rbind, lapply(2:13, function(i){
      data.frame(wtMean.ja = weighted.mean(s[,i], w = w2, na.rm = TRUE))
      }))
> rownames(newDF) <- names(s)[2:13]
> newDF
#      wtMean.ja
# 1979  86.56735
# 1981  81.48000
# 1984  83.56127
# 1987  68.52000
# 1989  72.30636
# 1994  69.86950
# 1995       NaN
# 1996       NaN
# 1999  69.28708
# 2004  63.17060
# 2007       NaN
# 2009  58.99465


text:
Q: java.lang.IllegalArgumentException: Cannot register after unregistered Filter class I am developing login service using spring boo. when developing it I got below error and the class
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jwt.logincservice.filter.JwtFilter
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private Jwtutil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(jwt, userDetails)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

WebSecurityConfigurerAdapter class
@EnableWebSecurity
public class SecurityConfigureAdapter extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUseserDeatailService;

    @Autowired
    private JwtFilter jwtRequestFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUseserDeatailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/authentication").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, JwtFilter.class).authorizeRequests();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

A: you are trying to add the jwtRequestFilter before the JwtFilter.class which is kind of telling spring security to put itself before itself.
can you try changing this line to:
http.addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class).authorizeRequests();

additionally, every Filter bean in spring boot is automatically added also to your default servlet filter chain, so after initialization, it will be present twice:

*

*as a Servlet Filter in your chain

*as a Filter in your springSecurityFilterChain

if you just want to use it as a spring security filter remove the @Component annotation and instantiate it by yourself before adding it to the springSecurityFilterChain:
http.addFilterBefore(new JwtFilter(),UsernamePasswordAuthenticationFilter.class).authorizeRequests();

A: If you are using java config for bean configuration you have to register your filter bean in WebInitializer class.
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //your configs

    @Override
    protected Filter[] getServletFilters() {
        DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
        filterProxy.setTargetBeanName("jwtFilter");
        return new Filter[]{filterProxy};
    }
}

A: The list of filters to put in the *class part can be retrieved by increasing the debug level on spring security. Any filters there will work.


text:
Q: how to start an app within container automatically using docker-compose.yml I often have to recreate my container using "docker-compose up" command. The problem I have is every time after I recreate the container, I have to go to terminal within the container to run command like "sudo service xx start" to start the app. Is there provision for me to include that sudo command within my docker-compose file? so that I can avoid this extra step.
I tried adding following line within docker-compose but does not work "command: sudo service.."
Any help is appreciated. Thank you.

A: Docker needs a process to keep running otherwise the container will exit. Therefore a sudo service xx start which starts the process in background won't work.
One possible solution is to append another command such as tail or bash:
command: service xx start && tail -f /dev/null

Edited to add a concrete example with cron.
The Dockerfile:
FROM ubuntu:latest

RUN apt-get update && apt-get -y install cron

# Create the log file to run run tail
RUN touch /var/log/cron.log

# set the CMD and ENTRYPOINT in docker-compose

Build the image
docker build -t my-test .

Add entrypoint and command in docker-compose.yml:
version: "3.4"
services:
 service:
   image: my-test
   entrypoint: /bin/bash
   command: -c "service cron start && tail -f /var/log/cron.log"

By adding the tail command the container does not exit.


text:
Q: NFS showing files in directory, but can't open or stat I'm using a network of Linux (Debian Squeeze on kernel 2.6.32) machines, sharing files using NFS (v3). The scenario is that a process running on client A will create a file through NFS on file server Z. Then after the process is finished running on A (flushing its output and closing the file), client B will try to access the file. 99.9% of the time there's no problem with this approach.
The problem is that the very rarely client B when attempting to read will throw an error saying that the file does not exist. The wrinkle is that B always shows the file when an "ls" or readdir is made on the containing directory. However when trying to open, or even calling "stat" on the file the does not exist error is thrown.
Some additional points:

*

*The files are only written once on a single client, but can be read many times by many different clients (WORM). The files are also never deleted in the process.

*When the errors show up, they only appear to affect some of the clients (randomly). Other clients can open and read the files without a problem. Furthermore when the problem occurs it tends to occur repeatedly. Rebooting the file server and re-mounting on the clients seems to eliminate the problem

*The file is able to be read after enough time. It could be anywhere from a few seconds to ten minutes. Sometimes it will go away immediately after a readdir on the containing directory, sometimes it will not.

*I initially suspected it was an NFS attribute cache coherence issue. So I remounted with noac option enabled. The problem continued to pop up (in addition to be grindingly slow).

*The problem only appears during heavy NFS traffic when a lot of large files are being created, written and read.

*Nothing indicating a problem appears in any of the syslogs or dmesg on either the client or server side.

I strongly suspect this is an NFS cache coherence issue of some type. But I can't figure out what the exact cause or possible solution might be. Unless I'm misunderstanding the NFS manual, this type of behavior should be precluded by close-to-open cache coherence. Has anyone else had experience with this problem of NFS files that exist to the "readdir" system call, but don't exist to the "stat" system call? Any insight would be greatly appreciated. Thanks.


text:
Q: Is there a way to export Team Projects and their Work Items from a VSTS (Azure DevOps) instance to an On-premise TFS 2018 Server instance? I need your help to find out if is there a way to export Team Projects and their Work Items from a VSTS (Azure DevOps) instance to an On-premise TFS 2018 Server instance?
Thanks in advance!

A: No. There is no way to just take a team project from VSTS/Azure DevOps and bring it back on-prem.
There are various tools that allow for synchronization of some aspects by taking advantage of APIs, but there is always some degree of loss of information involved.


text:
Q: How large should matrices be if I use BLAS/cuBLAS for it to perform better than plain C/CUDA? I am currently implementing Stochastic Gradient Descent on a GPU using CUDA, Thrust and cuBLAS.
In my initial implementation I used plain CUDA to perform matrix-vector operations, and now I'm trying to optimize this by using cuBLAS for such operations instead.
What I'm observing currently is that for matrices of size rows x cols, for small number of cols, plain CUDA consistently outperforms cuBLAS, apparently regardless of the number of rows.
For large number of cols however, the cuBLAS implementation wins out.
So I was wondering: Are there any rules of thumb/guidelines about what should be the minimal dimensions of matrices/vectors after which using BLAS or cuBLAS will be better performing than plain C/CUDA, or is this completely dependent on the application/BLAS function?

A: I have run a few benchmarks which I will post here:
The results are for linear regression task running for 10 iterations of SGD, on datasets with 10000 rows. The implementation and more results are available here: https://github.com/thvasilo/cuda-sgd-sese-project
Runtimes for 10-100 features/columns:

So for my implementation the change-point at which plain CUDA becomes slower  is at 50 columns. There is a jump in runtime for 100 features for cuBLAS, but that could be an artifact, these experiments were only run once and the differences are not that large anyway.
When running with more columns BLAS Lvl. 2 consistently performs better:


text:
Q: How to add two timestamps in SQL Server I suppose to add two timestamps like '03:59:39','03:43:04' in SQL Server and i require the result like sum of the two timestamps is 7 hours 42 minute 43seconds.
Without any casting... can any one suggest on this?

A: TRY this

    DECLARE @TIME1 TIME(0)
        ,@TIME2 TIME(0);

    SELECT @TIME1 = CONVERT(TIME(0), '2013-07-20 03:59:39')
        ,@TIME2 = CONVERT(TIME(0), '2013-07-25 03:43:04');

    SELECT @TIME1 AS [@REQUESTEDTIME]
        ,@TIME2 AS [@TIMEINTERVEL];

    SELECT DATEADD(SECOND, DATEDIFF(SECOND, '00:00:00', @TIME1), @TIME2) AS FINALRESULT;

Try this one also

DECLARE @TimeVal TIME
    ,@TotalTime TIME;

SET @TimeVal = '03:59:39';
SET @TotalTime = '03:43:04'

SELECT @TimeVal
    ,@TotalTime
    ,dateadd(hour, DATEPART(HOUR, @TotalTime), dateadd(minute, DATEPART(MINUTE, @TotalTime), dateadd(ss, DATEPART(SECOND, @TotalTime), @TimeVal)))


text:
Q: How can I prove that $X$ and $Y$ have the same distribution? Let $\Omega=[0,\infty)$, $A=B([0,\infty))$ and $P$ be a probability measure on $A$ which has a density. Define two stochastic processes $(X(t):t\ge 0)$ and $(Y(t):t\ge 0)$ by
\begin{align}
X(t)(\omega)&=\begin{cases}1 & \text{if }t=\omega \\ 0 & \text{otherwise}\end{cases}\\
Y(t)(ω)&=0
\end{align}
How can I prove that $X$ and $Y$ have the same distribution?


text:
Q: mcrypt_module_open() is deprecated error on laravel 5.4 + consolibyte quickbooks Good Day,
I tried integrating Quickbooks into laravel 5.4, I saw this tutorial in the net "http://lamparchitect.blogspot.com/2016/03/how-to-implement-quickbooks-online-api.html" I have successfully installed it on my localhost, also added the plugin successfull.
Now When I tried to use the connect button which accesses to oauth url.. I get to be redirected to QB page where it asks you to authorize the app or not.. when I clicked authorized button.. I got error from my laravel app
(1/1) ErrorException
Function mcrypt_module_open() is deprecated
in Aes.php (line 34)
at HandleExceptions->handleError(8192, 'Function mcrypt_module_open() is deprecated', 'D:\\xampp\\htdocs\\quickbooks_appx\\vendor\\consolibyte\\quickbooks\\QuickBooks\\Encryption\\Aes.php', 34, array('key' => 'bcde1234', 'plain' => 'a:2:{i:0;s:48:"qyprdJZmHoC2RX8aG8EaUGKyJ6awxzVpDO7Nr2IKsqmUcZ0o";i:1;s:32:"b4e2SK3n6GduTsMl9pDhX0w1IWJHki5P";}', 'salt' => 'b4e2SK3n6GduTsMl9pDhX0w1IWJHki5P'))
in Aes.php (line 34)
at QuickBooks_Encryption_AES::encrypt('bcde1234', 'a:2:{i:0;s:48:"qyprdJZmHoC2RX8aG8EaUGKyJ6awxzVpDO7Nr2IKsqmUcZ0o";i:1;s:32:"b4e2SK3n6GduTsMl9pDhX0w1IWJHki5P";}')
in Driver.php (line 1401)
at QuickBooks_Driver->oauthAccessWrite('bcde1234', 'qyprd24BSQ8j0dG36yW7bNCzUrlwFPLpFdn2OFzItLALcFRL', 'qyprdJZmHoC2RX8aG8EaUGKyJ6awxzVpDO7Nr2IKsqmUcZ0o', 'QV7iDw7oaXpFWtxGLMe3kX7Ab1irgYxGaWX52nud', '193514559060839', 'QBO')
in IntuitAnywhere.php (line 417)
at QuickBooks_IPP_IntuitAnywhere->handle('DO_NOT_CHANGE_ME', '12345')
in QuickBookController.php (line 53)


text:
Q: Dolby Sound not playable in Chrome due to license So my problem is that I came across the license issue with Dolby Atmos on Google Chrome.
I want to create a website where people can listen to the difference between a dolby encoded sound and a normal one. But since some browsers don't support Dolby I wonder if there is some workaround to ensure anyone can use the website?


text:
Q: Display dates in an order irrespective of which culture preference it is in DateTimeFormatInfo us = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo cc = new CultureInfo(culturepreference, false).DateTimeFormat;
foreach (DataRow row in culturetable.Rows)
{
    DateTime dt = DateTime.Parse(row["date"].ToString());
    row["date"] = dt.ToString(cc.ShortDatePattern);
}

I used above code to display dates as per culture preference.
    **OUTPUT :
dates are out of order...
When Australia  en-AU culture preference is selected
1/09/2015
10/09/2015
11/09/2015
19/09/2015
2/09/2015
20/09/2015
24/08/2015
3/09/2015
30/08/2015
31/08/2015
4/09/2015
5/09/2015

When USA en-US is selected as culture preference we get below dates...
8/24/2015
8/30/2015
8/31/2015
9/1/2015
9/10/2015
9/11/2015
9/19/2015
9/2/2015
9/20/2015
9/3/2015
9/4/2015
9/5/2015

***The dates displayed are not in sorted manner. I will need to display dates in an order irrespective of which culture preference it is in.

A: You can use the Sort property of the default view of your table. Make sure you use the DefaultView to access DataRowView instead of using the tables rows. Something like:
culturetable.DefaultView.Sort = "date ASC";

Console.WriteLine("==== en-AU ====");
DateTimeFormatInfo au = new CultureInfo("en-AU", false).DateTimeFormat;
foreach(DataRowView row in culturetable.DefaultView){
    Console.WriteLine(((DateTime)row[0]).ToString(au.ShortDatePattern));
}
Console.WriteLine("==== en-US ====");
DateTimeFormatInfo us = new CultureInfo("en-US", false).DateTimeFormat;
foreach(DataRowView row in culturetable.DefaultView){
    Console.WriteLine(((DateTime)row[0]).ToString(us.ShortDatePattern));
}

Here is a fiddle

A: You are sorting the column as a string type after the column value has been converted from datetime type to string type. That is why you are seeing this issue. If you are not going to sort on a datetime type column, then add a hidden column and specify a custom "YYYYMMDD" string conversion for your datetime conversion to a string. Then sort on the hidden string column, and your data will always be correct regardless of your local culture display for the datatime value.


text:
Q: Android JQuery focus() workaround I'm working on an HTML5 mobile app (using regular jQuery, not mobile), which implements a custom autocomplete list that appears below a textarea. The user selects an option from the list, the word is autocompleted, and the user continues typing as usual.
The problem is that the user taps outside of the textbox to select an item from the autocomplete, so the textarea momentarily loses focus. Since focus() is deactivated in the android browser, I can't immediately re-focus and retain the caret's last position as I usually would.
Is there a workaround that would allow me to re-focus on a textarea, preserving caret position as regular blur() and focus() calls would?
Edit:
Sources of underlying assumption: mentioned here: https://stackoverflow.com/a/10243010/832607 and here:
http://ambrusmartin.wordpress.com/2012/08/30/soft-keyboards-in-android-iphone-phonegap-applications-when-we-call-focus/ (Already tried solution mentioned in link)

A: Instead re-focusing the textarea I'd recommend trying to not lose the focus in the first place. I'm achieving this when preventing the default action on mousedown.
Here is the jQuery, assuming list is your list of options and all options have listEl class:
list.on('mousedown', '.listEl', function(e) {
  e.preventDefault();
});


text:
Q: How to bind refreshing Aptana's internal web browser to a keystroke? Looking through Preferences --> Keys, I don't see any option for refreshing the internal web browser that I can bind a keystroke to. While there is a "Refresh" option bound to F5, it's for the file view, not the browser. As I'm working with Sinatra (and "Reloader"), once the Webrick server is started "Run" really just involves refreshing the browser view, so I would like to be able to do so without having to mouse over to the browser window.
As I'm new to Aptana (I've used Eclipse way back when, but in a different life), perhaps I'm looking in the wrong places but all my searches have been for naught at this point.

A: There should be a shortcut, for php developers it would be a miracle like F9 in a compiled language ide enviroment.


text:
Q: Support of likelihood ratio test statistic Say I'm testing $H_0: Y \sim \text{Exp}(1)$ against $H_1: Y \sim \text{U}(0, 1)$. I believe this gives me the following likelihood ratio test:
$$
t^*(y) = \frac{p_1(y)}{p_0(y)}
 = \frac{1}{e ^ {-y}}
 = e ^ {y}
$$
The problem is defining the support for this statistic. Since $p_0(y)$ is defined $\forall y > 0$ and $p_1(y)$ $\forall y \in (0, 1)$, I don't know what to make of the support of the function $t^*(y)$, could I simply make it the intersection between $y > 0$ and $0 < y < 1$ (i.e., $0 < y < 1$)?

A: This statistic weighs evidence for the two hypotheses by comparing their probability densities at the observed value of $y$.  Because the denominator could be zero in this situation, we have to consider two possibilities:

*

*The denominator is positive.  This means that $H_0$ assigns a positive chance to any tiny neighborhood of $y$.  It occurs when $0 \lt y$.  There is no problem with a division by zero.  In terms of the indicator function $\mathcal{I}$, a formula for the likelihood ratio is $$\frac{\mathcal{I}_{(0,1)}(y)}{e^{-y}}.$$  This equals $e^y$ for $0 \lt y \lt 1$ and otherwise is zero.

*The denominator is zero.  This means $H_0$ assigns no probability density to $y$.  There are two possibilities:

*

*$H_1$ assigns no probability density to $y$, either.  Thus, this $y$ has no chance of being observed under either hypothesis.  We needn't consider this any further.  The set of $y$ for which this is the case is the intersection of the complements of the supports of the hypotheses: the non-positive real numbers.

*$H_1$ assigns some probability density to $y$.  Thus, this $y$ is possible under $H_1$ but not under $H_0$.  The conclusion is obvious.  As a convention we may use values in an extended Real number line $\{-\infty, \infty\}\cup \mathbb{R}$ to designate such likelihood ratios (or their logarithms); here we would say that the likelihood ratio (and its log) is $\infty$.
To summarize, let $S_i\subset\mathbb{R}$ be the supports of the hypotheses.  Then the likelihood ratio must be considered a function whose domain is the union of supports $S_0\cup S_1$ which takes values in the extended positive reals $[0,\infty)\cup\{\infty\}$.  The log likelihood ratio takes values in the extended reals $\mathbb{R}\cup\{-\infty,\infty\}$, with $\log(0)$ defined to be $-\infty$.
When $S_0=S_1$, the zero-denominator case has no chance of happening, regardless of the hypothesis, and we may dispense with using the extended reals if we wish.  This is a frequent assumption in likelihood ratio settings.

A: Actually both densities are defined over the whole line, they're just 0 elsewhere than the places you mention.
You have to think carefully about the density across at least the +ve half-line -- your ansẃer defines what you get when $0<y<1$, but what's the LR when y=4.3?
That could happen, if the distribution really were exponential, so you have to consider it.


text:
Q: Is there an efficient/low-complexity extension of Gauss-Hermite quadratures to N dimensions where N is not too large? I should say that this question comes from an engineer who is not very familiar with the various techniques tackling numerical integration. I read some of the corresponding articles on wikipedia, but they do not provide sufficient details in order to answer my question.
Currently, I am using Gauss-Hermite quadratures to approximate a one-dimensional integral of the form
$$
 \int_{-\infty}^{\infty} \exp(-y^2) f(y) \, dy \approx \sum_{i=1}^L w_i f(\xi_i)
$$
This turns out to be extremely accurate and efficient for the function $f(y)$ that I have, for example considering $L= 10$ values of the quadrature sum is absolutely fine, in the sense that increasing $L$ does not change much. The efficiency is rather important because I am using the result of this integral within an optimization routine. However, now I want to extend my problem to a more general case and then the above integral becomes four-dimensional. If I understood correctly, the straightforward extension of the Gauss-Hermite quadrature rule would then lead to an expression with four summations and thus I need to consider $10^4$ function evaluations of $f()$ to get the same precision. This, unfortunately, would render the numerical integration too complex for my optimization routine. Is there any way around this? Is there a more efficient extension of the Gauss-Hermite quadrature rule to such "moderate" dimensional problems? I already tried to apply a Monte-Carlo integration, which, however, turned out to be very unreliable for similar complexity as the one-dimensional case. Any help is appreciated.


text:
Q: MongoDB - Only displaying data for selected information I have a collection of data I wish to display, however I only need the specific records that have the type of data I want. I also want to display the remaining field details that only has that data. How do I approach this? This is what I currently have
db.test.find({}, {Field: "info", _id: false})
so far I can display the complete database however there are some blank fields that I do not require which is why I'm wondering what kind of alternative I should approach to display the remaining field data instead of using {} to display everything
Thanks

A: You can approach it something like this:
Lets say you want to search all the documents which has Field : "info" in it, and you only want field1, field2, and field3 to come in the result docs, then you can query it something like this:
db.test.find({field : "info"},{ field1:1,field2:1,field3:1,_id:0})

Here, First parameter of find query : { field:"info"} , is used to match the required/selected documents. and 2nd parameter : { field1:1,field2:1,field3:1,_id:0} is used to include only those fields in the result.
Add all those fields you want in the second parameter like below:
field4:1,
field5:1,
...

I hope this helps you.


text:
Q: Handle null server response cases I'm calling an endpoint to GET a list of objects from the server. Using Retrofit2.0 + RxJava for the api calls.
The server has made it in such a way that when there are no items in the list, instead of returning an empty list, it returns null with the response code 204...
If I use an Observable<List<Item>> when the list is empty it will hit onError because of the null body
If I use Completableor Observable<Void> I won't be able to handle any data returned....
I thought about handling this by verifying the error message and assuming that if is an null exception to continue with the normal flow but I'm not fully comfortable with this hack....
Is there a way to handle this situation?

A: *

*204 : No content means that the query successfully processed but no information to return.

You can use this in OnError method to have more visibilty :
@Override
public void onError(Throwable e) {
    try {

          Log.e("errorL", ((HttpException) e).response().errorBody().string());

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

Good luck !


text:
Q: Swing positioning issue I am writing a small game, using Swing for GUI and I ran into a problem. I'm posting a screenshot, so that you can get a better grasp of the situation.

At first I only had the board for which I used a GridLayout.
However, I needed to add a panel for displaying the scores, so I dropped the GridLayout in favour of GridBagLayout. I positioned properly the new JPanel for the scores and added 2 JTextArea in it for displaying the results.
The thing is that each time one of the players will make a move(and hence the board gets redrawn to reflect its new state) the text areas will flicker and be partially covered by the board(see screenshot). Any idea what the issue might be? I have set the preferred size of all the components and tried using setOpaque but it was to no avail.
The code of the main layout holder.
public class BoardLayout extends JFrame implements ModelObserver {

    /**
     * {@value}
     */
    private static final long serialVersionUID = 5834762299789973250L;

    /**
     * {@value}
     */
    private static final int RESULTS_PANEL_HEIGHT = 100;

    private final BoardEventsListener eventsListener;

    private final ResultsLayout resultsLayout;

    private class CellMouseListener implements MouseListener {

        private final int cellIndex;

        public CellMouseListener(final int index) {
            cellIndex = index;
        }

        @Override
        public void mouseClicked(final MouseEvent event) {
            eventsListener.onCellSelected(cellIndex);
        }

        @Override
        public void mouseEntered(final MouseEvent event) {
            // blank
        }

        @Override
        public void mouseExited(final MouseEvent event) {
            // blank
        }

        @Override
        public void mousePressed(final MouseEvent event) {
            // blank
        }

        @Override
        public void mouseReleased(final MouseEvent event) {
            // blank
        }

    }

    public BoardLayout(final BoardEventsListener listener) throws HeadlessException {
        this(listener, "", null);
    }

    public BoardLayout(GraphicsConfiguration graphicsConfiguration) {
        this(null, "", graphicsConfiguration);
    }

    public BoardLayout(final BoardEventsListener listener, String title,
            GraphicsConfiguration graphicsConfiguration) {
        super(title, graphicsConfiguration);

        eventsListener = listener;

        setLayout(new GridBagLayout());
        setBoardSize();
        populateCells();
        resultsLayout = attachResultsLayout();

        resultsLayout.setOpaque(true);

        setVisible(true);
    }

    private ResultsLayout attachResultsLayout() {
        final ResultsLayout resultsLayout = new ResultsLayout(Game.BOARD_COLUMN_COUNT
                * BoardCellLayout.WIDTH_BOARD_CELL, RESULTS_PANEL_HEIGHT);
        final GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.gridheight = GridBagConstraints.REMAINDER;
        constraints.gridx = 0;
        constraints.gridy = 8;
        getContentPane().add(resultsLayout, constraints, 64);
        return resultsLayout;
    }

    private void setBoardSize() {
        final Dimension boardDimension = getBoardDimension();
        setMinimumSize(boardDimension);
        setSize(boardDimension);
        setResizable(false);
    }

    private void populateCells() {
        final Container container = getContentPane();
        for (int i = 0; i < Game.BOARD_ROW_COUNT; ++i) {
            for (int j = 0; j < Game.BOARD_COLUMN_COUNT; ++j) {
                final BoardCellLayout currentCell = new BoardCellLayout();
                final int cellIndex = i * Game.BOARD_COLUMN_COUNT + j;
                final GridBagConstraints constraints = new GridBagConstraints();
                constraints.gridx = j;
                constraints.gridy = i;
                container.add(currentCell, constraints, cellIndex);
                currentCell.setOpaque(true);
                currentCell.addMouseListener(new CellMouseListener(cellIndex));
            }
        }
    }

    private Dimension getBoardDimension() {
        final Dimension boardDimension = new Dimension(Game.BOARD_COLUMN_COUNT
                * BoardCellLayout.WIDTH_BOARD_CELL, (Game.BOARD_ROW_COUNT + 1)
                * BoardCellLayout.HEIGHT_BOARD_CELL);
        return boardDimension;
    }

    public BoardLayout(String title) throws HeadlessException {
        this(null, title, null);
    }

    @Override
    public void setVisible(final boolean isVisible) {
        super.setVisible(isVisible);
        setBackground(Color.WHITE);
        pack();
    }

    @Override
    public void onModelChanged(Collection<Cell> changedCells, final int whiteDiscsCount,
            final int blackDiscsCount) {
        for (final Cell cell : changedCells) {
            final BoardCellLayout boardCell = getCellAt(cell.getIndex());
            boardCell.take(cell.getOwner());
        }
        resultsLayout.onResultChanged(whiteDiscsCount, blackDiscsCount);

    }

    @Override
    public void onNextMovesAcquired(Collection<Cell> nextMoves) {
        clearCellHighlight();
        for (final Cell cell : nextMoves) {
            final BoardCellLayout boardCell = getCellAt(cell.getIndex());
            boardCell.highlight();
        }
    }

    private void clearCellHighlight() {
        final Container container = getContentPane();
        for (int i = 0; i < container.getComponentCount() - 1; ++i) {
            final BoardCellLayout boardCellLayout = (BoardCellLayout) container.getComponent(i);
            boardCellLayout.clearHighlight();
        }
    }

    private BoardCellLayout getCellAt(final int index) {
        final Container container = getContentPane();
        return (BoardCellLayout) container.getComponent(index);
    }
}

Code of the panel, holding the results:
public class ResultsLayout extends JPanel {

    /**
     * {@value}
     */
    private static final long serialVersionUID = 8379710427718395507L;

    private final ResultsTextView whiteTextView;

    private final ResultsTextView blackTextView;

    public ResultsLayout(final int width, final int height) {
        super(new GridLayout(2, 1));

        setVisible(true);

        final Dimension dimension = new Dimension(width, height);
        setMinimumSize(dimension);
        setPreferredSize(dimension);
        setSize(dimension);

        whiteTextView = new ResultsTextView(Player.WHITE);
        blackTextView = new ResultsTextView(Player.BLACK);

        add(whiteTextView, 0);
        add(blackTextView, 1);
    }

    public void onResultChanged(final int whiteDiscsCount, final int blackDiscsCount) {
        whiteTextView.setDiscCount(whiteDiscsCount);
        blackTextView.setDiscCount(blackDiscsCount);
    }

}

Code of the JTextArea, holding the result:
public class ResultsTextView extends JTextArea {

    /**
     * {@value}
     */
    private static final long serialVersionUID = -6354085779793155063L;

    /**
     * {@value}
     */
    public static final String BACKGROUND_COLOR = "#066f02";

    private static final int START_DISCS_NUMBER = 2;

    private final Player player;

    public ResultsTextView(final Player player) {
        super();
        setEditable(false);

        setBackground(Color.decode(BACKGROUND_COLOR));

        this.player = player;
        setText(player.toString() + " result is: " + START_DISCS_NUMBER);

        final Dimension dimension = new Dimension(100, 20);
        setPreferredSize(dimension);
        setMinimumSize(dimension);
        setMaximumSize(dimension);
    }

    public void setDiscCount(final int discCount) {
        setText(player.toString() + " result is:" + discCount);
    }

}

A: Adding a score panel makes me think of an MVC pattern in which both the game board and the score are views that listen to the same game model. An example cited there is also a grid based game that might offer some insight on design and layout. In particular, the RCStatus view, in BorderLayout.NORTH, and the RCInfo view, in BorderLayout.SOUTH, each listen to the RCModel. The game panel occupies BorderLayout.CENTER.
A few notes on the fragments you provided:

*

*Let your main view extend JPanel and add it to a JFrame instance.

*Don't try to solve every problem with a single layout.

*Consider extends MouseAdapter over implements MouseListener.

*Reconsider setXxxSize().

A: Problem was that I was not using SwingUtilities.invokeLater for updating the GUI and that was causing the flickering. I started using it and it's all fine now :)


text:
Q: PHP sort multi array  <?php
   foreach ($model->deadlineFwds(array(
        'order' => 'fl_due_date, returned_date')
      ) as $index => $deadline):
 ?>

Above is the code for my script, im sure somehow it is working, as if i delete it, the order for the display is changed.
So, the problem is when i use this code, it is sorted according to fl_due_date, however the sorting doesn't make the inputs with earliest fl_due_date on the top of the list, yet is is sorted by fl_due_date at the bottom of the list.
I want it to be sorted on the top of the list.


text:
Q: Struct inside a union I came across the following c code.
union packet_t {
    uint8_t raw[10];
    struct {
        union {
            uint16_t number;
            uint8_t number_byte[2];
        };
        union {
            uint32_t size;
            uint16_t size_word[2];
            uint8_t size_byte[4];
        };
        uint8_t body[4];
    };
} packet;

When I try to test it, I came across some weird behavior, I hope someone can help me figure out what's wrong with this definition. I did some search, but there were no similar problems.
Here is what I tried:
uint8_t test1[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
int i = 0;
for(i = 0; i < sizeof(test1); i++)
{
    packet.raw[i] = test1[i];
}

printf("packet.size_word[0]=0x%04x\n", packet.size_word[0]);
printf("packet.size_word[1]=0x%04x\n", packet.size_word[1]);

Output is
packet.size_word[0]=0x0605
packet.size_word[1]=0x0807

It completely missed 0x03 and 0x04.
When I use the following definition (remove "uint32_t size;"), it works fine.
union packet_t {
    uint8_t raw[10];
    struct {
        union {
            uint16_t number;
            uint8_t number_byte[2];
        };
        union {
            uint16_t size_word[2];
            uint8_t size_byte[4];
        };
        uint8_t body[4];
    };
} packet;

Here is the output:
packet.size_word[0]=0x0403
packet.size_word[1]=0x0605

Does anyone know why this is happening? I thought items in union always occupied same memory location.
Here is the link for the code.
The original Code is here.
--------------------------Update 11/25/2018---------------------------------
So I'm confident now it's the structure padding and it depends on the CPU architecture.
I tested on Arduino with Atmega328p (an 8-bit MCU), it works like a charm. There was no struct padding since the MCU process 1 byte each time.
However, the code is not portable at all as @selbie mentioned, when writing such code, we have to consider CPU architecture and environment. Simplest solution is not using it.
Further reading:
C – Structure Padding
Structure padding and packing


text:
Q: How to Highcharts max height based on width of bars in chart Looking at the best way to set a chart height property using highcharts bar chart.
Currently I have set chart height to be equal to the number of X axis categories, but not less than 400 using:
this.resultsChartOptions.chart.height = ((categories.length * 50) > 400 ? categories.length * 50 : 400);

This however means there are overlaps between bars especially on larger charts (as the legend and other chart stuff takes up room I have not accounted for).
I have set a default pointWidth to 50 and that is the widest bar - ideally every category would just be 50 wide and the chart would auto expand.
Anyone any ideas on how to do this?

A: In load event you can calculate and set the required height taking into account all elements of the chart:
chart: {
    type: 'bar',
    height: 400,
    events: {
        load: function() {
            var categories = this.xAxis[0].tickPositions,
                plotHeight = categories.length * 50,
                chartHeight = plotHeight + (this.chartHeight - this.plotHeight);

            if (chartHeight > this.chartHeight) {
                this.setSize(null, chartHeight, false)
            }
        }
    }
}

Live demo: http://jsfiddle.net/BlackLabel/hkuLfogj/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#setSize


text:
Q: How to let PHP set the evercookie securely
How to let PHP set the evercookie wihtout from within another page .
in another words , i have a page that checks the ever cookie , but i don't want the page to give the cookie value to the user (i don't want the user to see the evercookie value in the page source) , this might be done using some other page that is called by evercookie if there's no cookie value . how can i do it ?

A: What you should do is use a value that's unique to a database entry that actually means something, but is nothing more than a randomly generated string to the user. So that when you wanna know what it means, you just check your database for the unique entry and then get the information. Then it doesn't matter what the user sees.
For example, on my sites if a user wishes to remain logged in I set their cookie as a random string (such as 2947927e9suipohdoy20 [it's usually much longer though, like a random number hashed by SHA-512]) and then in their account I have a RememberMe field that stores unique values, I search my database for the string and bam! I have their account!

A: There is no way of sending data to the browser such that a user could not retrieve it if they wanted, since that information has to be sent back as part of a HTTP response. HTTP is plain text, and anyone even remotely interested in what you're sending can easily obtain the full response.
Just because (your average) browser doesn't necessarily display some things, doesn't mean you can't get to them. Anything else would make it impossible.

A: studied the class , edited it .
now the class checs if cookie has no value , it creates an image object , and fetches it from server , the server creates a string [value][one-way-encrypted-value] and encodes it in a PNG image , the class opens the png image and decodes the image back to a strig and sets the value .
i hope this would be a pain for any bot to make it .


text:
Q: Parsing xml with "not well-formed" characters in python I am getting xml data from an application, which I want to parse in python:
#!/usr/bin/python

import xml.etree.ElementTree as ET
import re

xml_file = 'tickets_prod.xml'
xml_file_handle = open(xml_file,'r')
xml_as_string = xml_file_handle.read()
xml_file_handle.close()

xml_cleaned = re.sub(u'[^\x01-\x7f]+',u'',xml_as_string)
root = ET.fromstring(xml_cleaned)

It works for smaller datasets with example data, but when I go to real live data, I get
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 364658, column 72

Looking at the xml file, I see this line 364658:
WARNING - (1 warnings in check_logfiles.protocol-2013-05-28-12-53-46) - ^[[0:36mnotice: Scope(Class[Hwsw]): Not required on ^[[0m</description>

I guess it is the ^[ which makes python choke - it is also highlighted blue in vim. Now I was hoping that I could clean the data with my regex substitution, but that did not work.
The best thing would be fixing the application which generated the xml, but that is out of scope. So I need to deal with the data as it is. How can I work around this? I could live with just throwing away "illegal" characters.

A: You already do:
xml_cleaned = re.sub(u'[^\x01-\x7f]+',u'',xml_as_string)

but the character ^[ is probably Python's \x1b.  If xml.parser.expat chokes on it, you need simply to clean up more, by only accepting some characters below 0x20 (space).  For example:
xml_cleaned = re.sub(u'[^\n\r\t\x20-\x7f]+',u'',xml_as_string)

A: I know this is pretty old, but stumbled upon the following url that has a list of all of the primary characters and their encodings.
https://medium.com/interview-buddy/handling-ascii-character-in-python-58993859c38e


text:
Q: removeEventListener not removing the listener I have a event listener on my element which does not remove for some reason I don't know why.
I set it like this:
for (i = 0; i < data[0].length; i++) {
  (function(i){
    document.getElementById(i).addEventListener('click',
        function(){var self = this; begin(i,self,1);},false);})(i);
}

And the removal of the listener:
function begin(i,el,type){
    console.log('test');
    el.removeEventListener('click',function(){begin(i,el,type);},false);
}

But some reason the event listener is still assigned.... what am I not getting right here?

A: You will need to retain reference to the event listener so that you can remove it. You can store it on the DOM element if you like.
for (var i = 0; i < data[0].length; i++) {
    (function(i){
        var el = document.getElementById(i);
        el['click-listener'] = function () {
            var self = this;
            begin(i, self, 1);
        };
        el.addEventListener('click', el['click-listener'],false);
    })(i);
}

function begin(i, el, type) {
    el.removeEventListener('click', el['click-listener'], false);
}


text:
Q: Limit Clause While Fetching Child Records in Doctrine I have two tables Entity and Message. as each entity can have many messages so it's like parent child relation. I dont want to use doctrine custom query so I am loading entity message like
$this->currentUser  = Doctrine_Core::getTable('Entity')->find($entityID);
and then "$currentUser->getMessage()" gives me all messages of that person.
So is there any way to get only few message? let's say 3 message only? How can I use LIMIT claue in this case?
Thanks
Ali


text:
Q: Yii postback value for dropdownlist Like described in the title, i' trying to use a dropdownlist for post back page.
The post is receive in the controller but the value selected is empty.
Here is my dropdownlist
<?php echo CHtml::dropDownList('groupe',$groupe,
array("A"=>"A","B"=>"B","C"=>"C","D"=>"D","E"=>"E","F"=>"F","G"=>"G","H"=>"H"),
array(
'prompt'=>'--Choisir un groupe--',
'submit'=>CController::createUrl('classement'),
//'data'=>array('groupe'=>'js:this.value'),
));  ?>

And here is my controller
public function actionClassement($groupe="")
    {echo $groupe;
            if(isset($_POST['groupe'])){echo $_POST['groupe']."ici=".$groupe;
                $groupe = $_POST['groupe'];
            }echo 'test';
            $model = Team::model()->getClassementByGroupe($groupe);
            $games = array();
            $games = Game::model()->getGameByGroupe($groupe);
            //echo '
test';echo print_r($model);echo '
';
            $this->render('classement',array(
                    'model'=>$model,
                    'groupe'=>$groupe,
                    'games'=>$games,
            ));
    }

Thanks for your help because i don't find my mistake :-s

A: You need to wrap your dropdown in a form. This worked. Also note $groupe gets assigned if there is a $_GET variable. Your combo is posting, so you need to use $_POST['groupe']
<form method="post" action="<?= $this->createUrl('') ?>">
  <?php
  echo CHtml::dropDownList('groupe', $groupe, array(
      "A" => "A",
      "B" => "B",
      "C" => "C",
      "D" => "D",
      "E" => "E",
      "F" => "F",
      "G" => "G",
      "H" => "H"
          ), array(
      'prompt' => '--Choisir un groupe--',
      'submit' => CController::createUrl('classement'),
          //'data'=>array('groupe'=>'js:this.value'),
  ));
  ?>

</form>

I removed the models for testing the controller.
public function actionClassement($groupe = "") {
  echo $groupe;
  if (isset($_POST['groupe'])) {
    echo $_POST['groupe'] . "ici=" . $groupe;
    $groupe = $_POST['groupe'];
  }echo 'test';
//   $model = Team::model()->getClassementByGroupe($groupe);
//   $games = array();
//   $games = Game::model()->getGameByGroupe($groupe);
  //echo '
test';echo print_r($model);echo '
';
  $this->render('view', array(
      'groupe' => $_POST['groupe'],
  ));
}


text:
Q: How to use external API SDK with Angular4/5 I want to use Moltin for a project but their SDK requires the use of async wait which isn't really used in Angular4/5 my question is how can I make use of the SDK without having to use global functions as this is considered bad practice.
async getCustomerOrders() {
  var customer = await Moltin.Customers.Token("ron@swanson.com", "mysecretpassword");
  await Moltin.Orders.All(customer.token);
}


text:
Q: How to auto format code file *.ctp in PDT Helios? I am using Eclipse for PHP (PDT) Helios, how to auto format CakePHP Template file? For example: when I follow this tutorial  , when I edit file index.ctp like this:

Blog posts

        Id
        Title
        Created

    <?php foreach ($posts as $post): ?>

        <?php echo $post['Post']['id']; ?>

            <?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>

        <?php echo $post['Post']['created']; ?>

    <?php endforeach; ?>
    <?php unset($post); ?>

I don't undestand how Eclipse autoformat above snippet code. Please help me, thank you!

A: In Aptana Studio (is based on Eclipse) try this:
Window / Preferences / General / Editors / File Associations

If You haven't .ctp file, You must add it, after add to this extension Assiociated files to PHP

A: I do this like my follow screenshot:


text:
Q: Does Java Apache Olingo query the database itself? In .NET C#, we used Odata to filter, page, sort the database results from SQL database. Odata in .NET would actually go into the database, and query WHERE, ORDER By Filters to database, instead of extracting all the database results, and applying filtering on the api memory.
I am curious of Java Apache Olingo, queries the database internally or applies filtering on the API memory set.
Resources:
https://www.odata.org/libraries/
https://www.odata.org/documentation/odata-version-2-0/uri-conventions/

A: Short answer, Olingo 2 JPAProcessor will query the database to only fetch limited data if $filter and $orderby are specified.
TLDR;
There are two things we need to consider here. Apache Olingo is a framework which allows people to implement OData Server and Client in Java, bare bones if will just provide you with the Abstract Classes and Interfaces which you implement OdataProcessors, how ever one wants.
Now coming to the second point there is a JPA Implementation also provided in the Olingo Project, which you can locate here
To answer your question, lets  dig into the code of this project to see, how its implemented
We will have to start with JPAProcessorImpl and hop into process(final GetEntitySetUriInfo uriParserResultView), this is where the query and the actuals of how the data is fetched in the database are implemented.
At line 150 the actual query is already built,so if you pass $filter(where clause) and $orderby, we can see the values are actually being passed to the database and are baked in query

A: Edit: As @Olivier mentions, my original answer referred to OData in .NET and not Olingo.
Unfortunately as you probably have found out yourself, the standard Olingo documentation doesn't answer this particular question directly, though it does mention support for lazy-loading and streaming behaviour (which would not make any sense to filter on the application level).
However, you would be hard-pressed to find an ORM or DB Adapter nowadays that does not support filtering on the database level, as this will almost always be faster than doing so in your application for non-trivial workloads.
I will try to update this answer with a more authorative source.

(original answer)
According to this analysis:

As long as your data provider supports deferred queries and you don't force evaluation by calling something like .ToList(), the query will not be evaluated until the OData filters are applied, and they'll be handled at the database level.