text:
Q: How to Open Multiple PopUp windows with JQuery on form submission (popUps should be relative to form submited data)? I have A HTML form like this:
    <form>
<fieldset class="ui-widget-content ui-corner-all">
<select id="Streams" class="multiselect ui-widget-content ui-corner-all" multiple="multiple" name="Streams[]">

<option value="35">  Example Name (35)</option>
<option value="44">  Example Name (44)</option>
<option value="5698">  Example Name (5698)</option>
<option value="777">  Example Name (777)</option>
<option value="12">  Example Name (12)</option>
    </select>

      <input type="submit" class="ui-state-default ui-corner-all" name="submitForm" id="submitForm"  value="Play Stream from selected URL's!"/>
  </fieldset>
</form>

in my JS + HTML page I use JQuery.
As you can see I allow user to select multiple Items.
I want to open on Submit button click as many popup windows as many Items he selected in a list. Each popUp window should open some url like www.example.com/test.php?id=OPTION_SELECTED .
And here I mean by PopUp Window a real browser window.
So for each of the selected options I ll get a pop up window whith diferent url.
Please Help.

A: it would be something like this...
$("form").submit(function() {
    int i = 0;
    $("#Streams option:selected").each(function() {
        window.open("www.example.com/test.php?id=" + $(this).val(),"window" + i.toString());
        i++;
    });
});


text:
Q: How create another partition automated using all free space? I have fresh installation linux from certified image,
and I would like to create automated script to create another partion using all free space.
In my current situation I have 60GB disk and 47GB free space,
But I would like to create universal script to create another partition (disk size can be different)
How to do it ?
To create new partition in non-interactive mode I need to know start-end sector, correct ?
is there any option with sfdisk/parted  to just create new partition ?
Workaround can be sfdisk -F  /dev/sda,to get start-end sectors,  but I have to parse somehow this.
# fdisk -l
Disk /dev/sda: 60 GiB, 64424509440 bytes, 125829120 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x32082de6

Device     Boot   Start      End  Sectors  Size Id Type
/dev/sda1  *       2048  1026047  1024000  500M 83 Linux
/dev/sda2       1026048 25602047 24576000 11.7G 8e Linux LVM

# sfdisk -F  /dev/sda
Unpartitioned space /dev/sda: 47.8 GiB, 51316260864 bytes, 100227072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes

   Start       End   Sectors  Size
25602048 125829119 100227072 47.8G

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intellij Tomcat fails to deploy artifact I ran my Web Apps on Tomcat, and they can run successfully. However, after my computer was configured with another company's domain, I can not deploy my app on Tomcat anymore. The server console (a hello world web app) is shown as follows:
10-Apr-2017 17:42:04.102 Info [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.13
10-Apr-2017 17:42:04.113 Info [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
10-Apr-2017 17:42:04.125 Info [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
10-Apr-2017 17:42:04.132 Info [main] org.apache.catalina.startup.Catalina.start Server startup in 80 ms
Connected to server
[2017-04-10 05:42:04,349] Artifact 2017.04.10-testHelloWorld:war exploded: Artifact is being deployed, please wait...
[2017-04-10 05:42:04,408] Artifact 2017.04.10-testHelloWorld:war exploded: Error during artifact deployment. See server log for details.
10-Apr-2017 17:42:14.123 Info [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor Deploying configuration descriptor C:\Users\z674149\.IntelliJIdea2016.1\system\tomcat\Unnamed_2017_04_10-testHelloWorld\conf\Catalina\localhost\ROOT.xml
10-Apr-2017 17:42:17.663 Info [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
10-Apr-2017 17:42:17.811 Info [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of configuration descriptor C:\Users\z674149\.IntelliJIdea2016.1\system\tomcat\Unnamed_2017_04_10-testHelloWorld\conf\Catalina\localhost\ROOT.xml has finished in 3,687 ms

My development environments:

*

*Java 8

*Intellij 2016.1.2 (build 145.972)

*Tomcat 8.5.13

*Windows 7

I have tried several methods:

*

*Re-install Tomcat and Intellij;

*Re-config $JAVA_HOME, $CATALINA_HOME and so on;

*Create and add a new Artifact on Intellij.

This problem puzzles me heavily. Kindly Help me out please.


text:
Q: How do i switch to Unity from Xmonad Im a real noob with computers and installed accidentally Xmonad, without knowning that it was code-based. How can i switch back to unity?

A: Two imperfect ways to do this:
(Assuming Unity is still installed)

*

*ctrl + alt + t to open up a terminal, and type:
unity --replace
or

*

*Log out of your account, and do this Switching window manager/desktop environments?

A: Use CTRL + ALT + F1 like you did before and login with your username and password.
Then type this:
sudo apt-get purge xmonad && sudo apt-get install --reinstall ubuntu-desktop

When that's said and done with, you can start a regular xsession with this command:
sudo service lightdm start

or
sudo service lightdm restart

To bypass the login screen and go directly into your default desktop type:
startx

To see if there are any other related packages still installed you can type this command:
dpkg -l | grep xmonad

No output = no packages are installed.


text:
Q: Cannot read file into R I'n a new R user and  I'm trying to read my file P506A-data-time-v3.csv into R, however it responds with:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file '
P506A
-
data
-
time
.csv': Invalid argument

I changed the directory to the folder on my computer that the file was saved in.
So I looked up other similar questions and people said to use choose.file, however I think I entered it in correctly. The result R gave me was:
> file.choose
function (new = FALSE)
.Internal(file.choose(new))
<bytecode: 0x07c80118>
<environment: namespace:base>
> P506A
Error: object 'P506A' not found
> -
+ data
Error in -data : invalid argument to unary operator
> -
+ timeP506A-data-time-v3<-read.table(file.choose(),header=T,sep="\t")

Error in -timeP506A - data - time - v3 <- read.table(file.choose(), header = T,  :

  object 'timeP506A' not found

In addition: Warning message:

In read.table(file.choose(), header = T, sep = "\t") :`enter code here`

  incomplete final line found by readTableHeader on 'D:\Uni\114\Probelm Solving

So it seems like a complicated problem too me, so any help with figuring out how to get R to read my file would be very much appreciated.
Thanks

A: Try the following
File = read.csv("P506A-data-time-v3.csv", header = TRUE)

and you can also refer the following tutorial
http://www.cyclismo.org/tutorial/R/input.html#read

A: I had the same problem using R Studio (latest version) and with my workspace correctly set up. To be precise, I had:
file 'FILENAME.csv' has magic number 'YEAR,'
  Use of save versions prior to 2 is deprecated
So I changed the row 1 column 1 header 'YEAR' to something else, and the problem went away !

A: I agree with other recommendations although here's something easier. First execute
getwd(). Now is that the folder where your required file is in? Likely it is not. Hopefully you are using R Studio. If so, then manually go to the bottom right panel next to the console and click files, which is at the top left of that panel. Then click the the three dots "..." and go to your preferred working directory. Click Ok. Then click "More" which is next to a blue wheel and just to the left of the three dots. Then select "Set as Working Directory". That's it! :)

A: very late but correct answer
I have also faced this issue, this is not a big issue.
You must be giving wrong file name or not giving correct extension to the file.


text:
Q: Prove there is a formula $\phi(x,z)$ of VC dimension $\kappa$ and dual VC dimension $2^\kappa$ I first recall some definition since the notation can differ somewhat.
Consider a formula $\phi(x,z)$ defining a binary relation $\{(u,v)\in U\times V|\quad \phi(u,v)\}$.
$\phi$ defines subsets of $U$ as $\phi(U,b)=\{a\in U|\quad \phi(a,b)\}$.
The corresponding collection of defined subsets is $\phi(U,b)_{b\in V}\subset\wp(U)$
Now, we say $\phi$ has VC dimension $\kappa$ if $\kappa$ is the maximum cardinality of $A\subset U$ such that $\phi$ shatters $A$ i.e. $\phi(A,b)_{b\in V}=\wp(A)$
The dual dimension is just the dimension of the dual formula $\phi^*(z,x):=\phi(x,z)$
Now I am asked to find a formula as in the title.
The only way I know to produce a formula (actually a set-system, in an equivalent fashion) of arbitrary $\kappa$ VC dimension is to consider:
$$\Phi=U^{\leq\kappa}:=\{A\subset U|\quad |A|\leq\kappa\}\subset\wp(U)$$
Now this is equivalent to the binary relation defined by
$$\phi(u,B)\Leftrightarrow u\in B \quad\quad on\ \ U\times\Phi$$
So my try is to prove that $\phi^*(B,u)$ has VC dimension $2^k$.
To asess that it has dimension $\geq2^\kappa$ I would try by proving that since there must be $A\subset U\ \ |A|=\kappa$ shattered by $\phi$ then $\phi^*$ shatters $\wp(A)\subset \phi\ \ |\wp(A)|=2^\kappa$.
Anyhow I am quite stuck on this.
I think that similarly one can prove that $\phi^*$ has VC dimension $\leq 2^\kappa$
Can someone help?

A: I'll assume $\kappa$ is finite in this answer. For infinite $\kappa$, there's one major issue: The function $\kappa\mapsto 2^\kappa$ may not be strictly increasing on infinite cardinals. If you're really interested in infinite $\kappa$, I think that everything I wrote goes through with minor modifications if you assume GCH. I'm not sure what happens when $\kappa\mapsto 2^\kappa$ is not strictly increasing.

The set system $\mathcal{P}_{\leq\kappa}(U) = \{A\subseteq U\mid |A|\leq \kappa\}$ is a natural guess, since it is somehow the canonical set system with VC dimension $\kappa$. Unfortunately, it can't have dual VC-dimension $2^\kappa$. Suppose we have $\mathcal{B} = \{B_1,\dots,B_{d}\}\in \wp_{\leq\kappa}(U)$. To shatter $\mathcal{B}$, we need a family $(a_X)_{X\subseteq \mathcal{B}}$  of $2^{d}$-many (distinct) elements of $U$ such that for any subset $X\subseteq \mathcal{B}$, we have $a_X\in B_j$ if and only if $B_j\in X$. But for each $j$, $B_j$ is in exactly half of the $2^{d}$-many subsets of $\mathcal{B}$, so $B_j$ contains $2^{d-1}$ many distinct elements $a_X$, and hence $\kappa \geq |B_j|\geq 2^{d-1}$. This shows that $\lfloor \log_2(\kappa)\rfloor + 1$ is an upper bound for the dual VC dimension of $\mathcal{P}_{\leq\kappa}(U)$. And that quantity is much smaller than $2^\kappa$, for all $\kappa>0$.
However, this suggests that $\mathcal{P}_{\leq 2^\kappa}(U)$ might be an example of a set system with VC dimension $2^\kappa$ and dual VC dimension $\kappa$. This is equivalent to what you asked for, by dualizing. In fact, this system has dual VC dimension $\kappa+1$. But we can fix the example:  rather than considering the subsets of size at most $2^\kappa$ of some large set $U$, let's just think about the full power set of a set $U$ of size $2^\kappa$ (and note that all such sets have size at most $2^\kappa$!).

Let $U$ be a set of size $2^\kappa$, and consider the set system $\mathcal{P}(U)$ (the full power set). Clearly $\mathcal{P}(U)$ has VC dimension $2^\kappa$, since it shatters $U$, but there is no subset of $U$ of size greater than $2^\kappa$ to shatter. But also the dual VC dimension is at most $\kappa$, since we would need $2^{\kappa+1}$ points in $U$ to shatter a subset of $\mathcal{P}(U)$ of size $\kappa+1$. So it remains to show that the dual VC dimension is at least $\kappa$.
This follows from the usual bound (see below): If the dual VC dimension of a set system is $d$, then the VC dimension of the set system is strictly less than $2^{d+1}$.
In the contrapositive, this says that if the VC dimension of a set system is at least $2^{d+1}$, then the dual VC dimension is strictly greater than $d$. Equivalently, taking $\kappa = d+1$, if the VC dimension of a set system is at least $2^{\kappa}$, then the dual VC dimension is at least $\kappa$, which is what we wanted.

Proof of the usual bound: We prove it in the modified contrapositive form, that if the VC dimension of a set system $\Phi$ on the set $U$ is at least $2^{\kappa}$, then the dual VC dimension is at least $\kappa$.
Let $A\subseteq U$ be a subset of size $2^\kappa$ which is shattered by $\Phi$. Put the elements of $A$ in bijection with binary sequences of length $\kappa$. For $a\in A$ and $n < \kappa$, write $a(n)\in \{0,1\}$ for the $n^\text{th}$ term in the corresponding sequence. Now for each $n < \kappa$, let $B_n\in \Phi$ be a set such that for all $a\in A$, $a\in B_n$ if and only if $a(n) = 1$ (we can do this since $\Phi$ shatters $A$). Then $\mathcal{B} = \{B_n\mid n<\kappa\}$ has size $\kappa$, and $\mathcal{B}$ is shattered by $A$. Indeed, for any subset $X\subseteq \mathcal{B}$, let $a\in A$ be the element such that $a(n) = 1$ if and only if $B_n\in X$. Then for all $n$, $a\in B_n$ if and only if $a(n) = 1$ if and only if $B_n\in X$. So the dual VC dimension is at least $\kappa$.

Incidentally, exactly the same argument shows that the usual bound is tight. That is, we can do better than what you asked for: We can find a set system with VC dimension $2^{\kappa+1}-1$ and dual VC dimension $\kappa$.
Let $U$ be a set of size $2^{\kappa+1}-1$, and consider the set system $\mathcal{P}(U)$. Clearly $\mathcal{P}(U)$ has VC dimension $2^{\kappa+1}-1$. But the dual VC dimension is at most $\kappa$, since we would need $2^{\kappa+1}$ elements of $U$ to shatter a subset of $\mathcal{P}(U)$ of size $\kappa+1$. And by the usual bound, since the VC dimension is at least $2^\kappa$, the dual VC dimension is at least $\kappa$, and hence equal to $\kappa$.


text:
Q: Does an array of bytes with negative values lose information when converted to String? I've got a code like this where in the encoding i convert the letters to bytes and then flip them with unary bitwise complement ~ at the end convert it to String.
After that i want to decrypt it with a similar method. The problem is that for two similar input Strings (but not the same) i get the same encoded String with the same hashcode.
Does the String(bytes) method lose the information because the bytes are negative or can i retrieve it somehow without changing my encryption part?
thanx
static String encrypt(String s){
        byte[] bytes=s.getBytes();
        byte[] enc=new byte[bytes.length];

        for (int i=0;i<bytes.length;i++){

            enc[i]=(byte) ~bytes[i];
        }

        return new String(enc);
    }

 static String decrypt(String s){
 ...

A: You should never use new String(...) to encode arbitrary binary data. That's not what it's there for.
Additionally, you should only very rarely use the default platform encoding, which is what you get when you call String.getBytes() and new String(byte[]) without specifying an encoding.
In general, encryption converts binary data to binary data. The normal process of encrypting a string to a string is therefore:

*

*Convert the string into bytes with a known encoding (e.g. UTF-8)

*Encrypt the binary data

*Convert the encrypted binary data back into a string using base64.

Base64 is used to encode arbitrary binary data as ASCII data in a lossless fashion. Decryption is just a matter of reversing the steps:

*

*Convert the base64 text back to a byte array

*Decrypt the byte array

*Decode the decrypted byte array as a string using UTF-8

(Note that what you've got currently is not really encryption - it's obfuscation at best.)

A: Your effectively converting arbitrary byte data into a String.
That's not what that constructor is for.
The String constructor that takes a byte[] is meant to convert text in the platform default encoding into a String. Since what you have is not text, the behaviour will be "bad".
If, for example, your platform default encoding is a 8-bit encoding (such as ISO-8859-*), then you'll "only" get random characters.
If your platform default encoding is UTF-8 you'll probably get random characters and some replacement characters for malformed byte sequences.
To summarize: don't do that. I can't tell you what to do instead, since it's not obvious what you're trying to achieve.


text:
Q: При создании динамического блока не работает mask'a для ввода С помощью JS создается динамический блок, часть кода:
divtest.innerHTML =
    '
'+
        '<form action="" method="post">'+
            'Дата рождения'+
            '<input type="text" name="birthday[]" id="birthday" class="form-control" data-mask="00/00/0000" placeholder="__/__/____">'+
         '</form>'+
    '
';

Блоки создаются, но в них не работает маска, если на странице отдельно взять этот код (не динамически), то в нем уже все работает. Что может быть не так?

A:  $('#test').append('
'+
        '<form action="" method="post">'+
            'Дата рождения'+
            '<input type="text" name="birthday[]" id="birthday" class="form-control" data-mask="00/00/0000" placeholder="__/__/____">'+
         '</form>'+'
'
)


text:
Q: Rake db:migrate returns "rake aborted! no such file to load -- spec" For some reason, out of no where, rails began giving me an error on "rake db:migrate", and I can no longer run migrations. It returns the error "no such file to load -- spec /home/ti/rails_apps/appname/Rakefile:10"
I've spent two hours searching google for answers, trying to figure this out, but to no avail. What could be the problem?
Here is the trace:
-jailshell-3.2$ rake db:migrate --trace
(in /home/ti/rails_apps/teamisrael)
rake aborted!
no such file to load -- spec
/usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/home/ti/rails_apps/teamisrael/vendor/plugins/google-geocoder/tasks/rspec.rake:5
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load_without_new_constant_marking'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:7
/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:7:in `each'
/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:7
/usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/home/ti/rails_apps/teamisrael/Rakefile:10
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2349:in `load'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2349:in `raw_load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1985:in `load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1984:in `load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1969:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31
/usr/local/bin/rake:19:in `load'
/usr/local/bin/rake:19

A: Maybe its your google-geocoder plugin rake task that is requiring something you don't have?
/home/ti/rails_apps/teamisrael/vendor/plugins/google-geocoder/tasks/rspec.rake:5

A: Looks like in the stacktrace the google-geocoder plugin is requiring an older version of RSpec.


text:
Q: Balls and boxes pigeonhole problem One has $60$ boxes and many (one colored) balls with $8$ different colors. In every box one puts $3$ balls with different colors. Must there exist (at least) two boxes with the same three colored balls?
If one puts $3$ balls with different colors each in a box, we must find first how many combinations we can have from $8$ different colors choosing 3 each time. That is $(\frac{8}{3}) = 56$ different combinations of colors, which means that there are exactly $4$ boxes with the same color (according to the pigeonhole principle).
I just want to check if my way of thinking is right?

A: Your explanation is partially correct.
There are $\binom{8}{3} = 56$ ways of selecting three of the eight colors.  Since there are $60$ boxes, this means that there must be at least two boxes containing the same combination of three colors.
However, we cannot conclude that there are four boxes containing the same combination of colors, as you seem to be stating.  Crostul has provided you with an example in the comments. One extreme case is all $60$ boxes contain the same three colors.  The other extreme is that all $56$ color combinations are used, with four of them being used twice. Is that what you meant?
To guarantee that there are at least three boxes containing balls with the same combination of three colors, we would require that there be at least $2 \cdot 56 + 1 = 112 + 1 = 113$ boxes.  If we had only $112$ boxes, we could use every color combination exactly twice.
The strong form of the pigeonhole principle states that if $k$ objects are to be placed in $n$ boxes, then the number of boxes that must contain the same number of objects is
$$\left\lceil \frac{k}{n} \right\rceil$$
where $\lceil x \rceil$ is the least integer greater than or equal to $x$.  In our case, $k = 60$ and $n = \binom{8}{3} = 56$, so we are guaranteed at most
$$\left\lceil \frac{60}{56} \right\rceil = 2$$
boxes that contain the same combination of three colors.


text:
Q: QT setMouseTracking(true) has no effect at all so here is my code, I am trying to capture mouse input which does not work unless I hold down my left key on my mouse. Keyboard input works perfectly fine.
  QWidget *window = new QWidget();
  QHBoxLayout *hl = new QHBoxLayout();
  QVBoxLayout *vl = new QVBoxLayout();
  main = new input_browser_main();
  main->setFixedWidth(640);
  main->setFixedHeight(480);

  hl->addWidget(vncmain);
  vl->addLayout(hl);
  QWidget* centralWidget = new QWidget();
  centralWidget->setLayout (layout);
  centralWidget->setFixedHeight(100);
  vl->addWidget(centralWidget);
  window->setLayout(vl);

  this->setCentralWidget(window);
}

For some reason the mouse movement is not captured? I am calling setMouseTracking but I receive no data. I am relatively new to QT and C++ and am making this application in response to a UI demanded by a client.. So what I am trying to achieve is to get the mouse x,y for only inside the Widget.

A: You need to enable mouse tracking for the widgets the mouse is actually on. It seems you have child widgets. Those child widgets need to have mouse tracking enabled so that they propagate the mouse move events to their parent.
You can just call setMouseTracking(true); once. You don't need to enable/disable mouse tracking when the mouse enters/leaves. That means you don't need enterEvent() and leaveEvent() handlers.


text:
Q: Cause of "The specified path is invalid" error when using ScheduledToastNotification I'm getting "The specified path is invalid" error when trying to show a ScheduledToastNotification, if I use ToastNotification in my app it works.
System.Exception was unhandled by user code
  HResult=-2147024735
  Message=The specified path is invalid. (Exception from HRESULT: 0x800700A1)
  Source=Windows
  StackTrace:
       at Windows.UI.Notifications.ToastNotifier.AddToSchedule(ScheduledToastNotification scheduledToast)

I'm not opening any files or dealing with paths at this point and the exception definitely occurs on the line to launch a ScheduledToastNotification, I'm using Windows 10 Universal Application Platform but can't find any reference to this error or issue anywhere

A: Error "The specified path is invalid" was due to the API in the build of Windows 10 not yet supporting the API call, documentation for Windows 8.1 mentions that ScheduledToastNotification was not supported, however in the 10240 build of Windows 10 this API call now is fully supported on desktop and mobile


text:
Q: Error when communicating with the native messaging host with java application and chrome extension i built java application that get data from chrome extension and return data.
the chrome extension work perfect when my java app without this line:
scanner = Scanner.getDevice();

in this code:
    ImageIO.scanForPlugins();
    scanner = Scanner.getDevice();
    scanner.addListener(this);

but when i not delete the line i got error on my background.js:
Error when communicating with the native messaging host

how can i debug the problem ?
the Scanner its:
uk.co.mmscomputing.device.scanner

library
tnx a lot.


text:
Q: Grouping globs of data incrementally I have a data set that consists of contiguous chunks of non-zero numeric values separated by contiguous chunks of zeros. I want to incrementally group the contiguous chunks of non-zero values (ala dplyr::group_by), then drop the zeros. I've figured it out, but I'm using a helper function with a for loop that is rather inefficient and very inelegant. (Note that this is a time-series dataset so order must be maintained).
Is there a more elegant way to do this using dplyr or data.table (or vectorize)?
library(dplyr)

df <- data.frame(var1 = c(0, 0, 2.5, 3.4, 5.7, 2.1, 0, 0, 0, 16.3, 14.9, 0, 0, 129.1, 764.3, 345.5, 0))

myfun <- function(x){
  n <- 1
  mygroup <- 1
  for(i in 2:length(x)){
    if(x[[i]] == 0 && x[[i-1]] != 0){
      n <- n + 1
    }
    mygroup[[i]] <- n
  }
  mygroup
}

df1 <- df %>%
  mutate(group = myfun(df[[1]])) %>%
  filter(var1 != 0) %>%
  group_by(group)

Here is the desired output
> df1
   var1 group
1   2.5     1
2   3.4     1
3   5.7     1
4   2.1     1
5  16.3     2
6  14.9     2
7 129.1     3
8 764.3     3
9 345.5     3

A: One way using dplyr could be:
df %>%
 mutate(group = with(rle(var1 == 0), rep(seq_along(lengths), lengths))) %>%
 filter(var1 != 0) %>%
 mutate(group = cumsum(!duplicated(group)))

   var1 group
  <dbl> <int>
1   2.5     1
2   3.4     1
3   5.7     1
4   2.1     1
5  16.3     2
6  14.9     2
7 129.      3
8 764.      3
9 346.      3

Or:
df %>%
 mutate(group = with(rle(var1 == 0), rep(seq_along(lengths), lengths))) %>%
 filter(var1 != 0) %>%
 mutate(group = dense_rank(group))

A: df %>%
    mutate(group = cumsum((var1 == 0))) %>%
    dplyr::filter(var1 != 0) %>%
    mutate(group = cumsum(!duplicated(group)))


text:
Q: How do you use custom keys inside of firebase .update method? When I try to assign a key to in a multi-path .update() like this:
key1 = 'bar';
key2 = 'baz';

db.ref('path').update({
                key1: 'value1',
                key2: 'value2'});

It literally writes the key as a string to the DB:
/path/key1/value1
/path/key2/value2

QUESTION: how can I get the expected output with dynamic keys?
/path/bar/value1
/path/baz/value2

A: To get the expected output, you need to use brackets around your [keys]:
key1 = 'bar';
key2 = 'baz';

db.ref('path').update({
                [key1]: 'value1',
                [key2]: 'value2'});

This will give you:
/path/bar/value1
/path/baz/value2


text:
Q: How does 'subexpression' work in "replace-match" function in emacs When reading the description of "replace-match" function in Emacs I can't understand what is the 'subexpression' attribute and how it should be used? For example in
(replace-match (format-time-string writestamp-format (current-time)) t t nil 1)
what does the '1' mean?!

A: From the manual:

If subexp is non-nil, that says to replace just subexpression number
  subexp of the regexp that was matched, not the entire match. For
  example, after matching 'foo (ba*r)', calling replace-match with 1
  as subexp means to replace just the text that matched '(ba*r)'.

You will need to understand subexpressions of a regular expression first, to understand this feature: By delimiting a part of a regular expression with braces, you can group it and then access those groups. This is very useful if you want to reuse parts of the match in the replacement text when doing a query-replace-regex. This is simply the way it works here.
Imagine you want to replace every occurence of bar(SOMETHING) with foo(SOMETHING). So you first match with bar(\([^)]*\)) (this means every character besides ) is allowed within the parentheses and that our first subexpression is everything that is matched between \( and \).

A: I googled "emacs subexpression" and the first hit explains it:
Recall that the subexpressions of a regular expression are those expressions grouped with escaped parentheses, '\(...\)'. The countth subexpression is found by counting occurrences of '\(' from the beginning of the whole regular expression. The first subexpression is numbered 1, the second 2, and so on.
For example, if you do a regular expression search for \([a-z]+\) \([0-9]+\), then the first subexpression contains the [a-z]+ part, and the second subexpression contains the [0-9]+ part.


text:
Q: Where is user 'nginx' in nginx on debian 8 I had nginx 1.6.0 on Debian 7 (wheezy), and now I want to install nginx on Debian 8 (Jessie). The version of this new nginx is 1.6.2. I copied the old version of the configuration file nginx.conf to the new server, but when I try to start the service, It fails:
service nginx restart

output:
nginx nginx[10743]: nginx: [emerg] getpwnam("nginx") failed in /etc/nginx/nginx.conf:1

I know my problem is the first line in nginx.conf:
user    nginx;

And I know too, if I changed this line to user   www-data, the problem will disappear, but why is that so? I have also used nginx as a load balancer not as a webserver.

A: $ man getpwnam

The getpwnam() function returns a pointer to a structure containing the
         broken-out  fields  of  the  record in the password database (e.g., the
         local password file /etc/passwd, NIS, and LDAP) that matches the  user‐
         name name.

The user nginx does not exist. You can create it or you can just use www-data as the user.


text:
Q: Cyrus on ClearOs 7 - how to teach it about spam and ham I have recently set up a Cyrus IMAP email system on ClearOs 7 - it is configured as it comes out of the box, to deliver mail locally, and to receive mail for my users from elsewhere.
A lot of spam from people who claim to be Russian has been arriving. It seems to be detected as such (the Subject is prefixed by [SPAM]), but it still appears in the user's inboxes.
Also some ham has been filed in the SPAM folder.
I want to set up a system for the users to tell spamassassin about unrecognised spam, and incorrectly spammed ham. To that end I set up additional folders in each user's mailboxes for Junk and NotSpam. The users move any spam they find in their inbox to Junk, and and normal mail they find in their spam to NotSpam.
I now want to write or find a script which will look in the Junk folder, send the contents to sa-learn --spam, then move the messages to the regular spam folder. It should also look in the NotSpam folder, send the contents to sa-learn --ham, and move them into the inbox.
I have tried to write shell scripts for this, and I have also downloaded and tried to follow sa-learn-cyrus, plus looked at the script I found at wiki.apache.org/spamassassin/RemoteImapFolder.
My script finds the email files OK, and sends them to sa-learn (although I worry that the Spam score and subject alteration should really be reversed before doing this, and I don't know how). I'm stuck on moving the messages to the correct folder, as I suspect a plain Linux mv command will just confuse cyrus, as it has cache, header, index and squat files in the folder, which presumably need to be updated.
sa-learn-cyrus seems to be able to find emails ok, but (as far as I can tell from running it in simulate mode) it does not attempt to move the mails to the right folder, just purges them.
The other script runs OK (after suitable modifications for my setup), but the Junk emails keep reappearing in the inbox.
Specific questions I need to answer are:
1) Why does mail with [SPAM] in the Subject still appear in the INBOX?
2) Is there an existing script which does what I want?
3) What is the proper method to move an email from one mailbox folder to another in Cyrus? Ideally callable from a shell script.

A: Answers I have found, for posterity:
1) Why does mail with [SPAM] in the Subject still appear in the INBOX?
Cyrus has a built-in filtering system which can redirect mail to folders according to rules you supply. I found on my old server I had set up some rules, but had forgotten all about it.
The rule I needed (for user nikki) was:
# cat spamrule
require
["fileinto","envelope","reject","vacation","imapflags","relational","comparator-i;ascii-numeric","regex","notify"];
if header :contains "x-spam-flag" "YES" {
  fileinto "user/nikki/SPAM";
  stop;
}

And, when logged in as user nikki, I can add this rule to the system using sieveshell as follows (nb: the sieveshell prompt is >):
sieveshell -u nikki localhost:2000
Please enter your password:
> put spamrule
> activate spamrule
> list
spamrule  <- active script
> quit

Of course, this presupposes you can open a shell for each user (I logged in as root and used su -s /bin/bash - nikki), and that you know each user's password (which I do).
There is a helpful web interface to Cyrus sieve called SmartSieve which I am trying to get working, but struggling with at present. Ideally you would add it to the server webconfig, and let the users alter their scripts themselves.
2) Is there an existing script which does what I want?
I used the script from Apache Spamassassin RemoteImapFolder, slighly modified:
# $u is the user name
/usr/bin/fetchmail -a -s -n -u $u -p IMAP --folder 'INBOX/Junk E-mail' -m 'bash -c "/usr/bin/tee >(/usr/bin/sa-learn --spam --single \
> /dev/null)|/usr/bin/spamc|/usr/lib/cyrus-imapd/deliver -m SPAM '$u'"' localhost 2>/dev/null
/usr/bin/fetchmail -a -s -n -u $u -p IMAP --folder 'INBOX/NotSpam' -m 'bash -c "/usr/bin/tee >(/usr/bin/sa-learn --ham --single \
> /dev/null)|/usr/bin/spamassassin -d|/usr/lib/cyrus-imapd/deliver '$u'"' localhost 2>/dev/null

Improved script
I have approached the idea from a different, and I think better, angle. All mail which SpamAssassin things is spam has an X-Spam-Flag: YES header, and mail which it thinks is ham has a X-Spam-Flag: NO header. So, if I just tell users to move any misfiled mail into the right folder, I can then look through it for headers which don't match the folder.
To that end, I have written a bash script to do that very job, and placed it on GitHub at cyrus-mark-ham-spam.


text:
Q: Finding $\lim_{n \to \infty} 1+ 1/2 + 1/3 +\dots +1/n - \log n$. $$x_n = 1 + 1/2 +\dots +1/n- \log n$$
Then -
$1.$ Is the sequence increasing?
$2.$ is the sequence convergent?
For $(1)$, $\sum 1/n$ is increasing and $\log n $ is also increasing. First few terms are increasing, but i don't know about later terms.
$(2)$ $n^{th}$ term of the sequence can be written as $a_n = (\sum_{i=1}^{n}) - \log n$
So, $\lim_{n\to \infty} a_n = \lim_{n \to \infty} \sum 1/n -\lim_{n \to \infty} \log n$
Neither first part nor second is convergent here. so i could not conclude anything.
How to solve?

A: This sequences converges to the Euler–Mascheroni constant.
It's very important in number theory.

A: Let $x_n=-\log(n)+\sum_{k=1}^n \frac1k$.  Then, using $\log(1+x)\ge \frac{x}{1+x}$, we see that
$$\begin{align}
x_{n+1}-x_n&=\frac1{n+1}-\log\left(1+\frac1n\right)\\\\
&\le \frac1{n+1}-\frac{1}{n+1}\\\\
&=0
\end{align}$$
and $x_n$ is decreasing.

Next, we can estimate the harmonic sum as $\sum_{k=1}^n \frac1k\ge \frac12 \sum_{k=1}^{n-1}\left(\frac1k+\frac1{k+1}\right)$, which represents the Trapezoidal Rule approximation of $\int_1^n \frac1x\,dx$.
Inasmuch as $\frac1x$ is convex, the trapezoidal rule approximation overestimates the integral of $\frac1x$ and we have
$$\sum_{k=1}^n\frac1k-\log(n)\ge \sum_{k=1}^n \frac1k -\log(n)-\frac12-\frac1{2n}\ge0 $$
whence we see that
$$x_n\ge \frac12$$
Since $x_n$ is decreasing and bounded below by $\frac12$, the sequence $x_n$ converges.


text:
Q: Get the Size of every function in a file How would I find the size of every function in a file using python?
For context, I'm learning pyplot as well as scipy, and I wanted to measure the size of the functions in a programming file, and then measure the frequency of that size.
What I'm looking for is a way to read a file, identify a function, count the lines of the function, and then add it to a list, I don't really care if the function returns a list, I can always write a function that condenses the list of lists into one list.
Example of what I'm trying to implement:
Function A has a length of 10 lines
Function B has a length of 16 lines
Function C has a length of 8 lines
Function D has a length of 5 lines

Given the above data, I want to be able to condense that into a list of [10,16,8,5].
Additionally: I'm going to be testing this on a couple of beginner C projects, and only want to test the files with the .c extension, not .h.
Code I have so far:
# Counts the number of lines in the file
def line_counter(file_name):
    tot_line = 0
    with open(file_name, 'r') as f:
        for line in f:
            tot_line += 1
    return (tot_line)

# Counts the number of lines that end with a semicolon
def semi_counter(file_name):
    tot_semi = 0
    with open(file_name, 'r') as f:
        for line in f:
            sline = line.strip()
            if len(sline) > 0 and sline[-1] == ';':
                tot_semi += 1
    return (tot_semi)

# Returns the maximum nesting depth of the file
def max_depth(file_name):
    max_dep = 0
    dep = 0
    with open(file_name, 'r') as f:
        for line in f:
            for ch in line:
                if ch == '{':
                    dep += 1
                if ch == '}':
                    dep -= 1
                if dep > max_dep:
                    max_dep = dep
    return max_dep

# Counts the number of characters in a file
def char_counter(file_name):
    tot_chars = 0
    with open(file_name, 'r') as f:
        for line in f:
            tot_chars += len(line)
    return (tot_chars)

# Counts the number of comments in the file
def comm_counter(file_name):
    comm_chars = 0
    with open(file_name, 'r') as f:
        block_comment = False
        for line in f:
            lch = None
            line_comment = False
            for ch in line:
                if lch == '/' and ch == '*':
                    block_comment = True
                if lch == '*' and ch == '/':
                    block_comment = False
                if lch == '/' and ch == '/':
                    line_comment = True
                lch = ch
                if line_comment or block_comment:
                    comm_chars += 1
    return comm_chars

# Counts the number of root level functions
def block_counter(file_name):
    block_tot = 0
    dep = 0
    with open(file_name, 'r') as f:
        for line in f:
            for ch in line:
                if ch == '{':
                    dep += 1
                if ch == '}':
                    dep -= 1
                    if dep == 0:
                        block_tot += 1
    return block_tot


text:
Q: read RFID tags from browser on Android Is it possible to access the NFC chip and scan a RFID tag from within a webpage displayed in the browser (Chrome or Firefox) on Android? Preferably in JavaScript, so we can put the data read from the tag into a web form and send it to the server.
I found some React Native Libraries that are capable of reading data from RFID tags, but I'm wondering if it's the right language for the job? I have no idea about React native, but I don't think I can just run it on a webpage, or can I?


text:
Q: I am new to react native and firebase image upload, and im trying to upload an image selected from the library to firebase storage Trying to capture result.uri from Image picker and store in firebase storage but error keeps popping up.
Am i calling it from firebase config.js wrong?
Dependencies

{

  "dependencies": {
...
    "expo": "~46.0.16",
    "firebase": "^9.13.0",
    "..react": "18.0.0",
    "react-native": "0.69.6
}

App.js
...
export default function App() {

  useEffect(() => {
      getPermission();
  },[]);

  const getPermission = async () => {
    if(Platform.OS !== 'web'){
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if(status !== 'granted'){
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  }

  const pickImage = async () => {
    try{
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4,3],
      quality: 1,
    });

    if(!result.cancelled){
       //the storage itselg
    const storage = getStorage();

    const ref = ref(storage, `images/${result.uri}`)

    await uploadBytes(ref, result).then( (snapshot) => {
      alert('hello there')
    }).catch((error)=> {
      alert('error')
    });

    }

  }catch(error){
    alert(error.message)
  }
  }

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={pickImage}>
      <Text>Select An Image</Text>
      </TouchableOpacity>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Error
_ref3 is not a function. (In '_ref3(storage, "images/" + result.uri)', '_ref3' is undefined)
..........................................................................................


text:
Q: Will gunicorn wait for spawned threads to complete before accepting the next request? I have a web server running Django with gunicorn using synchronous workers (my gunicorn config is straight out of the box, no gevent or anything).
In a gunicorn worker process, there is obviously a main thread. I've also written some custom middleware to send request & response data to Keen.io, which I do from a celery worker. BUT, the call to enqueue to the celery worker requires a remote call to my RabbitMQ queueing service, so I do that in ANOTHER thread, so that Django's http response will be sent to client even if the enqueue call hasn't completed by the time the response is rendered.
If you wonder why I do this, let's just say in my experience on highly-scaled systems, you will inevitably see failures or extreme latencies with enqueueing, or really with any over-the-wire call. I don't want these latencies to mess with my response times.
My question is, will gunicorn WAIT for the spawned threads to complete before accepting a subsequent request? Or could those spawned threads potentially "pile up"? This is concerning to me, because I use a database connection pool which would quickly deplete if these threads keep piling up.


text:
Q: cbind converting factor to numeric Not sure why this is happening.  I have a dataframe df2 with the variables below:
          EVTYPE TOTAL_FATALITIES TOTAL_INJURIES
          (fctr)            (dbl)          (dbl)
1        TORNADO             5633          91346
2 EXCESSIVE HEAT             1903           6525
3    FLASH FLOOD              978           1777
4           HEAT              937           2100
5      LIGHTNING              816           5230
6      TSTM WIND              504           6957

    > df2$TOTAL_FATALITIES

 [1] 5633 1903  978  937  816  504  470  368  248  224  206  204  172  160  133  127  103  101  101

    > df2$EVTYPE

 [1] TORNADO           EXCESSIVE HEAT    FLASH FLOOD       HEAT              LIGHTNING
 [6] TSTM WIND         FLOOD             RIP CURRENT       HIGH WIND         AVALANCHE
[11] WINTER STORM      RIP CURRENTS      HEAT WAVE         EXTREME COLD      THUNDERSTORM WIND
[16] HEAVY SNOW        STRONG WIND       BLIZZARD          HIGH SURF
985 Levels:    HIGH SURF ADVISORY  COASTAL FLOOD  FLASH FLOOD  LIGHTNING ... WND

    > df2$TOTAL_INJURIES

 [1] 91346  6525  1777  2100  5230  6957  6789   232  1137   170  1321   297   309   231  1488  1021
[17]   280   805   152

I am trying to create new column called SevType -- where I will store whether a value is either an injury or fatal.
However, when I use cbind on df2$EVTYPE, it converts the factor into a numeric as seen below.
    > head(cbind(Event=df2$EVTYPE,Total = df2$TOTAL_INJURIES,Severity="INJURE"))
     Event Total   Severity
[1,] "834" "91346" "INJURE"
[2,] "130" "6525"  "INJURE"
[3,] "153" "1777"  "INJURE"
[4,] "275" "2100"  "INJURE"
[5,] "464" "5230"  "INJURE"
[6,] "856" "6957"  "INJURE"

Notice that Event at [1,] has changed from TORNADO to 834.
Any hints on why this is happening?

A: We are cbinding vectors and the output will be a matrix.  The matrix can hold only a single class.  So, if there is any vector that is non-numeric, it will convert the whole matrix to 'character' and as the first column is already a factor, we get the numeric levels of that factor.  Better would be to use data.frame
data.frame(Event=df2$EVTYPE,Total = df2$TOTAL_INJURIES,Severity="INJURE")

Or we can use bind_cols or data_frame from dplyr


text:
Q: Using update-able FlowDocument XAML files as my WPF help system I'm putting together a simple help system for my WPF app using XAML FlowDcouments (just .xaml files, no code-behind). I've simply added them to my project with Build Action = Resource, and I can load and display them as required.
Now, I'm trying to make it a bit more flexible, in that after the installation of the app, I want the user to be able to download additional (or newer versions of the existing) FlowDocument XAML help files. Given this, I'm now wondering where the best place to store these files is. A few questions/ideas:

*

*Can I leave them as resource files, and overwrite or add new files as required? I can't find a example of how to add/edit resources at runtime on SO/Google. Is it even possible?

*If not, is there a recommended location to store these files? They should be available to all users, so they can't go into the User's directory - they would have to go in the program directory. Does the program directory have write-access (I remember having issues with that before)?

*Any other ideas?
Thanks.

A: The resource files are embedded into the executable and therefore you cannot change them.
As for a common place to put your downloaded help files, you cannot store them in "Program Files" since you would need admin privileges to write there.
I suggest you put them into SpecialFolder.CommonApplicationData (see http://msdn.microsoft.com/en-us/library/system.environment.specialfolder(v=vs.80).aspx), which is defined as "The directory that serves as a common repository for application-specific data that is used by all users."


text:
Q: Can I use geofence to mark all roads within the shape coords as avoids or favors? Fleet telematics API tool https://tcs.ext.here.com/examples/v3/fleet_telematics_api has examples "Prefer certain links and route through them" and "Avoid certain links and route by avoiding them".
The question is does HERE maps provide an API to mark geofence as avoid or favor similarly how it provides the ability to mark route links as avoids or favors?
UPD: Additionally is there a way of matching router links within the geofence so that we can get them and mark as avoids/favors?

A: The geofence/shape can be used only to restrict the area. See Overlay Override Area chapter in Fleet telematics Custom Routes docs.
So you can't do areas "preferred". Only route links — roads can be marked both either "favored" or "avoided".


text:
Q: aws ec2 t2.small vs t2.medium CPU performance Since t2.medium has 2 VCPU and t2.small has 1 VCPU would it be faster as a web server? (Apache/php).
I am wondering if I upgrade if I will gain any performance benefits.

A: Your server will be able to do more work in parallel. If it's just serving static web pages I wouldn't expect much difference. If it's executing php on a loaded server then I would expect some improvement.
Other than cores / RAM, the primary difference between t2 instances is the rate the CPU credit that lets you burst to high performance accumulates. Once you run out of credits you run at the baseline performance for the instance.
You would probably get some improvement in performance moving to new t3 instances. The t3.small has 2 vCPUs and earns twice as much CPU credits per hour as the t2.small (12 for the t2.small vs 24 for the t3.small). The t3.small is slightly cheaper than the t2.small, and because the hypervisor largely runs in hardware you might get a bit more performance out of it.
Using t3 instances, beware t3.unlimited is turned on by default. This feature enables you to pay more for CPU once you run out of credits. I had a process that sat on 100% CPU for a few days on a t3.micro before I noticed and added alerts, which cost money.


text:
Q: Lagrange's theorem proof I read the answers to these questions:
Proof of Lagrange theorem - Order of a subgroup divides order of the group
Lagrange's theorem
How do I know that the cosets of H have the same number of elements?(That equivalence classes form a partition of G.)

A: Consider a function defined by $f:H\to Ha$ by $f(x)=xa.$ Then it can be easily verified that $f$ is bijection. i.e., $H$ and $Ha $ has same cardinality.

A: Hint:
Consider the map $H\to gH$ given by $h\mapsto gh$. Prove that it is bijective.

A: Let $a$ and $b$ be any two elements, $H$ a finite subgroup. Consider $aH$ and $bH$. If $|aH|\neq|bH|$ then there must be two elements in $H$, say $f$ and $g$ such that either $af=ah$ or $bf=bh$. Assume WLOG $af=ah$. Then $f=h$, a contradiction. Thus all the coasts have the same size.


text:
Q: Total TLAB Size vs Total Object Size in Java Mission Control I am looking into Oracle Java Mission Control for memory consumption investigation. To get started I used the Flight Recording wldf.jfr provided in the JDK 8 samples. I am puzzled about the columns Total TLAB Size vs Total Object Size:

For the first thread, the Total Object Size is 1.52MB, but the Total TLAB Size is 809.91MB (different magnitude). How is this explained? The application was executed using
-Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=256m
My understanding until now is that each thread has a single TLAB. A TLAB  can be retired and a new one is allocated for the thread based (among other factors) on the value of
-XX:TLABWasteTargetPercent
The data of the retired TLAB remain in Eden and their fate is decided on the next Minor GC. Is then the column TLABs referring to the total number retirement/allocations? This in turn should suggest that Total TLAB Size, is a cumulative measure of these allocations of new TLABs.
Can I extract any conclusions on the memory management? Maybe too many TLAB allocations could suggest increasing the size of TLAB?

A: The 'Allocation in new TLAB' event is a bit tricky,
it represents one object allocation, which is causing a new TLAB to be allocated for the thread. (That TLAB is heuristically assumed to contain only objects of the same type as the first object)
The event contains information both about the object allocation itself, and about the TLAB.
The 'Total Object Size' column (not enabled by default), just sums the object sizes for the individual objects causing the new TLABS, so it's quite a weird statistic really.
In JMC 6, included in JDK 9, I believe we have removed this particular calculation.


text:
Q: Analysis of completion time data I'm struggling with the data of an experiment in an online shop. Participants were presented with a picture of an item available in the shop and asked to browse trough the different categories and add the correct item into the shopping cart. The variable of interest is task completion time (i.e. how long it took participants to find the item and add it to the cart). I have four groups (different versions of the shop). As you can see in the boxplots, the distribution of completion times is right skewed and there are a bunch of outliers in all four groups.

I have tried several different ways - and combination of these -  to account for the non-normal distribution and the outliers, which all lead to different results:

*

*Trimming of Outliers

*Winzorization (i.e. setting most extreme values to 95% percentile)

*Log-Transforming the data

Eventually, I want to be able to perform an ANOVA. In your opinion, which method for the analysis of completion time data is the most appropriate and are there other ways, which I have not mentioned?

A: I believe that your data would best be analyzed using, in order of preference, a time-to-event method such as Kaplan-Meier or Cox's model or, less optimal, a Poisson regression.
Provided that you are interested in the differences in time until completion, survival analysis will give you the best sense of the difference between completion rates of your groups. The main role of survival analysis is to understand differences in an underlying process ( the "force of mortality" in healthcare applications) leading some units to fail (or not fail) deferentially as a function of time. Survival analysis takes into account that not all units are under observation at all time points in the analysis- some have already failed or, in your case, completed the task. This is called censoring. Your analysis may not succeed in identifying differences in the underlying completion rate at any given time if you do not account for the fact that some persons have already completed the task. Thus, one of the methods of survival analysis is most appropriate. Also, skewness is often seen in survival analysis and, as long as the proportional hazards assumption is met, survival analysis is particularly well-suited to handle this skewness, while still preserving the ability to differentiate between rates over time between groups or covariates.
Poisson regression can also be used to model failure time data under special circumstances (see: Does Cox Regression have an underlying Poisson distribution?). However, it has never been clear to me why this offers an advantage over survival analysis, as this method requires the data fits the Poisson distribution and does not account for changing membership in the at-risk group over time.


text:
Q: Backbone Model: empty attribute with get method but in attributes object I have these lines:
console.log(JSON.stringify(this.model.attributes));
console.log(this.model.get('name'));

And this is the output:
"{"name":"ffg","key":"1c277f82-f093-d359-4cfb-febe4614a3b1"}"
""

I'm starting with Backbone.
Any ideas why the object is in the attributes but it returns empty with the get method??
EDIT:
This shouldn't affect answers, but I'm working with Phone Gap.
The 2 console.log are lines next to each other.
EDIT 2:
var temp = _(this.model.attributes).clone();
console.log(JSON.stringify(temp));
console.log(temp.name);

This logs:
{"name":"ss","questions":[],"order":0,"key":"5c35c304-4863-02c0-4d18-101c655aa4ae"}
""

A: I would consider logging this.model and inspecting the object into a browser (e.g. Chrome or Firefox) then  look into the attributes property of the object. Make sure that the name property is defined as you intended. Also, please make sure that no event is triggered that could modify your model object.

A: When you fetch model, try set this yourModel.fetch({async: false})


text:
Q: How can I find the date that is 1 day later than another date in PHP? How can I find the next day's date after a given date.
For example, I have a date 2011-11-31.  How can I get the next date (2011-12-01) using PHP?
Similarly, how would I get the previous day's date?

A: $nextdate = date("Y-m-d",strtotime($olddate." +1 day"));

A: You can use the strtotime() function in php:
$date="2011-11-11";
$nextdate = date('Y-m-d', strtotime($date . " +1 day"));
echo $nextdate;

It will echo as "2011-11-12".

Similarly to find the previous date use:
$nextdate = date('Y-m-d', strtotime($date . " -1 day"));
It will echo as "2011-11-10".


text:
Q: Snap crashes while installing any application Installing any application from snap bricks my laptop and I need to force power down.
The command I run is:
sudo snap install spotify

Setup snap "spotify" (60) security profiles for auto-connections.

And the system freezes. I've tried this with flutter and spotify but they both crash at the same security profile... step.
My system Details:
         .';:cccccccccccc:;,.            ---------------------------------------
      .;cccccccccccccccccccccc;.         OS: Fedora Linux 36 (KDE Plasma) x86_64
    .:cccccccccccccccccccccccccc:.       Host: 80WK Lenovo Y520-15IKBN
  .;ccccccccccccc;.:dddl:.;ccccccc;.     Kernel: 5.17.6-300.fc36.x86_64
 .:ccccccccccccc;OWMKOOXMWd;ccccccc:.    Uptime: 5 mins
.:ccccccccccccc;KMMc;cc;xMMc:ccccccc:.   Packages: 1927 (rpm)
,cccccccccccccc;MMM.;cc;;WW::cccccccc,   Shell: bash 5.1.16
:cccccccccccccc;MMM.;cccccccccccccccc:   Resolution: 1366x768
:ccccccc;oxOOOo;MMM0OOk.;cccccccccccc:   DE: Plasma 5.24.5
cccccc:0MMKxdd:;MMMkddc.;cccccccccccc;   WM: kwin
ccccc:XM0';cccc;MMM.;cccccccccccccccc'   Theme: [Plasma], Adwaita [GTK2]
ccccc;MMo;ccccc;MMW.;ccccccccccccccc;    Icons: [Plasma], breeze-dark [GTK2/3]
ccccc;0MNc.ccc.xMMd:ccccccccccccccc;     Terminal: konsole
cccccc;dNMWXXXWM0::cccccccccccccc:,      CPU: Intel i5-7300HQ (4) @ 3.500GHz
cccccccc;.:odl:.;cccccccccccccc:,.       GPU: NVIDIA GeForce GTX 1050 Ti Mobile
:cccccccccccccccccccccccccccc:'.         GPU: Intel HD Graphics 630
.:cccccccccccccccccccccc:;,..            Memory: 2632MiB / 15888MiB

Snap Version:
snap    2.55.3-1.fc36
snapd   2.55.3-1.fc36
series  16
fedora  36
kernel  5.17.6-300.fc36.x86_64


text:
Q: How can I prove the fact that "a prime ring has no nontrivial central idempotent"? It seems like "a prime ring has no nontrivial central idempotent" is a well known fact since the Book of Rowen and Goodearl and lots of other papers use this fact freely. However, I cannot find the proof of this fact.
Can anyone give me at least a hint to prove : a prime ring has no nontrivial central idempotent?

A: A ring $R$ is prime if, from $axb=0$, for all $x\in R$, it follows $a=0$ or $b=0$.
If $e$ is a central idempotent, $ex(1-e)=e(1-e)x=0$, so, by definition, either $e=0$ or $1-e=0$.

A: Suppose $\;R\;$ is a prime ring and $\;0,1\neq r\in R\;$ is central and idempotent, so for any $\;x\in R\;$ :
$$(1-r)rx=(r-r^2)x=(r-r)x=0\cdot x=0\implies\,1-r=0\;\;\text{or}\;\;x=0$$
In the first case we get $\;r=1\;$ and thus $\;r\;$ isn't trivial, and in the second we get $\;R=\{0\}\;$

A: A ring is prime iff the product of two nonzero ideals is nonzero.
If $e$ is a nontrivial central idempotent, then $A=eR$ and $B=(1-e)R$ are two ideals, and $AB=\{0\}$.
Actually in this case, $A\oplus B=R$ is a ring decomposition into two other nonzero rings, which is never a prime ring. This is sort of like being prime in the sense it can't be factorized into smaller rings.
Factorizations of a ring into smaller nonzero rings correspond to central idempotents. If a ring has no nontrivial central idempotents, you can think of it as "irreducible." Prime rings are always irreducible, but the converse is not always true. (This closely parallels the standard situation of prime and irreducible elements in integral domains.


text:
Q: Help me understand what this log means I'm constantly getting this log in my var/debug.log file. I'm quite curious about this. I do not understand what it means.

main.DEBUG: cache_invalidate:
  {"method":"GET","url":"http://127.0.0.1/m4/paym/redirect/?SID=rpgvdrc7v23j38i36i8a274ae1","invalidateInfo":{"tags":["vendor_payment_gateway_2","FPC"],"mode":"matchingTag"},"is_exception":false} []

I some how figured out that it has some connetions with my
 model which is as below:
class Createorder extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
    const CACHE_TAG = 'vendor_payment_gateway';
    protected $_cacheTag = 'vendor_payment_gateway';
    protected $_eventPrefix = 'vendor_payment_gateway';
    protected function _construct()
    {
        $this->_init('Vendor\Gateway\Model\ResourceModel\Createorder');
    }

    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    public function getDefaultValues()
    {
        $values = [];

        return $values;
    }
}

Being a magento developer I must understand what my logs are saying.


text:
Q: AttributeError: 'LevelingSystem' object has no attribute 'author' I am making a discord bot, and I'm currently working on a leveling system. But I am constantly getting an
AttributeError: 'LevelingSystem' object has no attribute 'author'
This is the code for it
import discord
from discord.ext import commands
from discord.utils import get
import json
import random
import time

class LevelingSystem(commands.Cog):
    """ Leveling system for discord """

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(message, guild):

        if message.author.bot:
            return
        else:
            with open("X:\\Code\\Projects\\Python\\AlphaWolf\\cogs\\levels.json", 'r') as f:
                levels = json.load(f)

            await update_data(levels, message.author.id)

        async def update_data(levels, user):
            for member in guild.members:
                if user not in levels:
                    levels[user] = {}
                    levels[user]["experience"] = 0
                    levels[user]["level"] = 1
                    print(" Registered {} to .json".format(user))
                    with open("X:\\Code\\Projects\\Python\\AlphaWolf\\cogs\\levels.json", 'w') as f:
                        json.dump(levels, f)

def setup(bot):
    bot.add_cog(LevelingSystem(bot))

A: You're using cogs, and because your event is in a class, you'll need to include the self keyword as the first arg in your class methods.
class LevelingSystem(commands.Cog):
    """ Leveling system for discord """

    def __init__(self, bot): # self is used here
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message, guild): # need it here as well
        # rest of the code

It's assuming that the self keyword is called message because it's always the first argument in class methods.
So when you're saying message.author, the program is actually assuming that there's an attribute called author in your class - it sees message.author as self.author.


text:
Q: MySQL Global Triggers for a connection Is it possible to create a trigger that will listen for any insert or update for one database connection/instance (all schemas)?
Here is my business case:

*

*I have multiple schemas on one MySQL server.

*Each of these schemas has multiple tables.

*All of the tables have a 'lastChanged' datetime column.

*I need to update the 'lastChanged' column in a table whenever an update or insert occurs on that table.

So to summarize, I am looking to see if it is possible to create a global rule that would make it so I do not need to create a trigger for every table, in every schema.
I haven't much experience with triggers, so if you think of something other than a trigger as the answer for catching these events and updating rows in corresponding tables that would be a fantastic answer as well!!

A: You can't do this with a single trigger.
However, if you change the lastChanged column from DATETIME to TIMESTAMP then you can use the DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP feature to set the value automatically on any insert or update.
One tradeoff is that the TIMESTAMP data type can only support values from 1970 to 2038, so you can't use that if you need to store values outside that range.
Since you are looking to make this as simple as possible, and you said all of the tables already have a column named lastChanged, you can consider using information_schema to generate the alter table statements you need, and then execute them all at once.
Something like this:
select concat('alter table ',
   t.table_schema,
   '.',
   t.table_name,
   ' modify column ',
   c.column_name,
   ' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;') as ddl
into outfile '/tmp/lastChanged.sql'
from information_schema.columns c
  inner join information_schema.tables t
    on t.table_schema = c.table_schema and t.table_name = c.table_name
where c.table_schema = database()
and c.data_type = 'datetime'
and c.column_name = 'lastChanged'
and t.table_type = 'base table';

\. /tmp/lastChanged.sql


text:
Q: How to add library from custom remote repository I want to add a library from custom remote repository to my Java project but I couldn't manage to do it.
Library is published at a custom Maven repository:
<repository>
  <id>cefdigital</id>
  <name>cefdigital</name>
  <url>https://ec.europa.eu/cefdigital/artifact/content/repositories/esignaturedss/</url>
</repository>

The library I'm trying to use is named dss-rest-client (Package name: eu.europa.esig.dss.ws.signature.rest.client)
I tried adding the repository XML to <project>/pom.xml and <home>/.m2/settings.xml. I also added the URL to Settings -> Build Execution Deployment -> Remote Jar Repositories.
But when I try to use search in Project Structure -> Libraries -> Add -> Maven - Search nothing comes up.
What am I doing wrong?

A: In the end I couldn't do what I wanted (add libraries from search interface) but I managed to add them as artifacts using pom.xml. You need to define repository in a profile and use that profile to maven build. You may need to restart IntelliJ after adding dependencies. Sample profile:
<profiles>
        <profile>
            <id>myprofile</id>
            <activation>
                <activeByDefault>true</activeByDefault><!--makes this profile the default profile-->
            </activation>
            <repositories>
                <repository>
                    <id>cefdigital</id>
                    <name>cefdigital</name>
                    <url>https://ec.europa.eu/cefdigital/artifact/content/repositories/esignaturedss/</url>
                </repository>
            </repositories>
        </profile>
    </profiles>


text:
Q: CPAN modules claim to install but dont Running UBUNTU 14.04 through VirtualBox.
When executing a script, i get the following error:
Can't locate XML/Simple.pm in @INC (@INC contains:...
Now, when I check the directories in @INC, they indeed do not contain XML/Simple.pm
I then tried installing it through cpan
sudo cpan XML::Simple
and it tells me that:
XML::Simple is up to date (2.20).
which, according to perl is not true, since the output of
perl -e "use XML::Simple "
is
Can't locate XML/Simple.pm in @INC (@INC contains:
So, what am I missing?

A: An alternative way to install Perl modules on Linux systems is from the distribution repository.  On Debian/Ubuntu systems the general rules for converting a CPAN distribution name to an apt package name is:

*

*convert the module name to lower case

*convert '::' to '-'

*add a 'lib' prefix and a '-perl' suffix

So the package name for XML::Simple would be: libxml-simple-perl and you could install it with:
sudo apt-get install libxml-simple-perl

There are exceptions to these rules, but you can always search by Perl module name:
apt-cache search XML::Simple

You won't get the absolute latest version of the module from your distro's package repository but for stable (some might say 'moribund') modules like XML::Simple that usually doesn't matter.
If you do have multiple versions of Perl installed, then installing from your distro's package repository will usually only make the package available for the system Perl in /usr/bin

A: In general, you should not mess with the system perl.
Use
$ which perl
and
$ sudo which perl
to see where each perl lives.

A: As a System Administrator or Application developer there is a common problem that you usally face. When you develope an Application you probably always want the newest and latest modules, and not the modules that are shiped with the distribution. But even if you are fine with the versions in your Linux distibution sometimes you have the problem that you want a specific Perl module and it is not included in your distribution.
The usally way to solve that problem was just a call to lets say cpan XML::Simple and the latest module gets downloaded and installed.
But when you do this, you are messing with the package system of your Linux distribution. Lets say you already had XML::Simple installed from your package system. Your cpan command will now update the already installed version and replace it with a newer version. All of that is fine, until your Linux distribution for example would ship an update for libxml-simple-perl. What than could happen is that your new version gets reverted to an old version.
And because all Perl modules usally depends on other Perl Modules, an install command also can update a lot of other Perl modules.
All of that behaviour can leads to weired bugs. Either way in application you write, or also in application shiped in your distribution.
To "resolve" that problem, usally the best way is to leave the system Perl completly alone. Compile your own Perl Version completly from source. That Perl version than has its own perl libraries that you can install directly from CPAN without messing with the System Perl.
Now to do that very easy, their exists a tool named Perlbrew
With this tool you can easily install any Perl Version. For example just typing perlbrew install perl-5.16.0 and it completly installs Perl 5.16.0 in your home directory! It also setups all paths so a call to perl in your system resolve to this perlbrew installation.
Also an important part is that this Perl installation is just in your home directory under a normal user account. You don't need sudo or a root Account, because Perl gets installed in your home directory.
The same goes for Perl Modules. If you want to install a Perl Module in your Perlbrew installation you just type cpan XML::Simple (or cpanm XML::Simple checkout App::cpanminus).
Now the important part. On your system you already had a setup for Perlbrew. When you executed your installation program that Perlbrew installation was used. But in this Perlbrew installation there was no XML::Simple installed.
You then executed sudo cpan XML::Simple to install XML::Simple. The problem is that all sudo commands just gets executed as a root user. That means your system Perl /usr/bin/perl is used instead of your Perlbrew installation in /home/qiime/perl5/perlbrew/perls/perl-5.16.0/bin/perl
You successfully install XML::Simple in your System Perl. But your Perlbrew installation didn't had XML::Simple installed and thus it still returned an error that it could not found XMl::Simple.
The only thing you really needed to do was just cpan XML::Simple installing XML::Simple in your perlbrew installation in your home directory.


text:
Q: Google "One Tap" Verification: Wrong number of segments in token In the HTML in the site I have got from the docs here
<script src="https://accounts.google.com/gsi/client"></script>

      <div
        id="g_id_onload"
        data-client_id={googleClientID}
        data-login_uri='https://mytestdomain.appspot.com/google'
        data-return_uri={uri}
      ></div>

When the site loads it shows me the prompt to continue with my google account, I click continue and it shows me as logged in, the webhook does get called and I can get the g_csrf_token from the cookie, then I try to verify it using the google-auth-library as described here in the docs which is linked from the one-tap docs here
const { OAuth2Client } = require("google-auth-library");
...
app.post("/google", function(req, res) {
  const idToken = req.cookies.g_csrf_token;
  const audience = process.env.GOOGLE_CLIENT_ID
  const client = new OAuth2Client(audience);
  async function verify() {
    const ticket = await client.verifyIdToken({ idToken, audience });
    const payload = ticket.getPayload();
    const userid = payload["sub"];
    console.log('------------------ userid');
    console.log(userid);
  }
  verify().catch(console.error);
  res.status(200).send({ req });
});

Th error I get is
Error: Wrong number of segments in token: 87ba1eb4d6261b6b      at OAuth2Client.verifySignedJwtWithCertsAsync (/app/node_modules/google-auth-library/build/src/auth/oauth2client.js:525:19)      at OAuth2Client.verifyIdTokenAsync (/app/node_modules/google-auth-library/build/src/auth/oauth2client.js:391:34)      at processTicksAndRejections (internal/process/task_queues.js:97:5)      at async verify (/app/server.js:71:20)

The docs do suggest that we should get the token as a POST parameter as well as in the cookie, I have checked req.body.credential, req.query.credential, req.params.credential but there is no token to be found, from the docs here
After an ID token is returned from Google, it's submitted by an HTTP POST method request to your login endpoint with the parameter name credential.

A: I figured it out - we were both using the g_csrf_token cookie for the idToken but that's wrong!
You basically need to get the request.body.credential (or req.body.credential in your case) instead, which is a JWT. Then it should work!


text:
Q: enable_if and auto return type? I want to use type_traits to overload by shared_ptr or not.
struct A {
    A(int i) : x(i) {}
    int x;
};

int main()
{
    A a{4};
    auto b = std::make_shared<A>(7);
    A& c = a;
    A* d = b.get();
    A* e = &a;

    std::cout << getX(a) << std::endl;
    std::cout << getX(b) << std::endl;
    std::cout << getX(c) << std::endl;
    std::cout << getX(d) << std::endl;
    std::cout << getX(e) << std::endl;

    return 0;
}

This is one solution but has the problem that the return type must be pre-defined.
template <typename T>
typename std::enable_if_t<!boost::has_dereference<T>::value, int> getX(T t)
{
    return t.x;
}

template <typename T>
typename std::enable_if_t<boost::has_dereference<T>::value, int> getX(T t)
{
    return t->x;
}

But using the method below, I can make the return type auto but it kind of looks clunky.
template <typename T, typename std::enable_if_t<!boost::has_dereference<T>::value>* = nullptr>
auto getX(T t)
{
    return t.x;
}

template <typename T, typename std::enable_if_t<boost::has_dereference<T>::value>* = nullptr>
auto getX(T t)
{
    return t->x;
}

Is there a method to use the first type and still get return type auto?
I do not want to specify the type of A::x and so auto return type would be best. The second type does that but feels a bit clunky.
Or is there a better way of doing this? Thanks.

A: If you just want to run a different line of code or two for different types then constexpr if lets you do that without having to use enable_if and allows you to use automatic return type deduction.  You can simplify getX into
template <typename T>
auto getX(T t)
{
    if constexpr (boost::has_dereference<T>::value)
        return t->x;
    else
        return t.x;
}

and this works because the path that is not executed is discarded so at compile time only the true path compiled.

A: This is an interesting version using C++20 (two variants, in fact):
template <typename T> auto getX(T t) {
    if constexpr (requires(T t) { t->x; })
        return t->x;
    else
        return t.x;
}

template<typename T> concept HasDereference = requires(T t) { *t; };

template <typename T> auto getX_v2(T t) {
    if constexpr (HasDereference<T>)
        return t->x;
    else
        return t.x;
}

struct X {
    int x;
};

#include <iostream>
using namespace std;

int main() {
    cout << HasDereference<X> << endl;  // 0
    cout << HasDereference<X*> << endl; // 1
    X x{42};
    cout << getX(x) << endl;  // 42
    cout << getX(&x) << endl; // 42
    cout << getX_v2(x) << endl;  // 42
    cout << getX_v2(&x) << endl; // 42
}


text:
Q: Problems with DNS I'm in charge of the admin of the VPS of the company I'm working. Basically, those VPS host our websites and also serve as name servers for the domain names we purchased. To manage all this, I'm using ISPConfig 3 on Linux debian Wheezy machines.
The problem is that we purchased some domain names at our registrar and asked him to point those names to our VPS. Then on the VPS, with the help of ISPConfig I added the zones for each purchased domain, mentioning the host name of our registrar's name servers. But the domain name is not working. When I try to ping after setup, I get : "unknown host etaxe.bj" error (one of the domain names is etaxe.bj). The registrar confirmed that he pointed the domain name to my VPS IP address. So the problem may be at my side. As I'm very newbie in managing DNS zone, I'd like to know what I can do to first find where is the problem and try to solve it. How to troubleshoot DNS zone issues ?

A: The nameservers for your domain are not valid.
Currently they are set to:
Name Server: ns1.hesystems.group.com
Name Server: ns2.hesystems.group.com

But neither of these actually exists.
$ host ns1.hesystems.group.com
Host ns1.hesystems.group.com not found: 3(NXDOMAIN)
$ host ns2.hesystems.group.com
Host ns2.hesystems.group.com not found: 3(NXDOMAIN)

You need to set these correctly at your registrar.


text:
Q: MASKING URL with HTACCESS I am trying to redirect visitors of alldomain.com to the domain newdomain.com it does redirect however I want that when the user open's alldomain.com the data should be of newdomain.com however the top url should be alldomain.com
My Current HTACCESS:
RedirectMatch .* http://www.newdomain.com

A: I believe the solution to this consist of two parts: correct .htaccess, and using mod_proxy on your Apache server:
Uncomment these lines in httpd.conf (and restart Apache!):
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Add the following lines to your .htaccess:
RewriteEngine    on
RewriteRule      .*  http://www.newdomain.com/  [P]
ProxyPassReverse /   http://www.newdomain.com/

The key here is that the [P] flag in the RewriteRule tells Apache to use mod_proxy (which you enabled earlier), and the ProxyPassReverse makes sure that any links from the new domain are properly "attributed" to the old domain as well. I think that does it, but I can't test... Let me know whether this works for you!


text:
Q: CNTK: csv column format in example 104 In CNTK example (CNTK_104_Finance_Timeseries_Basic_with_Pandas_Numpy)
the data look likes:
    get_stock_data
I have try pd.read_csv to read my own csv data:
url = 'http://localhost/csv/SPY0.csv'
data = pd.read_csv(url)
data.tail(5)

...the result:
pandas.read_csv
Question is: How csv column format like "get_stock_data" does?

A: You need add parameter index_col for read column to index in read_csv.
Also you can convert index to DatetimeIndex by parse_dates.
#convert first column to index (python counts from 0)
data = pd.read_csv(url, index_col=[0], parse_dates=[0])

#convert column with name Date to index
data = pd.read_csv(url, index_col=['Date'], parse_dates=['Date'])

Another solution is use to_datetime and set_index:
data = pd.read_csv(url)
data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')


text:
Q: How to improve a complicated and poor SQL query I have the following tables for a messaging application:
`messaging_message`
 - thread_id
 - content
 - timestamp
 - sender_id

`messaging_messagestatus`
 - thread_id # though redundant here, makes messaging queries much easier
 - message
 - recipient_id
 - status

A few notes:

*

*Each message will have two messagestatus entries that refer to it, one for each user in the message thread.

*There may be multiple messages in a single message thread.

*A user may delete a message (status='deleted'), one user deleting a message will obviously not delete that same message for the other user in the thread.

Doing my best with a rudimentary knowledge of SQL, I have created a query to get:
Given a user, get all distinct non-deleted threads, showing 1) thread_id; 2) message_id // 3) timestamp // 4) content of the most recent message in that thread; 5) who the other person in the message thread is; and 6) whether the user sent the most recent message. Here is what I have so far:
SELECT thread_id, message_id, timestamp, content,
(SELECT DISTINCT recipient_id FROM messaging_messagestatus ms WHERE ms.thread_id=thread_id
  AND recipient_id !=4) as other_recipient,
(CASE WHEN sender_id=4 THEN True ELSE False END) as sent_last_message

FROM
( SELECT m.thread_id, recipient_id, timestamp, m.id as message_id, content, sender_id
    FROM messaging_messagestatus ms
    INNER JOIN messaging_message m
    ON ms.message_id = m.id
WHERE recipient_id = 4 AND m.thread_id NOT in
    ( SELECT thread_id FROM messaging_messagestatus WHERE status='deleted'
      AND recipient_id = 4)

ORDER BY timestamp DESC) combined GROUP BY thread_id

This query DOES WORK and will give me something like:
thread_id   message_id  timestamp       content         other_recipient   sent_last_message
2           3       2012-06-09 13:02:08 newest message  80                 1

With about 20k message rows / 35k status rows, the first query takes about 14s! Subsequent queries about 3s.

A: You should merge those tables.  Having two separate tables that have such directly related data is not good programming.  This would eliminate any joins between those two data sources and make querying data easier and faster.


text:
Q: Animate $2D$ butterfly curve in $3D$ There is a butterfly curve
$$r(\theta)=e^{\sin(\theta)}-2.4\cos(4\theta)+\sin \bigg( \frac{\theta}{12} \bigg)^5$$
PolarPlot[
  E^Sin[θ] - 2.4 Cos[4 θ] +Sin[θ/12]^5, {θ, 0, 24 Pi},
  PlotStyle -> {Thickness[0.004], Black}, PlotPoints -> 150]

How to animate it in 3D as a flying butterfly in  Mathematica?
(Sorry for my English)

A: r[t_] := E^Sin[t] - 24/10 Cos[4 t] + Sin[t/12]
x[t_, a_] := r[t] Cos@t Cos@a
y[t_, a_] := r[t] Sin@t
z[t_, a_] := x[t,a] Sign[x[t,a]] Sin@a

Manipulate[
 ParametricPlot3D[{x[t, a], y[t, a], z[t, a]}, {t, 0, 20 Pi},
  PlotRange -> 8 {{-1, 1}, {-1, 1}, {-1, 1}},
  ColorFunction -> Function[{x, y, z, u}, Hue@z]], {a, 0, Pi}]

A: (with apologies to Temple Fay)
Animate[ParametricPlot3D[{Cos[θ], Sin[θ], (1 + 2 Abs[t - 1]) (1 - Abs[t - 1])^2 - 1/2}
                         (Exp[Cos[θ]] - 2 Cos[4 θ] + Sin[θ/12]^5), {θ, 0, 24 π},
                         Axes -> None, Boxed -> False, PerformanceGoal -> "Quality",
                         PlotRange -> {{-4, 4}, {-4, 4}, {-3, 3}},
                         PlotStyle -> Directive[AbsoluteThickness[1], ColorData[97, 2]]],
        {t, 0, 2 - 1/20, 1/20}]

A: Here's one where we treat the abdomen differently.
First, look at this as a 2D parametric curve:
r[t_] := E^Sin[t] - 24/10 Cos[4 t] + Sin[t/12]
x[t_] := r[t] Cos[t]
y[t_] := r[t] Sin[t]

We can locate the abdomen by carefully partitioning the roots of x[t].
vals = First[Cases[Plot[Evaluate[x[t, 0]], {t, 0, 20π}], Line[l_] :> l, ∞]];

xroots = t /. FindRoot[x[t], {t, ##}, WorkingPrecision -> 30] & @@@
 Select[Partition[vals, 2, 1], Sign[#[[1, 2]]] != Sign[#[[2, 2]]] &][[All, All, 1]];

We now will define the abdomen through inequalities of our parameter t.
AbdomenQ[r_] := With[{s = Chop@y[r]},
  s < 0 || (s > 1 && s > Chop@y[r - 1/100])
]

abdomenextrema = Select[xroots, AbdomenQ];

abdomen = N[Or @@ (#1 <= t <= #3 & @@@
  Cases[Partition[xroots, 3, 1], {_, Alternatives @@ abdomenextrema, _}])];

Now when we define our 3D parametric equation, we need to make sure our point rotates if and only if it's on a wing.
r[t_] := E^Sin[t] - 24/10 Cos[4 t] + Sin[t/12]
(x[t_, a_] := If[#, r[t] Cos[t], r[t] Cos[t] Cos[a]]) &[abdomen]
y[t_, a_] := r[t] Sin[t]
(z[t_, a_] := If[#, 0., Sign[a] Abs[r[t] Cos[t] Sin[a]]])&[abdomen]

We also keep the abdomen black and make the wings colorful.
cf = Function[{x, y, z, t},
  If[#,
    Black,
    #2[Sqrt[x^2 + y^2]/6]
  ]
]&[abdomen, ColorData["FruitPunchColors"]];

And now we place this in a nicely formatted Animate.
Animate[ParametricPlot3D[{x[t, a], y[t, a], z[t, a]}, {t, 0, 20π},
   PlotRange -> 8 {{-1, 1}, {-1, 1}, {-1, 1}},
   PlotPoints -> ControlActive[100, Automatic],
   ColorFunction -> cf,
   ColorFunctionScaling -> False,
   Boxed -> False,
   Axes -> False
  ],
  {{a, 0.001}, -Pi/6, Pi/2},
  AnimationDirection -> ForwardBackward,
  AnimationRate -> 1
]


text:
Q: What is the origin of the phrase "buck naked"? The phrase buck naked is well known and means "completely naked". It is synonymous to butt naked and stark naked, both self-explanatory. However, there are a few confusing aspects to the etymology of buck naked.
My research brought me across a few plausible explanations:

*

*The word "buck" comes from buckskin, which is a deer/horse like animal.

*A slang term used by Americans against natives (Indians) for young males who often fought or hunted without clothing.

*It is a Bowdlerization of "butt naked" so that it can be used in public without causing unnecessary discomfort. A euphemism of some sort.
All three explanations seemed equally possible to me, and I failed to unearth an authoritative source to confirm any of them.
It would also be interesting to know if the phrase is more popular in some parts of the world than others.

A: I remembered reading about this subject a few years ago and I found the source:

The standard expression is "buck naked," and the contemporary "butt naked" is an error that will get you laughed at in some circles. However, it might be just as well if the new form were to triumph. Originally a "buck" was a dandy, a pretentious, overdressed show-off of man. Condescendingly applied in the US to Native Americans and black slaves, it quickly acquired negative connotations. To the historically aware speaker, "buck naked" conjures up stereotypical images of naked "savages" or—worse—slaves laboring naked on plantations. Consider using the alternative expression "stark naked."

A: The possibility you left out is that, rather than a bowdlerisation of "butt naked," it was an eggcorn of it; however, determining whether such a change was deliberate or accidental would be nigh on impossible.
Of the three, we can argue in favour of the second, though with the people referenced being as much those of African as of American origin.
We find "buck naked" in the 19th Century.
We do not find "butt naked" during that period.
We do not find it any earlier.
We do find "buck" being used to refer to men of African and of American Indian origin.
We do find the lack of clothing in some parts of Africa and America remarked upon. We also find slaves in the American South often working with little clothing. (We also find it overstated, a cartoon of an African might likely feature them as naked even if that would be highly unlikely in the scenario depicted — we're talking about people with some pretty strong racial prejudices here).
As such, we have a group of people being called "bucks" whose nakedness is often remarked upon. This suggests that the likelihood of it being the origin is quite high.
It's far from conclusive though, and you aren't going to get any better unless you hit documents from the period and manage to track it down better yourself.

A: From African American oral history as well as scholarly historical research, "buck naked" refers to a young, black male slave, "a buck," who was naked during a close arm inspection prior to sale. [A popular imagining of this historical practice can be seen in this still from the movie {Mandingo} (1975) starring Ken Norton. http://d1oi7t5trwfj5d.cloudfront.net/5e/2b/cb9b59aa498b8adc716394aad1a3/ken-norton-mandingo.jpg] (Although there were strict norms governing nakedness and decorum among Whites, the same norms did not apply to enslaved persons.) As commodities, slaves were frequently forced to endure invasive inspections (including of the genitals) to assess their health, sexual prowess, and potential fertility, similar to how we inspect cars today or horses were inspected prior to that. After the outlawing of the international importation of slaves in 1807, (forced) reproduction with other slaves or (master and slave) was the primary means of increasing slave stock. (Black women slaves were also similarly evaluated prior to sale and/or for the owners' sexual amusement and satisfaction.) This type of inspection was considered critical given the cost of investment. For instance, in Texas, in 1850, a prime field hand aged 18–31 would cost an average of $1,200, or $36,515 in 2014 dollars.http://www.tshaonline.org/handbook/online/articles/yps01
Black male slaves were referred to as 'bucks,' akin to young deer. [Enslaved Blacks were considered livestock under chattel slavery.] Native American men were also referred to as "bucks," both because of the association with buck skins and their being thought savage animals whose traditional habitat was the wild.


text:
Q: Convert ClamAV log output to JSON I'm working on a project using ClamAV to scan several CentOS 7 machines and a Ubuntu 16.04 machine. We need to integrate the output into a SIEM solution, but Clam's output is incompatible;
----------- SCAN SUMMARY -----------
Known viruses: 33840
Scanned directories: 145
Scanned files: 226
Infected files: 1
Data scanned: 54.22 MB
I/O buffer size: 131072 bytes
Time: 20.831 sec (0 m 20 s)

I imagine its possible to convert this output to json using pythong, but being relatively new to python I'm not sure where to start. Any help is appreciated.

A: here is a python solution
def clam_result_str_to_json(clam_result_str):

    clam_result_list = clam_result_str.split("\n")
    clam_result_list.remove('')

    results_marker = \
        clam_result_list.index("----------- SCAN SUMMARY -----------")

    hit_list = clam_result_list[:results_marker]
    summary_list = clam_result_list[(results_marker + 1):]

    r_dict = { "hits": hit_list }
    for s in summary_list:
        # in case of blank lines
        if not s:
            continue
        split_index = [c == ':' for c in s].index(True)
        k = s[:split_index].lower()
        k = k.replace(" ", "_")
        v = s[(split_index + 1):].strip(" ")
        r_dict[k] = v

    return r_dict

when clam is invoked with the -i option, this function takes this
/tmp/foo.tar.gz: Eicar-Signature FOUND

----------- SCAN SUMMARY -----------
Infected files: 1
Time: 0.004 sec (0 m 0 s)
Start Date: 2022:03:25 21:40:15
End Date:   2022:03:25 21:40:15

and turns it into this:
{
    "end_date": "2022:03:25 21:40:15",
    "hits": [
        "/tmp/foo.tar.gz: Eicar-Signature FOUND"
    ],
    "infected_files": "1",
    "start_date": "2022:03:25 21:40:15",
    "time": "0.004 sec (0 m 0 s)"
}

A: Using awk :
$ awk -vmax=$(wc -l < file) -F: '
    BEGIN{print "{"}
    NR>1{
        gsub(/^ /, "", $2);
        printf "%s",  "\t\042"$1"\042:\042"$2"\042"
        if (NR<max) {print ","}else{print "\n"}
    }
    END{print "}"}
' file

Output:
{
    "Known viruses":"33840",
    "Scanned directories":"145",
    "Scanned files":"226",
    "Infected files":"1",
    "Data scanned":"54.22 MB",
    "I/O buffer size":"131072 bytes",
    "Time":"20.831 sec (0 m 20 s)"

}


text:
Q: How can I save my drawings(such as rectangle, circle) from panel into image? How can I save my drawings(such as rectangle,circle) from panel into image?
I have tried this code but I don't know why it only gives me white image always:
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "bmp";
saveFileDialog.Filter = "Bitmap files|*.bmp";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
  int width = panel1.Width;
  int height = panel1.Height;
  Bitmap bitMap = new Bitmap(panel1.Width, panel1.Height);
  panel1.DrawToBitmap(bitMap, new Rectangle(0, 0, panel1.Width, panel1.Height));
  bitMap.Save(saveFileDialog.FileName);
}

A: Do not use CreateGraphics for drawing your graphic, since that is only a temporary drawing (it will get erased by other windows or if you minimize the the form, etc).
Use the panel's paint event to do your drawing:
panel1.Paint += panel1_Paint;

void panel1_Paint(object sender, PaintEventArgs e) {
  // draw stuff with e.Graphics
}

call the panel's Invalidate method to make the paint method get called again.


text:
Q: Laptop display automaticaly changes brightness, despite all options being set to not do it I'm on ACER laptop (v3-371 with Intel HD Graphics 5500), running Windows 10. The issue I'm struggling with is the screen brightness that keeps automaticaly adjusting when I'm running on battery. I've done a lot research but I'm still unable to fix the problem. Here is the list of the things I've done so far:

*

*Disabled "Display Power Saving Technology" in INTEL Graphics Control Power

*Disabled "Adaptive screen brightness" in Windows Advanced Power Options

*Uninstalled and re-installed the latest Intel HD Graphics drivers from the
ACER site (I was unable to install the drivers downloaded directly from the INTEL site - the install dialog box told me that I need to get my drivers from the laptop manufacturer's site)

A: Check BIOS/UEFI settings...There's probably something in there along the lines of "Adaptive Display Brightness" or "Adaptive Display Dimness" or some equivalent lenghty way of saying "auto-dimming".
I don't have any Acers here, so here's the abbreviated version:

*

*do a complete shutdown(look up Win 8/Win 10's "hybrid shutdown" if that doesn't mean anything to you).

*get into BIOS/UEFI settings (some variant on repeatedly tapping a key when you power on, usually one of F1/F2/Del/Esc)

*find something in the settings that mentions Brightness/Dimness and turn it off

*save and reboot


text:
Q: iPad Mini background refresh not working, other devices also running iOS 8.1 work fine I am fetching the location in the background and sending it to a server. It seems like my code works fine for all devices except iPad Mini (all device are iOS 8.1). It's sending data only for 15 to 20 minutes.

A: Maybe your iPad mini doesn't have GPS, only cellular version have it


text:
Q: Running Moqui on Tomcat over SSL (setting http-port and htts-port) - return code 302 I have a Tomcat server with SSL configured. I can access the Tomcat Web Application Manager, the connection is secured. Tomcat server is accessible on ports ports 80 and 443, and is dockerized (the container's ports are 8080 and 8443).
The application is working fine over http, no problems spotted.
Then I decided to switch to https. So I modified the MoquiProductionConf.xml web-app tag this way:
<webapp-list>
    <!-- NOTE: when you set https-enabled="true" make sure to set the http-port and https-port attributes -->
    <webapp name="webroot" http-port="80" http-host=""
            https-port="443" https-host="" https-enabled="true"
            require-session-token="true">
        <root-screen host=".*" location="component://webroot/screen/webroot.xml"/>
    </webapp>
</webapp-list>

The app is neither accessible on http:// nor on https://. I have not changed the http-host/https-host. The return code is 302 (according to tomcat's localhost_access_log).
Do I have to fill in the hosts as well?
Do I have to change anything else in the configuration? I found the web.xml file in the framework's WEB-INF folder, is there something in it that needs a modification.

A: For those searching for an answer - this one worked for me.
<webapp-list>
    <!-- NOTE: when you set https-enabled="true" make sure to set the http-port and https-port attributes -->
    <webapp name="webroot" http-port="80" http-host="<server_address>"
            https-port="443" https-host="<server_address>" https-enabled="true"
            require-session-token="true">
        <root-screen host=".*" location="component://webroot/screen/webroot.xml"/>
    </webapp>
</webapp-list>

Hope it helps someone.


text:
Q: How do i match with regex special chars that are not alphanumeric whilst ignoring emojis? i'm currently having an problem, i don't know how to make regex match special characters whilst ignoring emojis.
Example, i want to match the special chars that are not emojis in this string: ❤❤
currently as my regex i have
[^\x00-\x7F]+

Current output: ❤❤
Wanted output:
How would i go around fixing this?

A: Maybe, this expression might work:
$re = '/[\x{1f300}-\x{1f5ff}\x{1f900}-\x{1f9ff}\x{1f600}-\x{1f64f}\x{1f680}-\x{1f6ff}\x{2600}-\x{26ff}\x{2700}-\x{27bf}\x{1f1e6}-\x{1f1ff}\x{1f191}-\x{1f251}\x{1f004}\x{1f0cf}\x{1f170}-\x{1f171}\x{1f17e}-\x{1f17f}\x{1f18e}\x{3030}\x{2b50}\x{2b55}\x{2934}-\x{2935}\x{2b05}-\x{2b07}\x{2b1b}-\x{2b1c}\x{3297}\x{3299}\x{303d}\x{00a9}\x{00ae}\x{2122}\x{23f3}\x{24c2}\x{23e9}-\x{23ef}\x{25b6}\x{23f8}-\x{23fa}]/u';
$str = '❤❤';
$subst = '';

echo preg_replace($re, $subst, $str);

Output

The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.
Reference:
javascript unicode emoji regular expressions

A: Use the following unicode regex:
[^\p{M}\p{S}]+

*

*\p{M} matches characters intended to be combined with another character (here  ).

*\p{S} matches symbols (❤ in this case).

Demo

A: I think that your posts' title does not match it's body.
There is virtually no overlap between emoji and AlphaNum characters.
There are a couple of keycap emoji but since their sequence beyond
the first digits don't overlap the alphanum, it's enough just to put
a negative look ahead in front of the alphanum class.
'~(?![0-9]\x{FE0F}\x{20E3}|\x{2139})[\pL\pN]+~'
https://regex101.com/r/1JcUqY/1