text:
Q: How efficient is std::string compared to null-terminated strings? I've discovered that std::strings are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall program by a factor of 2.
I expected STL to be slower, I didn't realise it was going to be this much slower.
I'm using Visual Studio 2008, release mode. It shows assignment of a string to be 100-1000 times slower than char* assignment (it's very difficult to test the run-time of a char* assignment).  I know it's not a fair comparison, a pointer assignment versus string copy, but my program has lots of string assignments and I'm not sure I could use the "const reference" trick in all places.  With a reference counting implementation my program would have been fine, but these implementations don't seem to exist anymore.
My real question is:  why don't people use reference counting implementations anymore, and does this mean we all need to be much more careful about avoiding common performance pitfalls of std::string?
My full code is below.
#include <string>
#include <iostream>
#include <time.h>

using std::cout;

void stop()
{
}

int main(int argc, char* argv[])
{
    #define LIMIT 100000000
    clock_t start;
    std::string foo1 = "Hello there buddy";
    std::string foo2 = "Hello there buddy, yeah you too";
    std::string f;
    start = clock();
    for (int i=0; i < LIMIT; i++) {
        stop();
        f = foo1;
        foo1 = foo2;
        foo2 = f;
    }
    double stl = double(clock() - start) / CLOCKS\_PER\_SEC;

    start = clock();
    for (int i=0; i < LIMIT; i++) {
        stop();
    }
    double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC;

    char* goo1 = "Hello there buddy";
    char* goo2 = "Hello there buddy, yeah you too";
    char *g;
    start = clock();
    for (int i=0; i < LIMIT; i++) {
        stop();
        g = goo1;
        goo1 = goo2;
        goo2 = g;
    }
    double charLoop = double(clock() - start) / CLOCKS_PER_SEC;
    cout << "Empty loop = " << emptyLoop << "\n";
    cout << "char* loop = " << charLoop << "\n";
    cout << "std::string = " << stl << "\n";
    cout << "slowdown = " << (stl - emptyLoop) / (charLoop - emptyLoop) << "\n";
    std::string wait;
    std::cin >> wait;
    return 0;
}

A: When writing C++ code using any utility class (whether STL or your own) instead of eg. good old C null terminated strings, you need to rememeber a few things.

*

*If you benchmark without compiler optimisations on (esp. function inlining), classes will lose. They are not built-ins, even stl. They are implemented in terms of method calls.

*Do not create unnesessary objects.

*Do not copy objects if possible.

*Pass objects as references, not copies, if possible,

*Use more specialised method and functions and higher level algorithms. Eg.:
std::string a = "String a"
std::string b = "String b"

// Use
a.swap(b);

// Instead of
std::string tmp = a;
a = b;
b = tmp;

And a final note. When your C-like C++ code starts to get more complex, you need to implement more advanced data structures like automatically expanding arrays, dictionaries, efficient priority queues. And suddenly you realise that its a lot of work and your classes are not really faster then stl ones. Just more buggy.

A: You are most certainly doing something wrong, or at least not comparing "fairly" between STL and your own code. Of course, it's hard to be more specific without code to look at.
It could be that you're structuring your code using STL in a way that causes more constructors to run, or not re-using allocated objects in a way that matches what you do when you implement the operations yourself, and so on.

A: This test is testing two fundamentally different things: a shallow copy vs. a deep copy. It's essential to understand the difference and how to avoid deep copies in C++ since a C++ object, by default, provides value semantics for its instances (as with the case with plain old data types) which means that assigning one to the other is generally going to copy.
I "corrected" your test and got this:
char* loop = 19.921
string = 0.375
slowdown = 0.0188244

Apparently we should cease using C-style strings since they are soooo much slower! In actuality, I deliberately made my test as flawed as yours by testing shallow copying on the string side vs. strcpy on the :
#include <string>
#include <iostream>
#include <ctime>

using namespace std;

#define LIMIT 100000000

char* make_string(const char* src)
{
    return strcpy((char*)malloc(strlen(src)+1), src);
}

int main(int argc, char* argv[])
{
    clock_t start;
    string foo1 = "Hello there buddy";
    string foo2 = "Hello there buddy, yeah you too";
    start = clock();
    for (int i=0; i < LIMIT; i++)
        foo1.swap(foo2);
    double stl = double(clock() - start) / CLOCKS_PER_SEC;

    char* goo1 = make_string("Hello there buddy");
    char* goo2 = make_string("Hello there buddy, yeah you too");
    char *g;
    start = clock();
    for (int i=0; i < LIMIT; i++) {
        g = make_string(goo1);
        free(goo1);
        goo1 = make_string(goo2);
        free(goo2);
        goo2 = g;
    }
    double charLoop = double(clock() - start) / CLOCKS_PER_SEC;
    cout << "char* loop = " << charLoop << "\n";
    cout << "string = " << stl << "\n";
    cout << "slowdown = " << stl / charLoop << "\n";
    string wait;
    cin >> wait;
}

The main point is, and this actually gets to the heart of your ultimate question, you have to know what you are doing with the code. If you use a C++ object, you have to know that assigning one to the other is going to make a copy of that object (unless assignment is disabled, in which case you'll get an error). You also have to know when it's appropriate to use a reference, pointer, or smart pointer to an object, and with C++11, you should also understand the difference between move and copy semantics.

My real question is: why don't people use reference counting
  implementations anymore, and does this mean we all need to be much
  more careful about avoiding common performance pitfalls of
  std::string?

People do use reference-counting implementations. Here's an example of one:
shared_ptr<string> ref_counted = make_shared<string>("test");
shared_ptr<string> shallow_copy = ref_counted; // no deep copies, just
                                               // increase ref count

The difference is that string doesn't do it internally as that would be inefficient for those who don't need it. Things like copy-on-write are generally not done for strings either anymore for similar reasons (plus the fact that it would generally make thread safety an issue). Yet we have all the building blocks right here to do copy-on-write if we wish to do so: we have the ability to swap strings without any deep copying, we have the ability to make pointers, references, or smart pointers to them.
To use C++ effectively, you have to get used to this way of thinking involving value semantics. If you don't, you might enjoy the added safety and convenience but do it at heavy cost to the efficiency of your code (unnecessary copies are certainly a significant part of what makes poorly written C++ code slower than C). After all, your original test is still dealing with pointers to strings, not char[] arrays. If you were using character arrays and not pointers to them, you'd likewise need to strcpy to swap them. With strings you even have a built-in swap method to do exactly what you are doing in your test efficiently, so my advice is to spend a bit more time learning C++.

A: Well there are definitely known problems regarding the performance of strings and other containers. Most of them have to do with temporaries and unnecessary copies.
It's not too hard to use it right, but it's also quite easy to Do It Wrong. For example, if you see your code accepting strings by value where you don't need a modifiable parameter, you Do It Wrong:
// you do it wrong
void setMember(string a) {
    this->a = a; // better: swap(this->a, a);
}

You better had taken that by const reference or done a swap operation inside, instead of yet another copy. Performance penalty increases for a vector or list in that case. However, you are right definitely that there are known problems. For example in this:
// let's add a Foo into the vector
v.push_back(Foo(a, b));

We are creating one temporary Foo just to add a new Foo into our vector. In a manual solution, that might create the Foo directly into the vector. And if the vector reaches its capacity limit, it has to reallocate a larger memory buffer for its elements. What does it do? It copies each element separately to their new place using their copy constructor. A manual solution might behave more intelligent if it knows the type of the elements before-hand.
Another common problem is introduced temporaries. Have a look at this
string a = b + c + e;

There are loads of temporaries created, which you might avoid in a custom solution that you actually optimize onto performance. Back then, the interface of std::string was designed to be copy-on-write friendly. However, with threads becoming more popular, transparent copy on write strings have problems keeping their state consistent. Recent implementations tend to avoid copy on write strings and instead apply other tricks where appropriate.
Most of those problems are solved however for the next version of the Standard. For example instead of push_back, you can use emplace_back to directly create a Foo into your vector
v.emplace_back(a, b);

And instead of creating copies in a concatenation above, std::string will recognize when it concatenates temporaries and optimize for those cases. Reallocation will also avoid making copies, but will move elements where appropriate to their new places.
For an excellent read, consider Move Constructors by Andrei Alexandrescu.
Sometimes, however, comparisons also tend to be unfair. Standard containers have to support the features they have to support. For example if your container does not keep map element references valid while adding/removing elements from your map, then comparing your "faster" map to the standard map can become unfair, because the standard map has to ensure that elements keep being valid. That was just an example, of course, and there are many such cases that you have to keep in mind when stating "my container is faster than standard ones!!!".

A: If you have an indication of the eventual size of your vector you can prevent excessive resizes by calling reserve() before filling it up.

A: The main rules of optimization:

*

*Rule 1: Don't do it.

*Rule 2: (For experts only) Don't do it yet.

Are you sure that you have proven that it is really the STL that is slow, and not your algorithm?

A: Good performance isn't always easy with STL, but generally, it is designed to give you the power.  I found Scott Meyers' "Effective STL" an eye-opener for understanding how to deal with the STL efficiently. Read!
As others said, you are probably running into frequent deep copies of the string, and compare that to a pointer assignment / reference counting implementation.
Generally, any class designed towards your specific needs, will beat a generic class that's designed for the general case. But learn to use the generic class well, and learn to ride the 80:20 rules, and you will be much more efficient than someone rolling everything on their own.

One specific drawback of std::string is that it doesn't give performance guarantees, which makes sense. As Tim Cooper mentioned, STL does not say whether a string assignment creates a deep copy. That's good for a generic class, because reference counting can become a real killer in highly concurrent applications, even though it's usually the best way for a single threaded app.

A: It looks like you're misusing char* in the code you pasted.  If you have
std::string a = "this is a";
std::string b = "this is b"
a = b;

you're performing a string copy operation.  If you do the same with char*, you're performing a pointer copy operation.
The std::string assignment operation allocates enough memory to hold the contents of b in a, then copies each character one by one.  In the case of char*, it does not do any memory allocation or copy the individual characters one by one, it just says "a now points to the same memory that b is pointing to."
My guess is that this is why std::string is slower, because it's actually copying the string, which appears to be what you want.  To do a copy operation on a char* you'd need to use the strcpy() function to copy into a buffer that's already appropriately sized.  Then you'll have an accurate comparison.  But for the purposes of your program you should almost definitely use std::string instead.

A: They didn't go wrong. STL implementation is generally speaking better than yours.
I'm sure that you can write something better for a very particular case, but a factor of 2 is too much... you really must be doing something wrong.

A: If used correctly, std::string is as efficient as char*, but with the added protection.
If you are experiencing performance problems with the STL, it's likely that you are doing something wrong.
Additionally, STL implementations are not standard across compilers. I know that SGI's STL and STLPort perform generally well.
That said, and I am being completely serious, you could be a C++ genius and have devised code that is far more sophisticated than the STL. It's not likely , but who knows, you could be the LeBron James of C++.

A: I would say that STL implementations are better than the traditional implementations. Also did you try using a list instead of a vector, because vector is efficient for some purpose and list is efficient for some other

A: A large part of the reason might be the fact that reference-counting is no longer used in modern implementations of STL.
Here's the story (someone correct me if I'm wrong):  in the beginning, STL implementations used reference counting, and were fast but not thread-safe - the implementors expected application programmers to insert their own locking mechanisms at higher levels, to make them thread-safe, because if locking was done at 2 levels then this would slow things down twice as much.
However, the programmers of the world were too ignorant or lazy to insert locks everywhere.  For example, if a worker thread in a multi-threaded program needed to read a std::string commandline parameter, then a lock would be needed even just to read the string, otherwise crashes could ensue. (2 threads increment the reference count simultaneously on different CPU's (+1), but decrement it separately (-2), so the reference count goes down to zero, and the memory is freed.)
So implementors ditched reference counting and instead had each std::string always own its own copy of the string.  More programs worked, but they were all slower.
So now, even a humble assignment of one std::string to another, (or equivalently, passing a std::string as a parameter to a function), takes about 400 machine code instructions instead of the 2 it takes to assign a char*, a slowdown of 200 times.
I tested the magnitude of the inefficiency of std::string on one major program, which had an overall slowdown of about 100% compared with null-terminated strings.  I also tested raw std::string assignment using the following code, which said that std::string assignment was 100-900 times slower.  (I had trouble measuring the speed of char* assignment).  I also debugged into the std::string operator=() function - I ended up knee deep in the stack, about 7 layers deep, before hitting the 'memcpy()'.
I'm not sure there's any solution.  Perhaps if you need your program to be fast, use plain old C++, and if you're more concerned about your own productivity, you should use Java.
#define LIMIT 800000000
clock_t start;
std::string foo1 = "Hello there buddy";
std::string foo2 = "Hello there buddy, yeah you too";
std::string f;

start = clock();
for (int i=0; i < LIMIT; i++) {
    stop();
    f    = foo1;
    foo1 = foo2;
    foo2 = f;
}
double stl = double(clock() - start) / CLOCKS_PER_SEC;

start = clock();
for (int i=0; i < LIMIT; i++) {
    stop();
}
double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC;

char* goo1 = "Hello there buddy";
char* goo2 = "Hello there buddy, yeah you too";
char *g;

start = clock();
for (int i=0; i < LIMIT; i++) {
    stop();
    g = goo1;
    goo1 = goo2;
    goo2 = g;
}
double charLoop = double(clock() - start) / CLOCKS_PER_SEC;

TfcMessage("done", 'i', "Empty loop = %1.3f s\n"
                        "char* loop = %1.3f s\n"
                        "std::string loop = %1.3f s\n\n"
                        "slowdown = %f",
                        emptyLoop, charLoop, stl,
                        (stl - emptyLoop) / (charLoop - emptyLoop));

A: std::string will always be slower than C-strings. C-strings are simply a linear array of memory. You cannot get any more efficient than that, simply as a data structure. The algorithms you use (like strcat() or strcpy()) are generally equivalent to the STL counterparts. The class instantiation and method calls will be, in relative terms, significantly slower than C-string operations (even worse if the implementation uses virtuals). The only way you could get equivalent performance is if the compiler does optimization.

A:
                        string  const string&   char*   Java string
---------------------------------------------------------------------------------------------------
Efficient               no **       yes         yes     yes
assignment

Thread-safe             yes         yes         yes     yes

memory management       yes         no          no      yes
done for you

** There are 2 implementations of std::string:  reference counting or deep-copy. Reference counting introduces performance problems in multi-threaded programs, EVEN for just reading strings, and deep-copy is obviously slower as shown above.  See:
 Why VC++ Strings are not reference counted?
As this table shows, 'string' is better than 'char*' in some ways and worse in others, and 'const string&' is similar in properties to 'char*'. Personally I'm going to continue using 'char*' in many places.  The enormous amount of copying of std::string's that happens silently, with implicit copy constructors and temporaries makes me somewhat ambivalent about std::string.


text:
Q: trying to overwrite `/var/backups/infodir.bak', which is also in package x when compiling software I do always . ./configure && make && checkinstall -D make install to build the software.
Now i run into the issue when using checkinstall that I get the error

"trying to overwrite `/var/backups/infodir.bak', which is also in
  package libtasn1-3.2".

I also created libtasn1-3.2 with ./configure && make && checkinstall -D make install.
I tried to remove the file /var/backups/infodir.bak, but I still get the error.
Does anyone know how I can solve this issue?
Building Debian package...OK
Installing Debian package... FAILED!
Failed to install the package

Do you want to see the log file?  [y]: y (Reading database ... dpkg:
serious warning: files list file for package `squeezecenter-readynas'
missing, assuming package has no files currently installed. 30739
files and directories currently installed.) Unpacking libgcrypt-1.5.1
(from .../libgcrypt-1.5.1_1.5.1-1_sparc.deb) ... dpkg: error
processing
/c/backup/zarafa/libgcrypt-1.5.1/libgcrypt-1.5.1_1.5.1-1_sparc.deb
(--install):  trying to overwrite `/var/backups/infodir.bak', which is
also in package libtasn1-3.2 dpkg-deb: subprocess paste killed by
signal (Broken pipe) Errors were encountered while processing:
/c/backup/zarafa/libgcrypt-1.5.1/libgcrypt-1.5.1_1.5.1-1_sparc.deb

A: in debian it is forbidden for two packages to install the same file.
thus, whenever you try to install a package that contains file "/path/to/foo" and another package is already installed that contains file "/path/to/foo", you get a conflict and thus an error.
part of the maintainer's work is to make sure that such things do not happen,

*

*either by setting an explicit conflict between the two packages (so you cannot even mark the two packages at the same time for installation)

*or by renaming the file in one package (or both) and adjusting the software accordingly

*or by preventing one (or both) packages from installing such file (e.g. in the case where the installed file is really not necessary)
maintaining debian packages is generally a lot of work.
now the tool checkinstall is a "poor man's" package maintainance tool, as it makes it super easy to create packages from "make install".
since it is an automation tool, it simply cannot replace the work and sophistication of a maintainer. (else we wouldn't need any debian maintainers any more; just upload the source-packages to some build-server and run "checkinstall" on them)
so the reason why you get problems, is because you are installing badly maintained (or rather: automatically created and thus not-at-all maintained) packages.
the reason why deleting the offending file doesn't work is because the package management is more than just downloading archives and extracting them. among other things it maintains a list of installed files in a database, and this list indicates that you alredy have /var/backups/infodir.bak installed (regardless whether the file is actually on the harddisk or not)... resulting in the conflict you see.
so the solution to your problem is, to invest more time in maintenance.
in any case, you should investigate why the two "packages" both require /var/backups/infodir.bak (and whether they require it at all).
you can omit certain files from checkinstall via
 checkinstall --exclude /var/backups/infodir.bak -D make install

whether this will break any of your packages, i cannot say.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simulink: How does one assign a double to a constant in a subsystem through the mask? This is a slightly long-winded problem, but should be easy to follow along.
End goal: Input a 'double' vector into a C++ S Function by assigning it to a Constant.
Starting point: A function within the Dialog Callback of my masked subsystem returns the double vector that I need.
Steps in the middle: So I have a double vector as an input, I need a double vector as an output, but I cannot pass the vector directly, because set_param requires that I pass the value as a string.
Problem: What I tried is this: set_param(gcb,'refNameArray',num2str(refName));
where,

*

*gcb (correctly) returns the block from within which I am doing
everything.

*refNameArray is the parameter which needs to be assigned
the double vector

*refName is the vector, in 'double' form, that I
have available within the dialog callback of the mask.

I use num2str because I cannot directly assign a vector, I must input it as a string.
But, even using num2str, I get an error saying Invalid Setting in Block <blockName> for parameter 'Value'.
Any suggestions?

A: The value you set for param in the dialog should be syntactically similar to an RHS expression in MATLAB. For example, for a vector value you would need to set it as '[1 3 4]'. Notice the square brackets. num2str does not add that square brackets. You can either add it manually at the ends before calling set_param or you can use mat2str which will create the string with the brackets.


text:
Q: Inspect element HTML set root file path I am working on a static (front end only) website and there are a ton of URLs relative to the root. I "run" the code by simply opening an HTML file on my computer, which takes me to  file:///C:/foo/bar/website/index.html. Because of this, the root-relative links don't work, since the root is file:/// instead of file:///C:/foo/bar/website/. I was thinking that maybe chrome inspect element had a way to set a root directory?
I can't fix all the paths because I am only supposed to work on a chunk of CSS in a single page, and if I change all the paths and something breaks for some reason, that would be on me (and even if nothing breaks, I would still be out of line).

A: To be able to use the website correctly with every URL working fine without to touch anything, I would recommend you to run a small PHP or Apache server. It's very light, it doesn't need any installation, no need to open any port, only to download a zip file.
You can download the PHP server at: https://www.php.net/downloads
Then run the exe file with command:
php -S localhost:8080
And go to localhost:8080 in your browser. You should have a perfectly working website hosted on your computer.

A:
maybe chrome inspect element had a way to set a root directory?

It doesn't.

Install a web server and test your code using that.
You could use the PHP built-in server:
php -S localhost:8080

or the live server extension for VS code
or the python HTTP module
… among others.


text:
Q: shrinking a Docker Image - from debian to scratch - how to migrate? i am trying to build a minimalistic docker image for one of my applicatoins
in my "usual" builds i do not rely on 3rd party applications. This time I need to include a precompiled executeable (xpdf) to the build; My go applications are prebuilt in a builder Docker and then copied over (no dependencies).
my current Dockerimage file looks like this: (working!) application launches
FROM debian:buster-slim
COPY ./bin64/pdftopng .
COPY ./config/xpdfrc .
# ... copy FONT files
# copy Test PDF
COPY ./test.pdf .
RUN chmod +x pdftopng
RUN apt-get update && apt-get install -y libfontconfig1
# execute pdftopng
ENTRYPOINT ["/pdftopng", "-cfg", "xpdfrc", "/test.pdf", "/test.pdf"]

as this results in a image file with over 100mb i tried to use scratch as a base (which usually results in images around 10-20mb)
FROM scratch
# ... copy my binaries to the docker
COPY --from=builder /dist/main /
# copy the XPDF -> pdf to png executeable (linux x64)
COPY ./bin64/pdftopng .
# copy font files (for this example i only copy one)
COPY ./fonts/n021003l.pfb /fonts/n021003l.pfb
# copy config file
COPY ./config/xpdfrc .
# copy test file
COPY ./test.pdf .
# execute the XPDF converter and convert the test.pdf to png
ENTRYPOINT ["/pdftopng", "-cfg", "xpdfrc", "/test.pdf", "test"]

outputs:
standard_init_linux.go:219: exec user process caused: no such file or directory

this error is the result of a missing library (something related to libfontconfig1)
how can i find out which files are missing (as i do have a working container this should be possible)

A: Solution
Step 1 - create libsource
create a docker image where you can grab all required libraries from
FROM debian:buster-slim AS libsource
COPY ./bin64/pdftopng .
COPY ./config/xpdfrc .
# ... copy FONT files
# copy Test PDF
COPY ./test.pdf .
RUN chmod +x pdftopng
RUN apt-get update && apt-get install -y libfontconfig1

Step 2 - find requirements
then obtain a list of libraries which the application [./pdftopng] needs to run
docker run --rm -it ldd ./pdftopng

this command lists all required libraries (direct use only):
    linux-vdso.so.1 (0x00007ffce1304000)
    libbz2.so.1 => /lib/x86_64-linux-gnu/libbz2.so.1 (0x00007fa1104ea000)
    libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fa1102cc000)
    libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007fa110286000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fa110265000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fa1100e1000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fa10ff5e000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fa10ff42000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fa10fd81000)
    libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fa10fcc5000)
    libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007fa10fc88000)
    libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007fa10fc7f000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fa110501000)
    libpng16.so.16 => /usr/lib/x86_64-linux-gnu/libpng16.so.16 (0x00007fa10fc44000)

Step 3 - copy requirements
in the last step copy the libraries from step 2 to the scratch image
COPY --from=libsource /lib/x86_64-linux-gnu/libbz2.so.1 /lib/x86_64-linux-gnu/libbz2.so.1
COPY --from=libsource /lib/x86_64-linux-gnu/libz.so.1 /lib/x86_64-linux-gnu/libz.so.1
COPY --from=libsource /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 /usr/lib/x86_64-linux-gnu/libfontconfig.so.1
COPY --from=libsource /lib/x86_64-linux-gnu/libpthread.so.0 /lib/x86_64-linux-gnu/libpthread.so.0
COPY --from=libsource /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /usr/lib/x86_64-linux-gnu/libstdc++.so.6
COPY --from=libsource /lib/x86_64-linux-gnu/libm.so.6 /lib/x86_64-linux-gnu/libm.so.6
COPY --from=libsource /lib/x86_64-linux-gnu/libgcc_s.so.1  /lib/x86_64-linux-gnu/libgcc_s.so.1
COPY --from=libsource /lib/x86_64-linux-gnu/libc.so.6 /lib/x86_64-linux-gnu/libc.so.6
COPY --from=libsource /usr/lib/x86_64-linux-gnu/libfreetype.so.6 /usr/lib/x86_64-linux-gnu/libfreetype.so.6
COPY --from=libsource /lib/x86_64-linux-gnu/libexpat.so.1 /lib/x86_64-linux-gnu/libexpat.so.1
COPY --from=libsource /lib/x86_64-linux-gnu/libuuid.so.1 /lib/x86_64-linux-gnu/libuuid.so.1
COPY --from=libsource /lib64/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2
COPY --from=libsource /usr/lib/x86_64-linux-gnu/libpng16.so.16 /usr/lib/x86_64-linux-gnu/libpng16.so.16

Result
in my case the result is a much smaller image 15.45 MB instead of 101.90 MB
which is a reduction by 84,84 %


text:
Q: How do I run mutlple SQL statements in an AppSync resolver? I have two tables, cuts and holds. In response to an event in my application I want to be able to move the values from a hold entry with a given id across to the cuts table. The naïve way is to do an INSERT and then a DELETE.
How do I run multiple sql statements in an AppSync resolver to achieve that result?  I have tried the following (replacing sql by statements and turning it into an array) without success.
{
 "version" : "2017-02-28",
 "operation": "Invoke",

 #set($id = $util.autoId())

"payload": {
    "statements": [
        "INSERT INTO cuts (id, rollId, length, reason, notes, orderId) SELECT '$id', rollId, length, reason, notes, orderId FROM holds WHERE id=:ID",
        "DELETE FROM holds WHERE id=:ID"
    ],
    "variableMapping": {
        ":ID": "$context.arguments.id"
    },
    "responseSQL": "SELECT * FROM cuts WHERE id = '$id'"
}

}

A: If you're using the "AWS AppSync Using Amazon Aurora as a Data Source via AWS Lambda" found here https://github.com/aws-samples/aws-appsync-rds-aurora-sample, you won't be able to send multiple statements in the sql field
If you are using the AWS AppSync integration with the Aurora Serverless Data API, you can pass up to 2 statements in a statements array such as in the example below:
{
    "version": "2018-05-29",
    "statements": [
        "select * from Pets WHERE id='$ctx.args.input.id'",
        "delete from Pets WHERE id='$ctx.args.input.id'"
    ]
}

A: You will be able to do it as the following.If you're using the "AWS AppSync Using Amazon Aurora as a Data Source via AWS Lambda" found here https://github.com/aws-samples/aws-appsync-rds-aurora-sample.
In the resolver, add the "sql0" & "sql1" field (you can name them what ever you want) :
{
    "version" : "2017-02-28",
    "operation": "Invoke",
    #set($id = $util.autoId())

    "payload": {
      "sql":"INSERT INTO cuts (id, rollId, length, reason, notes, orderId)",
      "sql0":"SELECT '$id', rollId, length, reason, notes, orderId FROM holds WHERE id=:ID",
      "sql1":"DELETE FROM holds WHERE id=:ID",
      "variableMapping": {
            ":ID": "$context.arguments.id"
      },
      "responseSQL": "SELECT * FROM cuts WHERE id = '$id'"
    }
}

In your lambda, add the following piece of code:
  if (event.sql0) {
  const inputSQL0 = populateAndSanitizeSQL(event.sql0, event.variableMapping, connection);
  await executeSQL(connection, inputSQL0);
  }
  if (event.sql1) {
  const inputSQL1 = populateAndSanitizeSQL(event.sql1, event.variableMapping, connection);
  await executeSQL(connection, inputSQL1);
  }

With this approach, you can send to your lambda as much sql statements as you want,and then your lambda will execute them.


text:
Q: Find and rigorously prove the supremum of the set: S = $\{a \in \Bbb{Z} | a < 2+1/2$}
Given that a is in the set of all integers ($\mathbb{Z}$), would the supremum of this set be equal to $(2 + 1/2)$? If so, given an upper bound of $(2 + 1/2)$, how would I prove that for an $\epsilon < (2 + 1/2)$ this couldn't possibly be an upper bound and hence $\sup(S) = (2 + 1/2)$?

A: The set $S$ has $2+\frac12$ as an upper bound, but $2+\frac12$ is not the supremum of $S$. For instance, 2 is an upper bound of $S$ which is strictly smaller than $2+\frac12$.

A: Just because you can write something doesn't mean that is the must efficient way to write it.
To prove that for any $r < \sup S$ is not an upper bound you prove that for any $r < \sup S$ there must be an element of $s \in S$ so that $r < s \le \sup S$.
If of $\sup S = 2\frac 12$ then that means for any $r < 2\frac 12$ there must be an integer $n$ so that $r < n \le 2\frac 12$.
Is that true.  What if $r = 2.49$.  Is there an integer $n$ so that $2.49 < n \le 2\frac 12$?
Obviously not.  There aren't any integers between $2$ and $3$ so if $n$ is an integer and $n < 2\frac 12 < 3$ then $n \le 2$.  So there are no integers and therefore no elements of $S$ that are between $2$ and $2\frac 12$.  So we can't have any number between $2$ and $2\frac 12$ actually be the $\sup S$
Can you finish this?
Here's food for thought.  Let $S=\{$ all even primes less than $2000\}$.  So how does $\sup S$ compare to $2000$.  If we notice that $S = \{2\}$ what does that tell us.

  Claim 1:  $2$ is an upper bound of $S$.  Pf: If $s \in S$ then $s\in \mathbb Z$ and $s < 2\frac 12$.  So $s < 3$.  ANd $s\in \mathbb Z$ so it is not true that $2 < s <3$.  And as $s < 3$ and it is not true that $s < $ and $s > 2$ it must not be true that $s > 2$. So $s \le 2$.  So $2$ is an upper bound of $S$.

 Claim 2: If $r < 2$ then $r$ is not an upper bound. Pf: $2\in \mathbb Z$.  And $2< 2\frac 12$.  So $2 \in S$.  So $r < 2\in \mathbb S$.  So $r$ is not an upper bound.....


text:
Q: Package conflict in meteor : Angular2 and Templating I am in and out of a project with Meteor, trying to wrap my head around this framework (documentation is comparable to Ruby... just terrible and fragmented), and I get this error :

While determining active plugins:
  error: conflict: two packages included in the app (barbatus:angular2 and
  templating) are both trying to handle *.html

And this is my installed packages :
autopublish               1.0.4  (For prototyping only) Publish the entire d...
blaze-html-templates      1.0.1  Compile HTML templates into reactive UI wit...
ecmascript                0.1.5  Compiler plugin that supports ES2015+ in al...
es5-shim                  4.1.13  Shims and polyfills to improve ECMAScript ...
flemay:less-autoprefixer  1.1.0  The dynamic stylesheet language + Autoprefixer
insecure                  1.0.4  (For prototyping only) Allow all database w...
jquery                    1.11.4  Manipulate the DOM using CSS selectors
meteor-base               1.0.1  Packages that every Meteor app needs
mobile-experience         1.0.1  Packages for a great mobile user experience
mongo                     1.1.2  Adaptor for using MongoDB and Minimongo ove...
semantic:ui               2.1.4  Official Semantic UI Integration for Meteor
session                   1.1.1  Session variable
standard-minifiers        1.0.1  Standard minifiers used with Meteor apps by...
tracker                   1.0.9  Dependency tracker to allow reactive callbacks
urigo:angular2-meteor     0.2.0+ Angular2 and Meteor integration

Now, I know that barbatus:angular2 is used by urigo:angular2-meteor, but I'm unsure why it would conflict with templating (which is obviously required by something else... if not meteor-base itself.
How do I fix this?
** Edit **
This is my only .html file :

  <title>larpdb</title>

Welcome to Meteor!

  {{> hello}}

<template name="hello">
  <button>Click Me</button>

You've pressed the button {{counter}} times.

</template>

Basically, this is a brand new empty project; how can I avoid getting this error? Do I have to strictly not use <template> tags in my project?

A: In Meteor 1.2.0.2 you can use
> meteor remove blaze-html-templates

 Changes to your project's package version selections:

 blaze-html-templates   removed from your project
 caching-compiler       removed from your project
 caching-html-compiler  removed from your project
 templating             removed from your project
 templating-tools       removed from your project

Then add the urigo:angular2-meteor package (must download from GitHub)
 > meteor add urigo:angular2-meteor

A: In meteor .html file have templates only. If you are creating angular templates and giving same extension then at that time it will throw error. because in meteor only master file have html tag and if you adding different html file not having template tag then it will treat it as HTML file and add html tag in it while building.
so if you are creating templates for angular just rename it somefile.ng.html.
so that while meteor build it will don't have conflict.

A:
meteor remove blaze-html-templates
meteor remove ecmascript

Run the following commands to remove meteor's default ecmascript package .
Now the app should run fine .


text:
Q: Blending multiple images with OpenCV What is the way to blend multiple images with OpenCV using python? I came across the following snippet:
img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0)

on https://docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html
that shows a way to blend 2 images mountain and dog. What if I want to blend more than 2  images? How could I do this?

A: Try This:
blendedImage = weight_1 * image_1 + weight_2 * image_2 + ... + weight_n * image_n

A: You can blend all of your images by blending according to follwoing sequence:

*

*Blend the first two images

*Take the result and blend it with the next image

*and so forth

for idx, img in enumerate(imgs):
    if idx == 1:
        first_img = img
        continue
    else:
        second_img = img
        first_img = cv2.addWeighted(first_img, 0.5, second_img, 0.5, 0)

You might have a problem with the weights of each image, but this is another issues. To achieve an equal weigth for all images you can use the index to calculate the appropriate portion:
for idx, img in enumerate(imgs):
    if idx == 1:
        first_img = img
        continue
    else:
        second_img = img
        second_weight = 1/(idx+1)
        first_weight = 1 - second_weight
        first_img = cv2.addWeighted(first_img, first_weight, second_img, second_weight, 0)

A: Here is Python code to blend multiple images in a list. I used the basic formulation from Shamsheer's answer.
First, let's get three images.
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

dim = (425, 425)

apple = mpimg.imread('apple.jpg')
apple = cv2.resize(apple, dim)

banana = mpimg.imread('banana.jpg')
banana = cv2.resize(banana, dim)

orange = mpimg.imread('orange.jpg')
orange = cv2.resize(orange, dim)

_ = plt.imshow(apple)
_ = plt.show()

_ = plt.imshow(banana)
_ = plt.show()

_ = plt.imshow(orange)
_ = plt.show()

Here are the images:

Now let's blend them together equally. Since there are three images, the fraction of each image's contribution to the final output is 0.333.
def blend(list_images): # Blend images equally.

    equal_fraction = 1.0 / (len(list_images))

    output = np.zeros_like(list_images[0])

    for img in list_images:
        output = output + img * equal_fraction

    output = output.astype(np.uint8)
    return output

list_images = [apple, banana, orange]
output = blend(list_images)

_ = plt.imshow(output)

And here is the result:


text:
Q: How do I prevent grails' default main.css being linked on a specific page I have a simple web-app that I'm throwing together.
By & large, the default grails main.css is fine for all the scaffolded pages.
However, I want to supress this and use different, in-line css for the landing page.
How do I configure grails not to link main.css on a specific page?
The html is extremely simple, and contains no grails specific markup:
<!doctype html>
<html>
<head>
<meta name="layout" content="main" />
<title>My landing page</title>
<style type="text/css" media="screen">

body
{
background-color: #fff;
}
img {
    display: block;
    margin: auto;
}

</style>
</head>
<body>
    <img alt="Welcome!"
        src="${resource(dir:'images',file:'Landing.png') }">
</body>
</html>

Also -- is main.css linked purely out of convention, or is there some configuration lurking somewhere I haven't spotted?  (I've done a search but couldn't find it anywhere).
Can someone please reference where in the docs it talks about these conventions?

A: main.css is included in your landing page because you have specified that your landing page is based on the main layout
<meta name="layout" content="main" />

this layout is defined by grails-app/views/layouts/main.gsp and includes the main.css, most likely with a tag like this in the <head> of the page:
<link rel="stylesheet" href="${resource(dir: 'css', file: 'main.css')}" type="text/css">

If you remove:
<meta name="layout" content="main" />

your landing page will no longer be based on the main layout, so it will not include anything defined therein (e.g. main.css).
However, rather than removing the layout completely just to prevent main.css from being included, it may be simpler to just override the CSS rules that you want to cusomise on the layout page by including custom rules in a <style> block in the <head> of the landing page
<style type="text/css">

  body {
  /* styles in here override styles from main.css */
  }

</style>

A: Take a look at the resources plugin in grails 2.0.x. You can define Modules comprising of specific javascript and CSS files which will be compressed, optimized for the web. In the page of your choice, you can include the module you want. In your case, you could add a case like this in your main.gsp
<g:if test="${controllerName == "landing"}">
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'custom.css')}"/>
</g:if>
<g:else>
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'main.css')}"/>
</g:else>


text:
Q: I want to extend my disk patition for ubuntu (dual booted ubuntu and windows) So I want to extend my disk space for ubuntu 16.04
I shrinked the disk for windows in Windows 10 disk manager and now I want to add that unallocated partition to my ubuntu partition. But I don't know how. I don't know how to move stuff and I don't want to break my computer at the same time. Can anyone help me?
Also I can't seem to understand the other posts, if anyone says you can go to this other post. Because I did see every other posts that I could've found about this.

A: Make sure that you have a good backup of your important Ubuntu files, as this procedure can corrupt or loose data.
The use of an extended partition (sda3) makes this a little difficult. I'll outline the easiest way first, and we can add more to the procedure if we have to.
Keep these things in mind:

*

*always start the entire procedure with issuing a swapoff on any mounted swap partitions, and end the entire procedure with issuing a swapon on that same swap partition

*a move is done by pointing the mouse pointer at the center of a partition and dragging it left/right with the hand cursor

*a resize is done by dragging the left/right side of a partition to the left/right with the directional arrow cursor

*if any partition can't be moved/resized graphically, you may have to manually enter the specific required numeric data (don't do this unless I instruct you to)

*you begin any move/resize by right-clicking on the partition in the lower part of the main window, and selecting the desired action from the popup menu, then finishing that action in the new move/resize window
Do the following...
Note: if the procedure doesn't work exactly as I outline, STOP immediately and DO NOT continue.

*

*boot the a Ubuntu Live DVD/USB

*start gparted

*right-click on /dev/sda5 in the lower pane and select swapoff

*right-click on /dev/sda3 in the lower pane and select move/resize

*resize the left side of /dev/sda3 all the way left

*right-click on /dev/sda5 in the lower pane and select move/resize

*move /dev/sda5 all the way left

*right-click on /dev/sda6 in the lower pane and select move/resize

*resize the left side of /dev/sda6 all the way left

*if it all looks correct, then click the green "Apply" icon to do the work

*quit gparted

*reboot


text:
Q: jquery array result in a div i am trying to show array result in a div. please help
var events = [
    { Title: "Five K for charity", Date: new Date("03/13/2013"), Time: "11:15" },
    { Title: "Dinner", Date: new Date("03/25/2013"), Time: "11:15" },
    { Title: "Meeting with manager", Date: new Date("03/01/2013"), Time: "11:15" }
];

var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];
$(myArray).each(function() {
$(".myarray").text();
});

please advice where I am wrong?

A: since your myArray is array of object .. so use loop to get array object and . operator to get that particular objects value...
try this
 var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];
 $.each(myArray,function(i,v) {
   $(".myarray").append(v.Title);
 });

A: it should be
var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];
$(myArray).each(function() {
    $(".myarray").append(this.Title);
});

Demo: Fiddle or Fiddle2
Or Better
var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];

$(".myarray").append($.map(myArray, function(v, i){
    return v.Title;
}).join());

Demo: Fiddle

A: var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];

var text = myArray.map(function(o) {
    return '<p>' + o.Title + '</p>';
}).join(' ');

$(".myarray").html(text);

Fiddle

A: var myArray = [{Title : "one" }, {Title: "two"}, {Title: "three"}];
for(var i in myArray)
{
var title = myArray[i];
alert(title.Title);

}


text:
Q: Can I access to website using IP address I recently got to know about DNS (Domain Name System Or Domain Name Server) and how it works. I want to know - can I access to a website by using its IP address and how?
-ThankYou

A: TL;DR: It depends how the server is configured but probably not and I would not rely on it.
This is because the website you are trying to access is likely behind a reverse proxy or load balancer. The load balancer acts like a railroad switch depending on the hostname you use to connect to it.
For simplicity, imagine that google.com and mail.google.com are on the same server with the same IP: 192.168.1.1.
If you were to try to connect directly to http://192.168.1.1/, how would the web server know which service you wanted?  It wouldn't.  In fact there are companies who's business is based solely around load balancing other companies' servers.
When you connect to a host with your browser, for example: https://www.google.com, your browser sends a special HOST=www.google.com header behind the scenes.  The load balancer processes this header and routes the request to the correct server (which may be on a completely different server, network, etc).
Digital Ocean has a great tutorial on how to configure a basic virtual host for nginx.  This demonstrates the basics of what a multi-host configuration might look like.
If you don't want to mess with DNS servers, you could set up a local lab environment on your desktop simply by modifying your hosts file.  You can google where your operating systems hosts file is located.
If you have access to cURL, you can test the results like so:
# if you've configured a virtual host for mysite01.local on port 80
curl --verbose --header 'Host: mysite01.local' 'http://127.0.0.1'

# if you've configured a virtual host for mysite02.local on port 80
curl --verbose --header 'Host: mysite02.local' 'http://127.0.0.1'

# depending on your configuration this may return a 404 or point to one of your previous sites
curl --verbose 'http://127.0.0.1'

A: Yes, you can access any domain using IP address. Domain is just a name of website, IP address is the address of the page/website.
You can always ping website using command prompt:
ping www.google.com

You get one ip address which in this case is 216.58.197.78. Now when you hit the ip address in browser you will be redirected to google.com.
You can think of DNS (Domain Name System) as a table which provides mapping between IP address(216.58.197.78) and domain name(www.google.com)


text:
Q: c# Regex img src I want to get the links to the images from the img src in the html.
I have a string of the html that I read into a method which returns an arraylist of the image urls.
Into the method I pass the string of html and the url of the webpage.
I need some help with the regex to get the image name with the extension.
If you can help with matching against the html string that would be a bonus.
I will accept the right answer or close to it, thank you all.
I heard about HTML parsers but I would rather use this way thank you.
here is my method:
   private ArrayList GetImageLinks(String inputHTML, String link)
    {
        ArrayList imageLinks = new ArrayList();
        var regex = new Regex(@"<img.*?src=[\"'](.+?)[\"'].*?");

        //using http://gskinner.com/RegExr/ this regex seems to get: <img src="beach.png" for example. while I need just beach.png.

        //match the regex to the html and get all the image links like: image5.png
        //link = inputHTML + link
        //add new link to arraylist

        return imageLinks;
    }

A: I did not understand what you want to do with image source after extracting.
Here is how you can extract image links.
static IEnumerable<String> GetImageLinks(String inputHTML, String someLink)
{
    const string pattern = @"<img\b[^\<\>]+?\bsrc\s*=\s*[""'](?<L>.+?)[""'][^\<\>]*?\>";

    foreach (Match match in Regex.Matches(inputHTML, pattern, RegexOptions.IgnoreCase))
    {
        var imageLink = match.Groups["L"].Value;

        /* Do something from your image link here*/

        yield return imageLink;
    }
}

A: You can use WebBrowser to do that instead of string manipulation
       private string HtmlUpdateWithImage(string stringHtml)
        {
            System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser();
            browser.Navigate("about:blank");
            HtmlDocument doc = browser.Document;
            doc.Write(stringHtml);

            if (null != browser.Document && null != browser.Document.Images && browser.Document.Images.Count > 0)
            {
                // Here you can get the image list browser.Document.Images
                foreach (System.Windows.Forms.HtmlElement item in browser.Document.Images)
                {
                    // To get file path for each image
                    string imageFilePath = item.GetAttribute("src");
                    // Or either you can set those values

                    item.SetAttribute("src","testPath");
                }
            }
            return "" + browser.Document.Body.OuterHtml + "";
        }

A: If you want just take name of image, just use method GetFileName() of class Path:
string internetAddress=@"http://hello.com/a/s/s/fff.jpg";
string takeName=Path.GetFileName(internetAddress);


text:
Q: detecting multitouch longpress event using rxjs Been playing around with rxjs. I find it really good, but it really took some time to get my head around it.
Here's a little one I can't solve, so I'm looking for some insight.
Consider a multitouch interface where for each touchstart/touchmove/touchend you would have as params an object with {id:, x:x, y:y, t:t, current_pointers: }
I would like an observable that would trigger an event for each down pointer after 1500 ms unless touchmove or touchup happens for that pointer.
For a single touch it's straightforward, you would just takeUntil touch move or touchup, but how would you use takeUntil when the id of the pointer is within the first observable in the chain ?

A: It helps to flatten the touches array so you can treat the touches individually.  Here's the basic idea, using the Rx-jQuery bindings.  I've not tested it so it might be a bit buggy:
var flattenTouches = function (ev) {
    return ev.changedTouches.map(function(t) { return { ev: ev, touch: t }; });
};
var starts = $element.bindAsObservable("touchstart")
    .selectMany(function (ev) { return Rx.Observable.fromArray(flattenTouches(ev)); });
var moves = $element.bindAsObservable("touchmove")
    .selectMany(function (ev) { return Rx.Observable.fromArray(flattenTouches(ev)); })
    .publish().refCount(); // to prevent multiple subscriptions
var ends = $element.bindAsObservable("touchend")
    .selectMany(function (ev) { return Rx.Observable.fromArray(flattenTouches(ev)); })
    .publish().refCount(); // to prevent multiple subscriptions

var moveOrEnds = Rx.Observable.mergeObservable(moves, ends);
var timer = Rx.Observable.timer(1500);

var longpresses = starts
    .selectMany(function (start) {
        var thisPointerMovesOrEnds = movesOrEnds.where(function(t) {
            return t.touch.identifier === start.touch.identifier;
        });
        return timer
            .takeUntil(thisPointerMovesOrEnds)
            .select(start);
    });

longpresses.subscribe(function (t) {
    console.log("longpress", t.touch.pageX, t.touch.pageY, t.touch.identifier);
});


text:
Q: All divs back to default except for the active one jQuery Okay, so here is my script.
When you click on a learn more button, it corresponds to that particular box and pulls down the right information accordingly.
I want to add a feature so when you click on ANOTHER learn more, and there is already a div open with information, it closes itself like the tail end of the toggle in this script.
Essentially, I don't want to have two learn more's open at the same time.  If you choose one, then all the rest of them are closed.  The way the page is setup, I can only have one open at a time.
$(document).ready(function(){

 var service = $(".service"), text = $(".service-text, h1.service-heading"), moretext = $(".more-text");

$(".learn").toggle(
               function()
               {
                $(this).parent().find(service).animate({ backgroundColor : "#000000" }, 800);
                $(this).animate({ backgroundColor : "#FFFFFF" }, 800);
                $(this).parent().find(text).animate({ color: "#FFF"}, 800);
                $(this).parent().find("span.more").animate({ color : "#000000" }, 800, function () {
                    $(this).parent().parent().find(".service").animate({ height : "500px"}, 800, function () {
                            $(this).find(moretext).show().animate({ color: "#FFFFFF"}, 800);

                            $(this).parent().find("span.more").animate({ color : "#FFF"}, 800, function () {
                                                                                $(this).hide();
                                                        $(this).parent().find("span.less").show( function () {
                                                                                $(this).animate({ color: "#000000"}, 800);
                                                                                });
                                                                                });
                                                                                });
                                                                                });
               },
               function()
               {
                $(this).parent().find(service).animate({ backgroundColor : "#FFFFFF" }, 800, function () {
                            $(moretext).animate({ color: "#FFFFFF"}, 800, function () {
                                                                                $(this).hide();
                                                                                });
                             });
                $(this).animate({ backgroundColor : "#000000" }, 800);
                $(this).parent().find(text).animate({ color: "#000000"}, 800);
                $(this).parent().find("span.less").animate({ color: "#FFFFFF"}, 800, function() {
                    $(this).parent().parent().find(service).animate({ height: "180px"}, 800, function () {
                                        $(this).parent().find("span.less").animate({ color: "#000000"}, 800, function () {
                                                                                $(this).hide();
                                                            $(this).parent().find("span.more").show( function () {
                                                                                $(this).animate({ color: "#FFFFFF"}, 800);
                                                                                });
                                                             });
                                                                                });
                                                                                });

                   });
   });

A: you can make it this way
$(".learn").click(function(){
    $(".learn").not(this).doSomeThing(/* some code */);
});

by this code you can exclude the current clicked item from the set

A: Pseudo code:

*

*Give all the relavent divs a special class name

*Separate your "close" function in the tail end of toggle out into a separate function, make it so it doesn't close divs with a class of "active"

*Setup a listener for clicking on learn mores that add the class "active" to the thing clicked then calls that close function for all (other) divs before doing its thing


text:
Q: How do I pass prop to style object in vue Js I'm trying to use an object to control the style of certain parts of an app as I'm trying to avoid inline styling. What how do I use Colour from props in the styling object below please?
 data: () => ({
         props: ['header', 'questions', 'index', 'colour'],
         sectionScore: [],
         styling: {
             borderLeft: '10px solid ${this.colour}'
         }
     }),

I'm using the object in the main body with :style="styling".

A: First the props option should be declared as a property outside the data option, second, define the styling property as a computed one :
props: ['header', 'questions', 'index', 'colour'],
data: () => ({

         sectionScore: [],

     }),

computed:{
   styling(){
     return {
             borderLeft: `10px solid ${this.colour}`
         }
  }
}


text:
Q: Finding local maximum of solution of a differential equation The problem is this:

Given the differential equation
  $$y' + \frac{1}{2}y = 2\cos t, y(0)=-1$$
  Find the coordinates of the first local maximum for the solution when $t>0$

I'm not sure, how to proceed here. I have found the solution given the initial condition which is
$$y(t) = \frac{1}{5}(-9e^{-t/2} + 8 \sin t + 4 \cos t)$$
and from my calculus courses I remember that you have to set $y'(t)=0$ to find the critical points, so I did and got
$$y'(t)=0 \Rightarrow \frac{9}{2}e^{-t/2} + 8 \cos t - 4 \sin t = 0$$
This seems to suggest an infinite number of local maxima and minima for $t>0$, which I corroborated by looking at a graph of the function.

Using wolfram I found that the first local maximum is at $t\approx 1.36431,$ but I haven't had a course on numerical apporximation, so my question is:

Is there an analytic method for finding this local maximum?

I appreciate any help!
Note: There is an identical question here:Given: $y'+\frac{1}{2}y =2\cos t, \ y(0) = -1$ to find the coordinates of the first local maximum point $t>0$ but it never got answered so I hope this one doesn't get closed. Thanks!

A: As you suspect, using numerical methods will solve the problem easily but we shall not use any of them and we shall try to approximate the solution of the transcendental equation which, by definition, cannot show any analytical expression.
Considering the first derivative
$$y'(t)= \frac{9}{2}e^{-t/2} + 8 \cos(t) - 4 \sin( t) $$ and using your observation from the plot, let us consider Taylor series built around $t=a$. They are $$e^x=e^{-a}-e^{-a} (x-a)+\frac{1}{2} e^{-a} (x-a)^2+O\left((x-a)^3\right)$$ $$\sin (x)=\sin (a)+(x-a) \cos (a)-\frac{1}{2} (x-a)^2 \sin (a)+O\left((x-a)^3\right)$$
$$\cos(x)=\cos (a)-(x-a) \sin (a)-\frac{1}{2} (x-a)^2 \cos (a)+O\left((x-a)^3\right)$$ Applying them (using for simplicity $a=\frac \pi 2$), we then have
$$y'(t)=\left(\frac{9 e^{-\pi /4}}{10}-\frac{4}{5}\right)-\left(\frac{8}{5}+\frac{9
   e^{-\pi /4}}{20}\right) \left(t-\frac{\pi }{2}\right)+\left(\frac{2}{5}+\frac{9
   e^{-\pi /4}}{80}\right) \left(t-\frac{\pi }{2}\right)^2+O\left(\left(t-\frac{\pi
   }{2}\right)^3\right)$$ which then reduces to a quadratic equation in $\left(t-\frac{\pi }{2}\right)$.
Using the classical formula, we then arrive to $$y'(t)=0 \implies t=\frac{\pi }{2}+\frac{2 \left(9+32 e^{\pi /4}-\sqrt{3 \left(-27+48 e^{\pi /4}+512 e^{\pi
   /2}\right)}\right)}{9+32 e^{\pi /4}}\approx 1.36548$$ while the exact solution would be $t\approx 1.36431$ which seems to be quite good.
Using the result of the approximation, the maximum would be $\approx 0.820081$ while the exact solution would be $\approx 0.820082$.
Edit
We could have done better using $a=\frac{5 \pi }{12}$ (we know the values of the trigonometric functions for this angle). Doing the same as above, we should have
$$y'(t)=\left(-3 \sqrt{2}+\sqrt{6}+\frac{9}{2} e^{-5 \pi /24}\right)-\left(\sqrt{2}+3
   \sqrt{6}+\frac{9}{4} e^{-5 \pi /24}\right) \left(t-\frac{5 \pi
   }{12}\right)+\left(\sqrt{6-3 \sqrt{3}}+\frac{9}{16} e^{-5 \pi /24}\right)
   \left(t-\frac{5 \pi }{12}\right)^2+O\left(\left(t-\frac{5 \pi
   }{12}\right)^3\right)$$ Ignoring the quadratic term, the zero would be given as $t\approx 1.36392$. Using the quadratic term, $t\approx 1.36429$.

A: My first answer was using Taylor series to approximate locally the function $y'(t)$.
We could also use Padé approximants which are ratios of polynomials of different degrees of the form $$f(x)=\frac{\sum_{i=0}^m a_i (x-x_0)^i}{1+\sum_{i=1}^n b_i (x-x_0)^i}$$ the coefficients being defined from the successive derivatives of the function evaluated at point $x=x_0$.
To simplify the calculations here, we shall use $x_0=0$ (which extremely simplify the value of the different terms), $m=1$ (to just solve a linear equation) and vary $n$; this will make the solution to be $t=-\frac{a_0}{a_1}$.
The table below reproduces for $y'(t)=0$ the exact results and their decimal representation as well as the value of $y(t)$ as a function of $n$.
$$\left(
\begin{array}{ccc}
 n & t_n & & y(t_n)\\
0 & 2 & 2.00000 & 0.459775 \\
 1 & \frac{20}{21} & 0.95238 & 0.649412 \\
 2 & \frac{126}{85} & 1.48235 & 0.806614 \\
 3 & \frac{200}{153} & 1.30719 & 0.816871 \\
 4 & \frac{5202}{3797} & 1.37003 & 0.820050 \\
 5 & \frac{75940}{55651} & 1.36458 & 0.820082 \\
 6 & \frac{333906}{245327} & 1.36107 & 0.820072 \\
 7 & \frac{137383120}{100565709} & 1.36610 & 0.820079 \\
 8 & \frac{1810182762}{1327776461} & 1.36332 & 0.820081 \\
 9 & \frac{26555529220}{19459260621} & 1.36467 & 0.820082 \\
 10 & \frac{428103733662}{313814366413} & 1.36419 & 0.820082
\end{array}
\right)$$


text:
Q: blank Recyclerview inside Fragment I am using fragment and recyclerview together. I also have database and I want to query results coming from the database and display the results inside the activity.
However every time I try to run the application and switch to the part to get and view the results, I don't seem to get anything. No results at all just blank. I don't know why it's not showing up.
This is my full code
Sample class
public class Sample extends Fragment {
    private View rootView;

    public Sample() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        rootView = inflater.inflate(sample, container, false);

        RecyclerView mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView_sample);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(true);

        DatabaseHandler db= new DatabaseHandler(getActivity());
        List<SampleModel> list = db.getResults();

        SampleAdapter sampleAdapter = new SampleAdapter(list);
        mRecyclerView.setAdapter(sampleAdapter);

        return rootView;
    }
}

Adapter Class
public class SampleAdapter extends RecyclerView.Adapter <SampleAdapter.ViewHolder> {

    private List<SampleModel> list;
    private Context mContext;

    public SampleAdapter (List<SampleModel> list) {
        list = list;
    }

    @Override
    public SampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.sample_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(SampleAdapter.ViewHolder holder, int position) {
        SampleModel sample = list.get(holder.getAdapterPosition());
        holder.title.setText(sample.getTitle())
    }

    @Override
    public int getItemCount() {
        return (list != null? list.size():0);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView title;

        public ViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
        }
    }
}

XML
sample.xml
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <include layout="@layout/sample_recyclerview" />

    </android.support.design.widget.CoordinatorLayout>

sample_recyclerview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView_sample"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"/>

</RelativeLayout>

sample_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:focusable="true"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardBackgroundColor="#808080">

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

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff" />

    </LinearLayout>

</android.support.v7.widget.CardView>

A: In your SampleAdapter change
list = list;

to
this.list = list;

A: Your Adapter constructor is wrong. You are not passing the dataSource to your adapter. Change it to
 public SampleAdapter (List<SampleModel> list) {
        this.list = list;
    }

Furthermore you have to notify the adapter that you changed your dataSource. You do that by calling the method notifyDataSetChanged
SampleAdapter sampleAdapter = new SampleAdapter(list);
mRecyclerView.setAdapter(sampleAdapter);
sampleAdapter.notifyDataSetChanged();

A: RecyclerViews will return nothing if the size is not rightly returned(e.g using : return 0;)
 change your code from :
  public int getItemCount() {
        return (list != null? list.size():0);
     To:
 public int getItemCount() {
    return list.size();


text:
Q: Clipping polygons and lines at exact borders within PostGIS I have OSM data of the whole world in a PostGIS db.
For some reasons, I want to work with tables which have only data from a given bounding box inside.
I create this tables with following command:
CREATE TABLE export.osm_adminareas_a AS
  SELECT *
  FROM public.osm_adminareas_a
  WHERE geom && ST_MakeEnvelope(12,47,13,48, 4326)

But only when doing this with point geometry, the result is what I expect, e.g. only the points inside the bounding box.
When doing this with lines or polygon, I will get data not only outside the box, but also from regions which were absolutely far away from my box.
(For example my box is in the border region of Austria and Germany and I will get admin borders from France, and even Russia or the USA,....)

What are your recommendations for clipping polygon and line geometry exactly at the borders of my bounding box?

A: @Vince gave an educational comment, @Cyril named it directly, and I like to avoid further confusion; the simple answer is:
 clip those grometries!
All queries present in this post do one thing, one way or another, that is selecting every row whose geometries minimum bounding rectangle, the bbox, intersects the created envelope, another bbox.
And that's good, the bbox intersection search will drastically reduce the actual (costly) clipping operation that is now needed to retrieve only those parts of the found geometries that actually intersect:
CREATE TABLE export.osm_adminareas_a AS
  SELECT <col_1>,
         <col_n>,
         ST_Intersection(a.geom, ST_MakeEnvelope(12,47,13,48, 4326)) AS geom
  FROM   public.osm_adminareas_a AS a
  WHERE  a.geom && ST_MakeEnvelope(12,47,13,48, 4326)
    -- AND  ST_Intersects(a.geom, ST_MakeEnvelope(12,47,13,48, 4326))
;

The ST_Intersection is the crucial part here, as it recreates a geometry that represents the intersecting part only. To not retrieve the original geometry along you have to name all columns except the geom column.
I included the conditional ST_Intersects check; use whatever combo you like, I doubt there will be any noticeable performance gains with whatever condition.

A: Nearly perfect answer from @ThingumaBob
Only thing to extend ist that in his script the geometry type will only by geometry instead of Multipolygon. So i extended your example with the ST_Multi() function:
CREATE TABLE export.osm_adminareas_a_clip5 AS
  SELECT a.fclass,
         ST_Multi(ST_Intersection(a.geom, ST_MakeEnvelope(12, 47, 13, 48, 4326)))::geometry(Multipolygon,4326) AS geom
  FROM   public.osm_adminareas_a AS a
  WHERE  geom && ST_MakeEnvelope(12, 47, 13, 48, 4326)
      AND  ST_Intersects(a.geom, ST_MakeEnvelope(12, 47, 13, 48, 4326))

A: Try the following with both the overlap condition and the intersects
CREATE TABLE export.osm_adminareas_a AS
    SELECT *
    FROM public.osm_adminareas_a
    WHERE geom && ST_MakeEnvelope(12, 47, 13, 48, 4326)
    AND ST_INTERSECTS(geom, ST_MakeEnvelope(12,47,13,48, 4326))

The reason why I include the overlap condition is that the ST_INTERSECTS is costly, and thus running it only on overlapping boundings boxes speeds up the process


text:
Q: "Error invoking Lambda: Unable to execute HTTP request: Read timed out"... for a simple POST request? I'm struggling to do a simple POST request without it failing with this message :
Error invoking Lambda: Unable to execute HTTP request: Read timed out
My Lambda code consists of this :
const axios = require("axios");
const api = require('lambda-api')();
let PROJECT_ID = process.env.PROJECT_ID_CREATE
let TOKEN = process.env.TOKEN

api.post("/api-gitlab-launcher/create", async (lambdaRequest, res) => {
            return {
                "ami_id": lambdaRequest.body["ami_id"],
                "ip_address":lambdaRequest.ip
            }
    }
)

exports.handler = async (event, context) => {
    let config = {
        method: 'post',
        url: `https://gitlab.com/api/v4/projects/${PROJECT_ID}/trigger/pipeline?token=${TOKEN}&ref=terraform-v1-mirror`,
        headers: {}
    };

   await axios(config)
        .then(function (response) {
            console.log(JSON.stringify(response.data));
        })
        .catch(function (error) {
            console.log(error);
        });

    return await api.run(event, context);
}

This problem has been driving me mad for days... And I can't pinpoint where the bug is! If someone has an idea where it could from, I'd be glad.
UPDATE
It does work locally. Just tested it and the POST request is sent when run locally. I checked with the VPCs and it's allowing all outbound traffic.
UPDATE 2


text:
Q: Handling Null values in GetSQLDateTime and GetSQLMoney AS part of an import I'm writing I'm using parameterised values, however the database i'm exporting to cannot handle NULL values, so I need to find a way to handle NULL values.
The closest I've gotten is:
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
}
else
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}

and A similar thing with SQLDateTime
if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
    tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
     tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}

However this does not appear to work, instead I receive the following:

Message=Data is Null. This method or property cannot be called on Null values.

A: Instead of
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))

you should probably use
if (tenantexportReader.IsDbNull(8))

Since the value in the database is NULL (which is DbNull.Value in c#), I assume that GetSqlMoney and GetSqlDateTime throw the exception you received. DbNull.Value cannot be converted to SqlMoney or DateTime.
Check if the value is null via IsDbNull before calling GetSqlMoney or GetSqlDateTime.

So your final if statements should look something like this:
if (tenantexportReader.IsDbNull(8))
{
     tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
}
else
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}

A: Why would you assign a string to a monetary value???
Probably what you would want to do is like this:
var priceFinal = tenantexportReader.GetSqlMoney(8);

tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);

I really don't understand why you set it to "0.00" (string) when it is null and to a decimal value when it is not null.
And also for date/datetime values, again, why do you ever use string conversions and invite errors? Simply pass a date as a datetime.


text:
Q: Schwarzschild metric in terms of a falling observer's coordinates The Schwarzschild metric tensor $\textbf{g}(r)$ in terms of a distant observer's coordinates $(t,r,\Omega)$, can be written as:
$$ds^2=-\left(1-\frac{r_s}{r}\right)dt^2 + \left(1-\frac{r_s}{r}\right)^{-1}dr^2 +r^2\,d\Omega^2.$$
How would the metric tensor $\textbf{g}(\tilde{r})$ in terms of a inertal observer's coordinates $(\tilde{t}, \tilde{r}, \tilde{\Omega})$, $x$ units away from let's say the singularity, knowing that $\textbf{g}(\tilde{x})$ should reduce to the Minkowski metric since spacetime is locally flat in his coordinates? (where $\tilde{x}$ is how far he is in his coordinates)
I am asking this question because I'm interested in how a falling observer would see spacetime at $r=\infty$ away from the singularity. Someone very far from the effect of gravity will see the metric reduce to the Minkowski metric.

A:
Habouz asked: "What's the Schwarzschild metric in terms of a falling observer's coordinates?"

The transformation rule can be found here and here:
$${\rm dt = d\tau+dr \ v} / \hat g_{\rm tt} \ , \ \ {\rm v = -c \ \sqrt{r_s/r}} \ , \ \ 1/\gamma = \rm \sqrt{1-v^2/c^2}$$
with that you transform the old coordiantes $\rm \hat x$ to the new ones $\rm \bar x$:
$$\bar g_{\mu \nu} = \sum_{\sigma, \kappa} \ \hat g_{\sigma \kappa} \ \rm \frac{\partial \hat x^{\sigma}}{\partial \bar x^{\mu}} \ \frac{\partial \hat x^{\kappa}}{\partial \bar x^{\nu}}$$
so the metric in regular Schwarzschild/Droste coordinates (with time $\rm \hat x^0 = t$) where the local observers are stationary with respect to the black hole:
$$\hat g_{\mu \nu} = \left(
\begin{array}{cccc}
 \rm c^2/\gamma^2 & 0 & 0 & 0 \\
 0 & \rm -\gamma^2 & 0 & 0 \\
 0 & 0 & \rm -r^2 & 0 \\
 0 & 0 & 0 & \rm -r^2 \sin ^2 \theta  \\
\end{array}
\right)$$
transforms to Gullstrand/Painlevé coordinates (with time $\rm \bar x^0 = \tau$) where the local observers are free falling raindrops with the negative escape velocity $\rm v$:
$$\bar g_{\mu \nu} = \left(
\begin{array}{cccc}
 \rm c^2/\gamma^2 & \rm v & 0 & 0 \\
 \rm v & \rm -1 & 0 & 0 \\
 0 & 0 & \rm -r^2 & 0 \\
 0 & 0 & 0 & \rm -r^2 \sin ^2 \theta  \\
\end{array}
\right)$$
where the covariant spatial components are euclidean:
$$\bar g_{\rm i j} = \left(
\begin{array}{cccc}
 \rm -1 & 0 & 0 \\
 0 & \rm -r^2 & 0 \\
 0 & 0 & \rm -r^2 \sin ^2 \theta  \\
\end{array}
\right)$$
which is just flat space in spherical $\{ \rm r, \ \theta, \ \phi \}$ coordinates:

Hamilton & Lisle wrote: "In the river model, space itself flows like a river through
a flat background, while objects move through the river according to the rules of special relativity"

Here are two such free falling raindrops in Gullstrand/Painlevé coordinates sending signals to each other when they are half way through the black hole (at $\rm r=r_s/2=1$, photons in green):

If you take ${\rm dt = d} {}_T-{\rm dr \ c} /  \hat g_{\rm tt}$ or alternatively ${\rm dt = d{}_T-dr \ c \ r_s/r} / \hat g_{\rm tt}$ instead you get the Schwarzschild metric in ingoing Eddington/Finkelstein coordinates where radially ingoing photons have a constant coordinate velocity of $\rm dr/d{}_T=-c$, while in Gullstrand/Painlevé coordinates the free fallers have a coordinate velocity of $\rm dr/d\tau=v$. In regular Schwarzschild/Droste coordinates on the other hand, at $\rm r=r_s$ you get $\rm dr/dt=0$ for all particles and photons since the bookkeeper's coordinate time $\rm t$ freezes at the horizon.


text:
Q: Display .jsonld Files in gh-pages I'm trying to display JSON-LD data using the .jsonld extension in our gh-pages in the browser instead. I'd like to use the actual files as a reference. We can serve them as downloadable files but would prefer to display the raw data. We're using a Jekyll theme. Is there a config setting for this? Thanks

A: AFAICT that's not possible. You could use Gists instead or directly link to the file on GitHub


text:
Q: Python selenium test gets stuck in urlopen My app relies on:

*

*Python 3

*Django 1.8

*Weasyprint

*Selenium

It runs flawlessly on dev and production environment, but not while testing with selenium.
Using weasyprint, I create a PDF from HTML, this library uses urllib to download CSS (e.g. http://localhost:8081/static/lib/bootstrap/css/bootstrap.min.css), but it hangs (no errors, just stuck) while opening these.
If I enter this url directly in my browser while hanged, the CSS is displayed.
Command used:
./manage.py test tests.test_account.HomeNewVisitorTest

Relevant part of the test:
from selenium import webdriver

class HomeNewVisitorTest(StaticLiveServerTestCase):
    def setUp(self):
        if TEST_ENV_FIREFOX:
            self.driver = webdriver.Firefox()
        else:
            self.driver = webdriver.PhantomJS()
        self.driver.set_window_size(1440, 900)

    def tearDown(self):
        try:
            path = 'worksites/' + self.worksite_name.lower()
            os.rmdir(settings.MEDIA_ROOT + path)
        except FileNotFoundError:
            pass
        super().tearDown()

    def test(self):
        d = self.driver
        d.get(self.get_full_url('home'))
        d.find_element_by_css_selector('.btn-success[type=submit]').click()

In my view:
    # Generate PDF for contact directory
    template = get_template("pdf/annuaire.html")
    context = {"worksite": worksite}
    html = template.render(RequestContext(self.request, context))
    base_url = self.request.build_absolute_uri("/")
    pdf = weasyprint.HTML(string=html, base_url=base_url)
    pdf.write_pdf(directory + '/annuaire.pdf')

Here is the thread dump when stuck:
Fatal Python error: Aborted

Thread 0x0000000106f92000 (most recent call first):
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socket.py", line 374 in readinto
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 313 in _read_status
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 351 in begin
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 1171 in getresponse
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 1185 in do_open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 1210 in http_open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441 in _call_chain
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 481 in _open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 463 in open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161 in urlopen
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/urls.py", line 276 in default_url_fetcher
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/urls.py", line 311 in fetch
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/contextlib.py", line 59 in __enter__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/__init__.py", line 297 in _select_source
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/contextlib.py", line 59 in __enter__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/__init__.py", line 223 in __init__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/css/__init__.py", line 198 in find_stylesheets
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/css/__init__.py", line 448 in get_all_computed_styles
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/document.py", line 312 in _render
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/__init__.py", line 132 in render
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/weasyprint/__init__.py", line 164 in write_pdf
  File "/Users/sebcorbin/Sites/planexo/worksite/views.py", line 111 in done
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/formtools/wizard/views.py", line 357 in render_done
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/formtools/wizard/views.py", line 730 in render_done
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/formtools/wizard/views.py", line 300 in post
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/formtools/wizard/views.py", line 686 in post
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/views/generic/base.py", line 89 in dispatch
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/formtools/wizard/views.py", line 237 in dispatch
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/views/generic/base.py", line 71 in view
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/contrib/auth/decorators.py", line 22 in _wrapped_view
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/handlers/base.py", line 132 in get_response
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189 in __call__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/test/testcases.py", line 1099 in __call__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/contrib/staticfiles/handlers.py", line 63 in __call__
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wsgiref/handlers.py", line 137 in run
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/servers/basehttp.py", line 182 in handle
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 673 in __init__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/servers/basehttp.py", line 102 in __init__
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 344 in finish_request
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 331 in process_request
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 305 in _handle_request_noblock
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 238 in serve_forever
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/test/testcases.py", line 1182 in run
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 920 in _bootstrap_inner
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 888 in _bootstrap

Current thread 0x00007fff7996a300 (most recent call first):
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socket.py", line 374 in readinto
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 313 in _read_status
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 351 in begin
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/client.py", line 1171 in getresponse
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 1185 in do_open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 1210 in http_open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441 in _call_chain
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 481 in _open
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 463 in open
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/selenium/webdriver/remote/remote_connection.py", line 457 in _request
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/selenium/webdriver/remote/remote_connection.py", line 389 in execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 191 in execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 447 in _execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 68 in click
  File "/Users/sebcorbin/Sites/planexo/tests/test_account.py", line 203 in _test_worksite_form
  File "/Users/sebcorbin/Sites/planexo/tests/test_account.py", line 36 in test
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 577 in run
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 625 in __call__
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/test/testcases.py", line 186 in __call__
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/suite.py", line 122 in run
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/suite.py", line 84 in __call__
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/runner.py", line 168 in run
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/test/runner.py", line 178 in run_suite
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/test/runner.py", line 211 in run_tests
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/commands/test.py", line 90 in handle
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/base.py", line 441 in execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/commands/test.py", line 74 in execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/base.py", line 390 in run_from_argv
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/commands/test.py", line 30 in run_from_argv
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/__init__.py", line 330 in execute
  File "/Users/sebcorbin/.virtualenvs/planexo-py3/lib/python3.4/site-packages/django/core/management/__init__.py", line 338 in execute_from_command_line
  File "./manage.py", line 10 in <module>

A: Thanks to you all for pinpointing the problem, I took for inspiration this article http://nedbatchelder.com/blog/201103/quick_and_dirty_multithreaded_django_dev_server.html and modified my manage.py file:
#!/usr/bin/env python
from http import server
import os
from socketserver import ThreadingMixIn
import sys

def monkey_patch_test_server():
    # This monkey-patches HTTPServer to create a base HTTPServer class that
    # supports multithreading
    originalhttpserver = server.HTTPServer

    class ThreadedHTTPServer(ThreadingMixIn, originalhttpserver):
        def __init__(self, server_address, RequestHandlerClass=None):
            originalhttpserver.__init__(self, server_address,
                                        RequestHandlerClass)

    server.HTTPServer = ThreadedHTTPServer

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planexo.settings")

    from django.core.management import execute_from_command_line

    if sys.argv[1] == 'test':
        monkey_patch_test_server()

    execute_from_command_line(sys.argv)

Now it works!

A: Use Python faulthandler module to print the traceback of all hung threads. This will pinpoint you the actual functions were the hanging is happening.
If needed edit your question and add the relevant information.
Otherwise my guess is that you are using Django test / development server in such a way that it can only handle one request at a time. Your initial HTTP request to dev server triggers a request to request data from itself, which Django dev server is unable to do. But this is just a guess.
Also relevant source code missing from the question.

A: I'll share my case:
I had this issue with my Django selenium tests (django==1.7.12 and selenium==2.53.1) with ChromeDriver 2.21.371459 and Google Chrome 48.0.2564.116.
I was able to isolate the issue. In my case it was happening only for pages referencing a static file (an image in a HTML <img> tag for instance http://cdn.local.myproject.net/static/myimage.png) on my custom local cdn domain. The issue was not present if I used a relative path "/static/myimage.png" or localhost "http://127.0.0.1/static/myimage.png" so I figured it was a DNS problem.
I was able to bypass the problem by using the --dns-prefetch-disable option of chrome.
Example in Python:
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
driver = Chrome(chrome_options=options)

I don't know if this is the general case but hopefully it can help some of you.

A: Use the faulthandler module. Maybe it can also be that Django, can only take 1 request.


text:
Q: Add html plugin into wordpress I purchased an HTML5 Video & Youtube background plugin,
I want to use it with WordPress.
http://codecanyon.net/item/html5-video-youtube-background/1555660
Any Suggestions? Maybe create a template, page,etc..?


text:
Q: Was not declared in the scope error I have a class that saves a student data. Before it will be stored, the ID will be check first if valid or not. In overloading the operator >>, I call the validate_id function. I already declared it as a friend, however upon compiling, it says 'validate_id was not declared in scope  . Is it because its a static function?
#include <iostream>
#include <string>
#include <locale>
#include <utility>
#include <algorithm>
#include <stdexcept>

typedef std::pair<std::string, std::string> Name;

class Student {

   public:
       Student(){};

       bool operator <( const Student& rhs ) const {
          return ( id_ < rhs.id_ );
        }

   friend std::ostream& operator <<(std::ostream& os, const Student& s);
   friend std::istream& operator >>(std::istream& is, Student& s);

   private:
    std::string     id_;
    Name        name_;

    static bool validate_id(const std::string& id){
        if(id.length() != 9 && id[0] != 'a')
            return false;

        for(size_t i = 1, sz = id.length(); i < sz; i++){
            if(!isdigit(id[i]))
              return false;
        }

            return true;
    }

};

std::ostream& operator <<(std::ostream& os, const Student& s){
    return os << s.id_ << " " << s.name_.first << " " << s.name_.second;
}

std::istream& operator >>(std::istream& is, Student& s){
     is >> s.id_ >> s.name_.first >> s.name_.second;

    if(!validate_id(s.id_))  // error here, says validate_id is not in scope
        throw std::invalid_argument( "invalid ID" );

    return is;
}

A: validate_id is a static member of Student, so you need to use the class' scope to name it:
if(!Student::validate_id(s.id_))
    ^^^^^^^^^

A: When you are calling a static member function in c++, you have to call it with the class scope. that means here you have to use
 !Student::validate_id(s_id)
Meaning of a Static is that what ever you declared is goes to class scope.Not to object scope. That's why you have to call it with the class.

A: Either declare validate_id outside of the Student class or call Student.validate_id.


text:
Q: adding a search bar and search display controller on tableview in Storyboard? How do you add the search bar and search display controller on tableview or view Controller on storyboard?
When I add the search bar and search display controller on the tableview and run the app, the search bar does not auto layout to the tableview (parts of the right side is not showing) and when i click on the search bar in the iOS simulator, it crashes.
But when I add the search bar and search display controller on the table View Controller, it works perfectly fine.
What am I doing wrong?


text:
Q: Home button in Android studio with kotlin I have created a splash screen for my app in Android studio using kotlin. When the home button is pressed in splash screen time, the app restarts and opens the next activity i.e login activity instead of putting the app to background.
How can I put the app into background and avoid it to restart automatically when home button is pressed in splash screen time

A: Can you add this code to your splash screen activity?
override fun onPause() {
    super.onPause()
    finish()
}

I hope this helps.