text:
Q: Realtek can't separate headphone from frontspeaker I have an updated windows 10 pro running on an asus b150m-c/br (Intel B150 chipset Realtek ALC887) and I'm running in the strangest of bugs. My PC front speaker (rear panel, green) is mute and realtek can only see my headphone (front panel, green).
When I download Realtek driver from my manufacturer (https://www.asus.com/br/Motherboards/B150M-C-BR/HelpDesk_Download/) and I install it, the first step is unistalling previous Realtek and reboot.
After this reboot my system works! Except for the mic (rear panel, red) which is also mute. But if I restart or go trough with the instalation, it ceases to work again.
If I manually uninstall Realtek I do not have the same result (things doesn't work).
I tried to "separate all input jacks as independent input devices", but it's of no use.
I also have a TV plugged as a second monitor, but the tv works as intended.

A: After some struggle I uninstalled Realtek driver and used a generic Windows Driver. Using the driver as Windows High Definition audio solved all my problems and now I'm able to use both front speaker and headphone, and also bluetooth headphones and my mic.


text:
Q: How do I find the length attained by a bullet when fired by a rifle? The problem is as follows:

The horizontal range of a bullet fired by a rifle from a certain height above sea level is given by the minimum value of the function presented below:
$$f(x)=2\sec\left(\pi x-\frac{\pi}{4}\right)+1$$
in kilometers when, $-\frac{1}{12}\leq x \leq \frac{5}{12}$
With the given information, find the length attained by the bullet.

The alternatives given in my workbook are as follows:
$\begin{array}{ll}
1.&\textrm{4 km}\\
2.&\textrm{1 km}\\
3.&\textrm{3 km}\\
4.&\textrm{2 km}\\
\end{array}$
What I attempted to do in order to solve this problem was to use the given domain to reconstruct the function and hence having the range, and with that minimum value I can get what it is being asked. In other words the horizontal range of that bullet.
Since the domain is in this:
$-\frac{1}{12}\leq x \leq \frac{5}{12}$
Then:
$-\frac{\pi}{12}\leq \pi x \leq \frac{5\pi}{12}$
$-\frac{\pi}{12}\leq \pi x \leq \frac{5\pi}{12}$
$-\frac{\pi}{12}-\frac{\pi}{4}\leq \pi x - \frac{\pi}{4} \leq \frac{5\pi}{12}-\frac{\pi}{4}$
$-\frac{4\pi}{12}\leq \pi x - \frac{\pi}{4} \leq \frac{2\pi}{12}$
$-\frac{\pi}{3}\leq \pi x - \frac{\pi}{4} \leq \frac{\pi}{6}$
Now here's where it comes the source of controversy.
I'm assuming that I can "take the secant function" to that interval in order to get the range.
Which would yield.
$\sec\left(-\frac{\pi}{3}\right)\leq \sec \left(\pi x - \frac{\pi}{4}\right) \leq \sec \left(\frac{\pi}{6}\right)$
Since the negative sign is absorved by the secant function this will generate:
$2 \leq \sec \left(\pi x - \frac{\pi}{4}\right) \leq \frac{2}{\sqrt{3}}$
$4 \leq 2\sec \left(\pi x - \frac{\pi}{4}\right) \leq 2\frac{2}{\sqrt{3}}$
$4 +1  \leq 2\sec \left(\pi x - \frac{\pi}{4}\right)+1 \leq \frac{2 \cdot 2}{\sqrt{3}}+1$
The finally:
$5  \leq 2\sec \left(\pi x - \frac{\pi}{4}\right)+1 \leq \frac{4}{\sqrt{3}}+1$
But rewritting this doing the rationalization it would be:
$5 \leq f(x) \geq \frac{4\sqrt{3}+3}{3}$
Now:
$\frac{4\sqrt{3}+3}{3} \approx 3.3094$
But looking at the orientation of the signs it doesn't make sense. How it can possibly be that this result is greater than $4$? What went wrong here?.
Can someone help me here?. Or is it just that I did not got the right picture?.
I can spot that $4\,km$ appears in one of the choices But I have no idea if whether I got to the right answer or some critical concept I missunderstood here. Thus I require help to settle down this contradiction. Help please?. I'd also like to know that since I got this problem in my precalculus workbook I'd like that the answer would follow the similar approach given here and not use derivatives.

A: The function you are given determines the following domain for the secant function:
$$
\left[-\frac1{12}\pi-\frac\pi4,\frac5{12}\pi-\frac\pi4\right]=\left[-\frac{\pi}{3},\frac\pi{6}\right]
$$
On this interval the function $\sec (t)$ is positive and takes on the minimal value $1$ at $t=0$. To obtain the answer simply substitute the value into the equation.

A: Hint: a simpler way for solving this problem is taking the derivative of the function and after taking the value of $x$ such that $y$ of the line is mininum.

A: Combining some of the comments ...
Here is one conceptual error:

I'm assuming that I can "take the secant function" to that interval in order to get the range.

It is true that for any function $f,$ if $a=b=c$ then $f(a)=f(b)=f(c).$
But $\leq$ does not work the same as $=$.
From $a \leq b \leq c$ you get $f(a) \leq f(b) \leq f(c)$
if $f$ is a monotonically increasing function,
but not for functions $f$ in general.
In particular, the function $\sec(x)$ is sometimes decreasing and sometimes increasing.
The second conceptual error is unclear, but somehow you lost track of what the question asked. The question simply requires you to find the minimum value of
$$ f(x)=2\sec\left(\pi x-\frac{\pi}{4}\right)+1 $$
where $-\frac1{12} \leq x \leq \frac5{12}.$
You made some progress: you found that the input of the secant function in this formula,
$x - \frac\pi4$, is between $-\frac\pi3$ and $\frac\pi6.$
Now you need to find the minimum output value the secant function can have if its input is between $-\frac\pi3$ and $\frac\pi6.$
If you sketch the secant function over this interval, you should find that it is decreasing at the start and increasing at the end; the final value is less than the initial value, but the function's minimum value occurs at an input somewhere in between the two ends of the interval.
Once you identify that minimum value, multiply by $2$ and add $1.$
By the way, this question really has nothing to do with the range of a bullet or a rifle;
you would never use a function like this to compute such a thing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically created menu items position giving same item id in navigation drawer I have created menu items dynamically in navigation drawer by using following code.
   Menu m;
   navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        m = navigationView.getMenu();
        m.add("menu item 1");
        m.add("menu item 2");

which is working fine and items are being created dynamically. But when I want to get the position of clicked menu item it shows me "0" every time using following code.
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Toast.makeText(order.this , "pos is : " + id  ,Toast.LENGTH_LONG).show();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Any help would be appreciated. Kindly tell me where I am getting me wrong.
Thanks!

A: Use Menu.add() with more parameters.
From Documentation
https://developer.android.com/reference/android/view/Menu.html#add(int,int,int,java.lang.CharSequence)
use:
MenuItem add (int groupId,
                int itemId,
                int order,
                CharSequence title)

in your code give Unique itemId to each menuItem
menu.add(0, 0, 0, "menu item 1")
menu.add(0, 1, 0, "menu item 2")
menu.add(0, 2, 0, "menu item 3")


text:
Q: Changing the Accept header for a session with Chrome If I want to change the user agent string for an entire session, I can start Chrome from the command line with the user agent switch, e.g.
open ~/Applications/Google\ Chrome.app --args -user-agent="STRING"

and every request will use that string with no further input needed from me. I want to do something similar with the Accept header. There are extensions out there that do this per request and per tab/domain, but I want this done blanket fashion for an entire browsing session (not HTTP session).
Is there a way? I found a list of Chromium command line switches, but none appear to help with this
Any help is much appreciated.

A: also you can use EditThisCookie chrome extension
for more info  see :
https://chrome.google.com/webstore/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg?hl=en


text:
Q: Sync clock derived from AC power source I am developing a wireless device which stores data by sampling an Analogue sensor at a specific time. The only 'wires' to this device are the two power wires. I am using a 12V AC power supply and I am wondering if I can send a 'clock' signal using the power line. The clock rate I am looking to achieve is from 10Hz to 400Hz. Can anyone point me in the right direction of how to do this.
Many Thanks
Stuart.

A: AC power supplies convert voltage from mains power, which is 50/60Hz depending on where you live.  If you can use any clock between 10 and 400Hz, then you can produce a clock by feeding it into a comparator/Schmitt Trigger with a ground reference:

simulate this circuit – Schematic created using CircuitLab
If you need a specific frequency other than 50/60Hz that is a multiple of 50/60Hz, you can multiply/divide the frequency.  If you need adjustable frequency, you could use any sort of RC-controlled oscillator or a programmable timer/counter on a microcontroller.


text:
Q: Remove first and last line from files I am brand new to PHP and I have thousands of records I need to analyze. It appears that the first 2 lines and the last line of each record need to be removed. Is there some type of line count function that I could use to put each line into an array and then delete the first two and do like a max count to get the last line and then delete that? I am at a loss and appreciate any help. Thanks.

A: Assuming you're on a Unix/Linux host, you'd be better off using some simple shell tools to do this for you. Specifically wc -l, head, and tail.
for i in *.txt; do
    lines=`wc -l $i`
    tail $(($lines - 2)) $i | head $(($lines - 1)) > /fixed/files/$i
done

not tested, YMMV, etc... but should get the idea across.

A: <?php

$file = file("file.txt");

array_shift($file); // Removing the first line
array_shift($file); // Removing the second line

array_pop($file); // Removing last line

// Creating the new file:

$fp = fopen("newFile.txt", "a+");

for ($x=0; $x < sizeof($file); $x++)
{
fputs($fp, $file[$x]. "\n");
}

fclose($fp);

?>


text:
Q: Apache Spark worker executor EXITED with exit status 1 I have a Spark standalone setup (v 1.4.1) with 3 workers.
I have an application that read a stream from a Kafka Topic elaborate data and store it in another Kafka Topic.
Last night the application fell down and all worker was down.
The worker's logs report like the following:
16/02/04 21:02:10 INFO ExecutorRunner: Launch command: "/opt/jdk1.8.0_45/bin/java" "-cp" "/dati/spark-1.4.1-bin-hadoop2.4/sbin/../conf/:/dati/spark-1.4.1-bin-hadoop2.4/lib/spark-assembly-1.4.1-hadoop2.4.0.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-core-3.2.10.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-api-jdo-3.2.6.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-rdbms-3.2.9.jar" "-Xms1024M" "-Xmx1024M" "-Dspark.driver.port=52180" "-DenabledWorkerLog=false" "-Dcom.sun.management.jmxremote.port=54330" "-Dcom.sun.management.jmxremote.ssl=false" "-Dcom.sun.management.jmxremote.authenticate=false" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "akka.tcp://sparkDriver@driverHost:52180/user/CoarseGrainedScheduler" "--executor-id" "24279" "--hostname" "worker2" "--cores" "1" "--app-id" "app-20160201182749-0007" "--worker-url" "akka.tcp://sparkWorker@worker2:57853/user/Worker"
16/02/04 21:02:10 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160201182749-0007/24279/stdout with daily rolling
16/02/04 21:02:10 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160201182749-0007/24279/stderr with daily rolling
16/02/04 21:02:10 INFO Worker: Executor app-20160129184621-0001/1430 finished with state EXITED message Command exited with code 1 exitStatus 1
16/02/04 21:02:10 INFO Worker: Asked to launch executor app-20160129184621-0001/1431 for stream-elaboration
16/02/04 21:02:10 INFO ExecutorRunner: Launch command: "/opt/jdk1.8.0_45/bin/java" "-cp" "/dati/spark-1.4.1-bin-hadoop2.4/sbin/../conf/:/dati/spark-1.4.1-bin-hadoop2.4/lib/spark-assembly-1.4.1-hadoop2.4.0.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-core-3.2.10.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-api-jdo-3.2.6.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-rdbms-3.2.9.jar" "-Xms1024M" "-Xmx1024M" "-Dspark.driver.port=57297" "-DenabledWorkerLog=false" "-Dcom.sun.management.jmxremote.port=54326" "-Dcom.sun.management.jmxremote.ssl=false" "-Dcom.sun.management.jmxremote.authenticate=false" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "akka.tcp://sparkDriver@driverHost:57297/user/CoarseGrainedScheduler" "--executor-id" "1431" "--hostname" "worker2" "--cores" "1" "--app-id" "app-20160129184621-0001" "--worker-url" "akka.tcp://sparkWorker@worker2:57853/user/Worker"
16/02/04 21:02:10 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160129184621-0001/1431/stdout with daily rolling
16/02/04 21:02:10 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160129184621-0001/1431/stderr with daily rolling
16/02/04 21:02:11 INFO Worker: Executor app-20160201182749-0007/24279 finished with state EXITED message Command exited with code 1 exitStatus 1
16/02/04 21:02:11 INFO Worker: Asked to launch executor app-20160201182749-0007/24280 for stream-elaboration
16/02/04 21:02:11 INFO ExecutorRunner: Launch command: "/opt/jdk1.8.0_45/bin/java" "-cp" "/dati/spark-1.4.1-bin-hadoop2.4/sbin/../conf/:/dati/spark-1.4.1-bin-hadoop2.4/lib/spark-assembly-1.4.1-hadoop2.4.0.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-core-3.2.10.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-api-jdo-3.2.6.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-rdbms-3.2.9.jar" "-Xms1024M" "-Xmx1024M" "-Dspark.driver.port=52180" "-DenabledWorkerLog=false" "-Dcom.sun.management.jmxremote.port=54330" "-Dcom.sun.management.jmxremote.ssl=false" "-Dcom.sun.management.jmxremote.authenticate=false" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "akka.tcp://sparkDriver@driverHost:52180/user/CoarseGrainedScheduler" "--executor-id" "24280" "--hostname" "worker2" "--cores" "1" "--app-id" "app-20160201182749-0007" "--worker-url" "akka.tcp://sparkWorker@worker2:57853/user/Worker"
16/02/04 21:02:11 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160201182749-0007/24280/stdout with daily rolling
16/02/04 21:02:11 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160201182749-0007/24280/stderr with daily rolling
16/02/04 21:02:11 INFO Worker: Executor app-20160129184621-0001/1431 finished with state EXITED message Command exited with code 1 exitStatus 1
16/02/04 21:02:11 INFO Worker: Asked to launch executor app-20160129184621-0001/1432 for stream-elaboration
16/02/04 21:02:11 INFO ExecutorRunner: Launch command: "/opt/jdk1.8.0_45/bin/java" "-cp" "/dati/spark-1.4.1-bin-hadoop2.4/sbin/../conf/:/dati/spark-1.4.1-bin-hadoop2.4/lib/spark-assembly-1.4.1-hadoop2.4.0.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-core-3.2.10.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-api-jdo-3.2.6.jar:/dati/spark-1.4.1-bin-hadoop2.4/lib/datanucleus-rdbms-3.2.9.jar" "-Xms1024M" "-Xmx1024M" "-Dspark.driver.port=57297" "-DenabledWorkerLog=false" "-Dcom.sun.management.jmxremote.port=54326" "-Dcom.sun.management.jmxremote.ssl=false" "-Dcom.sun.management.jmxremote.authenticate=false" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "akka.tcp://sparkDriver@driverHost:57297/user/CoarseGrainedScheduler" "--executor-id" "1432" "--hostname" "worker2" "--cores" "1" "--app-id" "app-20160129184621-0001" "--worker-url" "akka.tcp://sparkWorker@worker2:57853/user/Worker"
16/02/04 21:02:11 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160129184621-0001/1432/stdout with daily rolling
16/02/04 21:02:11 INFO FileAppender: Rolling executor logs enabled for /dati/spark-1.4.1-bin-hadoop2.4/work/app-20160129184621-0001/1432/stderr with daily rolling
16/02/04 21:02:11 INFO Worker: Executor app-20160201182749-0007/24280 finished with state EXITED message Command exited with code 1 exitStatus 1
16/02/04 21:02:11 INFO Worker: Asked to launch executor app-20160201182749-0007/24281 for stream-elaboration

at the end of the log:
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "qtp291507283-42"
Exception in thread "qtp291507283-37" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "ExecutorRunner for app-20160201182749-0007/29488" java.lang.OutOfMemoryError: GC overhead limit exceeded

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "sparkWorker-scheduler-1"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "qtp291507283-38" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "JMX server connection timeout 81"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "JMX server connection timeout 81"

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "sparkWorker-10"

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "qtp291507283-40"
Exception in thread "qtp291507283-35" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"

Exception in thread "qtp291507283-39" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "qtp291507283-41" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "qtp291507283-36" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "RMI TCP Connection(idle)"

....

Running:
ps aux | grep "worker"

the process is still active, but I can't see it on sparkUI.
Why are worker executor restart so frequently?

A: The logs show multiple java.lang.OutOfMemoryError: GC overhead limit exceeded messages, which means your executors throw errors which cause them to exit.
This error means your program spends too much time running GC (see more details here). To resolve this - you can try one of these paths:

*

*The brute-force way would be disabling this safety by adding -XX:-UseGCOverheadLimit to your executors' JVM options, but it might leave your application doing mostly GC, hence running very slowly

*Analyze your job's memory usage and optimize it - your code might be consuming more memory than needed, forcing the GC to work too hard

*Tune your memory settings - for example, if you can increase heap space for the executors, pressure on GC might be reduced

A: You're essentially running out of memory to run the process smoothly. Options that come to mind:

*

*Specify more memory like you mentioned, try something in between like -Xmx512m first.

*Debug your code to find out possibilities of memory leaks.

Why are worker executor restart so frequently?

You are using Spark Streaming which is built on Spark, so it enjoys the same fault-tolerance for worker nodes that means if the worker goes down due to some unexpected error as in your case Spark engine will attempt to restart it.


text:
Q: Undesired shortcut shown in the Recent Opened Programs in start menu on Windows 7 My software has two .EXE files : A.exe and B.exe. After installed on Window 7, the shortcut to A.exe is always shown in the start menu. (I don't know if 'Start menu' is the correct name or not, what I mean is the area above 'All Programs').
The menu in my computer looks like:

Getting Started
Windows Media Center
Calculator
Sticky Notes
Snipping Tool
Paint
A                   <-- My program, and I want 'B' to be shown here
All programs

How can I change my installer to make B.exe shown instead of A.exe?
Best regards,
Zach

EDIT
I found a similar post on this problem. The URL is
http://digital.ni.com/public.nsf/allkb/779545E28688F5CD862576430042680E?OpenDocument
except that in the article the user is using NI installer.

A: Here is answer from Microsoft:
http://msdn.microsoft.com/en-us/library/windows/desktop/hh127439(v=vs.85).aspx
or here (how to do it from msi)
http://blogs.msdn.com/b/windows_installer_team/archive/2009/09/02/windows-7-taskbar-support-with-the-msishortcutproperty-table.aspx?Redirected=true


text:
Q: Asus G73SW's backlit keyboard doesn't work, nor does the FN+F3- & F4 hotkeys Asus G73SW's backlit keyboard doesn't work, nor does the FN + F3 and F4 hotkeys.
Any solutions for this?

A: Perhaps this would work for your backlit keyboard. Just came across it.
http://ubuntuforums.org/showthread.php?t=1752900


text:
Q: Good Sources for Lecture Movies in Set Theory, Logic and Philosophy of Maths Of course as any other researcher I'm not able to attend any scientific event in my research area. But it is always interesting and useful to watch the lecture movies of these events.

I will appreciate if you help me by introducing some links and sources to some lecture movies (or any other type of movies including debates, documentaries, etc.) particularly related to set theory, Logic and philosophy of maths.

A: Gresham College website is a general source for Public Scientific Lectures including different branches of logic.
See also these video lectures from Institute for Advanced Study:

*

*Voevodsky - What if Current Foundations of Mathematics are Inconsistent?

*Voevodsky - Univalent Foundations: New Foundations of Mathematics

*Magidor - Can the Continuum Problem be Solved?

*Kojman - Does Infinite Cardinal Arithmetic Resemble Number Theory?

*Bombieri - The Mathematical Infinity
And these with Hugh Woodin and Keith Devlin participation in "Infinity Program".
Here is a lecture by Justin Moore on Forcing.
The following sets of set theory video tapes are from Fields Institute video archive.

*

*Three lectures of Foreman on large cardinals.

*Workshop on Iterated Forcing and Large Cardinals.

*Workshop on Forcing Axioms and their Applications.
Note: In above links click on the "static" button beside each title to watch the tape.

A: Here's something to start with.
Logic at Harvard - Exploring the Frontiers of Incompleteness.

A: Another good alternative are the video lectures from this web page.

A: Look at the Mathematics Illuminated series (Magnet link: magnet:?xt=urn:btih:e7d9f0ab4e6bf8e9b7cadf37d0e6ba3285172352 ). Individual segments of that series can also be found on YouTube.


text:
Q: How to reshape multi index in a pandas dataframe like an excel pivot table I have a dataframe where I have a multindexing of 2 or 3 levels and I would like to reshape it as the usual pivot table in Excel to be able to do 'inter' Grand Total (see the image).
I tried with the df.pivot_table() and the multiindexing through .groupby() but nothing conclusive
I only have that DataFrame

Here is the code
 df = pd.DataFrame({'Products': ['Products A','Products A',
                           'Products A','Products B', 'Products B',
                           'Products A', 'Products B', 'Products A'],

                   'Sub Products': ['Phone A','Phone B',
                                   'Laptop B','Phone B', 'Laptop
                                    B','Phone A','Phone B','Laptop A'],

                   'Color' : ['Green',  'Blue','Red',
                            'Red','Red','Blue','Green','Blue']})

df.groupby(['Products','Sub Products','Color' ]).count()

If you have any idea it would be super helpful !
Thanks.

A: In pandas you typically wouldn't include this aggregate information as part of the same grouped DataFrame, you would get it with a separate command afterwards, for instance:
grand_total = df.sum()
Note that the data you supplied in your question doesn't quite produce what you have in your images. The numbers differ and some of the A/B labeling was inconsistent. Below I edited the code you provided reproduce something that matches your images, assuming each row of the example data you supplied is one "unit".
df = pd.DataFrame(
    {
        "Products": [
            "Products A",
            "Products A",
            "Products A",
            "Products B",
            "Products B",
            "Products A",
            "Products B",
            "Products A",
        ],
        "Sub Products": [
            "Phone A",
            "Phone A",
            "Laptop A",
            "Phone B",
            "Laptop  B",
            "Phone A",
            "Phone B",
            "Laptop A",
        ],
        "Color": ["Green", "Blue", "Red", "Red", "Red", "Blue", "Green", "Blue"],
    }
)
df['Count'] = 1
df = df.groupby(['Products','Sub Products','Color' ]).sum()

# To view the totals at any particular level of the multi-index
display(df.groupby(level=0)['Count'].sum())
display(df.groupby(level=1)['Count'].sum())
display(df.groupby(level=2)['Count'].sum())

This will give you the information you want... However from your comment, it sounds like you just want a particular display format. This is possible with the code below, but it loses the actual organization of the multi-indexed Data Frame:
out = pd.DataFrame(columns=['Product','Count'])
for n1, d1 in df.groupby(level=0):
  out = pd.concat([out,pd.DataFrame({"Product": n1, "Count": d1.sum().values})])
  d1 = d1.droplevel(0)
  for n2, d2 in d1.groupby(level=0):
    out = pd.concat([out,pd.DataFrame({"Product": n2, "Count": d2.sum().values})])
    d2 = d2.droplevel(0)
    for n3, d3 in d2.groupby(level=0):
      out = pd.concat([out,pd.DataFrame({"Product": n3, "Count": d3.sum().values})])
display(out)

yields:

Product Count
0   Products A  5
0   Laptop A    2
0   Blue    1
0   Red 1
0   Phone A 3
0   Blue    2
0   Green   1
0   Products B  3
0   Laptop  B   1
0   Red 1
0   Phone B 2
0   Green   1
0   Red 1

even better, here is the recursive version of the above:
# recursive version for arbitrarily deep multi-index
def traverse_multiindex(d, out):
  for n1, d1 in d.groupby(level=0):
    out = pd.concat([out,pd.DataFrame({"Product": n1, "Count": d1.sum().values})])
    if (d1.index.nlevels>1):
      d2 = d1.droplevel(0)
      out = traverse_multiindex(d2, out)
  return out

# initialize empty
out = pd.DataFrame(columns=['Product','Count'])
out = traverse_multiindex(df, out)
display(out)


text:
Q: how to create a httpGate with Obserservable I have multiple requests which I want to pause until the authenticate http request has been confirm. This means I should have a http gate which request can go thru without having to auth and some will wait until authenticate token comes back.
I thought of using switchmap like below code but then it will not work because a observable switch with a return value.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 return next.handle(req)
  .switchMap((event: HttpEvent<any>, index: number): Observable<HttpEv

ent<any>> => {

// without the **req.url.indexOf('/index')>-1**
//// Error Meassage: ***You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.***

   if(this.token || req.url.indexOf('/index')>-1) {
    return Observable.of(event);
   }
  })
  .do(
   next: function(data){
    console.log(data);
   },
   error: function(error: HttpErrorResponse){
    // retry
    // or handling data
   }
  );

Error MESSAGE
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

A: Instead of do it from intercept(), I would recommend you create your own ApiService, expose a few methods and make all of your HTTP calls from there.
Inside your ApiService, you could have for example:
Get(url: string): Observable {
  return of(0).pipe(
    switchMap(() => this.waitForAuth()),
    switchMap(() => this.$http.get(url))
  );
}

So every time you call your endpoint, your request will hang there until the user is authenticated. Or it'll make the call immediately if the user is already authenticated.


text:
Q: MySQL - Storing groups the user is in I have a website that assigns user to groups and each user can be in unlimited number of groups.
Example:
User A:

*

*Chess Group

*String Orchestra Group

*Basketball Group

User B

*

*Football Group

*Chess Group

Currently, my table structure is as follows:
Table: login

*

*id (auto-increment)

*username

*password

I'm considering storing PHP serialise array by having a new row in the table login. However, editing a user's groups would be difficult as I would have to unserialise it then serialise it again.
Or would it be better to store the groups in a new table entirely?
What is the fastest and most efficient way to store the groups that each user belongs to?
This method needs to be easy when updating the groups and also fast when querying.
Hope that there's a better method than serialise.

A: What you're describing is called a many-to-many relationship (each group has multiple members, and each person is a member of multiple groups.) The usual approach would be to have a second table for groups, indexed by a unique group ID and storing all information about each group except membership, and a third table for membership.
The membership table (known as an "intersection entity") has as its columns the primary keys of the other two tables, that is, login_id and group_id. Its primary key would be the concatenation of both its columns (PRIMARY KEY (login_id, group_id)) and each of its columns would also be a foreign key referencing one of the other tables.
This situation is well-known and well-studied, and in fact is about the second thing you learn when you begin to study normalization of database tables.
An example might be
CREATE TABLE login
(
  id INT AUTO_INCREMENT,
  username VARCHAR(255),
  password VARCHAR(255),
  -- other columns go here
  PRIMARY KEY (id)
);

CREATE TABLE groups
(
  id INT AUTO_INCREMENT,
  name VARCHAR(255),
  description TEXT,
  -- other columns go here
  PRIMARY KEY (id)
);

CREATE TABLE membership
(
  login_id INT,
  group_id INT,
  -- possibly more columns, or perhaps not
  PRIMARY KEY (login_id, group_id),
  CONSTRAINT member_user FOREIGN KEY (login_id) REFERENCES login (id),
  CONSTRAINT member_group FOREIGN KEY (group_id) REFERENCES groups (id)
);

The foreign keys on membership ensure that a user cannot be a member of a group unless both the user and the group already exist. The composite primary key for membership ensures that a given person can belong to a given group only once; neglecting this point can lead to some really bizarre problems when you try to query the tables later.
Hope that helps.


text:
Q: Common-LISP - Subtraction I have this function:
(defun test (variable)
  (cond
    ((null variable) nil)
    ((< (- 12 (other-function variable) 3) 0) 1)
    (t (- 12 (other-function variable) 3))
  )
)

The idea is, if the result of the subtraction of 12 with the value of the function with 3 is less than 0, it returns 1. Else, it will just make the subtraction.
The "other-function" returns a number.
When i run this function, lispworks freezes. But if i run the function without the first condition:
(defun test (variable)
  (cond
    ((null variable) nil)
    (t (- 12 (other-function variable) 3))
  )
)

it makes the subtraction without any problem.
Can someone help?
Thanks.
EDIT:
I tried this way with let:
(defun test (variable)
(let (x (other-function variable))
  (cond
    ((null variable) nil)
    ((< (- 12 x 3) 0) 1)
    (t (- 12 x 3)))
  )
)

But i still got the same problem with lispworks wich is, it freezes. When i run without the following condition:
 ((< (- 12 x 3) 0) 1)

This function works correctly.

A: Unless you come up with your full code and a test case, this can't be reproduced.
CL-USER 1 > (lisp-implementation-type)
"LispWorks"

CL-USER 2 > (defun test (variable)
              (cond
               ((null variable) nil)
               ((< (- 12 (other-function variable) 3) 0) 1)
               (t (- 12 (other-function variable) 3))))
TEST

CL-USER 3 > (defun other-function (foo) (+ foo 1))
OTHER-FUNCTION

CL-USER 4 > (test 5)
3

CL-USER 5 > (test 500)
1

Also: LispWorks usually does not 'freeze' on an error.


text:
Q: Excel VBA single message box for all empty cells I am trying to return the "titles" of the cells and not the address of all cells that are empty in the range below, or in the form below aswell.
I would like to display a single message box listing all the returned titles of the cells (I gave the titles above the cells) if there are any.
So, instead of Range("C17, E23"), I'd like to show the title of the cell.
Example:
Range ("C17") = "Nome/Razão Social"
Range ("E23") = "Celular"
Range and title of the cells: https://imgur.com/a/V9qU5Zb
Code run perfect, but I'd like to improve like I said above.
Code running: https://imgur.com/a/MMdgtvb
Thanks!

Dim C As Range
Dim MsgStr As String
Dim rng As Range

'Define which cell must not be empty in the range below
Set rng = Planilha4.Range("C17, E23")

'Check every cell in the range
For Each C In rng
    If C.Value2 = "" Then
        If MsgStr = "" Then
            MsgStr = C.Address(False, False)
        Else
            MsgStr = MsgStr & "," & C.Address(False, False)
        End If
    End If
Next C

Dim lLastComma As Long: lLastComma = InStrRev(MsgStr, ",")
If lLastComma > 0 Then: MsgStr = Left(MsgStr, lLastComma - 1) & Replace(MsgStr, ",", " and ", lLastComma, 1)
MsgBox MsgStr & " cell" & IIf(lLastComma > 0, "s are ", " is ") & "empty"

'MsgBox MsgStr & " cells are empty", vbExclamation

End Sub

A: Here's an approach using " Named Range" 's.
Set up your names in the "Name Manager".  You could either use one Name for each field, and ensure the heading is always offset at a specific place (eg previous row, same column), or use two Names for each field (in which case the header can be anywhere - much more difficult to maintan in my opinion)
Better still, use a specific format for the Names so you don't have to manage the Fields in two places (Name Manager and Code)
I've used Names formatted as "Field#_Required".  Set up in Name Manager like this

Then this code will process all Workbook scoped Named Ranges looking for Names with the format "Field*_Required" that refer to a range on the specified sheet.  Headers are assumed to be in the same column, previous row.
Sub Demo()
    Dim ws As Worksheet
    Dim nm As Name
    Dim MsgStr As String
    Dim LastComma As Long

    Set ws = Worksheets("YourForm")  ' set to the Form sheet

    ' Check every named range
    For Each nm In ActiveWorkbook.Names
        If nm.Name Like "Field*_Required" Then
            If nm.RefersToRange.Worksheet Is ws Then
                If IsEmpty(nm.RefersToRange.Value2) Then
                    MsgStr = MsgStr & ", " & nm.RefersToRange.Offset(-1, 0).Value2
                End If
            End If
        End If
    Next

    If MsgStr <> vbNullString Then
        MsgStr = Mid$(MsgStr, 3) ' strip leading ", "
        LastComma = InStrRev(MsgStr, ",")
        If LastComma > 0 Then
            MsgStr = Left$(MsgStr, LastComma - 1) & _
                     Replace$(MsgStr, ",", " and", LastComma, 1)
        End If
        MsgStr = MsgStr & " cell" & IIf(LastComma > 0, "s are", " is") & " empty"
        MsgBox MsgStr, vbCritical + vbOKOnly, "Missing Fields!"
    End If
End Sub

A: Named ranges aren't the solution here. You want to enter "E23" and return "Celular". That is a dictionary's job. If you don't want to set up a dictionary a simple array might do, like
Dim Dict(1,10) As Variant
Dict(0, 0) = "E23"
Dict(1, 0) = "Celular"
Dict(0, 1) = "C17"
Dict 1, 1) = [Whatever]

If Dict were a dictionary you could call "Celular" by the name of "E23". If it's an array, as above, you can use an Enum to define its position in the array by another name.
Edit Feb 10, 2019 ======================
I set up a worksheet called "Dict" .
Now you can run code like below. Remember, however, that you need to set a reference to MS Scripting Runtime.
Option Explicit

Enum Nda                                ' Dictionary array
    NdaAddress
    NdaCaption
    NdaCapCell
    NdaTip
End Enum

Sub CreateDict()
    ' https://excelmacromastery.com/vba-dictionary/

    Dim Dict As Scripting.Dictionary
    Dim Arr As Variant
    Dim R As Long, C As Long
    Dim DictVal() As String

    Set Dict = New Scripting.Dictionary
    Arr = Worksheets("Dict").Range("A2:E5").Value
    For R = 1 To UBound(Arr)
        ReDim DictVal(1 To UBound(Arr, 2) - 1)
        For C = 2 To UBound(Arr, 2)
            DictVal(C - 1) = Arr(R, C)
        Next C
'        Debug.Print Arr(R, 1), Join(DictVal, "|")
        Dict.Add Arr(R, 1), Join(DictVal, "|")
    Next R

    Dim Key As Variant
    For Each Key In Dict.Keys
        Debug.Print Key,
        DictVal = Split(Dict(Key), "|")
        Debug.Print DictVal(NdaAddress), DictVal(NdaCaption), DictVal(NdaCapCell), DictVal(NdaTip)
    Next Key
End Sub

The idea is that the Key "Tel" will give you the address of the cell, the adress of the caption cell, the caption itself and a control tip. Add or reduce as desired/required. Consider using a small utility function to retrieve the part you want.
Debug.Print DictItem(Dict("Name"), NdaCaption)
Private Function DictItem(DictKey As String, _
                          Itm As Nda) As String
    DictItem = Split(DictKey, "|")(Itm)
End Function


text:
Q: How can I jump to the error line in Vscode Just like Intellij idea what should I do to go to the error line just like intellij idea in vscode
vscode debug info
idea debug info

A: *

*Open the View menu

*Select the Problems menu item

*Press the Enter key to move to the first problem

*Press F8 to move to the next problem

Alternatively, the keyboard shortcut is CTRL + SHIFT + M. You might want to look at the official quick start guide.


text:
Q: DateTimeFormatter zero out empty is there a way to have a DateTimeFormatter like that
DateTimeFormatter.ofPattern("HH:mm")

and it should convert to a LocalDateTime and just zero out whats missing?
Actually on Joda there was DateTimeFormat which gave back a DateTime and not a exception. Is there any equivalent to that?
val formatter = org.joda.time.format.DateTimeFormat.forPattern(pattern)
formatter.parseDateTime(data).toDate

will always yield a real date no matter what the pattern is while on java8 it says its missing LocalDate.
Actually the pattern should be variable so that people could either insert HH:mm and dd.MM.yyyy and always get a LocalDateTime, that should be initalized / defaulted to 1970-01-01T00:00.
So doing:
// with pattern HH:mm
formatter.parse("00:00") should yield LocalDateTime.of(1970, 01, 01, 0, 0)

// with pattern YYYY-mm
formatter.parse("2016-11") should yield LocalDateTime.of(2016, 11, 01, 0, 0)

A: There are no built-in defaults. You have to provide the missing values.
// Parse HH:mm
LocalDateTime ldt1 = LocalTime.parse("12:34")
                              .atDate(LocalDate.of(1970, 1, 1));
System.out.println(ldt1); // Prints 1970-01-01T12:34

// Parse YYYY-mm
LocalDateTime ldt2 = YearMonth.parse("2016-11")
                              .atDay(1)
                              .atStartOfDay();
System.out.println(ldt2); // Prints 2016-11-01T00:00

Notice that you didn't even need a DateTimeFormatter for any of them.

UPDATE
If you must use DateTimeFormatter, then you can create one using DateTimeFormatterBuilder, where you can supply missing values using the parseDefaulting() method.
// Parse HH:mm
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
        .appendPattern("HH:mm") // other time fields default to 0, see "Resolving"
        .parseDefaulting(ChronoField.EPOCH_DAY, 0) // short for 1970-01-01
        .toFormatter();
LocalDateTime ldt1 = LocalDateTime.parse("12:34", formatter1);
System.out.println(ldt1); // Prints 1970-01-01T12:34

// Parse YYYY-mm
DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
        .appendPattern("uuuu-MM")
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) // see resolveDate()
        .parseDefaulting(ChronoField.NANO_OF_DAY, 0) // short for 00:00:00.000000000
        .toFormatter();
LocalDateTime ldt2 = LocalDateTime.parse("2016-11", formatter2);
System.out.println(ldt2); // Prints 2016-11-01T00:00

As for which fields are required for successful parsing, see:

*

*DateTimeFormatter - Resolving

*IsoChronology.resolveDate()

A: Just in case this solution works for me but I doubt it's not a "generic" answer since I only needed LocalDateTime and its also scala:
object MyDate {
  def parse(text: CharSequence, formatter: DateTimeFormatter): MyDate = new MyDate(formatter.parse(text))
}

class MyDate(accessor: TemporalAccessor) {

  private[this] def getOrDefault(field: TemporalField, default: Int): Int = {
    if (accessor.isSupported(field)) accessor.get(field) else default
  }

  def toLocalDateTime: LocalDateTime = {
    val year: Int = getOrDefault(ChronoField.YEAR, 1970)
    val month: Int = getOrDefault(ChronoField.MONTH_OF_YEAR, 1)
    val day: Int = getOrDefault(ChronoField.DAY_OF_MONTH, 1)
    val hour: Int = getOrDefault(ChronoField.HOUR_OF_DAY, 0)
    val minute: Int = getOrDefault(ChronoField.MINUTE_OF_HOUR, 0)

    LocalDateTime.of(year, month, day, hour, minute)
  }

}


text:
Q: Is the expression "to get understood" correct? Can I say

Get yourself understood.

with the sense of "make yourself understood"?
Are both correct? Is there a difference in meaning between the two?

A: Actually it depends to the situation. If the situation refers the future no matter how long it is to be happened, "to get understood" is correct. If the situation refers to the past, "to get understood" is absolutely wrong.


text:
Q: how to set ellipsize to two lines or multilines of textview in java android I need to set ellipsize=end to TextView which is allowed to expand on two lines.
I've tried this code:
<TextView
    android:id="@+id/carouselTitle"
    android:layout_width="228dp"
    android:layout_height="40dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="90dp"
    android:layout_marginRight="0dp"
    android:layout_marginTop="4.5dp"
    android:ellipsize="end"
    android:maxLines="2"
    android:textSize="24sp"
    android:textStyle="bold" >
</TextView>

Please reply with an example.

A: <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:ellipsize="marquee"
 android:singleLine="false"
 android:maxLines="2"
 android:text="here is my text" />

A: This one will be work:
<TextView
    android:id="@+id/carouselTitle"
    android:layout_width="228dp"
    android:layout_height="40dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="90dp"
    android:layout_marginRight="0dp"
    android:layout_marginTop="4.5dp"
    android:ellipsize="end"
    android:maxLines="2"
    android:singleLine="false"
    android:textSize="24sp"
    android:textStyle="bold" >
</TextView>

The only thing you missed is android:singleLine="false".
And I recommend to put android:gravity="center_vertical" for better UI. If the text just on one line, it will be center vertically.


text:
Q: ubuntu 16.04LTS compile obfuscator-llvm cmake version 3.5.1
ubuntu 16.04LTS
I want to compile llvm on ubuntu follow  git wiki:
$ git clone -b llvm-4.0 https://github.com/obfuscator-llvm/obfuscator.git
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release ../obfuscator/
When I execute cmake -DCMAKE_BUILD_TYPE=Release ../obfuscator/,report ab error:
-- Performing Test CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG
-- Performing Test CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG - Failed
CMake Error at cmake/modules/AddLLVM.cmake:1163 (add_custom_target):
  add_custom_target cannot create target "check-llvm-bindings-ocaml"
  because another target with the same name already exists.The
  existing target is a custom target created in source directory
  "/home/ryu/Ollvm/obfuscator/test". See documentation for policy
  CMP0002 for more details.
Call Stack (most recent call first):
  cmake/modules/AddLLVM.cmake:1226 (add_lit_target)
  test/CMakeLists.txt:150 (add_lit_testsuites)

I don't konw what check-llvm-bindings-ocaml is,and how cam I solve this problem? Can you help me? Thank you, thank you, thank you!!!

A: I had the same problem and the bellow command can solve it:
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release DLLVM_INCLUDE_TESTS=OFF

FYI:
https://github.com/obfuscator-llvm/obfuscator/issues/71


text:
Q: What is the remainder when 50! Divided by 47^2? I tried to solve it by Wilson theorem and I got 41 but answer is 1927.

A: You've probably found $$\frac{50!}{47}\equiv 41\pmod{47}$$ but you were looking for
$$50!\equiv 41\cdot 47\equiv 1927\pmod{47^2}$$


text:
Q: Select and GroupBy I have a table with the following fields
ID
fk_siteID
VisitDate

I want to write a query with LINQ that returns me the number of records in a day with a specific SiteID. For example if siteid=1 show me
12.1.2014   6
13.1.204    8

I wrote this query
 var n = from a in db.CompanyWebsiteUsers
         group a by EntityFunctions.TruncateTime(a.VisitDate) into g
         orderby g.FirstOrDefault().VisitDate
         where  g.FirstOrDefault().fk_siteID == WebsiteID
         select new
         {
             key = g.Key,
             dayofweek = SqlFunctions.DateName("weekday", g.Key),
             count = g.Count()
         };
grdDailyRes.DataSource = n;
grdDailyRes.DataBind();

The result that show me this query:
when 2 record is in my table that VisitDate field's of these record are same one of them with siteid=1 and second siteid=2.
If websiteid is 1 or is 2 this query count first of them.

A: You only check the first item in a group, but you have to check the other items as well. The simplest solution is to move the where statement, i.e.
var n = from a in db.CompanyWebsiteUsers
                    where  a.fk_siteID == WebsiteID
                    group a by EntityFunctions.TruncateTime(a.VisitDate) into g
                    orderby g.FirstOrDefault().VisitDate
                    select new


text:
Q: Power Query: sort by custom list I have a list of time seasons within school years:
"Fall 12-13",
"Winter 12-13",
"Spring 12-13",
"Fall 13-14",
etc.

I want to sort a large number of rows chronologically based on these values. In Excel it is possible to sort by a custom list where I simply input the order that I want the items to be sorted by.
I need that same functionality in Power Query but I have not yet figured out how to do this. I have only been able to set sort order to Order.Ascending or Order.Descending.
Is there a good way to implement sort-by-custom-list in Power Query?

A: I don't have enough reputation to address Ron Rosenfeld's question directly, but here's the answer:
You can implement the second argument as a list of functions as well. The columns will be sorted in the order you provide them in the list. E.g Column, Column1, Column2 in the example below.
= Table.Sort(Table,{ each List.PositionOf({"Fall 12-13", "Winter 12-13", "Spring 12-13", "Fall 13-14"}, [Column]), {"Column1",Order.Ascending}, {"Column2",Order.Ascending}})

A: Make a separate table with two fields: Season and SortOrder. Season is your text and SortOrder will be an integer indicating the order. Then join your existing table to this one on Season, include the SortOrder column, and sort on it.

A: The second argument to Table.Sort can also be a function: either a function that takes two rows and returns an ordering between them (a la strcmp) or a function that takes a single row and returns the value that should be used for comparisons. So one way to sort the values you describe would be to say
= Table.Sort(Table, each List.PositionOf({"Fall 12-13", "Winter 12-13", "Spring 12-13", "Fall 13-14"}, [Column]))


text:
Q: How do I get my SQL results to appear in one table instead of two within PHP/HTML I have a PDO connection to a database that returns any results for an item number that is searched. It currently returns each instance in its own table but i would like to see all instances in one table. Here is my code.
if (count($resultssample) > 0) {
        echo "
";
        echo "Number in the business: ".count($resultssample)."
";
        echo "
";
        foreach ($resultssample as $r) {
            echo "
";
            echo "
";
            echo  "
";
            echo    "site name	";
            echo    "location name	";
            echo    "creation time	";
            echo    "creation date	";
            echo    "damage status	";
            echo    "colour	";
            echo    "inventory status	";
            echo    "notes	";
            echo  "
";
            echo "
";
            echo "
";
            echo  "
";
            echo    "". $r['site_name'] ."	";
            echo    "". $r['location_name'] ."	";
            echo    "". $r['CreationTime'] ."	";
            echo    "". $r['CreationDate'] ."	";
            echo    "" . $r['damage_status'] . "	";
            echo    "" . $r['colour'] . "	";
            echo    "" . $r['inventory_status'] . "	";
            echo    "" . $r['Notes'] . "	";
            echo  "
";
            echo "
";
            echo "
";
        }
      } else {
        echo "No results found";
      }

How can this be achieved I cant currently get my head around it.
Any help would be greatly appreciated.

A: All you have to do is move table header out of the foreach loop:
if (count($resultssample) > 0) {
        echo "
";
        echo "Number in the business: ".count($resultssample)."
";
        echo "
";

        echo "
";
        echo "
";
        echo  "
";
        echo    "site name	";
        echo    "location name	";
        echo    "creation time	";
        echo    "creation date	";
        echo    "damage status	";
        echo    "colour	";
        echo    "inventory status	";
        echo    "notes	";
        echo  "
";
        echo "
";
        echo "
";

        foreach ($resultssample as $r) {

            echo  "
";
            echo    "". $r['site_name'] ."	";
            echo    "". $r['location_name'] ."	";
            echo    "". $r['CreationTime'] ."	";
            echo    "". $r['CreationDate'] ."	";
            echo    "" . $r['damage_status'] . "	";
            echo    "" . $r['colour'] . "	";
            echo    "" . $r['inventory_status'] . "	";
            echo    "" . $r['Notes'] . "	";
            echo  "
";

        }

        echo "
";
        echo "
";

    } else {
        echo "No results found";
    }


text:
Q: Error: Unable to resolve module stream from C:\**\node_modules\cipher-base\index.js: stream could not be found within the project The following error showed in my metro bundler when I run react-native with npm plugin @woocommerce/api library. It's currently active plugin for woocommerce rest api.
I've searched many solutions about the stream dealing with cipher-base. It doesn't work. I've also deleted node_modules and reinstall again. And then, npm start -- --reset-cache. Nothing Works for me. Please, help me out.
error: Error: Unable to resolve module stream from C:\**\node_modules\cipher-base\index.js: stream could not be found within the project.

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  1 | var Buffer = require('safe-buffer').Buffer
> 2 | var Transform = require('stream').Transform
    |                          ^
  3 | var StringDecoder = require('string_decoder').StringDecoder
  4 | var inherits = require('inherits')

A: Stream isn't installed by the node_module calling it. Stream is a native module inside NodeJS. https://nodejs.org/api/stream.html
In order to use Stream you'll need to use shims. You'll need to use some combination of https://github.com/juliangruber/stream and stream-browserify, which is a browser compatible version of Stream.
Just because it's Browser friendly, doesn't make it react-native friendly. React-native runs JavaScriptCore, Apple's JS engine. It only has definitive JS attributes, while other things that you may have thought of as JS are not there because those were supplied by the browser shell. WebCrypto is missing.
After getting some JS version of Stream, you may need to use rn-nodeify, a package that helps React Native emulate a Node environment. It installs many libraries that can emulate node, rendered in JS. However it may be enough to yarn add stream, probably yarn add events next.


text:
Q: Split a string message into 2d array I have a message coming containing 48 different values seperated as:
String values = "4774,55567,44477|14555,4447,5687|416644,4447,5623|...";
I need to convert it into 16 by 3 array as:
String[,] vals = {{"4774,55567,44477"},{14555,4447,5687},{416644,4447,5623}...}
I tried using the split() function but cannot figure how to feed it into the matrix

A: You can split it two times:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var rows = values.Split('|');
var matrix = new string[rows.Length][];
for (var i = 0; i < rows.Length; i++)
{
    matrix[i] = rows[i].Split(',');
}

and a more elegant solution using LINQ:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var data = values
    .Split('|')
    .Select(r => r.Split(','))
    .ToArray();

EDIT: as @RandRandom pointed out, the solution above creates a jagged array. The difference is explained here: link. If the jagged array is not an option for you, to create a 2d array you need to create a matrix, specifying the dimensions [rows.Length, rows[0].Split(',').Length] and with the help of 2 for-loops assign the values:
string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
string[] rows = values.Split('|');
string[,] matrix = new string[rows.Length, rows[0].Split(',').Length];
for (int i = 0; i < rows.Length; i++)
{
    string[] rowColumns = rows[i].Split(',');
    for (int j = 0; j < rowColumns.Length; j++)
    {
        matrix[i, j] = rowColumns[j];
    }
}

A: You can split the string based on the | character. Then, using linq.Select(), split each line based on , and create a two-dimensional array
string[] temp = values.Split('|');
var res=temp.Select(x => x.Split(',')).ToArray();

A: Use Linq if you can consider the jagged array instead of 2D array:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var result = values
   .Split('|')
   .Select(x => x.Split(','))
   .ToArray();

A: You can use the String.Split() method to split the string into an array of substrings, and then use a nested loop to iterate through the array and add the values to the 2D array.
Here is an example :
string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623|...";
string[] substrings = values.Split('|');
string[,] vals = new string[substrings.Length,3];
for (int i = 0; i < substrings.Length; i++)
{
    string[] subvalues = substrings[i].Split(',');
    for (int j = 0; j < subvalues.Length; j++)
    {
        vals[i, j] = subvalues[j];
    }
}

This will split the string values by the separator '|' and create an array of substrings. Then, it will iterate through each substring and split it again by ',' and store the result in a 2D array vals with 16 rows and 3 columns.

A: Try following :
            string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
            String[][] vals = values.Split(new char[] { '|' }).Select(x => x.Split(new char[] { ',' }).ToArray()).ToArray();

            string[,] vals2 = new string[vals.GetLength(0), vals[0].Length];
            for(int i = 0; i < vals.GetLength(0); i++)
            {
                for(int j = 0; j < vals.Length; j++)
                {
                    vals2[i, j] = vals[i][j];
                }
            }


text:
Q: How to use .boundingBox to draw a border around a barcode in Swift? I have an app with a barcode scanner, and I would like to draw a box around the barcode when the app scans it. I think I can do this with .boundingBox but I am not really sure how to go about this.
Here is my setup for the barcode handler right now:
func barcodeRequestHandler(request: VNRequest, error: Error?) {
    guard let results = request.results as? [VNBarcodeObservation],
          let payloadStringValue = results.last?.payloadStringValue,
          let box = results.last?.boundingBox

    else {
        return
    }

    // I think I can do something with 'box' here
}

This is used to create a VNDetectBarcodesRequest, which is passed to a VNImageRequestHandler.perform() function.
I have tried to find a way to draw the box with a CAShapeLayer, but haven't yet found a way to make that work. Is there something built into the barcode scanning system that would let me draw a box around the barcode? Or a different way I can use the bounding box to draw it?

A: Check if this link is useful. It is not related to border but you will get an idea about boundingbox.


text:
Q: Using SWIG with pointer to function in C struct I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs.  I can't figure out how to handle structs that contain function pointers.  A simplified example follows.
test.i:
/* test.i */

%module test
%{

typedef struct {
    int (*my_func)(int);
} test_struct;

int add1(int n) { return n+1; }

test_struct *init_test()
{
    test_struct *t = (test_struct*) malloc(sizeof(test_struct));
    t->my_func = add1;
}
%}

typedef struct {
    int (*my_func)(int);
} test_struct;

extern test_struct *init_test();

sample session:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.init_test()
>>> t
<test.test_struct; proxy of <Swig Object of type 'test_struct *' at 0xa1cafd0> >
>>> t.my_func
<Swig Object of type 'int (*)(int)' at 0xb8009810>
>>> t.my_func(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'PySwigObject' object is not callable

Anyone know if it's possible to get t.my_func(1) to return 2?
Thanks!

A: I found an answer.  If I declare the function pointer as a SWIG "member function", it seems to work as expected:
%module test
%{

typedef struct {
  int (*my_func)(int);
} test_struct;

int add1(int n) { return n+1; }

test_struct *init_test()
{
    test_struct *t = (test_struct*) malloc(sizeof(test_struct));
    t->my_func = add1;
    return t;
}

%}

typedef struct {
    int my_func(int);
} test_struct;

extern test_struct *init_test();

Session:
$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.init_test()
>>> t.my_func(1)
2

I was hoping for something that wouldn't require writing any custom SWIG-specific code (I'd prefer to just "%include" my headers without modification), but this will do I guess.

A: You forget to "return t;" in init_test():
#include <stdlib.h>
#include <stdio.h>

typedef struct {
 int (*my_func)(int);
} test_struct;

int add1(int n) { return n+1; }

test_struct *init_test(){
  test_struct *t = (test_struct*) malloc(sizeof(test_struct));
  t->my_func = add1;
  return t;
}

int main(){
  test_struct *s=init_test();

  printf( "%i\n", s->my_func(1) );
}


text:
Q: How to check data values for validation in ActiveRecord? I have "state" column in "Todo" model, which must one of the following strings: "new", "in progress" or "finished". How can I implement this in todo.rb file with validation?

A: You could use an inclusion validation for this:
validates :state, inclusion: { in: ['new', 'in progress', 'finished'] }

However like Marek Lipka already suggested, using enums might be better suited in this scenario.


text:
Q: Spring MVC: exception when using @ResponseBody and entity with circular reference I have the following method, which behind scenes uses Jackson to parse the list of entities to json:
@Controller
@RequestMapping("/user/")
public class EditarLugarController {

@RequestMapping(value = "stores/{id}/branches", method = RequestMethod.GET)
public @ResponseBody List<Branch> renderBranchesPerStore(@PathVariable(value = "id") Integer id) {
    if(branches == null) {
        //get branches based on store's id
    }
   return branches;
}

This method is called from the view through ajax using jquery
var idBranch = '${store.id}';
$.get("http://localhost:8080/myapp/user/stores/" + idBranch+ "/branches",
    function(data) {
        // show json objects in page
});

The problem is that when this method ends, it throws the following exception:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:639)

I tried removing the @PathVariable (returning some default value) and it works ok, but I need that parameter. Is there a workaroung to this issue?
EDIT: here's the branch code as requested, but again: I DONT think it's related to the issue because if I don't use @PathVariable it works ok, the list of Branches is parsed ok to json and sent to the view. Also, I'm using a Jackson plugin for Hibernate that tells Jackson not to parse attributes that are lazy loaded, to prevent exceptiosn
@Entity
@Table(name = "BRANCH")
public class Branch implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name="BRANCH_ID")
@GeneratedValue(strategy= GenerationType.TABLE)
private Integer id;

@Column(name = "DESCRIPTION")
@Size(max = 500)
private String description;

@Column(name="STREET")
@NotNull
@Size(max = 100)
private String street;

@Column(name="NUMBER")
@NotNull
@Size(max = 6)
private String number

@Column(name="FLOOR")
@Size(max = 3)
private String floor;

@Column(name="APT")
@Size(max = 10)
private String apt

@OneToMany(cascade = CascadeType.ALL, mappedBy="branch")
private List<BranchPhoto> photos;

@JoinColumn(name = "STORE_FK", referencedColumnName = "STORE_ID")
@ManyToOne(optional = false)
private Store store;

public Branch() {}

// getters & setters

}
EDIT: I've realized that even without PathVariable it thorws same exception, I must have tested that wrong. So the problem actually is for circular reference while parsing json

A: As NimChimpsky said, problem was caused for circular references in the model, in class Branch. Besides using dtos to make serialization simple, another solution for those who do not want to use DTOs (like me) is to use some annotations to tell Jackson how to handle the attributes. these are the annotations needed:
In class Store, the attribute branches:
@OneToMany(mappedBy = "store", cascade = CascadeType.ALL)
@JsonManagedReference // this annotation prevents the exception
private List<Branch> branches

And in class Branch, in the attribute store:
@JoinColumn(name = "LUGAR_FK", referencedColumnName = "LUGAR_ID")
@ManyToOne(optional = false)
@JsonBackReference // this annotation prevents the exception
private Lugar lugar;

A: Does Branch contain non-primtives ?
The serialziation of that looks to be the culprit ...specifically a circular reference.
I normally create form specific dto's and keep the serialziation simple.

A: I know this was answered a while ago, but it helped me to find some workaround.
In order to eliminate the circular references to value that I didn't needed anyway.
I created inner class with only fields that I needed (none of those were with reference one/many to one/many)
and wrote the inner private class to ResponseBody


text:
Q: Javascript Eval error with numbers having leading zeroes I was trying to do maths based on variables and use the outcome. The input sometimes has padding with leading zeroes at the start of it. Today while debugging my code I have found out the following;
eval("1*010 + -9") evaluates to -1 while eval("1*10 + -9") evaluates to 1
I do not have any idea how this could be possible since these following evaluations work as intended
eval("1*009 + -9") evaluates to 0
eval("1*011 + -9") evaluates to 2
Any explanation would be helpful, thanks for sharing your time.


text:
Q: Problem in getting current location of a map in iphone sdk As I need the current location of a map I used the code as:
locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

        [locationManager setDistanceFilter:10];
        [locationManager startUpdatingLocation];

And I am getting the error in the didFailWithError methos as:
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    printf("\nXXXXXXXXXXXXXXXXXXXXXXXXXX Inside didFailWithError in locationmanager method XXXXXXXXXXXXXXXXXXXXXXXXXX");
    NSLog(@"Error: %@", error);
}

And I am getting the error message in my console as follows:
XXXXXXXXXXXXXXXXXXXXXXXXXX Inside didFailWithError in locationmanager method XXXXXXXXXXXXXXXXXXXXXXXXXX2010-12-06 17:58:12.335 ParkingAreaLocator[6992:207] Error: Error Domain=kCLErrorDomain Code=0 "The operation couldn't be completed. (kCLErrorDomain error 0.)"

And the Wifi is on.
I am not getting the current location in both simulator and device 4.0 sdk.
Can any one please help me how to resolve this issue.
Thank you,
Monish

A: kCLErrorDomain=0 means kCLErrorLocationUnknown

The location manager was unable to obtain a location value right now.
If the location service is unable to retrieve a location fix right away, it reports a kCLErrorLocationUnknown error and keeps trying. In such a situation, you can simply ignore the error and wait for a new event.

Try with less accuracy

A: This is a lot simpler than you're making it. I assume from the title that you've got an MKMapView in your view? If so, you can use it to get the user's location.
In your .h, have this view controller adopt the  protocol.
Then in the .m, do this:
void viewDidLoad()
{
    ...
    myMapView.showsUserLocation = YES;
    ...
}

(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)location
{
    //Do whatever! that MKUserLocation is the location the map view just determined.
}


text:
Q: add client rendered component on nextjs what I am doing: creating SSG using nextjs 13 but still using pages folder structure, I am building and exporting the site with next export and planned to host it as static.
What I want to do: I want to make a time and add it to my header as client rendered, for example user request for the page at november, 01, 2023 9pm, I want to display november, 01, 2023 9pm, then at reload I want it to be updated on what time it is requested
What I did: tried many approach, add "use client" on the top of the time component, used useEffect also, named the component DateNow.client.tsx. still not working, the date displayed is the date the build or the next export happen.
any idea
this is the component

"use client";
import { useState, useEffect } from "react";

type Props = {};

export default function DateNow({}: Props) {
  useEffect(() => {
    const date = new Date();
    const day = String(date.getDay());
    const month = String(date.getMonth());
    const year = String(date.getFullYear());
    const second = String(date.getUTCSeconds());
    setFullDate({ day, month, year, second });
  }, []);

  const [fullDate, setFullDate] = useState({
    day: String(new Date().getDay()),
    month: String(new Date().getMonth()),
    year: String(new Date().getFullYear()),
    second: String(new Date().getUTCSeconds()),
  });
  return (

      {fullDate.day} - {fullDate.month} - {fullDate.year} - {fullDate.second}

  );
}

this is how I included it

import React from "react";
import DateNow from "./DateNow.client";

type Props = {};

export default function Header({}: Props) {
  return (

      Header <DateNow />

  );
}

this is the export output

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <meta name="next-head-count" content="2" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link
      rel="preconnect"
      href="https://fonts.gstatic.com"
      crossorigin="true"
    />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      rel="preload"
      href="/_next/static/css/4456f66f8b03e6d5.css"
      as="style"
    />
    <link
      rel="stylesheet"
      href="/_next/static/css/4456f66f8b03e6d5.css"
      data-n-g=""
    />

          Header
          2 - 0 - 2023 - 4

            How To Climb The Career Latter And Don't Waste Your Youth

            Morbi fermentum purus metus, eu consequat est congue ut. Proin ut
            eros ac tortor imperdiet convallis nec eu dui. Curabitur sed
            fermentum arcu. Vestibulum sed egestas purus. Donec dapibus
            malesuada eros quis suscipit. Praesent fermentum ipsum nec elit
            finibus, at cursus augue maximus. Praesent blandit efficitur
            bibendum. Integer tincidunt iaculis nunc, eget pharetra sem eleifend
            faucibus. Sed fermentum massa vitae sapien sodales, quis feugiat
            dolor condimentum. Aliquam eget leo nunc. Quisque ut nisi vulputate,
            euismod sem at, mollis leo. Vestibulum et tincidunt ex. In dignissim
            ex ante, a porta nisi rhoncus ut. Pellentesque dictum blandit elit,
            finibus suscipit tortor luctus ut. Sed aliquet leo id lacus feugiat,
            et molestie ante pretium. Proin nec augue et velit tincidunt
            feugiat. Vestibulum ante ipsum primis in faucibus orci luctus et
            ultrices posuere cubilia Curae; Mauris blandit eros a mi pharetra
            molestie ut efficitur libero. Donec ut luctus risus. In ut
            condimentum nibh. Nunc eu porta ligula. Aliquam erat volutpat.
            Maecenas sodales lectus vitae est tincidunt consequat.

            Proin id ultricies justo, fringilla pharetra enim. Phasellus
            vehicula pretium malesuada. Proin dolor enim, suscipit vitae luctus
            non, maximus malesuada odio. Phasellus condimentum tellus eget quam
            egestas, a lobortis mauris venenatis. Vestibulum id leo quis felis
            suscipit pulvinar. Duis aliquam mi urna, eu bibendum ante convallis
            eu. Praesent sit amet enim purus. Sed egestas pretium purus id
            consectetur. Fusce gravida ipsum tellus, quis pharetra lorem
            volutpat a. Proin feugiat tincidunt mattis. Integer laoreet nulla
            vel viverra semper. Pellentesque habitant morbi tristique senectus
            et netus et malesuada fames ac turpis egestas. Maecenas facilisis
            felis lorem, quis tempus nisi sagittis sit amet. In bibendum sodales
            risus, at convallis mi pellentesque sit amet. Morbi magna mauris,
            condimentum non interdum sed, tincidunt vitae odio. Fusce maximus
            mauris nec ex mattis, sed maximus enim gravida. Maecenas sit amet
            metus odio. Vivamus interdum orci nibh, non tincidunt eros vulputate
            non. Ut gravida nulla nunc. Ut facilisis odio eget est blandit
            egestas.


text:
Q: Regular Expression to find words (using word boundary) where words include a dash character Given the following Regular Expression:
\b(MyString|MyString-Dash)\b
And the text:
AString
MyString
MyString-Dash
Running a match against the text never finds a match for the second thing (MyString-Dash) because the '-' (dash) character isn't a word boundary character.  The following javascript always outputs "MyString,MyString" to the "matches" div (I would like to find MyString and MyString-Dash as distinct matches).  How can I define a pattern that will match both MyString and MyString-Dash ?

Content

        AString
        MyString
        MyString-Dash

Matches (expecting MyString,MyString-Dash)

A: Swap the order of your matching so that the longest possible is first:
content.innerHTML.match(/\b(MyString-Dash|MyString)\b/)

I believe regular expressions match from left to right. Just tested this in Firebug, it works.
I would also change that pattern var to a regular expression literal, from '\\b(MyString-Dash|MyString)\\b' to /\b(MyString-Dash|MyString)\b/g
You want the /g in there because that will make the regular expression return all matches, rather than just the first one.

A: Please see this answer for how to deal with words with dashes in them and the issues related to boundaries when you have those kinds of words.

A: There are a couple problems with your assumptions.

Running a match against the text never finds a match for the second thing (MyString-Dash) because the '-' (dash) character isn't a word boundary character.

There's no such thing as a word boundary character.  Word boundaries are the space between characters that match \w and don't match \w.  - does not match '\w', so on either side of it is a "word boundary", but that won't break your match: the - is a literal dash in your regex and the \b's are far outside of it.
Second, regexen will always try to match the first thing they can in the string that matches your regex.  As long as that first string in there matches, it will keep returning the first thing in there.  You're asking for the first match when you ask for a match.  That's the design.  If you didn't want it to match MyString, don't ask for it.
Third, most regex engines prioritize 'completing a match' over length of a match.  Thus, 'MyString', if it matches, will always be the first thing it returns.  You'll have to wait until Perl 6 grammars for a regex engine that prioritizes length. :)
The only way for you to really do this is with two checks, one for the longer one, first, and then one for the shorter one.  It will always match the first thing it finds that works.  If you have a priority other than that, it's up to you to code it in as separate checks.


text:
Q: SlidingTabLayout not showing the tabs I m trying  to implement a SlidingTabLayout inside a fragment using this example given in developer.android.com. But with that example I could only display ViewerPager, Tabs are not showing in my UI.

Here is the view I get once I run the project:

I can slide to every page but the problem is no tabs.
Here is my Fragment :
public class HomeFragment extends Fragment {
    static final String LOG_TAG = "SlidingTabsFragment";
    static final String PAGE_TITLE = "Page_Title";
    private ViewPager mPager;
    private SlidingTabLayout mTabs;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPager.setAdapter(new SamplePagerAdapter());
        mTabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
        mTabs.setViewPager(mPager);
    }

    private class SamplePagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return object == view;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            //  return super.getPageTitle(position);
            Log.i(PAGE_TITLE, position+1+"");
            return "Item " + (position + 1);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // Inflate a new layout from our resources
            View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
                    container, false);
            // Add the newly created View to the ViewPager
            container.addView(view);

            // Retrieve a TextView from the inflated View, and update it's text
            TextView title = (TextView) view.findViewById(R.id.item_title);
            title.setText(String.valueOf(position + 1));

            Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");

            // Return the View
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
        }
    }
}

And this is fragment_home.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="layout.HomeFragment">

    <!-- TODO: Update blank fragment layout -->
    <layout.home.factory.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</FrameLayout>

And this is my styles.xml :
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

</style>

<style name="Base.AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/md_indigo_500</item>
    <item name="colorPrimaryDark">@color/md_indigo_700</item>
    <item name="colorAccent">@color/md_pink_500</item>
    <item name="colorControlHighlight">@color/md_indigo_500_25</item>
    <item name="android:windowBackground">@color/md_white_1000</item>
</style>

<style name="ToolbarTheme" parent="AppTheme">
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:textColorSecondary">@android:color/white</item>
</style>

<style name="NavigationViewTheme" parent="AppTheme">
    <item name="textAppearanceListItem">@style/TextAppearance.AppCompat.Body2</item>
</style>

I m new to android and hope someone can give me a solution. Thanks in advance.
UPDATE :
activity_main.xml :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="@bool/fitsSystemWindows">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/status_bar_kitkat_height"
            android:background="?colorPrimary" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/status_bar_lollipop_height"
            android:background="?colorPrimaryDark" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/status_bar_margin_top">

        <FrameLayout
            android:id="@+id/fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ToolbarTheme"/>

    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="@bool/fitsSystemWindows"
        app:headerLayout="@layout/navigation_drawer_header"
        app:menu="@menu/navigation_drawer_menu"
        app:theme="@style/NavigationViewTheme" />

   </android.support.v4.widget.DrawerLayout>

A: android:marginTop="?actionBarSize"

add this lineto framelayout above toolbar

A: Actually you set the ViewPager height to "match_parent" that's the reason it overlapping tab view use LinearLayout instead of FrameLayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="layout.HomeFragment">

<!-- TODO: Update blank fragment layout -->
<layout.home.factory.SlidingTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="2dp" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

</LinearLayout>

or fix the height of SlidingTabLayout and give same marginTop to ViewPager view
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.HomeFragment">

<!-- TODO: Update blank fragment layout -->
<layout.home.factory.SlidingTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:elevation="2dp" />

<android.support.v4.view.ViewPager
    android:layout_marginTop="100dp"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1" />

</FrameLayout>


text:
Q: problems redirecting sections to new domain Same question as How to redirect a URL by only changing the domain name, while keeping other URL parameters
but as I have commented in the answers (I realized it´s from 2011 so I decided to ask again):
I follow the rewrite rule and only works for me without anything after the domainA name. If I have any subsection like domainA.com/team/ or domainA.com/contact/ the rewrite rule doesn´t work and stay in the domainA.com site instead of redirecting me to domainB.com/team/ or /contact/

A: The problem was due to a Wordpress rule above, I changed the order of rules, putting the redirecting rule before the Wordpress rule:
 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
 </IfModule>

Cpanel for any reason was adding the redirect rule after the Wordpress rule, instead of before.


text:
Q: Set CSS for input element of type file via JavaScript I have some code to set CSS of a input type of file. I create the box dynamically using JavaScript function like this:
/*
    var newLabel = document.createElement('label');
    newLabel.htmlFor='${id}File';
    newLabel.className='upload-file-input';
    ${id}_control_group.append(newLabel);
*/
    var newInput = document.createElement('input');
    newInput.type = 'file';
    newInput.name = 'myFile';
    newInput.id = 'myFile';
    newInput.accept="image/png, image/jpeg, image/gif";
    newInput.className='upload-file-input'; //this is not working.
    form_control_group.append(newInput);

This CSS is present in class no problem about that.

A: newInput.classList.add('upload-file-input')

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
The classList API is a dream.

A: newInput.setAttribute("class", 'upload-file-input')

https://www.w3schools.com/jsref/met_element_setattribute.asp
When to use setAttribute vs .attribute= in JavaScript?


text:
Q: Converting xml to json does not print xml in same form I'm trying to convert xml to json and I would like to get 1:1 using
<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

but the problem is output after converting is not the same form.
Code:
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);

xml:
<?xml version="1.0" encoding="UTF-8"?>
<!--Anagrafica del clienti del mercato-->
<anagrafica>
    <testata>
        <nomemercato id="007">Mercato di test</nomemercato>
        <data>Giovedi 18 dicembre 2003 16.05.29</data>
    </testata>
    <record>
        <codice_cliente>5</codice_cliente>
        <rag_soc>Miami American Cafe</rag_soc>
        <codice_fiscale>IT07654930130</codice_fiscale>
        <indirizzo tipo="casa">Viale Carlo Espinasse 5, Como</indirizzo>
        <num_prodotti>13</num_prodotti>
    </record>
    ...
</anagrafica>

and with code I get
{"anagrafica": {
    "record": [
        {
            "codice_fiscale": "IT07654930130",
            "rag_soc": "Miami American Cafe",
            "num_prodotti": 13,
            "codice_cliente": 5,
            "indirizzo": {
                "tipo": "casa",
                "content": "Viale Carlo Espinasse 5, Como"
            }
        ....
    ],
    "testata": {
        "data": "Giovedi 18 dicembre 2003 16.05.29",
        "nomemercato": {
            "id": "007",
            "content": "Mercato di test"
        }
    }
}}

As you can see testata is misplaced with record
I mean testata should be first, then record.
Could you tell me how can I fix this? Or what should I use to make it right?


text:
Q: phone number format checking javascript I have made a website with JS and php and as you can see below is my code at paste bin, I have looked around and seen regular expressions but I don't know how to use them or what I should use exactly....But basically I want to just allow the user to enter north american phone numbers and if they enter anything else then give them a message to enter a valid phone number...
Below is my code to help you understand what I have..What I need and what my site's interface looks like...
http://pastebin.com/8NwURm0G
possible phone numbers user can enter are 9058554678 OR 4167641689...
This is how the the list looks:
http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Edit.php

A: Here is regex that I have laying around to only match 10 digit NA numbers, based off the NANP
/(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/

A: ^\d{10}$

That matches 10-digit numbers.
^1?\d{10}$

That matches 10-digit numbers with an optional 1 at the front.
^(?:1-?\s*)?(?:\(?:\d{3}\)|\d{3})\s*-?\d{4}$

That matches digit groupings like 1-444-555-6666 or (444) 555-6666, and some related ones.

A: A quick search on google yielded the following result. You might want to combine it with mitchellhislop's answer.
function isPhoneNumber(s)
{

 // Check for correct phone number
 rePhoneNumber = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);

 if (!rePhoneNumber.test(s)) {
      alert("Phone Number Must Be Entered As: (555) 555-1234");
      return false;
 }

return true;
}

A: It's worth reading up on regular expressions before using them, since they can be a little tricky and unintuitive.
Good tutorial: http://www.regular-expressions.info/quickstart.html
Based on what you list as a valid input, you're looking to see if the user entered in 10 digits. This can be done by checking if a character is a digit, and then seeing if there are 10 of them, which would be the regular expression: [0-9]{10}. Example on how to use:
var myRegEx = /[0-9]{10}/;
var itemsToTest = ["9058554678","abc"];

for (var ii=0;ii<itemsToTest.length;ii++) {
    if ( myRegEx.test(itemsToTest[ii]) ) {
        alert(itemsToTest[ii] + " is valid!");
    }
}

Test: http://jsfiddle.net/87ea8/


text:
Q: How can I change the templating framework in Django? I want to integrate Mustache into my Django app. What steps would I need to take to completely replace Django's templating system with Mustache?
I would like to have render_to_response work properly with Mustache templates, passing in all the right variables with the context (STATIC_URL, request, etc.).

A: Basically, you have to replace the render_to_response function with your own implementation that uses the template system of your choice. Django's render_to_response is specific to Django's templating system. This function simply wraps some common grunt-work used when using the django template engine. The basics on how they work are covered in Django's tutorial.
Use the django.template.RequestContext to acquire all the context variables specified in the TEMPLATE_CONTEXT_PROCESSORS setting, (where STATIC_URL, request, etc. get defined). Since RequestContext behaves like a dictionary, you should be able to pass it through to mustache without problems. RequestContext takes the request object in its constructor.
Finally, don't forget to return the proper HttpResponse object!
Since I'm not much of a paragraph fan:

*

*Create RequestContext instance.

*Merge dictionary received with RequestContext instance.

*Render the template to a string.

*Wrap the final string with a HttpResponse instance.


text:
Q: Sublime Text 2 Build System I managed to get this build system doing the trick for me:
{
 "working_dir": "${file_path}",
 "cmd": ["g++", "${file}"],

 "variants":
 [
  {
   "name": "Run",
   "shell": true,
   "working_dir": "${file_path}",
   "cmd": ["start", "a.exe"]
  }
 ]
}

But I don't want the shell to close once if finishes. I want it to display a message like "Build process complete. Press any key to exit...". Is there any way to accomplish this?

A: Not the best solution, but I found out that adding a
while(true){}

to the end of the file makes it not close. Still waiting for a better solution tho.


text:
Q: Animated avatars in user profile and newsletter First, to make it clear Stack Exchange does not allow animated avatars, the Can I have an animated profile picture? feature request has been declined by SE staff back in 2016.
However, as of today, users who upload animated gif as avatar have the animation showing in their profile, e.g. this user. (on all sites)
Can this please be fixed, or if there was policy change, can the above feature request be changed to status-completed instead?
Note, this also affects the newsletter, which show the animation in the email, and this can become pretty irritating.

A: So... this looks like it was actually caused by the same server outage that was making it so that image resizing wasn't working as it should. So, when that was fixed, this was also fixed... YAY! Uploading a gif now should behave as expected.
I briefly uploaded the same gif from that user's profile to my own and it became a static image. If you want to check for yourself, it's worth noting that when I tested it out, the preview looks like a gif but after you actually save your settings, the resulting image on a profile page is static.
Unfortunately, it has the same side effect... content uploaded during that window is the way it is, so removing the gifs now would require the user re-upload the image.


text:
Q: Angular.js(SPA) loading times issue I have a website which is built with Angular.js. I'm having issues with a slow loading time (obviously), especially from users in countries that have slow internet connections. Even for some users, the page is not loaded at all. How can I improve the initial loading times?

A: Make sure you are using the minified versions of the libraries and use minification for your .js and .css files. Enable gzip compression on the server and use a CDN for content distribution.

A: Is it related to the Angular.js library or the page load speed parameters like "caching" or "server speed"? What I advice you to use google page speed analyser that gives you clear tips to speed-up your page.
If the pages are loaded because of the slow process of the Angular.JS than you should dig into your code and find the performance bottle-necks and then start trying to figure out what can be better than that solution.
I hope these help.


text:
Q: What is the best way to perform sentence segmentation for textual analysis? I am working on textual dataset containing data from official documents like reports by companies, legal documents, speeches by directors to shareholders etc. The content of textual documents are like:

*

*In respect of its fixed assets:
  a. The Company has maintained proper records showing full particulars including quantitative details and situation of fixed assets.

  Your Company owns 99.99 percent of 20 Microns Sdn. Bhd. During the year under review, the said Company reported Gross turnover Rs. 295.74 Lacs

There a lot's of period which donot represents the sentence boundary. Until now i have implemented the regular expression based sentence segmentation by designing some rules and considerably good performance. But still it need to be updated when new words with period occur in the sentences and which seems like never ending task. I have searched and somewhere it is recommended to have Maximum Entropy classifier based word segmentation. I don't get exactly how to use MaxEnt classifier for word segmentation. How do i implement machine learning based word segmentation i.e based on maximum entropy classifier or any other which performs better than regular expression thing?

A: For an ML-based solution you generally would want a sequence learner like a conditional random field or a recursive neural network. Now each symbol has a binary label for classification representing whether the current symbol is a sentence boundary or not. Supervised learning on such data will result in your required classifier. You could theoretically also try a sliding window approach on feed forward architectures, although I'd expect it to perform quite a bit worse.
Perhaps have a look at the relevant parts of NLTK, if you want an overview of various sentence tokenization methods: http://www.nltk.org/api/nltk.tokenize.html
Here is an example of how to perform supervised sentence segmentation: http://www.nltk.org/book/ch06.html