text:
Q: 'Uneven' breaks in long URLs (\url) I'm struggling with hyphenation of long URLs (using command \url{}).
Line breaking works fine in cases when URL is just part of line which doesn't fit to text area width. That means URL is hyphenated correctly if line starts with some text before URL - or if hyphenated URL is followed by other text which is also hyphenated.
Problem is in parts of URL which are at the line alone

*

*first line of very long URL

*middle lines of very long hyphenated URL
At screenshot there is visible that both cases overflowed the text area - case 1 is clearly visible, but also case 2 overflowed by few pixels.
In real document overflowed area is variable depending on contents which makes sometimes collisions with objects on the right side (images, ...).

How to hyphenate URLs correctly to avoid such overflows?

*

*ideal solution is perfectly aligned block

*but acceptable is also solution with underflowed line instead of overflowed (earlier line break instead of late)
I guess problem is mainly caused by non-proportional font and is fixed if other proportional text is present at the same line, but how to handle alone parts of long URLs?
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}

\usepackage{ulem}
\usepackage[unicode]{hyperref}
\def\UrlBreaks{\do{a}} % Force correct hyphenation for this example

\usepackage{pdfpages}

\usepackage{needspace}

\begin{document}

Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text.\newline
\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}\newline
Some text before. \url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.

\end{document}

Shorter MWE
\documentclass[a4paper]{book}

\usepackage{hyperref}
\def\UrlBreaks{\do{a}}

\begin{document}
Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text.\newline
\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}\newline
Some text before. \url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.
\end{document}

Edit 18-12-23: Additional issue
I've tried suggested solution:
\def\do#1{\appto\UrlSpecials{\do#1{\mathchar`#1 \mskip 0mu plus 1mu\penalty100}}}%
 \do\a

and initially everything was perfect. But I wasn't happy for long time :-) After I'd replaced the dummy URL with the real, document couldn't be even compiled - Number too big error, see details in screenshot.
Problem is only with combination "suggested solution" and "real URL". Old method and real URL is OK (only with wrong breaks, which was reason for this question) and suggested solution with dummy URL works also fine.
It has definitely something to do with special characters in URL.
Full code:
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}

\usepackage{ulem}
\usepackage[unicode]{hyperref}

% Old method - no error, but issues with breaks
%\def\UrlBreaks{\do\-\do\/\do\0\do\1\do\2\do\3\do\4\do\5\do\6\do\7\do\8\do\9\do\a\do\b\do\c\do\d\do\e\do\f\do\g\do\h\do\i\do\j\do\k\do\l\do\m\do\n\do\o\do\p\do\q\do\r\do\s\do\t\do\u\do\v\do\w\do\x\do\y\do\z\do\A\do\B\do\C\do\D\do\E\do\F\do\G\do\H\do\I\do\J\do\K\do\L\do\M\do\N\do\O\do\P\do\Q\do\R\do\S\do\T\do\U\do\V\do\W\do\X\do\Y\do\Z}

% New method - error for real URL (previous example with "aaa" works)
\def\do#1{\appto\UrlSpecials{\do#1{\mathchar`#1 \mskip 0mu plus 1mu\penalty100}}}
\do\-\do\/\do\0\do\1\do\2\do\3\do\4\do\5\do\6\do\7\do\8\do\9\do\a\do\b\do\c\do\d\do\e\do\f\do\g\do\h\do\i\do\j\do\k\do\l\do\m\do\n\do\o\do\p\do\q\do\r\do\s\do\t\do\u\do\v\do\w\do\x\do\y\do\z\do\A\do\B\do\C\do\D\do\E\do\F\do\G\do\H\do\I\do\J\do\K\do\L\do\M\do\N\do\O\do\P\do\Q\do\R\do\S\do\T\do\U\do\V\do\W\do\X\do\Y\do\Z

\usepackage{pdfpages}

\begin{document}

Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text.\newline
%\url{http://aaa.bbb.ccc/njrrjjriokf56opiyfl5ojiorij6m9h9r87vjvjytrjyiotryhjiothjvoi8jr8o7j8hohj8oj88jt6hj8ohjot6trhiothj8hj8ohitnhh8tr7t786ht76nvh6gtrhgoght6onbvgnhyg8o7hvntnvotr696yjvhopr76r}\newline
\url{http://www.portafontium.cz/iipimage/30063568/karlovy-vary-65\_0240-t?x=-45\&y=345\&w=927\&h=383}\newline

\end{document}

A: Just add the call of package xurl before package hyperref.
The following MWE
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}

\usepackage{ulem}
\usepackage[hyphens]{xurl} % <==========================================
\usepackage[unicode]{hyperref}

\usepackage{pdfpages}

\usepackage{needspace}

\begin{document}

Reference text. Reference text. Reference text. Reference text.
Reference text. Reference text. Reference text. Reference text.
Reference text. Reference text.\newline
\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}\newline
Some text before. \url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.

\end{document}

gives you:

I will inform the maintainer of xurl about this bug.  Meanwhile you can use the following (not perfect, but better than nothing ...) code ( I corrected the code in \def: \def\UrlBreaks{\do\a}):
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}

\usepackage{pdfpages}
\usepackage{needspace}
\usepackage{ulem}
\usepackage{showframe}

%\usepackage{xurl} % <==========================================
\usepackage[unicode]{hyperref}
\def\UrlBreaks{\do\a}

\begin{document}

Reference text. Reference text. Reference text. Reference text.
Reference text. Reference text. Reference text. Reference text.
Reference text. Reference text.

\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}

Some text before. \url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.

\end{document}

with the result:

A: url's are not hyphenated. They are broken. As they are actually set in math the parts are blocks of quite fix width, this makes it sometimes difficult to fill up a line.
You can add a bit stretchability after the a to avoid the problem:
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}

\usepackage{ulem}
\usepackage[unicode]{hyperref}
%\def\UrlBreaks{\do{a}} %
% some stretchability:
\def\do#1{\appto\UrlSpecials{\do#1{\mathchar`#1 \mskip 0mu plus 1mu\penalty100\relax}}}%
 \do\a

\begin{document}

Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text.\newline
\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}\newline
Some text before. \url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.

\end{document}

A: You can use the xurl package:
\documentclass[a4paper]{book}

\usepackage{fontspec}

\usepackage{polyglossia}
\setmainlanguage{czech}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.3pt}
\usepackage{ulem}
\usepackage{xurl}
\usepackage[unicode]{hyperref}

\usepackage{pdfpages}

\usepackage{needspace}

\begin{document}

Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text. Reference text.\newline
\url{http://aaa.bbb.ccc/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}\newline
Some text before. \url{http://abc.bbb.ccc/abcabcaaaaaaabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca} Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after. Some text after.

\end{document}


text:
Q: Oracle pro*c indicator variables vs NVL in query execution oracle-pro-c has recommended using indicator variables as "NULL flags" attached to host variables. As per documentation, we can associate every host variable with an optional indicator variable (short type). For example:
short indicator_var;
EXEC SQL SELECT xyz INTO :host_var:indicator_var
    FROM ...;

We can also alternatively use NVL as documented in https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions105.htm, for example, as:
EXEC SQL SELECT NVL(TO_CHAR(xyz), '') INTO :host_var
        FROM ...;

Which one is better in terms of performance?

A: Ah, Pro*C. It's a while back, over 20 years, but I think my memory serves me well here.
Using the indicator variables will be better in terms of performance, for two reasons:

*

*The SQL is simpler, so there is less parsing and fewer bytes will be transferred over the network to the database server.

*In Oracle in general, a "Null" value is encoded in 0 bytes. An empty string contains a length (N bytes) and storage (0 bytes). So a NULL value is encoded more efficiently in the returned result set.

Now in practice, you won't notice the difference much. But you asked :-)

A: In my experience NVL was much slower than indicator variables especially if nested (yes you can nest them) for INSERT or UPDATE of fields. it was a long time ago and I don't remember exactly the circumstances but I remember the performance gain was real.
On select it was not that obvious but using indicator variables allows also to detect cases when truncation happen.
If you use VARCHAR or UVARCHAR columns there is a third options to detect NULL/Empty strings in Oracle. The len field will be set to 0 and it means the value is empty. As Oracle does not distinguish between NULL and length 0 strings it is more or less the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can one import affect the other in matplotlib and pyplot? I'm having difficulties understanding this import feature and I would like some help with it.
Running this code
import matplotlib as mpl
fig = mpl.figure.Figure()

returns the following error:

AttributeError: module 'matplotlib' has no attribute 'figure

However, if besides importing matplotlib I also import matplotlib.pyplot. Such as,
import matplotlib as mpl
import matplotlib.pyplot as plt
fig = mpl.figure.Figure()

Then, mpl does include figure and no error is raised.
In fact, running print(dir(mpl)) gives different results whether pyplot is imported or not.
Why does one import affects the other?
What is the intention in having it behave this way?


text:
Q: Plotting library I'm looking for a good plotting library, with real-time plotting capabilities,  that can be used with wxWidgets.
I've looking for many such as wxMathPlot, wxArt2D or wxFreeChart(which is the one I'm actually using, but slows down when plotting many points).
So I'm acutally looking for a library that goes well with many points but I need a specific feature from wxFreeChart, which is the possiblity to draw different kinds of marks on the points.
So, nothing more and hope you can help me.

A: You may find this recent blog post interesting. In addition to discussing the library it is written about, it also mentions a few other ones.


text:
Q: How can I get the shuffler method to only shuffle certain indexes in an array? While not shuffling indexes which I want to stay the same My problem is as follows:
    char [] letters = {' ', 'a', ' ', 'b', ' ', 'c'};

    for(int i = 0; i < letters.length; i ++) {
        int random = (int) (Math.random()* letters.length);

        char temp = letters[i];
        letters [i] = letters [random];
        letters [random] = temp;

    }

This method shuffles the array, very good; however I would like the both the shuffle method and the Math.random method to ignore the spaces and only shuffle indexes that have a letter value. To further explain: I would like the output of the letters array to have all the spaces at the same index as they were originally, while only allowing indexes that contained a letter to be swapped. So an example of a random acceptable out put of the letters array after it goes through this method would look something like this:
[ ' ', 'b', ' ', 'c', ' ', 'a' ]
or maybe even
[ ' ', 'c', ' ', 'a', ' ', 'b' ]
any help on how I can accomplish this would be just absolutely fantastic... I have tried every variation of for, while, and if loops trying to constrict the boundaries of the Math.random method to just indexes that contain a letter, and same for the for loop, but I have come up with nothing. It has me beat. Thank you very much in advance to anyone who could help me out and explain a little.

A: Use the following logic :
char[] letters = { ' ', 'a', ' ', 'b', ' ', 'c', ' ', 'd' };

for (int i = 0; i < letters.length; i++) {
    int random = (int) (Math.random() * letters.length);

    // observe this
    if (!Character.isWhitespace(letters[random]) && !Character.isWhitespace(letters[i])) {
        char temp = letters[i];
        letters[i] = letters[random];
        letters[random] = temp;
    }

}

Explanation :

*

*You can add a simple if condition to check whether both elements (i.e letters[random] and letters[i]) to be swapped are not whitespaces.

A: Simply skip the whitespace indices:
char [] letters = {' ', 'a', ' ', 'b', ' ', 'c'};

for(int i = 0; i < letters.length; i++) {
    int random = (int) (Math.random()* letters.length);

    if (letters[random] == ' ' || letters[i] == ' ') continue; // here

    char temp = letters[i];
    letters [i] = letters [random];
    letters [random] = temp;
}


text:
Q: Patterns in residuals plot from linear regression: do they tell us what model to use? I have carried out a linear regression. This is the form of the model:
bounded (0-1) response variable ~ factor1 (2 levels) + factor2 (5 levels) + interaction between factor1:factor2 + factor3 (2 levels)
Sample size is about 350.
I have plotted the residuals against the predicted values from that model:

As there is a distinct pattern in the residuals, it appears linear regression is not a suitable model. I have carried out several other linear regressions lately with different data, and I have repeatedly seen this pattern in the residuals.
Does this pattern provide information on what model would be best to use? Should an interaction term be added? Is there a predictor missing? Should a non-linear model be used? Or instead, does this particular pattern in the residuals actually not provide any indicators as to what model to use?

A: Luciano:
1) at first glance, your residual plot seemingly shows heteroskedasticity of residuals. This violates one of the requirements of OLS. This often happens when factor variables are the only predictors.
2) But the most substantive issue rests on the consideration that OLS is unfit to deal with a binary dependent variable (if this is your case).


text:
Q: ANR after app process was killed After my application process was  killed and activities stack was restored I get ANR, but in log I can see that my Activity starting takes 1.5s?
What ca cause the such behavior? How to resolve this problem?


text:
Q: How can I rewrite this main thread - worker threads synchronization I've a program that goes something like this
public class Test implements Runnable
{
    public        int local_counter
    public static int global_counter
    // Barrier waits for as many threads as we launch + main thread
    public static CyclicBarrier thread_barrier = new CyclicBarrier (n_threads + 1);

    /* Constructors etc. */

    public void run()
    {
        for (int i=0; i<100; i++)
        {
            thread_barrier.await();
            local_counter = 0;
            for(int j=0 ; j = 20 ; j++)
                local_counter++;
            thread_barrier.await();
        }
    }

    public void main()
    {
        /* Create and launch some threads, stored on thread_array */
        for(int i=0 ; i<100 ; i++)
        {
            thread_barrier.await();
            thread_barrier.await();

            for (int t=1; t<thread_array.length; t++)
            {
                global_counter += thread_array[t].local_counter;
            }
        }
    }
}

Basically, I've a few threads with their own local counters, and I'm doing this (in a loop)
        |----|           |           |----|
        |main|           |           |pool|
        |----|           |           |----|
                         |

-------------------------------------------------------
barrier (get local counters before they're overwritten)
-------------------------------------------------------
                         |
                         |   1. reset local counter
                         |   2. do some computations
                         |      involving local counter
                         |
-------------------------------------------------------
             barrier (synchronize all threads)
-------------------------------------------------------
                         |
1. update global counter |
   using each thread's   |
   local counter         |

And this should all be fine and dandy, but it turns out this doesn't scale quite well. On a 16 physical nodes cluster, speedup after 6-8 threads is negligible, so I have to get rid of one of the awaits. I've tried with CyclicBarrier, which scales awfully, Semaphores, which do as much, and a custom library (jbarrier) that works great until there's more threads than physical cores, at which point it performs worse than the sequential version. But I just can't come up with a way of doing this without stopping all threads twice.
EDIT: while I appreciate all and any insight you might have concerning any other possible bottlenecks in my program, I'm looking for an answer concerning this particular issue. I can provide a more specific example if needed

A: A few fixes: your iteration over threads should be for(int t=0;...) assuming your thread array[0] should participate in the global counter sum. We can guess it's an array of Test, not threads. local_counter should be volatile, otherwise you may not see the true value across test thread and main thread.
Ok, now, you have a proper 2 phases cycle, afaict. Anything else like a phaser or 1 cycling barrier with a new countdown latch at every loop are just variations of a same theme: getting numerous threads to agree to let the main resume, and getting the main to resume numerous threads in one shot.
A thinner implementation could involve a reentrantlock, a counter of arrived tests threads, a condition to resume test on all test threads, and a condition to resume the main thread. The test thread that arrives when --count==0 should signal the main resume condition. All test threads await the test resume condition. The main should reset the counter to N and signalAll on the test resume condition, then await on the main condition. Threads (test and main) await only once per loop.
Finally, if the end goal is a sum updated by any threads, you should look at LongAdder (if not AtomicLong) to perform addition to a long concurently without having to stop all threads (them them fight and add, not involving the main).
Otherwise you can have the threads deliver their material to a blocking queue read by the main. There is just too many flavors of doing this; I'm having a hard time understanding why you hang all threads to collect data. That's all.The question is oversimplified and we don't have enough constraint to justify what you are doing.
Don't worry about CyclicBarrier, it is implemented with reentrant lock, a counter and a condition to trip the signalAll() to all waiting threads. This is tightly coded, afaict. If you wanted lock-free version, you would be facing too many busy spin loops wasting cpu time, especially when you are concerned of scaling when there is more threads than cores.
Meanwhile, is it possible that you have in fact 8 cores hyperthreaded that look like 16 cpu?
Once sanitized, your code looks like:
package tests;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.Stream;

public class Test implements Runnable {
    static final int n_threads = 8;
    static final long LOOPS = 10000;
    public static int global_counter;
    public static CyclicBarrier thread_barrier = new CyclicBarrier(n_threads + 1);

    public volatile int local_counter;

    @Override
    public void run() {
        try {
            runImpl();
        } catch (InterruptedException | BrokenBarrierException e) {
            //
        }
    }

    void runImpl() throws InterruptedException, BrokenBarrierException {
        for (int i = 0; i < LOOPS; i++) {
            thread_barrier.await();
            local_counter = 0;
            for (int j=0; j<20; j++)
                local_counter++;
            thread_barrier.await();
        }
    }

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        Test[] ra = new Test[n_threads];
        Thread[] ta = new Thread[n_threads];
        for(int i=0; i<n_threads; i++)
            (ta[i] = new Thread(ra[i]=new Test()).start();

        long nanos = System.nanoTime();
        for (int i = 0; i < LOOPS; i++) {
            thread_barrier.await();
            thread_barrier.await();

            for (int t=0; t<ra.length; t++) {
                global_counter += ra[t].local_counter;
            }
        }

        System.out.println(global_counter+", "+1e-6*(System.nanoTime()-nanos)+" ms");

        Stream.of(ta).forEach(t -> t.interrupt());
    }
}

My version with 1 lock looks like this:
package tests;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;

public class TwoPhaseCycle implements Runnable {
    static final boolean DEBUG = false;
    static final int N = 8;
    static final int LOOPS = 10000;

    static ReentrantLock lock = new ReentrantLock();
    static Condition testResume = lock.newCondition();
    static volatile long cycle = -1;
    static Condition mainResume = lock.newCondition();
    static volatile int testLeft = 0;

    static void p(Object msg) {
        System.out.println(Thread.currentThread().getName()+"] "+msg);
    }

    //-----
    volatile int local_counter;

    @Override
    public void run() {
        try {
            runImpl();
        } catch (InterruptedException e) {
            p("interrupted; ending.");
        }
    }

    public void runImpl() throws InterruptedException {
        lock.lock();
        try {
            if(DEBUG) p("waiting for 1st testResumed");
            while(cycle<0) {
                testResume.await();
            }
        } finally {
            lock.unlock();
        }

        long localCycle = 0;//for (int i = 0; i < LOOPS; i++) {
        while(true) {
            if(DEBUG) p("working");
            local_counter = 0;
            for (int j = 0; j<20; j++)
                local_counter++;
            localCycle++;

            lock.lock();
            try {
                if(DEBUG) p("done");
                if(--testLeft <=0)
                    mainResume.signalAll(); //could have been just .signal() since only main is waiting, but safety first.

                if(DEBUG) p("waiting for cycle "+localCycle+" testResumed");
                while(cycle < localCycle) {
                    testResume.await();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseCycle[] ra = new TwoPhaseCycle[N];
        Thread[] ta = new Thread[N];
        for(int i=0; i<N; i++)
            (ta[i] = new Thread(ra[i]=new TwoPhaseCycle(), "\t\t\t\t\t\t\t\t".substring(0, i%8)+"\tT"+i)).start();

        long nanos = System.nanoTime();

        int global_counter = 0;
        for (int i=0; i<LOOPS; i++) {
            lock.lock();
            try {
                if(DEBUG) p("gathering");
                for (int t=0; t<ra.length; t++) {
                    global_counter += ra[t].local_counter;
                }
                testLeft = N;
                cycle = i;
                if(DEBUG) p("resuming cycle "+cycle+" tests");
                testResume.signalAll();

                if(DEBUG) p("waiting for main resume");
                while(testLeft>0) {
                    mainResume.await();
                }
            } finally {
                lock.unlock();
            }
        }

        System.out.println(global_counter+", "+1e-6*(System.nanoTime()-nanos)+" ms");

        p(global_counter);
        Stream.of(ta).forEach(t -> t.interrupt());
    }
}

Of course, this is by no mean a stable microbenchmark, but the trend shows it's faster. Hope you like it. (I dropped a few favorite tricks for debugging, worth turning debug true...)

A: Well. I'm not sure to fully understand, but I think your main problem is that you try to re-use a predefined set of threads too much. You should let Java take care of this (that's what executors/fork-join pool are for). To solve your issue, a split/process/merge (or map/reduce) seems appropriate to me. Since java 8, it's a really simple approach to implement (thanks to  the stream/fork-join pool/completable future APIs). I propose 2 alternatives here:
Java 8 Stream
For me, your problem looks like it can be resumed to a map/reduce problem. And if you can use Java 8 streams, you can delegate performance issues to it. What I'd do :
 1. Create a parallel stream, containing your processing input (you can even use methods to generate inputs on the fly). Note that you can implement your own Spliterator, to fully control the browsing and splitting of your input (cells on a grid ?).
 2. Use a map to process the input.
 3. Use a reduce method to merge all previously computed results.
Simple example (based on your example):
// Create a pool with wanted number of threads
    final ForkJoinPool pool = new ForkJoinPool(4);
    // We give the entire procedure to the thread pool
    final int result = pool.submit(() -> {
        // Generate a hundred counters, initialized on 0 value
        return IntStream.generate(() -> 0)
                .limit(100)
                // Specify we want it processed in a parallel way
                .parallel()
                // The map will register processing method
                .map(in -> incrementMultipleTimes(in, 20))
                // We ask the merge of processing results
                .reduce((first, second) -> first + second)
                .orElseThrow(() -> new IllegalArgumentException("Empty dataset"));
    })
            // Wait for the overall result
            .get();

    System.out.println("RESULT: " + result);

    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);

Some things to be aware of :
 1. By default, parallel streams execute tasks on JVM Common fork-join pool, which could be limited in number of executors. But there's ways to use your own pool : see this answer.
 2. If well-configured, I think that's the best method, because parallelism logic has been taken care of by JDK developper themselves.
Phaser
If you cannot use java8 functionality (or I've misunderstood your problem, or you really want to handle low-level management yourself), the last clue I can give you is: Phaser object.
As stated by the doc, it's a re-usable mix of cyclic barrier and countdown latch. I've use it multiple times. It's a complex thing to use, but it's also really powerful. It can be used as a cyclic barrier, so I think it fits your case.

A: You could really consider following the 'official' example from its (CyclicBarrier) documentation:
 class Solver {
   final int N;
   final float[][] data;
   final CyclicBarrier barrier;

   class Worker implements Runnable {
     int myRow;
     Worker(int row) { myRow = row; }
     public void run() {
       while (!done()) {
         processRow(myRow);

         try {
           barrier.await();
         } catch (InterruptedException ex) {
           return;
         } catch (BrokenBarrierException ex) {
           return;
         }
       }
     }
   }

   public Solver(float[][] matrix) {
     data = matrix;
     N = matrix.length;
     barrier = new CyclicBarrier(N,
                                 new Runnable() {
                                   public void run() {
                                     mergeRows(...);
                                   }
                                 });
     for (int i = 0; i < N; ++i)
       new Thread(new Worker(i)).start();

     waitUntilDone();
   }
 }

In your case

*

*processRow() would generate a partial generation (the task is divided into N pieces, and the workers can get their number on initialization, or just use the number returned by barrier.await() (in this case the workers should start with an await)

*mergeRows(), in the anonymous Runnable passed to the barrier at construction, is the place where an entire generation is ready, you can print it on the screen or something (and perhaps swap some 'currentGen' and 'nextGen' buffers). When this method returns (or more precisely the run()), the barrier.await() calls in the workers also return and calculation of the next generation starts (or not, see the next bullet point)

*done() decides when the threads should exit (instead of producing a new generation). It can be a 'real' method, but a static volatile boolean variable would also work

*waitUntilDone() could be a loop over all the threads, join()-ing them. Or just wait for something what you can trigger (from 'mergeRows') when the program should exit


text:
Q: Detect if page is in frame of webcam I want to scan some documents and I want to know when a page is "in the frame" of the camera. What I mean by this is the optimal distance from camera to page document (but without cutting any of the document). I want to run the detection program in a loop, so that the user calibrates the camera distance for each document before scanning.
How can I do this?

A: You can apply OpenCV findContour on the image to detect the document edges. For this you need to determine an appropriate threshold value which discriminate between background and document.
Then using the contour information, you can tell if the document is touching the limits of the image.


text:
Q: Is there a way to subset arrays with nonmatching indices in python? I'm currently working on translating an R file into python for the sake of reproducibility. I'm stuck on a user-defined function titled get_density (see below). part of the user-defined function uses R's kernel density estimator function, which returns a list of 3 arrays. My problem is in the last line of the user-defined function. In that line, the last element of the kde2d list is subsetted from the list, and that element is then subsetted by a separate matrix. When I try the same thing in python I receive the error "index 100 is out of bounds for axis 0 with size 100."
I'm currently translating from rStudio in Spyder. I've recreated the kde2d and get_density function, except for the last line, but when I try to subset the resulting matrix 'z' in python, I continually get an error message.
Here is the original R code I am trying to translate:
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

Here is my python translation:
def kde2d(vals1, vals2, N):
    x=np.linspace(np.min(vals1), np.max(vals1), N)
    y=np.linspace(np.min(vals2), np.max(vals2), N)
    X,Y=np.meshgrid(x,y)
    positions = np.vstack([Y.ravel(), X.ravel()])

    values = np.vstack([vals1, vals2])
    kernel = sstat.gaussian_kde(values)
    Z = np.reshape(kernel(positions).T, X.shape)

    return [x, y, Z]

def get_density(x, y, N):
    dens = kde2d(x, y, N)
    ix = np.searchsorted(dens[0], x)
    iy = np.searchsorted(dens[0], y)
    ii = np.vstack([ix, iy])
    ii = np.rot90(ii)
    ii = np.flip(ii)
    ii = np.flip(ii, axis=1)
    z = dens[2]
    return(z[ii])

it is the return(z[ii]) line that causes the error.
The result from the working R code is a numeric list of values, and that is what I want in python. However the only result I get in python is
IndexError: index 100 is out of bounds for axis 0 with size 100

A: Contrary to R, Python, and most other programming languages, use zero-based indexing. So, an array/list with n elements starts with x[0] and ends with x[n-1]. In you case, x[99] is the last element of the list, and x[100] is out of range, so it produces an error.


text:
Q: entity generation in gateway app of jhipster I am using entity sub generator to generate entities in my jhipster gateway app by giving path of microservice app.
but looks like I have to run sub generator for every entity in microservice . is there any way that it can read all the .json file and in micro service and generate all the entities ?

A: I personally do as following :

*

*Copy repository ".jhipster" from the microservice repository into the Gateway repository

*Generate the gateway with the following command:
yo jhipster --with-entities

A: If you create your entities with jdl-studio you can specify microservices for them like in the doc.
microservice * with mysuperjhipsterapp except C
microservice C with myotherjhipsterapp

You can then generate the entitites with jhipster import-jdl my_file.jdl in both the gateway and the microservice.
You can skip entities from the gateway or the microservice by using  this options in your jdl file:
skipClient for A
skipServer for B


text:
Q: Gitlab-ce container on portworx volume fails to open unix sockets I'm trying to run Gitlab-ce docker container (12.6.1-ce) with a persistent volume for data (/var/opt/gitlab) configured on portworx cluster. The problem is, when Gitlab starts, it components try to open unix sockets on this volume, that is not supported.
How can I configure Gitlab to use unix sockets on another location (like /var/run), or maybe there is another solution?


text:
Q: How to enable Facebook OAuth 2.0 completely serverside? I basically want to save the facebook ID of a given user so I can receive more material via Facebook. Ideally I want a solution that neither uses javascript nor cookie, just serverside but there was no example, just directions,  so I've put together one we can discuss. Here's the code that I think works when I just link a user to the OAuth dialog for my website:
https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri=http://www.kewlbusiness.com/oauth
Then I handle it like this to get the userdata:
class OAuthHandler(webapp2.RequestHandler):
    def get(self):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://www.koolbusiness.com/oauth',
      )
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        token_response = file.read()
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = facebook.GraphAPI(access_token)
      user = graph.get_object("me")
      self.response.out.write(user["id"])
      self.response.out.write(user["name"])

So with this I can "log in with Facebook" for my website without a lot of messy javascript and cookies we don't want. I wanted to enable "log in with Facebook" for my website. It should work without cookies and without javascript but the first thing they try to make you do is Javascript and cookies. So I've made a solution that seems to work without cookie and without javascript, just OAuth 2.0: Can you say something about my "solution"? The practical use I'm looking for is enabling simple function which FB user did what on my website and admitting facebook accounts to log in the way that is getting standardized.
I just thought it must work without javascript SDK and without cookie and it seems it is the case. Can you tell what are my advantages and disdvantages with this "solution"? I think it's much better than Javascript + Cookie so why do they trick us to use javascript and cookie when the minimal example seems to be 100 % serverside?
Thank you
Update
It seems right and behaves right and I can also use the userdata with the datatore and render my FB name to the front page with no javascript and no cookie, just python:
class FBUser(db.Model):
    id = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    name = db.StringProperty(required=True)
    profile_url = db.StringProperty()
    access_token = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    picture = db.StringProperty()
    email = db.StringProperty()
    friends = db.StringListProperty()
    dirty = db.BooleanProperty()

class I18NPage(I18NHandler):

    def get(self):
    if self.request.get('code'):
          args = dict(
            code = self.request.get('code'),
            client_id = facebookconf.FACEBOOK_APP_ID,
            client_secret = facebookconf.FACEBOOK_APP_SECRET,
            redirect_uri = 'http://www.kewlbusiness.com/',
          )
      logging.debug("client_id"+str(args))
          file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
          try:
        logging.debug("reading file")
            token_response = file.read()
        logging.debug("read file"+str(token_response))
          finally:
            file.close()
          access_token = cgi.parse_qs(token_response)["access_token"][-1]
          graph = main.GraphAPI(access_token)
          user = graph.get_object("me")   #write the access_token to the datastore
      fbuser = main.FBUser.get_by_key_name(user["id"])
          logging.debug("fbuser "+str(fbuser))

          if not fbuser:
            fbuser = main.FBUser(key_name=str(user["id"]),
                                id=str(user["id"]),
                                name=user["name"],
                                profile_url=user["link"],
                                access_token=access_token)
            fbuser.put()
          elif fbuser.access_token != access_token:
            fbuser.access_token = access_token
            fbuser.put()
           self.render_jinja(
                'home_jinja',request=self.request,fbuser=user,...

having the variable fbuser for a facebook user and the variable user for a google user now admits me to use facebook for my website without buggy messy unneccessary javascript + cookie.
Now I could render and view my facebook name from my website which is great that it finally works the way it's supposed to indepedent of javascript and doesn't need a cookie.
Why does the documentation recommend javascript + cookie when serverside OAuth 2.0 is the cleanest solution? Do you agree that this is the best solution since it doesn't depend on if you use javascript or cookie?
Update
Possible duplicate question when I now have seen that other guys couldn't log out with server code, they had to resort to the Javascript SDK and a requirement can be that it must and should work with no javascript so I did some debugging and found that "clearing" the cookie and I had to change the name of the cookie and though it works I would like your comment and/or test how you think my project solved this. A logout link like this one should work but it doesn't. If I log out twice it works and that's why this is a strange bug since I could fix it but I still don't know what makes logout require a 2nd hit:
https://www.facebook.com/logout.php?next=http://www.myappengineproject.com&access_token=AAACVewZBArF4BACUDwnDap5OrQQ5dx0jsHEKPJkIJJ8GdXlYdni5K50xKw6s8BSIDZCpKBtVWF9maHMoJeF9ZCRRYM1zgZD
It looks like I was not the only one trying to avoid javascript altogether for a solution with OAuth 2.0 serverside. People could do everything but they couldn't logout:
Facebook Oauth Logout
The official documentation for OAuth 2.0 with Facebook says:

You can log a user out of their Facebook session by directing them to
  the following URL:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
YOUR_URL must be a URL in your site domain, as defined in the
  Developer App.

I wanted to do everything serverside and I found that the suggested way to link leaves the cookie so that the logout link doesn't work:
https://www.facebook.com/logout.php?next=http://{{host}}&access_token={{current_user.access_token}}
It does redirect but it doesn't log the user our of my website. It seemed like a Heisenbug since this was changing to me and there was not much documentation. I anyway seemed to be able to achieve the functionality with a handler that manipulates the cookie so that in effect the user is logged out:
class LogoutHandler(webapp2.RequestHandler):
    def get(self):
        self.set_cookie("fbsr_" + facebookconf.FACEBOOK_APP_ID, None, expires=time.time() - 86400)
        self.redirect("/")
    def set_cookie(self, name, value, expires=None):

        if value is None:
            value = 'deleted'
            expires = datetime.timedelta(minutes=-50000)
        jar = Cookie.SimpleCookie()
        jar[name] = value
        jar[name]['path'] = '/'
        if expires:
            if isinstance(expires, datetime.timedelta):
                expires = datetime.datetime.now() + expires
            if isinstance(expires, datetime.datetime):
                expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
            jar[name]['expires'] = expires
        self.response.headers.add_header(*jar.output().split(': ', 1))

So mapping the handler to /auth/logout and setting this to the link effectively logs the user out of my site (without logging the user out of facebook, hopefully and untested)
Some other parts of my code is handling the OAuth tokens and cookie lookups for the Oauth communication:
def get(self):
    fbuser=None
    profile = None
    access_token = None
    accessed_token = None
    logout = False
    if self.request.get('code'):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://self.get_host()/',
      )
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        token_response = file.read()
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = main.GraphAPI(access_token)
      user = graph.get_object("me")   #write the access_token to the datastore
      fbuser = main.FBUser.get_by_key_name(user["id"])
      logging.debug("fbuser "+fbuser.name)

      if not fbuser:
        fbuser = main.FBUser(key_name=str(user["id"]),
                            id=str(user["id"]),
                            name=user["name"],
                            profile_url=user["link"],
                            access_token=access_token)
        fbuser.put()
      elif fbuser.access_token != access_token:
        fbuser.access_token = access_token
        fbuser.put()

    current_user = main.get_user_from_cookie(self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
    if current_user:
      graph = main.GraphAPI(current_user["access_token"])
      profile = graph.get_object("me")
      accessed_token = current_user["access_token"]

I didn't make a loginhandler since login basically is the code above at my root request handler. My user class is as follows:
class FBUser(db.Model):
    id = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    name = db.StringProperty(required=True)
    profile_url = db.StringProperty()
    access_token = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    picture = db.StringProperty()
    email = db.StringProperty()

I mocked together two basic providers

And I use the variable current_user for the facebook user and the variable user for the google user and the variable fbuser for a user who is logging in and therefore has no cookie match.
The cookie lookup code I use is the following and I think I understand it and that it does what I want:
def get_user_from_cookie(cookies, app_id, app_secret):
    """Parses the cookie set by the official Facebook JavaScript SDK.

    cookies should be a dictionary-like object mapping cookie names to
    cookie values.

    If the user is logged in via Facebook, we return a dictionary with the
    keys "uid" and "access_token". The former is the user's Facebook ID,
    and the latter can be used to make authenticated requests to the Graph API.
    If the user is not logged in, we return None.

    Download the official Facebook JavaScript SDK at
    http://github.com/facebook/connect-js/. Read more about Facebook
    authentication at http://developers.facebook.com/docs/authentication/.
    """
    logging.debug('getting user by cookie')
    cookie = cookies.get("fbsr_" + app_id, "")
    if not cookie:
        logging.debug('no cookie found')
        return None
    logging.debug('cookie found')
    response = parse_signed_request(cookie, app_secret)
    if not response:
        logging.debug('returning none')
        return None

    args = dict(
        code = response['code'],
        client_id = app_id,
        client_secret = app_secret,
        redirect_uri = '',
    )

    file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
    try:
        token_response = file.read()
    finally:
        file.close()

    access_token = cgi.parse_qs(token_response)["access_token"][-1]
    logging.debug('returning cookie')
    return dict(
        uid = response["user_id"],
        access_token = access_token,
    )

I had to learn cookies to solve this and I hope you can comment more. Outputting the welcome message required 3 variables, one for google user, one for logged in facebook user and the variable fbuser for the case mentioned in the answer:

JavaScript/Cookies are used when you're trying to authenticate an new
  user. That aren't exists in your database, and you don't have his
  accessToken.

So I had to use 3 variables, maybe you can do it with only 2 variables?
    {% if user or current_user or fbuser %}

            {% trans %}Welcome,{% endtrans %} {{ current_user.name }}{% if not current_user and user %}{{ user.nickname() }}{% endif %}{% if not current_user and not user and fbuser %}{{ fbuser.name }}{% endif %}

        {% endif %}

A: JavaScript/Cookies are used when you're trying to authenticate an new user. That aren't exists in your database, and you don't have his accessToken.
When you you have user's accessToken - you can access Facebook API from any programing language, through HTTP, without cookies/javascript if you wish. There is python client, for example: http://github.com/pythonforfacebook/facebook-sdk (was https://github.com/facebook/python-sdk)

A: Found this. Looks good too and it caters for more than just fb. https://code.google.com/p/gae-simpleauth/


text:
Q: Work done in equilibrium positions I am confused in work done against friction. Let $F$ be the friction when a  big stone is pushed by person on ground and $T$ be the component of force applied by a  person in the direction of displacement $S$.
I think $T$ should be greater than $F$, otherwise stone will not move. Then $T$ is not equal to $F$. But why do we check work done against friction as $FS$? I mean why isn't it $TS$?

A: If $T$ > $F$  , the stone will have an acceleration ,say $a$ .
$$M_{stone}a=T-F$$
So , $a=\frac{T-F}{M_{stone}} >0$ .
The stone will have the speed $v(t)=at$ , so a kinetic energy $E_k=\frac{M_{stone}v^2}{2}=\frac{M_{stone}(at)^2}{2}=\frac{t^2(T-F)^2}{2M_{stone}}$ .
The idea is that you have done the work $TS$ , which goes in overcoming friction ( $FS$ ) and accelerating the stone ( $E_k$) .
As an exercise  , try to write the equation $TS=FS+E_k$ and see if it's checked.


text:
Q: About numpy array operations, new versus old, in python Sorry if I asked a stupid question. I cannot understand the following codes in python. Why my operations on the "new" array also work on the "old" array?
import numpy as np
old = np.array([[1, 1, 1], [1, 1, 1]])
new = old
new[0, :2] = 0
new==old

output is "TRUE".
I have been using MATLAB for years and just recently start to learn Python. This is totally different from Matlab. And I cannot comprehend the above codes and ask if there is any deep reason for such a result. Thanks a million!


text:
Q: Translator Trouble This is how the webpage looks like http://prntscr.com/5o16hz
I've created an onclick function for the 'generate romaji' button that checks if 'vowels' or 'all columns' is checked, and then displays random romaji characters in the div right under the 'generate romaji' button.
The problem is, it isn't working and i'm not sure why.
var vowel = document.getElementById("vowels");
//'vowel' var is for the 'vowels' checkbox//
var allhiragana = document.getElementById("all");
//'allhiragana' var is for the 'all columns' checkbox//
var genDiv = document.getElementById("romaji");
var showDiv = document.getElementById("hiragana");
var fullromaji = ['a','i','u','e','o',"ka","ki","ku""ke","ko","sa",'shi','su','se','so',
"ta","chi","tsu","te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi",
"mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro",
"wa","wo"];
var fullhiragana = ['あ','い','う','え','お','か','き','く','け','こ','さ','し','す','せ','そ',
'た','ち' 'つ','て','と','な','に','ぬ','ね','の','は','ひ','ふ','へ','ほ','ま','み','む','め','も',
'や','ゆ','よ','ら','り','る''れ','ろ','わ','ゐ','ゑ','を'];
//first random factor//
var r = Math.floor(Math.random() * fullromaji.length);
//second random factor//
var h = Math.floor(Math.random() * fullromaji.length);
//button functions//
var genromaji = function() {
    if(vowel.prop('checked')){
        fullromaji = ["a",'i','u','e','o'];
        fullhiragana = ['あ','い','う','え','お'];
        genDiv.innerHTML = fullromaji[r];
        showDiv.innerHTML = fullhiragana[r];
        showDiv.text().hide();
        }
    if(allhiragana.prop('checked')) {
        fullromaji = ["ka","ki","ku","ke","ko","sa",'shi','su','se','so',
"ta","chi","tsu","te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi",
"mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro",
"wa","wo"];
        fullhiragana = ['あ','い','う','え','お','か','き','く','け','こ','さ','し','す','せ','そ',
'た','ち','つ','て','と','な','に','ぬ','ね','の','は','ひ','ふ','へ','ほ','ま','み','む','め','も',
'や','ゆ','よ','ら','り','る''れ','ろ','わ','ゐ','ゑ','を'];
    genDiv.innerHTML = fullromaji[h];
    showDiv.innerHTML = fullhiragana[h];
    showDiv.text().hide();
    }
    else {
    alert("please check one box before generating Romaji");
};
var showhiragana = function() {
    if(getDiv.text() === typeof('string')) {
        showDiv.text().show();
    }
    else {
    alert("Please generate the Romaji first");
    }
};

The 'genDiv' is the div that is under the 'generate romaji' button, and its inner text should be a random string from the 'fullromaji' array, and the showDiv is the div under the
'show hiragana' button that shows the corresponding hiragana from the 'fullhiragana' array.
I'm not sure if the problem is the code itself, or maybe its the way I linked it in the html, which, for the sake of reading this question, is shorted but still visible in this printscreen
http://prntscr.com/5o1eb9


text:
Q: A non-existence example of a sufficient statistic In parametric statistical inference, a statistic $T$ of some variable $X$ (thought of as experimental or observational data) is sufficient for the parameter $\theta$ if is captures the essential information in the data $X$ about the parameter $\theta$ (there are several equivalent definitions for this). It is implicitly understood that the random variable $X$ has a probability distribution $f(x;\theta)$, where the parameter $\theta$ is of course unknown.
Related is the concept of a minimal sufficient statistic, which captures nothing more than the essential.

*

*Is it true that any random variable $X$ as above has a sufficient statistic?

*Suppose $X$ has a sufficient statistic $T$. Must it also have a minimal sufficient statistic?

I'd be glad to have either a concise proof or a simple counter-example for each of these two.

A: *

*In a degenerate manner your sample $(X_1,...,X_n)$ is always a sufficient statistic from Fisher's information perspective. $T(X)$ is sufficient statistic for $\theta$ iff $\mathcal{I}_{\theta}(T(X))=\mathcal{I}_{\theta}(X_1,...,X_n)$.Thus for every parametric structure you can take the data points themselves as the sufficient statistic.

*No. You have a minimial sufficient statistic iff your parametric distribution $f(X;\theta)$ can be factorized into $h(X)g(\theta; T(X))$, then the $T(X)$ is the minimal sufficient statistic or can be reduced to one. Moreover, it is pretty common to fail to satisfy this condition, e.g., Weibull distribution which density function is given by
$$
f(x;\theta)=\frac{\theta x^{\theta-1}}{\lambda^\theta}\exp\{-x^\theta/\lambda^\theta\}, x\ge 0,
$$
where $\theta > 0, \theta \neq 1$ is the unknown shape parameter, cannot be factorized w.r.t $\theta$.


text:
Q: .htaccess that redirects all subpages to their root I've got multiple domains that have been redirected to a specific subpage.
Example:
domain1.com -> domain.com/1
domain2.com -> domain.com/2
The problem is that it exists lots of links like this: domain1.com/test. With the 301 redirect now the result is the following domain.com/1test aka a 404.
How do I write a .htaccess file on my existing server that makes the domain1.com/test go to domain.com/1 on default. It's 1000 of links, so it need to be done by default.
Thanks to anyone who can help! :)

A: I think the following rewriteRule in your .htaccess
RewriteCond %{HTTP_REFERER} ^http://domain1.com [NC]
RewriteRule ^(.*)$ http://domain.com/1 [R=301,L]

should be your way to archive this.


text:
Q: Accessing a struct without the struct being global I've got a struct called members which contains a bunch of char arrays and integers. The struct has been declared in Header.h and defined it by "struct members pt" in source.c, inside main. From here a for-loop is being runned 5 times and adding variables to the character arrays and ints in pt[x].
Now I need to be able to access this from a function called void search(int a); (Should probably not be a void since I want it to return a value. But I'll fix that later)
What void search is supposed to do is basicly
int willReturn[10];
int b = 0;
for(int x = 0; x<a; x++)
{
    if(pt[x].hasPayed == 0)
    {
        willReturn[b] = x;
        b++;
    }
}

There might be something wrong about that code, but the thing that I need to know is how I can access pt[x].hasPayed.
Any ideas?
I do not want to use any global variables.
Thank you in advance.

A: Below sample code might help you.
header.h
struct members {
    int hasPayed;
};

main.c
#include <stdio.h>
#include <string.h>
#include "main.h"

typedef struct members MEMBERS;

void print_member(MEMBERS *pt) {
    int i;
    for(i =0 ; i< 10; i++)
    {
        printf(" %d\n",pt[i].hasPayed);
    }

}

void main () {
    MEMBERS pt[10];
    int i;
    for(i =0 ; i< 10; i++)
    {
        pt[i].hasPayed= i;
    }
    print_member(pt);
}

Instead of print_member code your search logic.

A: Pass a pointer to pt as a paraamter to search. e.g void search(int a, struct members *pt).

A: Another way if you don't want to pass pointers. Place pt in a function as a static variable.
struct members** ____get_pt(){
    static struct members pt[ /* size */ ];
    /*
        or for dynamical size,
    static struct members* pt;
    */
    return &pt;
}
// Define a macro for convenience, above where you want to use 'pt'.
#define PT (*____get_pt())

Then you can use PT[x].hasPayed everywhere, without global variables.
However, this could do not improve your code ...


text:
Q: Accessing an API (made in the Wolfram Cloud) using a standalone application I created an API function that given an integer, would return the factors of that integer.
func=APIFunction[{"x"->"Integer"},FactorInteger[#x]&];
api=CloudDeploy[func]

This returns a URL which I can now append my query string to and submit for an answer.
Hyperlink[First[api]<>"?x=2434500"]

Instead of making this function call in Mathematica, I would like to call this function in a standalone application (using LiveCode). When I attempt this, my application requests the info from the URL, but it returns nothing. I believe this may be because there are credentials that I must provide to the Wolfram Cloud so it knows it is me. However, I do not know how to do this. Does anyone have experience making API calls to Wolfram Cloud (without using the EmbedCode[] function)? How do I go about authenticating with Wolfram Cloud? Are there other things that must be done by my application before this would work?
I also tested this by making an API that was Public like so:
func=APIFunction[{"x"->"Integer"},FactorInteger[#x]&];
api=CloudDeploy[func,Permissions->"Public"]

This also did not work.

A: If you've made the API public, you should not need to authenticate. You can validate this by opening the URL in a different browser that does not have an OAuth session with any wolfram sites.  You may be running into XSS issues, which may require that you use CORS or similar.  I'm not familiar with LiveCode, but you might look into how it handles XSS issues.


text:
Q: Finding the decimal value of numbers in Two's and One's Complement I want to turn a negative float number into decimal one but I dont know how to do it.
for example I got the number 101.1011 and I need to find the decimal value in Two's complement ( the answer supposed to be -2.3125) and in One's complement (-2.25)

A: I assume you know what binary numbers represent in general.
For Two's complement you just have to know that the left-most bit is also telling you if the number is negative or positive.
So for the Two's complement of your example it would be:
-(22) + 20 = -4 + 1 = -3 for the integer part (left-side of the decimal point) and 2-1 + 2-3 + 2-4 = 0.5 + 0.125 + 0.0625 = 0.6875.
So, you get -3 + 0.6875 = -2.3125.
For One's complement you look at the left-most bit, that tells you it is a negative number. So you invert every bit and take the left-most bit as sign-bit (ignore its value). Then you compute it as a normal binary number.
For your example this would be:
101.1011 -> -10.0100 = -(21) + 2-2 = -2.25


text:
Q: FIM CM Broken After Manual Cert Renewal I recently attempted to renew the certificate for the clmAgent user account according to these directions:
http://technet.microsoft.com/en-us/library/hh149034%28v=ws.10%29.aspx
I logged in with the clmAgent account, went to Certificates MMC, right-clicked the clmAgent certificate in the Current User -> Personal store, and chose "Renew Certificate with New Key..."
The certificate update was successful.  I then updated the web.config with the new certificate Thumbprint/Hash.  I also added the new thumbprint to the Signing Certificates Tab under Policy Module on the CA.  I then did an iisreset and restarted the FIM CM Update service.
Now FIM is able to issue new smartcards, but is unable to retire existing ones. When I attempt a retire operation, I am given the error "Data at the root level is invalid. Line 1. Position 1."  CNG Key isolation service is running. Certificate template versions are 2003 and were not changed.  Furthermore it renders the smartcard seemingly unusable because it wipes the data off the card, but FIM insists that the card is still in use so I cannot re-enroll it.

A: Answering my own question.
Since I renewed the agent certificate with a new private key, that means that I had to put the hash of the new certificate in the web.config file as the Clm.Encryption.Certificate.Hash for new smartcards going forward, but I had to leave the Clm.Decryption.Certificate.Hash as the thumbprint of the previous (and now archived) certificate, so that smart cards deployed with the old certificate can be decrypted and thus retired.


text:
Q: Unable to download dependency org.codehaus.jackson:jackson-core-asl for version [1.9.13] I wite you because I am having some issue with maven and jackson-core-asl dependency, and I hope you can help me.
Since this morning (15/4/2019) we are having problems in our CI because of the following error:
Failed to collect dependencies at org.codehaus.jackson:jackson-core-asl:jar:[1.9.13,1.9.13]: No versions available for org.codehaus.jackson:jackson-core-asl:jar:[1.9.13,1.9.13] within specified range -> [Help 1]

As long as it was happening in a big maven project, I've created the following mini pom.xml in order to figure out what was happening.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.davide</groupId>
    <artifactId>davide-test</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>my-app</name>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>[1.9.13]</version>
        </dependency>
    </dependencies>
</project>

If you run mvn clean install against the previous pom , you will receive the aftermentioned error.
I am using the following maven configuration
$ mvn -version
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T20:49:05+01:00)
Maven home: /home/davide.pallaoro/.sdkman/candidates/maven/current
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8.0.171-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-957.10.1.el7.x86_64", arch: "amd64", family: "unix"

And I have no custom configuration in $HOME/.m2/settings.xml (the file doe not exist in my machine)
But if you change the version from [1.9.13] to 1.9.13 or to [1.9.9] and run mvn clean install this will work correctly.
So it compiles when version is :

*

*1.9.13

*1.9.12

*1.9.11

*[1.9.11]

*1.9.10

*[1.9.10]

*1.9.9

*[1.9.9]

And it does not compile when version is :

*

*[1.9.13]

*[1.9.12]

It seems that this problem started on Monday 15 April 2019, because on Friday 12 April 2019 we did not have those build problem and the project which we are working on did not change in the last days.
Do you know if something has changed in the last few days (from 12/4/2019 to 15/4/2019) about Jackson artifact in the public maven repos?
Many thanks for reading this and for your help, let me know in case you need any clarification.
Kind regards.
EDIT
Here is the output of the maven copilation
https://drive.google.com/open?id=1QYH_FCYZ7_iS08cKrUO-UFDZ1oyTktUS
(I put it in my drive because the output was too big and Stackoverlow did no let me add it to the post)
I've notices that in the maven central repo central.maven.org/maven2/org/codehaus/jackson/jackson-core-asl the 2 versions that fails if exact [1.9.12] [1.9.13] have no date. Maybe this could be the reason ?
maven central for jackson-core-asl


text:
Q: Triggering resize of jqGrid after user shows/hides columns In jqGrid, after a users chooses to remove a column(s), a grid's width becomes smaller.  Therefore, I think it would be appropriate to trigger a resize at this point using $("#myGrid").trigger("resize"). However, to what jqGrid event should I attach this?
I tried triggering a resize manually on the Firebug Console after using the Column Chooser and it worked well.
I also tried the recommendations in this question but without any results.

A: I solved my own problem:
     $("#myGrid").jqGrid("columnChooser", {
        done: function() {
          $("#myGrid").trigger("resize");
        }
      });

A: If you use the last version of jqGrid (currently it is 4.1.1) the bug fixes which I described before are already included in the main code of jqGrid. So how you can see from the demo all seems to work correct without doing anything.


text:
Q: How to handle new tab vs new window in selenium webdriver in multiple browsers I have a bit of code that goes through a help menu on a site i am testing and selects a few elements to interact with.  However if I run the code in Firefox, the elements open up in a new window.  If I run the code in Chrome, the elements open up in a new tab.  I can handle either or but I don't know how to handle both.
I tried to change the profile of Firefox to ONLY use new tabs but no matter what I set preferences to in code or just using a new profile via ProfileInt, Firefox always uses new windows regardless.
Is there a sure fire way programmatically to force firefox to open only tabs every time for a new link or chrome to always use a new window?  So far all my research has given me nothing.


text:
Q: Different behaviour in response if Accept:application/json is specified The Http method used is GET and I'm calling the same webservice method (with same parameters).
But if I add to request an Accept header with application/json, the output differs.
The cause is a Bitmap field in my object named User, which holds an avatar image.
If i leave out the Accept application/json header, this is the simplified output (XML):
<!-- language: lang-xml -->
<ArrayOfUser xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/XTraN4ForcesFSDomain.Domain">
<User>
    <Id>02ddf1e4-ad76-4778-8887-a186014939f8</Id>
    <Avatar xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing" i:nil="true" />
    <IsActive>false</IsActive>
    <LastAccess>0001-01-01T00:00:00</LastAccess>
    <Username>quisquam</Username>
    <!-- Other properties -->
</User>
<User>
    <Id>17db833c-5008-44f0-a713-a186014c22a5</Id>
    <Avatar xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing">
        <Data xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:base64Binary" xmlns="">iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABGdBTUEAAK/INwWK6[...]BIJS/Wd6Pgu/mOoS/HADwfwFUI4VkJHOgAgAAAABJRU5ErkJggg==</Data>
    </Avatar>
    <IsActive>false</IsActive>
    <LastAccess>0001-01-01T00:00:00</LastAccess>
    <Username>labore</Username>
</User>
</ArrayOfUser>

Well, this is just fine! The image (Base64) is there. If I change my request to get JSON, it returns no image, just the name of the class that it represents:
<!-- language: lang-json -->
[
    {
        "Username": "quisquam",
         "LastAccess": "0001-01-01T00:00:00",
        "IsActive": false,
        "Avatar": null,
        "Id": "02ddf1e4-ad76-4778-8887-a186014939f8"
   },
   {
       "Username": "reiciendis",
       "LastAccess": "0001-01-01T00:00:00",
       "IsActive": false,
       "Avatar": "System.Drawing.Bitmap",
       "Id": "17db833c-5008-44f0-a713-a186014c22a5"
   },
]

The webservice mthod is
<!-- language: lang-c# -->
public IQueryable<User> Get()
{
    // return stuff (no big deal here)
}

The code is the same, so why won't JSON return a base64 string like it should?

A: As LukeH said, converting my Bitmap to byte array solved my issues.


text:
Q: Search iOS photos by keyword? Apple's Photos app allows users to query photos with search keywords like "surfing", "food", "sky".
How could a third-party iOS app with Camera and Photos permissions search the phone's camera roll using arbitrary strings?
Searching for Photos is part of the SiriKit API. Could we pass strings as a possible approach or is there a better way?

A: I could not find a way even after longer research. But the good news is that you can use the exact same neural network used to achieve the results in the photo app to build your own search index. Here is some sample code:
let fetchOptions = PHFetchOptions()
let fetchResult = PHAsset.fetchAssets(with: fetchOptions)
fetchResult.enumerateObjects { asset, index, pointer in
    self.assetManager.requestImage(for: asset,
                                   targetSize: CGSize(width: 150, height: 100),
                                   contentMode: .aspectFit,
                                   options: .none) { image, metadata in
            if let uiImage = image, let cgImage = uiImage.cgImage {
                let requestHandler = VNImageRequestHandler(cgImage: cgImage)
                let request = VNClassifyImageRequest()
                try? requestHandler.perform([request])
                let results = request.results as! [VNClassificationObservation]
                // Filter the 1303 classification results, and use them in your app
                // in my case, fullfill promise with a wrapper object
                promise(.success(ClassifiedImage(imageIdentifier: asset.localIdentifier,
                                classifications: results.filter { $0.hasMinimumPrecision(0.9, forRecall: 0.0) }.map{
                                    ($0.identifier, nil)
                                    })))
            }

        }
}

More info: https://developer.apple.com/videos/play/wwdc2019/222
Also note: When building a search index you can use the localIdentifier of class PHAsset when fetching the assets.


text:
Q: Autoban asyncio client arguments Disclaimer: This is my first time working with WS and MQTT, so structure may be wrong. Please point this out.
I am using autoban with asyncio to receive and send messages to a HA (HomeAssistant) instance through websockets.
Once my python code receives messages, I want to forward them using MQTT to AWS IoT service. This communication needs to work both ways.
I have made this work as a script where everything is floating within a file.
I am trying to make this work in a class structure, which is how my final work will be done.
In order to do that, I need my WebSocketClientProtocol to have access to AWSIoTClient .publish and .subscribe. Although WebSocketClientProtocol initialization is done through a factory, as a result I am not sure how to pass any arguments to it. For instance:
if __name__ == "__main__":

    aws_iot_client = AWSIoTClient(...)

    factory = WebSocketServerFactory('ws://localhost:8123/api/websocket')
    factory.protocol = HomeAssistantProtocol

How can I pass aws_iot_client to HomeAssistantProtocol?

I have found examples of Autobahn - Twisted that do this using self.factory on the WebSocketClientProtocol subclass, but this is not available for asyncio.

A: I found that calling run_until_complete on returns transport, protocol instances, so I can then I can pass the AWS client to it.
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, '127.0.0.1', 9000)
transport, protocol = loop.run_until_complete(coro)


text:
Q: How to add logo image in this bootstrap snippet The code is taken from here https://bootsnipp.com/snippets/featured/resize-amp-fixed-header-shrinking-header.
I need to add an image as logo and when it is checked it should redirect to homepage, how do I do that?

/*!
 * classie v1.0.0
 * class helper functions
 * from bonzo https://github.com/ded/bonzo
 * MIT license
 *
 * classie.has( elem, 'my-class' ) -> true/false
 * classie.add( elem, 'my-new-class' )
 * classie.remove( elem, 'my-unwanted-class' )
 * classie.toggle( elem, 'my-class' )
 */

/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false */

(function(window) {

  'use strict';

  // class helper functions from bonzo https://github.com/ded/bonzo

  function classReg(className) {
    return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  }

  // classList support for class management
  // altho to be fair, the api sucks because it won't accept multiple classes at once
  var hasClass, addClass, removeClass;

  if ('classList' in document.documentElement) {
    hasClass = function(elem, c) {
      return elem.classList.contains(c);
    };
    addClass = function(elem, c) {
      elem.classList.add(c);
    };
    removeClass = function(elem, c) {
      elem.classList.remove(c);
    };
  } else {
    hasClass = function(elem, c) {
      return classReg(c).test(elem.className);
    };
    addClass = function(elem, c) {
      if (!hasClass(elem, c)) {
        elem.className = elem.className + ' ' + c;
      }
    };
    removeClass = function(elem, c) {
      elem.className = elem.className.replace(classReg(c), ' ');
    };
  }

  function toggleClass(elem, c) {
    var fn = hasClass(elem, c) ? removeClass : addClass;
    fn(elem, c);
  }

  var classie = {
    // full names
    hasClass: hasClass,
    addClass: addClass,
    removeClass: removeClass,
    toggleClass: toggleClass,
    // short names
    has: hasClass,
    add: addClass,
    remove: removeClass,
    toggle: toggleClass
  };

  // transport
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(classie);
  } else {
    // browser global
    window.classie = classie;
  }

})(window);
/* =Reset default browser CSS. Based on work by Eric Meyer: http://meyerweb.com/eric/tools/css/reset/index.html
-------------------------------------------------------------- */

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
font,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td {
  background: transparent;
  border: 0;
  margin: 0;
  padding: 0;
  vertical-align: baseline;
}

body {
  line-height: 1;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  clear: both;
  font-weight: normal;
}

ol,
ul {
  list-style: none;
}

blockquote {
  quotes: none;
}

blockquote:before,
blockquote:after {
  content: '';
  content: none;
}

del {
  text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */

table {
  border-collapse: collapse;
  border-spacing: 0;
}

a img {
  border: none;
}

/* =Scss Variables
-------------------------------------------------------------- */

/* =Global
-------------------------------------------------------------- */

*,
*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  background-color: #3cb5f9;
  color: #505050;
  font-family: "Ubuntu", sans-serif;
  font-weight: 300;
  font-size: 16px;
  line-height: 1.8;
}

/* Headings */

h1,
h2,
h3,
h4,
h5,
h6 {
  line-height: 1;
  font-weight: 300;
}

a {
  text-decoration: none;
  color: #3cb5f9;
}

a:hover {
  color: #0793e2;
}

/* =Template
-------------------------------------------------------------- */

#wrapper {
  width: 100%;
  margin: 0 auto;
}

#main {
  background-color: #fff;
  padding-top: 150px;
}

.container {
  width: 80%;
  margin: 0 auto;
  padding: 0 30px;
}

section {
  padding: 60px 0;
}

section h1 {
  font-weight: 700;
  margin-bottom: 10px;
}

section p {
  margin-bottom: 30px;
}

section p:last-child {
  margin-bottom: 0;
}

section.color {
  background-color: #3cb5f9;
  color: white;
}

/* =Info Bar
-------------------------------------------------------------- */

#info-bar {
  background-color: #3cb5f9;
}

#info-bar a {
  color: white;
  font-size: 14px;
  text-transform: uppercase;
  display: inline-block;
  margin: 0;
  padding: 10px;
}

#info-bar a:hover {
  background-color: #0793e2;
}

#info-bar span.all-tutorials,
#info-bar span.back-to-tutorial {
  display: block;
  width: 50%;
}

#info-bar span.all-tutorials {
  float: left;
  text-align: left;
}

#info-bar span.back-to-tutorial {
  float: right;
  text-align: right;
}

/* =Header
-------------------------------------------------------------- */

header {
  width: 100%;
  height: 150px;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  background-color: #0683c9;
  -webkit-transition: height 0.3s;
  -moz-transition: height 0.3s;
  -ms-transition: height 0.3s;
  -o-transition: height 0.3s;
  transition: height 0.3s;
}

header h1#logo {
  display: inline-block;
  height: 150px;
  line-height: 150px;
  float: left;
  font-family: "Oswald", sans-serif;
  font-size: 60px;
  color: white;
  font-weight: 400;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -ms-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

header nav {
  display: inline-block;
  float: right;
}

header nav a {
  line-height: 150px;
  margin-left: 20px;
  color: #9fdbfc;
  font-weight: 700;
  font-size: 18px;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -ms-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

header nav a:hover {
  color: white;
}

header.smaller {
  height: 75px;
}

header.smaller h1#logo {
  width: 150px;
  height: 75px;
  line-height: 75px;
  font-size: 30px;
}

header.smaller nav a {
  line-height: 75px;
}

/* =Footer
-------------------------------------------------------------- */

/* =Extras
-------------------------------------------------------------- */

.clearfix:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

/* =Media Queries
-------------------------------------------------------------- */

@media all and (max-width: 660px) {
  /* =Header
  -------------------------------------------------------------- */
  header h1#logo {
    display: block;
    float: none;
    margin: 0 auto;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  header nav {
    display: block;
    float: none;
    height: 50px;
    text-align: center;
    margin: 0 auto;
  }
  header nav a {
    line-height: 50px;
    margin: 0 10px;
  }
  header.smaller {
    height: 75px;
  }
  header.smaller h1#logo {
    height: 40px;
    line-height: 40px;
    font-size: 30px;
  }
  header.smaller nav {
    height: 35px;
  }
  header.smaller nav a {
    line-height: 35px;
  }
}

@media all and (max-width: 600px) {
  .container {
    width: 100%;
  }
  #info-bar a {
    display: block;
  }
  #info-bar span.all-tutorials,
  #info-bar span.back-to-tutorial {
    width: 100%;
  }
  #info-bar span.all-tutorials,
  #info-bar span.back-to-tutorial {
    float: none;
    text-align: center;
  }
  #info-bar span.all-tutorials {
    border-bottom: solid 1px #0793e2;
  }
}

          Pratik

          Lorem
          Ipsum
          Dolor

Header Resize On Scroll with Animations

Cupcake ipsum dolor sit amet lollipop. Macaroon candy cotton candy bear claw macaroon carrot cake pastry icing dessert. Cupcake pastry tart sesame snaps lollipop donut pie. Cookie apple pie toffee lemon drops jelly beans cheesecake sweet roll.
              Jelly-o soufflé donut candy canes wafer dragée sweet cheesecake. Macaroon caramels pie cookie gummi bears. Ice cream jelly-o toffee cookie gingerbread cookie. Soufflé fruitcake jelly-o jelly chupa chups jelly beans. Dragée marzipan pastry
              macaroon oat cake muffin soufflé topping liquorice. Jelly-o chocolate cake lollipop.

Sugar plum muffin cookie pastry oat cake icing candy canes chocolate. Gummi bears chupa chups fruitcake dessert jelly. Muffin cookie ice cream soufflé pastry lollipop gingerbread sweet. Unerdwear.com bonbon candy marzipan bonbon gummies chocolate
              cake gummi bears powder. Unerdwear.com tart halvah chocolate cake dragée liquorice. Sugar plum chocolate bar pastry liquorice dragée jelly powder. Jelly tootsie roll applicake caramels. Marzipan candy tootsie roll donut. Gummies ice cream
              macaroon applicake.

              « Connect With Me | Chauhan PRatik

              « Go back to all tutorials?

Cupcakes for the people!

Cupcake ipsum dolor sit amet lollipop. Macaroon candy cotton candy bear claw macaroon carrot cake pastry icing dessert. Cupcake pastry tart sesame snaps lollipop donut pie. Cookie apple pie toffee lemon drops jelly beans cheesecake sweet roll.
              Jelly-o soufflé donut candy canes wafer dragée sweet cheesecake. Macaroon caramels pie cookie gummi bears. Ice cream jelly-o toffee cookie gingerbread cookie. Soufflé fruitcake jelly-o jelly chupa chups jelly beans. Dragée marzipan pastry
              macaroon oat cake muffin soufflé topping liquorice. Jelly-o chocolate cake lollipop.

Sugar plum muffin cookie pastry oat cake icing candy canes chocolate. Gummi bears chupa chups fruitcake dessert jelly. Muffin cookie ice cream soufflé pastry lollipop gingerbread sweet. Unerdwear.com bonbon candy marzipan bonbon gummies chocolate
              cake gummi bears powder. Unerdwear.com tart halvah chocolate cake dragée liquorice. Sugar plum chocolate bar pastry liquorice dragée jelly powder. Jelly tootsie roll applicake caramels. Marzipan candy tootsie roll donut. Gummies ice cream
              macaroon applicake.

Chocolate, vanilla, and red velvet

Cupcake ipsum dolor sit amet lollipop. Macaroon candy cotton candy bear claw macaroon carrot cake pastry icing dessert. Cupcake pastry tart sesame snaps lollipop donut pie. Cookie apple pie toffee lemon drops jelly beans cheesecake sweet roll.
              Jelly-o soufflé donut candy canes wafer dragée sweet cheesecake. Macaroon caramels pie cookie gummi bears. Ice cream jelly-o toffee cookie gingerbread cookie. Soufflé fruitcake jelly-o jelly chupa chups jelly beans. Dragée marzipan pastry
              macaroon oat cake muffin soufflé topping liquorice. Jelly-o chocolate cake lollipop.

Sugar plum muffin cookie pastry oat cake icing candy canes chocolate. Gummi bears chupa chups fruitcake dessert jelly. Muffin cookie ice cream soufflé pastry lollipop gingerbread sweet. Unerdwear.com bonbon candy marzipan bonbon gummies chocolate
              cake gummi bears powder. Unerdwear.com tart halvah chocolate cake dragée liquorice. Sugar plum chocolate bar pastry liquorice dragée jelly powder. Jelly tootsie roll applicake caramels. Marzipan candy tootsie roll donut. Gummies ice cream
              macaroon applicake.

Come to me!

Cupcake ipsum dolor sit amet lollipop. Macaroon candy cotton candy bear claw macaroon carrot cake pastry icing dessert. Cupcake pastry tart sesame snaps lollipop donut pie. Cookie apple pie toffee lemon drops jelly beans cheesecake sweet roll.
              Jelly-o soufflé donut candy canes wafer dragée sweet cheesecake. Macaroon caramels pie cookie gummi bears. Ice cream jelly-o toffee cookie gingerbread cookie. Soufflé fruitcake jelly-o jelly chupa chups jelly beans. Dragée marzipan pastry
              macaroon oat cake muffin soufflé topping liquorice. Jelly-o chocolate cake lollipop.

Sugar plum muffin cookie pastry oat cake icing candy canes chocolate. Gummi bears chupa chups fruitcake dessert jelly. Muffin cookie ice cream soufflé pastry lollipop gingerbread sweet. Unerdwear.com bonbon candy marzipan bonbon gummies chocolate
              cake gummi bears powder. Unerdwear.com tart halvah chocolate cake dragée liquorice. Sugar plum chocolate bar pastry liquorice dragée jelly powder. Jelly tootsie roll applicake caramels. Marzipan candy tootsie roll donut. Gummies ice cream
              macaroon applicake.

Sugar rush, oh my...

Cupcake ipsum dolor sit amet lollipop. Macaroon candy cotton candy bear claw macaroon carrot cake pastry icing dessert. Cupcake pastry tart sesame snaps lollipop donut pie. Cookie apple pie toffee lemon drops jelly beans cheesecake sweet roll.
              Jelly-o soufflé donut candy canes wafer dragée sweet cheesecake. Macaroon caramels pie cookie gummi bears. Ice cream jelly-o toffee cookie gingerbread cookie. Soufflé fruitcake jelly-o jelly chupa chups jelly beans. Dragée marzipan pastry
              macaroon oat cake muffin soufflé topping liquorice. Jelly-o chocolate cake lollipop.

Sugar plum muffin cookie pastry oat cake icing candy canes chocolate. Gummi bears chupa chups fruitcake dessert jelly. Muffin cookie ice cream soufflé pastry lollipop gingerbread sweet. Unerdwear.com bonbon candy marzipan bonbon gummies chocolate
              cake gummi bears powder. Unerdwear.com tart halvah chocolate cake dragée liquorice. Sugar plum chocolate bar pastry liquorice dragée jelly powder. Jelly tootsie roll applicake caramels. Marzipan candy tootsie roll donut. Gummies ice cream
              macaroon applicake.

          ← all tutorials
          CHUAHAN PRATIK

A: Inside the h1 tag (id logo) you should add an anchor tag and inside that an img tag. Now h1 should finally look like this.

    Pratik


text:
Q: CICS - Updates by Multiple users If around 50 users are trying to update the same field in a DB2 table, how will CICS handle this?
How is this handled in a COBOL DB2  Program?

A: Some care must be taken to mange data integrity when CICS pseudo conversational programs interact with DB/2 to
update a database,
especially when multiple CICS transactions may be attempting to read/update the same
DB/2 table row at nearly the same time.
What follows is a very simplified explanation of a common design pattern for pseudo conversational
CICS transactions (this is the most common type of interactive programming pattern for CICS). The answers to this question:
what-are-the-advantages-of-pseudo-conversational-vs-conversational-cics-programm provides
a short overview of how pseudo conversational cics works, you might want to review this before continuing...
Pseudo conversational CICS transactions are designed to pick up their current running
state from a COMMAREA (a chunk of memory that persists between transactions). The saved state
in the COMMAREA is used by the program to determine what needs to be done next. It then does it, determines what the next state
should be, saves the new state and any data it may
need to "remember"
into the CICS COMMAREA and then it exits - releasing all resources, including any DB/2 locks that it is holding.
DB/2 locks are key to preserving database integrity in the face of multiple select/update/insert/delete transactions competing for
the same database rows. The problem with pseudo conversational CICS is that these locks are lost between the time a transaction picks up
its data from a table and the time it needs to update the table.
The states that a typical pseudo conversational CICS transaction might go through are something like:

*

*Initial - Start a fresh transaction, Ask user to input Key Data (set next state to Display)

*Display - Validate Key entered on Initial State. Retrieve related data from DB/2 and display it (set next state to Commit)

*Commit - Validate changed data from Display state and update DB/2 (set next state to Initial)

Notice that data are retrieved during Display. A read lock is taken by DB/2 at this
time to protect against other transactions from updating the row as it is being read. Depending on how DB/2 and your
DML are configured, this lock may only be active for the duration of the Display phase or just while the row is being
retrieved. In either case,
that lock is lost as soon as the program exits. When the program restarts again it will be in Commit state ready to
execute the appropriate DB/2 update/insert DML to effect the requested changes to the database.
Since there are no persistent DB/2 locks held between these state transitions nothing prevents another
transaction from accessing or changing data between the time the first transaction did its display and then its update.
This can lead to serious data integrity issues. Notice that while a transaction is active, it may hold DB/2 locks that
effectively prevent other transactions for either reading uncommitted updates or form updating the rows it
is "looking at" - but it cannot hold these between invocations of the "conversation".
A common mechanism used by programmers to maintain data integrity over the course of a pseudo conversational CICS
transaction is to have all transactions
rely on a single common updatable resource to act as an update collision detector. For example if your database
is managing data related to your customers, there is probably a common unique key used to identify any given customer. These
unique keys are often just a number or short string (eg. Customer-Id).
All rows in all tables of your customer database probably use this same common unique key to identify a specific customer (after all
that is what a key is all about).
Create a TRANSACTION table that contains two columns, one column for the Customer-Id and another for
some transaction unique identifier, this is commonly just a timestamp generated at the beginning of the transaction (could also be
a task-id, it just needs to be unique to a transaction). Call this transaction identifier the TRANS-KEY.
When the Display phase of a transaction is entered the transaction
has the Customer-Id for the first time. It then updates the TRANSACTION table for this Customer-Id with its TRANS-KEY. Both are saved
to the COMMAREA. Note that the update here is done based on Customer-Id only, it will replace the current TRANS-KEY with its own
unique value. The Display phase is entered, user enters their changes and Commit phase is entered. At this point the
transaction attempts to update the TRANSACTION table based its saved Customer-id and TRANS-KEY. If the update fails the transaction
"knows" some other
transaction has started working on the same customer (the other transaction changed the TRANS-KEY for the same Customer-id so the
current transaction either suffers a timeout or row-not-found error).
To preserve database integrity the current transaction must back out. It will display some
sort of message to the user notifying them that a concurrent update has been requested and that it must abandon the requested
updates. If,
on the other hand, the TRANS-KEY has not changed for the given Customer-id, a database lock will have been taken preventing any
other transaction from changing that row for the same Customer-Id. The current transaction may then update the database because it know no other transaction has looked at or updated the data between the time it first started to operate and the time it commited its updates.
The key to making all this work is that all transactions that update the Customer database use the same TRANSACTION table to detect concurrent update attempts.
The resource locking mechanism described here is commonly called "collision detection" and is just one of many possible ways to preserve database integrity over the
course of a pseudo conversational CICS transaction. The key point is that DB/2 locks are taken and dropped several times
over the course of the transaction and that it takes some "cooperation" between the DB/2 lock manager, CICS Syncpoint manager
and the application itself to maintain database integrity when using pseudo conversational CICS.
Finally, the transaction that actually gets to update the database will be the last one to retrive data - so the moral of this story is to get in late and finish early!
The above discussion is not COBOL specific, it will be true for all programming languages, including COBOL, used to develop applicaions using DB/2 and psuedo conversational CICS.

A: From the IBM manual, How CICS connects to DB2:

A CICS® DB2® attachment facility is provided with CICS. The CICS DB2 attachment facility provides CICS applications with access to DB2 data while operating in the CICS environment. CICS applications, therefore, can access both DB2 data and CICS data. CICS coordinates recovery of both DB2 and CICS data if transaction or system failure occurs.
The CICS DB2 attachment facility creates an overall connection between CICS and DB2. CICS applications use this connection to issue commands and requests to DB2. The connection between CICS and DB2 can be created or terminated at any time, and CICS and DB2 can be started and stopped independently. You can name an individual DB2 subsystem to which CICS connects, or (if you have DB2 Version 7 or later) you can use the group attach facility to let DB2 choose any active member of a data-sharing group of DB2 subsystems for the connection. You also have the option of CICS automatically connecting and reconnecting to DB2. A DB2 system can be shared by several CICS systems, but each CICS system can be connected to only one DB2 subsystem at a time.

In plain English, think of CICS as having a multiple connection pool to DB2.
When a DB2 table is defined, it is defined with either page or row locking.  (It can be defined with table locking, but this is rare).  The DB2 database engine will not allow more than one user to update a page or a row at a time, depending on the locking level.
There are also read locks to maintain read consistency of tables.  DB2 calls these read locks isolation levels.


text:
Q: How to fetch current month data from MySQL database How to fetch current month data from database. I tried the the following, Its fetch all data related to this month from all years. I mean November data of all previous years.
SELECT d.date,
       COALESCE(t1.marks, 0) AS class1,
       COALESCE(t2.marks, 0) AS class2,
       COALESCE(t3.marks, 0) AS class3
FROM (SELECT DATE(date_column) AS date FROM `table1`
      UNION
      SELECT DATE(date_column) FROM `table2`
      UNION
      SELECT DATE(date_column) FROM `table3`) AS d
LEFT JOIN (SELECT DATE(date_column) AS date,
                  COUNT(marks) AS marks
           FROM table1
           GROUP BY date) t1 ON t1.date = d.date
LEFT JOIN (SELECT DATE(date_column) AS date,
                  COUNT(marks) AS marks
           FROM table2
           GROUP BY date) t2 ON t2.date = d.date
LEFT JOIN (SELECT DATE(date_column) AS date,
                  COUNT(marks) AS marks
           FROM table3
           GROUP BY date) t3 ON t3.date = d.date
WHERE MONTH(CURDATE()) = MONTH(d.dates) ORDER BY d.date

A: Add the Year filter in where clause as below
WHERE MONTH(CURDATE()) = MONTH(d.date) and YEAR(CURDATE())=YEAR(d.date) ORDER BY d.date

This will get the data on the current month as well as the current year.


text:
Q: Не запускается приложение в эмуляторе Android Studio Эмулятор запускается, но в своем обычном режиме, то есть с рабочим столом, а приложения как будто и нет.
Притом подключала свое устройство через usb и тестировала на нем и такой проблемы нет
Ошибок никаких не выдает

A: А эмулятор соответствует требованиям приложения? Версия, разрядность и пр. Да и сам эмулятор может подвисать, попробуйте поискать свое приложение в меню. AS довольно прожорлив.

A: Посмотрите, это должно решить вашу проблему. После нажатия на Wipe Data жмём Yes.


text:
Q: Is it possible to install SSD with 6Gb/s in Mac pro Mid 2010? Is it possible to install Solid State Drive with 6Gb/s speed in Mac pro Mid 2010?

A: Yes it should be possible to install a SSD with SATA 6Gb/s.
The MacPro5,1 was offered with a 512 GB SSD by Apple actually. The internal interface is limited to 3 Gb/s (which roughly translates to 300 MByte/s max) though. As a consequence you will not benefit from the faster transfer rate of the SATA III SSD.
The same is valid for MacBookPro6,1 and MacBookPro6,2.
SATA 6Gb/s is backward compatible with SATA 3Gb/s. Some features recently implemented in SATA 6Gb/s won't work if a respective device is attached to a SATA 3Gb/s interface (e.g. Isochronous Native Command Queuing).


text:
Q: Is the cofinality function monotonic? Is the cofinality function $\operatorname{cf}$ monotonic?
I.e., if $\lambda \le \kappa$ for cardinals $\lambda$ and $\kappa$, does it then follow that $\operatorname{cf}(\lambda) \le \operatorname{cf}(\kappa)$?
If this does not hold in general, do there exist conditions on $\lambda$ and $\kappa$ (besides regularity) that allow to make this conclusion in special cases?

A: No, of course not. If you already know that not all cardinals are regular then it suffices to show that. Simply take $\kappa$ to be a singular cardinal and, $\lambda=\operatorname{cf}(\kappa)^+<\kappa$, then $\lambda$ is regular but $\kappa$ has a strictly smaller cofinality despite being larger.
For example, $\aleph_1<\aleph_\omega$ but $\operatorname{cf}(\aleph_1)=\aleph_1>\aleph_0=\operatorname{cf}(\aleph_\omega)$.
And to your question, no, there are no "easy" cases which are not tantamount to stating "the cofinality function is monotonic in this case".