text:
Q: Difference between malloc and calloc? What is the difference between doing:
ptr = malloc(MAXELEMS * sizeof(char *));

And:
ptr = calloc(MAXELEMS, sizeof(char*));

When is it a good idea to use calloc over malloc or vice versa?

A: calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized.
For large allocations, most calloc implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS) or Windows VirtualAlloc) so it doesn't need to write them in user-space.  This is how normal malloc gets more pages from the OS as well; calloc just takes advantage of the OS's guarantee.
This means calloc memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros.  (Assuming a system with virtual memory.)  The effects are visible with performance experiments on Linux, for example.
Some compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory.  (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.)
If you aren't going to ever read memory before writing it, use malloc so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS.  (Or instead of zeroing a block of memory on the free list for a small allocation).

Embedded implementations of calloc may leave it up to calloc itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.
On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS), which is only enabled for some embedded kernels because it's insecure on a multi-user system.

A: Difference 1:
malloc() usually allocates the memory block and it is initialized memory segment.
calloc() allocates the memory block and initialize all the memory block to 0.
Difference 2:
If you consider malloc() syntax, it will take only 1 argument. Consider the following example below:
data_type ptr = (cast_type *)malloc( sizeof(data_type)*no_of_blocks );

Ex: If you want to allocate 10 block of memory for int type,
int *ptr = (int *) malloc(sizeof(int) * 10 );

If you consider calloc() syntax, it will take 2 arguments. Consider the following example below:
data_type ptr = (cast_type *)calloc(no_of_blocks, (sizeof(data_type)));

Ex: if you want to allocate 10 blocks of memory for int type and Initialize all that to ZERO,
int *ptr = (int *) calloc(10, (sizeof(int)));

Similarity:
Both malloc() and calloc() will return void* by default if they are not type casted .!

A: The calloc() function that is declared in the <stdlib.h> header offers a couple of advantages over the malloc() function.

*

*It allocates memory as a number of elements of a given size, and

*It initializes the memory that is allocated so that all bits are
zero.

A: malloc() and calloc() are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)

There are mainly two differences between the two:

*

*Behavior: malloc() allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc(), on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.

*Syntax: malloc() takes 1 argument (the size to be allocated), and calloc() takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;

// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));

// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));

The same functionality as calloc() can be achieved using malloc() and memset():
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));

Note that malloc() is preferably used over calloc() since it's faster. If zero-initializing the values is wanted, use calloc() instead.

A: A difference not yet mentioned: size limit
void *malloc(size_t size) can only allocate up to SIZE_MAX.
void *calloc(size_t nmemb, size_t size); can allocate up about SIZE_MAX*SIZE_MAX.
This ability is not often used in many platforms with linear addressing.  Such systems limit calloc() with nmemb * size <= SIZE_MAX.
Consider a type of 512 bytes called disk_sector and code wants to use lots of sectors.  Here, code can only use up to SIZE_MAX/sizeof disk_sector sectors.
size_t count = SIZE_MAX/sizeof disk_sector;
disk_sector *p = malloc(count * sizeof *p);

Consider the following which allows an even larger allocation.
size_t count = something_in_the_range(SIZE_MAX/sizeof disk_sector + 1, SIZE_MAX)
disk_sector *p = calloc(count, sizeof *p);

Now if such a system can supply such a large allocation is another matter.  Most today will not.  Yet it has occurred for many years when SIZE_MAX was 65535.  Given Moore's law, suspect this will be occurring about 2030 with certain memory models with SIZE_MAX == 4294967295 and memory pools in the 100 of GBytes.

A: The documentation makes the calloc look like malloc, which just does zero-initialize the memory; this is not the primary difference! The idea of calloc is to abstract copy-on-write semantics for memory allocation. When you allocate memory with calloc it all maps to same physical page which is initialized to zero. When any of the pages of the allocated memory is written into a physical page is allocated. This is often used to make HUGE hash tables, for example since the parts of hash which are empty aren't backed by any extra memory (pages); they happily point to the single zero-initialized page, which can be even shared between processes.
Any write to virtual address is mapped to a page, if that page is the zero-page, another physical page is allocated, the zero page is copied there and the control flow is returned to the client process. This works same way memory mapped files, virtual memory, etc. work.. it uses paging.
Here is one optimization story about the topic:
http://blogs.fau.de/hager/2007/05/08/benchmarking-fun-with-calloc-and-zero-pages/

A: A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc isn't backed by real memory until the program actually touches it.
calloc does indeed touch the memory (it writes zeroes on it) and thus you'll be sure the OS is backing the allocation with actual RAM (or swap). This is also why it is slower than malloc (not only does it have to zero it, the OS must also find a suitable memory area by possibly swapping out other processes)
See for instance this SO question for further discussion about the behavior of malloc

A: There's no difference in the size of the memory block allocated. calloc just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc have initilial value as if they were initialized with literal 0, i.e. integers should have value of 0, floating-point variables - value of 0.0, pointers - the appropriate null-pointer value, and so on.
From the pedantic point of view though, calloc (as well as memset(..., 0, ...)) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.
Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc (and memset(..., 0, ...)). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.
In practice, calloc works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc instead and perform my own initialization.
Finally, another important detail is that calloc is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.

A: from an article Benchmarking fun with calloc() and zero pages on Georg Hager's Blog

When allocating memory using calloc(), the amount of memory requested is not allocated right away. Instead, all pages that belong to the memory block are connected to a single page containing all zeroes by some MMU magic (links below). If such pages are only read (which was true for arrays b, c and d in the original version of the benchmark), the data is provided from the single zero page, which – of course – fits into cache. So much for memory-bound loop kernels. If a page gets written to (no matter how), a fault occurs, the "real" page is mapped and the zero page is copied to memory. This is called copy-on-write, a well-known optimization approach (that I even have taught multiple times in my C++ lectures). After that, the zero-read trick does not work any more for that page and this is why performance was so much lower after inserting the – supposedly redundant – init loop.

A: Number of blocks:
malloc() assigns single block of requested memory,
calloc() assigns multiple blocks of the requested memory
Initialization:
malloc() - doesn't clear and initialize the allocated memory.
calloc() - initializes the allocated memory by zero.
Speed:
malloc() is fast.
calloc() is slower than malloc().
Arguments & Syntax:
malloc() takes 1 argument:

*

*bytes

*

*The number of bytes to be allocated

calloc() takes 2 arguments:

*

*length

*

*the number of blocks of memory to be allocated

*bytes

*

*the number of bytes to be allocated at each block of memory

void *malloc(size_t bytes);
void *calloc(size_t length, size_t bytes);

Manner of memory Allocation:
The malloc function assigns memory of the desired 'size' from the available heap.
The calloc function assigns memory that is the size of what's equal to 'num *size'.
Meaning on name:
The name malloc means "memory allocation".
The name calloc means "contiguous allocation".

A: calloc is generally malloc+memset to 0
It is generally slightly better to use malloc+memset explicitly, especially when you are doing something like:
ptr=malloc(sizeof(Item));
memset(ptr, 0, sizeof(Item));

That is better because sizeof(Item) is know to the compiler at compile time and the compiler will in most cases replace it with the best possible instructions to zero memory. On the other hand if memset is happening in calloc, the parameter size of the allocation is not compiled in in the calloc code and real memset is often called, which would typically contain code to do byte-by-byte fill up until long boundary, than cycle to fill up memory in sizeof(long) chunks and finally byte-by-byte fill up of the remaining space. Even if the allocator is smart enough to call some aligned_memset it will still be a generic loop.
One notable exception would be when you are doing malloc/calloc of a very large chunk of memory (some power_of_two kilobytes) in which case allocation may be done directly from kernel. As OS kernels will typically zero out all memory they give away for security reasons, smart enough calloc might just return it withoud additional zeroing. Again - if you are just allocating something you know is small, you may be better off with malloc+memset performance-wise.

A: One often-overlooked advantage of calloc is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:
size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);

vs.
size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);

The former could result in a tiny allocation and subsequent buffer overflows, if count is greater than SIZE_MAX/sizeof *bar. The latter will automatically fail in this case since an object that large cannot be created.
Of course you may have to be on the lookout for non-conformant implementations which simply ignore the possibility of overflow... If this is a concern on platforms you target, you'll have to do a manual test for overflow anyway.

A: There are two differences.
First, is in the number of arguments. malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

*

*calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.

Syntax: ptr_var = calloc(no_of_blocks, size_of_each_block);
i.e. ptr_var = calloc(n, s);

*

*malloc() allocates a single block of memory of REQUSTED SIZE and returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a null pointer.

Syntax: ptr_var = malloc(Size_in_bytes);
The malloc() function take one argument, which is the number of bytes to allocate, while the calloc() function takes two arguments, one being the number of elements, and the other being the number of bytes to allocate for each of those elements. Also, calloc() initializes the allocated space to zeroes, while malloc() does not.

A: Both malloc and calloc allocate memory, but calloc initialises all the bits to zero whereas malloc doesn't.
Calloc could be said to be equivalent to malloc + memset with 0 (where memset sets the specified bits of memory to zero).
So if initialization to zero is not necessary, then using malloc could be faster.


text:
Q: Why don't the people in The Walking Dead use more disguises? So, it is established that using the bodily fluids of a zombie hides you from zombies. The characters know this. (They also may know that keeping semi-disabled zombies also works).
Why don't they just keep the innards around to keep themselves safe?

A: Would you enjoy walking around covered in zombie guts?
Being covered in zombie guts provides some protection but if you are not also acting like a zombie it can be seen through (so to speak) the episode where they covered themselves in guts had zombies sniff at them and I believe even follow them for a time acting a little confused, also the guts will wash off which means if you used them to infiltrate a heavily infested area and a sudden rain storm moves in your royally screwed
"Tame" zombies may help a bit on the road but Michonne still had to fight on occasion when a zombie got too close. Maybe if you staked a bunch of tamed zombies on a perimeter outside of the line of sight of the prison it would protect it, but the sheer logistics of that undertaking would make it more trouble than any benefits you might derive from it

A: TWD Robert Kirkman was asked this question on the season six midseason finale of Talking Dead.  His reply, which I will include in full after I can access the video of the episode, boiled down to this:

*

*It isn't guaranteed to work (as we saw in Season 1, Episode 2, Guts), and you are still at an incredible risk of being bitten.

*It's an appalling situation in which to find yourself.

*Infection from the guts themselves is a very serious threat.

*You would need to stop and refresh your "camouflage" very frequently, because the stink wears off very quickly.

It's also worth noting that Kirkman was also asked why characters don't smear themselves in zombie guts to disguise themselves more often. Kirkman noted that it's usually an option of last resort because there's still a high risk of being bitten, that the zombie guts themselves can lead to infection, and that the entrails will dry out and have to be frequently replenished.
  -  Source

And in the season six midseason finale, we saw a small group attempt the guts trick.  Huge spoilers for the season six midseason premiere ahead:

  We'll see it fail miserably in the midseason premiere.  Sam is talking, calling attention to the group. He will be bitten.  Jesse will freak out and be attacked as well.  She will cling to Carl, begging for help.  When she refuses to let go of Carl, Rick will chop her hand off with his hatchet, which will provoke Ron to start shooting at Rick and Carl.  Carl will be shot in the face and lose an eye.  Michonne will kill Ron.  Then Rick and Michonne will take on the herd hand to hand, while Carl receives medical treatment.  This is a perfect example of the biggest reason they don't bother with the "disguises" more often - it is far from a foolproof system, and will frequently fail.  - Source

A: This is covered more in-depth in the comic. See Issue 83. It's disgusting and makes people physically sick from the stench. It also plays havoc on your focus and makes people on edge.
Ever smelled a small dead animal? How pungent and awful even a roadkill can be? Imagine that on a larger scale and being literally inside it. That's why.
SPOILER ALERT if you click on the link and are not caught up.
EDIT: The YouTube video of the comic issue was taken down. The relevant information is in the spoiler block below.

Douglas is "covering" them by continuing to shoot wildly and Rick tries to yell out to him to stop shooting. Douglas is attracting the undead, gets bitten several times, and he stops firing. Rick asks if everyone is okay and then asks Carl. When he does not answer, Rick looks down at Carl, only to discover that Carl has been shot in the eye.

NEW EDIT - 08-31-15
This info pertains only to the comic so far, but is relevant to the question. Spoilers!

There is now, in the comic, a huge group of people who dress up in the flesh of the dead, and walk among them. Their disguise protects them. It should also be noted that for all practical reasons, these people, or at least their leader, Alpha, seems to be insane or at least a proponent of radical devolution. They wear the flesh of the dead to walk among them, but also seem to lose what it means to be human. Or at least a fairly regular person. These "Whisperers" seem to be further away from Rick and his group than the band Right Said Fred is away from Slayer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Monitor working on Linux but not on Windows I started using my old monitor recently using a VGA-HDMI adapter. It worked the first time on my laptop running Windows 10 without making any changes to settings. Then I tried it on my work laptop and the monitor kept saying, "Input not supported" (probably because that laptop has a higher resolution). So, I connected it back to my laptop and now it displays the same message.
However, this message is only displayed when running Windows 10. When I dual boot into Pop OS, the display works fine. I've fiddled with all Windows Display settings (tried various resolutions and refresh rates) and even tried reinstalling the drivers. Not sure how to fix this.
Details about the hardware

*

*Personal Laptop - Dell Inspiron 5559

*Work Laptop - HP ProBook 440 G8

*HDMI to VGA adapter is non-branded one but it is in working
condition

*Monitor - HCL HCMELWBT11

A: The message "Input Not Supported" can have two causes:

*

*Bad physical connection with the monitor
(less likely since Linux works)

*The computer's resolution doesn't match with the monitor.

The second case is more likely. The explanation might be that the
monitor changed its resolution when connected to the work computer,
and now cannot work with Windows on the laptop.
Linux probably adapts itself better to the situation.
I would suggest:

*

*If the monitor has a Settings button, check its resolution setting,
or reset the monitor's settings (if possible)

*In Windows, change the resolution of this monitor to what it was
before.
Check other settings in Settings > System > Display, including
those in "Advanced display settings".

*Boot Windows in Safe Mode, run MSConfig, Boot tab, enable
"Base video" and reboot normally

If none of the above works for you, perhaps it is some hardware
incompatibility after all.
You would need to change adapter and cable and monitor,
which might perhaps help.
(Note: If you have changed any settings in the BIOS in order to run Linux,
undo them.)


text:
Q: sed - or another tool for regex text replacement I need to replace all $arr[key] with $arr['key'] but not $arr[$key] or $arr[CONST] or already rewritten as $arr['key']
Eventually $arr[key] with {$arr['key']}
Thanks!

A: You could try something like:
perl -pe 's/(\$\w+\[\s*)(?![A-Z\d]+\b)(\w+)(\s*])/$1\'$2\'$3/g' file.php

Example:
echo $arr[foo] $arr['ok'] $arr[3] $arr[CAPS] $arr[$var] $arr[ bar ] | perl -pe "s/(\$\w+\[\s*)(?![A-Z\d]+\b)(\w+)(\s*])/$1'$2'$3/g"
$arr['foo'] $arr['ok'] $arr[3] $arr[CAPS] $arr[$var] $arr[ 'bar' ]


text:
Q: How do i resolve this bug in C++? vector of the string takes input from a given string.
Input: Hello World
Expected Output: Hello World
Actual Output: Hello
#include <bits/stdc++.h>

using namespace std;

int main()
{
    string s1;
    getline(cin, s1);
    vector<string> vs1;
    string s2;
    for (int i = 0; i < s1.size(); i++) {
        if (s1[i] != ' ') {
            s2.push_back(s1[i]);
            continue;
        }
        if (s1[i] == ' ' || i == s1.size() - 1) {
            vs1.push_back(s2);
            s2.clear();
        }
    }
    for (string t : vs1) {
        cout << t << " ";
    }

    return 0;
}

A: Your first if statement will execute for any character besides a space. This means that the second if statement is not reached when i==s1.size()-1 because s1[10] == 'd' for your test input.
Since your first if statement includes a continue, the second branch is never evaluated at all when the first is true. That continue statement should not be there.

A: You can use std::stringstream so you don't need unnecessary if blocks.
#include <vector>
#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string s1;
    std::getline(std::cin, s1);
    std::string buffer;
    std::stringstream ss(s1);       // Insert the string into a stream

    std::vector<std::string> vs1; // Create vector to hold our words

    while (ss >> buffer)
        vs1.push_back(buffer);

    for (std::string t : vs1) {
        std::cout << t << " ";
    }
    return 0;
}

Output: Hello World
Note: using namespace std; is bad practice. Why is "using namespace std;" considered bad practice?

A: When you use vs1.push_back(s2) you are adding s2 to other element. You don't even have to use first if, if you want to add space to first element.
Here you are:
#include <bits/stdc++.h>

using namespace std;

int main()
{
string s1;
getline(cin,s1);
vector < string > vs1;
string s2;
for(int i=0;i<s1.size();i++)
{
    s2.push_back(s1[i]);

     if(s1[i]==' ' || i==s1.size()-1)
     {
        vs1.push_back(s2);
        s2.clear();
      }
 }
cout<<vs1[0]<<vs1[1];

 return 0;

}


text:
Q: Issue related to PowerBI DAX measure I am facing 1 issue related to DAX, let me show you the scenario.

DAX for ActualUpdates_60min_Te*
ActualUpdates_60min_Te* =

    VAR tbl60 =
        CALCULATETABLE(
            VALUES(EventDetail[ShipmentKey])
            ,ALL(EventDetail[TimelinessBreak])
            ,FILTER(
                EventDetail
                ,EventDetail[TimelinessBreak] = "<= 1 Hr"
            )
         )  // Returns 893 records

    VAR tbl30 =
        CALCULATETABLE(
             VALUES(EventDetail[ShipmentKey])
             ,ALL(EventDetail[TimelinessBreak])
             ,FILTER(
                 EventDetail
                 ,EventDetail[TimelinessBreak] = "<= 30 Mins"
             )
    )  // Returns 301 records

    VAR CntRows = COUNTROWS(EXCEPT(tbl60,tbl30)) // Returns 21 records

    VAR C = CntRows + [ActualUpdates_30min*]  // Returns 914 records

Return  C

If you see the Card - It is returning 914, when it is showing in a table it is showing 301.
What I need to achieve is I should have 914 in a table timelinessbreak is <= 1Hr.
Can anyone please help in achieving this.


text:
Q: How to fill colour part of image view with in border lines in objective-c Sample image here

I need to fill only in double lined circle with finger on image view.(Not entire circle at once). And need to calculate percentage of filled circle.
I tried lot of stuff to draw line. But i am not getting exactly as my requirement.
Please help me out how to achieve this.

A: here is a sample. You can check the code and upgrade for your needs.


text:
Q: In Swiftui, how to check the content from a URLsession? I am using SwiftUI in Xcode 11, trying to check the content of a .txt file from the internet.
The problem is that the URLSession.shared.downloadTask takes time to finish. The code to check the content is always performed before the download is finished. Can anyone help me please? Thanks very much.
Sorry, forgot to add some codes.
let url = URL(string: "https://www.myweb.com/myfile.txt")!
var myweb = "test"
URLSession.shared.downloadTask(with: url) { localURL, response, error in

    if let localURL = localURL {
        do { try myweb = String(contentsOf: localURL)}
        catch { print ("test") }
    }
}.resume()

if myweb != "test" { Call some function here}

A: I assume that you need to create ViewModel with Published property and change it flag on true statement if downloadTask has finished. Use this property inside View


text:
Q: Max value for cache control header in HTTP I'm using Amazon S3 to serve static assets for my website. I want to have browsers cache these assets for as long as possible. What meta-data headers should I include with my assets
Cache-Control: max-age=???

A: The people who created the recommendation of maximum 1 year caching did not think it through properly.
First of all, if a visitor is being served an outdated cached file, then why would it provide any benefit to have it suddenly load a fresh version after 1 year? If a file has 1 year TTL, from a functional perspective, it obviously means that the file is not intended to be changed at all.
So why would one need more than 1 year?
1) Why not? It doesn't server any purpose to tell the visitors browser "hey, this file is 1 year old, it might be an idea to check if it has been updated".
2) CDN services. Most content delivery networks use the cache header to decide how long to serve a file efficiently from the edge server. If you have 1 year cache control for the files, it will at some point start re-requesting non-changed files from the origin server, and edge-cache will need to be entirely re-populated, causing slower loads for client, and unnecessary calls to the origin.
What is the point of having max 1 year? What browsers will choke on an amount set higher than 31536000?

A: Consider not storing it for "as long as possible," and instead settling for as long as reasonable.  For instance, it's unlikely you'd need to cache it for longer than say 10 years...am I right?
The RFC discusses max-age here:  http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
Eric Lawrence says that prior to IE9, Internet Explorer would treat as stale any resource with a Cache-Control: max-age value over 2147483648 (2^31) seconds, approximately 68 years (http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx).
Other user agents will of course vary, so...try and choose a number that is unlikely (rather than likely!) to cause an overflow.  Max-age greater than 31536000 (one year) makes little sense, and informally this is considered a reasonable maximum value.

A: Generally one year is advised as a standard max value. See RFC 2616:

To mark a response as "never expires," an origin server sends an
  Expires date approximately one year from the time the response is
  sent. HTTP/1.1 servers SHOULD NOT send Expires dates more than one
  year in the future.

Although that applies to the older expires standard, it makes sense to apply to cache-control too in the absence of any explicit standards guidance. It's as long as you should generally need anyway and picking any arbitrarily longer value could break some user-agents. So:
Cache-Control: max-age=31536000


text:
Q: Shutting down of Raspberry pi hello there guys I have this raspberry pi and I got confuse when shutting down the pi
is use the following code:
sudo shutdown -h now

but the problem is that the pi still has this red LED on I'm confuse if it's ok to unplug the pi? will it damage the SDCARD? or the Pi?
is there any way to completely shutdown the pi inlcuding the power?

A: The red LED being on after shutdown is normal.
When you shut down the green LED will start blinking very fast, which means it is writing to SD card. When the screen has disappeared and it is safe you will see a fast regular blinking pattern on the green LED: ten times on/off and then all the LEDs but the red one will go out. Then it is safe to remove the power.
No, the Pi does NOT turn off its power like .e.g. a PC.
By the way:

*

*The Raspberry-Pi stack exchange is the better place to ask this: https://raspberrypi.stackexchange.com/questions/42929/how-to-safely-switch-off-the-raspberry-pi/42945

*Since a few years it is a lot more difficult to mess up the SD-card. Not impossible but a lot more then it was in the begin period.

*All this you can find on the internet in many places.

A: On known schematics for Rpi the RED LED is connected to 3.3 V power rail, either directly, or enabled by "power_good" voltage monitor (on RPi3).

As long as +5V is applied over USB u-B receptacle, the on-board regulators will produce "valid 3.3V", and the RED LED will be on. This is independent on any state of MCU, and will be always on. Shutting down the MCU properly should result in no damage to uSD. Once the GREEN "activity" LED stops blinking, it is safe to unplug the board.


text:
Q: why find a good field extension such that the curve has semi-stable model is important?  Hello everyone,
I'd like to ask some question about semi-stable reduction of curves.
The Deligne-Mumford theorem tell us "Let $A$ be an Dedekind domain, $K=K(A)$, for any smooth curve $X$ over $K$ and $g(X)>1$, there exist a separable extension $L$ of $K$, such that $X_{L}$ has semi-stable model."
But this theorem does not tell us any information about how to find the extension field $L$, but it seems is very important for arithmetic geometers.
My question is, in arithmetic geometry, why find the good extension field $L$ (for example:tame extension) such that $X_{L}$ has semi-stable model is so important?


text:
Q: How to do semantic Bootstrap layouts for data "display" screens in CRUD applications? I'm building a database-driven web application, heavy CRUD stuff, such as creating, editing, and displaying people's contact information and other related data.  Most information out there seems to be focused on how to design Bootstrap forms for inputting/editing data, but not much out there about proper read-only (i.e. data "display") layouts.
For example, I could do something like this:

    First Name

        @Html.DisplayFor(model => model.FirstName)

    Last Name

        @Html.DisplayFor(model => model.LastName)

... and so on (for all profile properties).  But this kind of a layout seems more typical/appropriate for create and edit screens with actual form controls.
I'm just wondering if there are good examples of applications (GitHub or elsewhere), of nice semantic layouts using consistent Bootstrap components, with standard-based, accessible HTML, that someone can point me to.
In addition to the simple First & Last Name scenario above, you can imagine a ton of other "person" related properties (address, email(s), phone(s), etc.).  Just looking for something established to follow.

A: Consider using the description list element, dl. Bootstrap has styles for these and it is designed for creating lists of information:

First Name

Jiveman

Last Name

Jivemanerson

Bootstrap styles will target the element, so you do not need to add classes. However, you can add dl-horizontal to the dl element if you'd like to display things horizontally.
These elements also have default implicit ARIA tags for improved accessibly:

*

*dl: role=list

*dd: role=definition

*dt: role=listitem


text:
Q: ASP.NET: Setting the Style of an HTML element Programatically I'm generating a menu with a Repeater control bound to an XmlDataSource.
<asp:Repeater ID="myRepeater" runat="server"
    DataSourceID="myDataSource"
    onitemdatabound="myRepeater_ItemDataBound"
    onitemcreated="myRepeater_ItemCreated">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

<asp:HyperLink ID="hrefMenuItem" runat="server" Text='<%# XPath("@text")%>' NavigateUrl='<%# XPath("@href")%>'></asp:HyperLink>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>
<asp:XmlDataSource runat="server" ID ="myDataSource" XPath="Menu/Items/*" EnableCaching="False" />

I'd like to be able to set the style of the containing LI based on mouseover events and currently selected menu item.  I tried via the HtmlGenericControl, but I receive an error that it's readonly.
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                HyperLink hrefCurrentMenuLink = e.Item.FindControl("hrefMenuItem") as HyperLink;
                HtmlGenericControl l_genericControl = e.Item.FindControl("liMenu") as HtmlGenericControl;

                if ((hrefCurrentMenuLink != null) && (l_genericControl != null))
                {
                    string l_currentPage = GetCurrentWebPage();

                    if (String.Compare(Path.GetFileNameWithoutExtension(hrefCurrentMenuLink.NavigateUrl), l_currentPage, StringComparison.OrdinalIgnoreCase) == 0)
                        l_genericControl.Style = "on-nav";
                    else
                        l_genericControl.Style = "off-nav";

                    l_genericControl.Attributes.Add("onmouseover", "navOn(this)");
                    l_genericControl.Attributes.Add("onmouseout", "navOff(this)");
                }
            }
        }

Is there any way to accomplish this?

A: The style property is a collection. Do this:
l_genericControl.Style.Add("css-name", "css-value")

Or if you are using CSS classes, then change the CssClass property:
l_genericControl.CssClass = "on-nav";

If you're trying to toggle the CSS class with your javascript, try something like this (untested):
l_genericControl.Attributes.Add("onmouseover", "this.className='on-nav';");
l_genericControl.Attributes.Add("onmouseout", "this.className='off-nav';");

If you want to change the style with your javascript, this might work:
l_genericControl.Attributes.Add("onmouseover", "this.style.color='red'; this.style.backgroundColor='yellow';");
l_genericControl.Attributes.Add("onmouseout", "this.style.color='black'; this.style.backgroundColor='none';");

A: at the basic level, you could do:
l_genericControl.Attributes["class"] = "on-nav";

A: The problem is with this part:
l_genericControl.Style = "off-nav";

which you can fix by applying a CssClass instead
// += to prevent overwriting a class you would set in the markup
l_genericControl.CssClass += "off-nav";


text:
Q: Portable native client Permission denied when resolving host I am writing a small application to test and understand PNaCl.
The aim of the application is to resolve an host name a the ip of an host using HostResolver class from PNaCl framework. The code seems to work properly but I am getting an access denied error (return value -7) because I haven't asked the permission to access the socket layer (I guess) to the user. The problem is that I have no idea how to do so. I trie to write a manifest file, but nothing happened.
Note : this application must run on the open Web and it must not require any installation process.
I don't want to write a Chrome app.
I haven't found any clue online so I would appreciate your help.
hello_tuttorial.cc:
#include <stdio.h>
#include <string.h>
#include <sstream>

#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/tcp_socket.h"
#include "ppapi/cpp/host_resolver.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/tcp_socket.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/utility/completion_callback_factory.h"

namespace {
  // exptected string from the browser
  const char * const kHelloString = "hello";
  // the sting sent from the nacl module to the browser
  const char * const kReplyString ="hello from the PNaCl";
}

class HelloTutorialInstance : public pp::Instance {

  pp::CompletionCallbackFactory<HelloTutorialInstance> callback_factory_;
  pp::TCPSocket tcp_socket_;
  pp::HostResolver resolver_;

 public:
  explicit HelloTutorialInstance(PP_Instance instance) : pp::Instance(instance),
      callback_factory_(this)
      {}

  virtual ~HelloTutorialInstance() {}

  virtual void HandleMessage(const pp::Var& var_message) {
    if (!var_message.is_string())
      return;

    std::string message = var_message.AsString();
    pp::Var var_reply;

    test_socket_support();

     if( message == kHelloString){
      var_reply = pp::Var("So far so good");
      PostMessage(var_reply);
    }

  }

 private:

 void test_socket_support(){

  if (!pp::TCPSocket::IsAvailable()) {
      PostMessage("TCPSocket not available");
      return;
    }

  tcp_socket_ = pp::TCPSocket(this);

  if (tcp_socket_.is_null()) {
      PostMessage("Error creating TCPSocket.");
      return;
   }

  if (!pp::HostResolver::IsAvailable()) {
    PostMessage("HostResolver not available");
    return;
  }

  resolver_ = pp::HostResolver(this);
  if (resolver_.is_null()) {
    PostMessage("Error creating HostResolver.");
    return;
  }

  int port = 80;
  pp::CompletionCallback callback = \
      callback_factory_.NewCallback(&HelloTutorialInstance::OnResolveCompletion);
  PP_HostResolver_Hint hint = { PP_NETADDRESS_FAMILY_UNSPECIFIED, 0 };
  resolver_.Resolve("http://www.google.com", port, hint, callback);
  PostMessage("Resolving ...");

  }

 void OnResolveCompletion(int32_t result) {
  if (result != PP_OK) {
    char str[100] = {0};
    sprintf(str, "Resolved failed %d", result);
    PostMessage(str);

    if( result == PP_ERROR_NOACCESS )
        PostMessage("Access denied");
    return;
  }

  pp::NetAddress addr = resolver_.GetNetAddress(0);
  PostMessage(std::string("Resolved: ") +
              addr.DescribeAsString(true).AsString());

  }
};

class HelloTutorialModule : public pp::Module {
 public:
  HelloTutorialModule() : pp::Module() {}
  virtual ~HelloTutorialModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new HelloTutorialInstance(instance);
  }
};

namespace pp {
  Module* CreateModule() {
  return new HelloTutorialModule();
  }
}  // namespace pp

Manifest.json :
{
  "name": "hello_tutorial",
  "version": "31.0.1650.57",
  "manifest_version": 2,
  "description": "socket Example",
  "offline_enabled": true,
  "permissions": [
    {
        "socket": [
            "tcp-listen:*:*",
            "tcp-connect",
            "resolve-host",
            "udp-bind:*:*",
            "udp-send-to:*:*"
        ]
    }
]
}

index.html:
<div id="listener">
  <script type="text/javascript">
    var listener = document.getElementById('listener');
    listener.addEventListener('load', moduleDidLoad, true);
    listener.addEventListener('message', handleMessage, true);
  </script>

  <embed id="hello_tutorial"
         width=0 height=0
         src="hello_tutorial.nmf"
         type="application/x-pnacl" />
</div>

OutPut:
Resolving ...
So far so good
Resolved failed -7
Access denied

A: Only packaged apps from the chrome store can use the sockets API.
You can access sockets for development by setting the '--allow-nacl-socket-api=foo' flag when you start Chrome. Replace 'foo' with the host name that you're loading your app from. 'localhost' if you're loading from your local machine. Note that you should not enable the 'allow-nacl-socket-api' option on 'about:flags'. This overrides the command line option but does not include a list of authorized hosts, so the result is that no host has permission to use the sockets API.

A: pp::HostResolver and other raw socket interfaces can only be used by Chrome Apps, not on the open web. See here.
Also, if you do decide to make a Chrome App, see the documentation here. You can't just add a manifest.json file, you also have to specify a background script that will launch your App.


text:
Q: Laravel проверка токена Sanctum для определенной модели Sanctum дает возможность при создании токена указать модель к которой относится этот токен - в таблице поле tokenable_type. Например
| tokenable_type   |
| -----------------|
| App\Models\User  |
| App\Models\User  |
| App\Models\User  |
| App\Models\Group |

Хотелось бы, что бы Sanctum проверял только токен, который относится к определенной модели например Group, а не в принципе существующий. Есть ли такая возможность?


text:
Q: Android onResume called when screen turns off First of all, I don't speak English, so please forgive me for my terrible grammar.
I try to create Android game, using GLSurfaceView.
I read "Beginning of Android Game" (the link is sample code) in Japanese and imitate its code, so my game almost works fine.
But I have a problem.
When android turns off the screen, onPause of the activity is called as expected.
But sometimes (not always) onResume is called and then onPause() is called again, although the screen is still black.
In onResume I call GLSurfaceView().resume, so onSurfaceCreated() and onSurfaceChanged() are also called.
After this, the game puts out ANR.
[Expected flow]
onPause - (turn on the screen) - onResume - onSurfaceCreated - onSurfaceChanged
[Problematic flow]
onPause - onResume - onPause - onSurfaceCreated - onSurfaceChanged - (turn on the screen) - ANR
Even in the problematic case, GLSurfaceView.onDrawFrame is called normally, and the game is being rendered.
But it doesn't accept any tap.Is there infinite loop?
I found similar questions here and here, for example.
But I think there is no configuration Change.
In Android Manifest,
android:configChanges="keyboard|keyboardHidden|orientation|screenSize
was already declared.
And I can't move my code into Application class because I want to do something (e.g. reload some textures) in onSurfaceCreated method.
So my question is...

Why is the onResume method called?
Why it causes ANR?
And How can I avoid this ANR?
EDIT: the problem was solved.I appreciate it!

Here is my activity.
public abstract class GLGame extends Activity implements Game, Renderer {
    enum GLGameState {
        Initialized,
        Running,
        Paused,
        Finished,
        Idle
    }
    /////////////////////////////inter-ad
    private static class AdHandler extends Handler {
        private final WeakReference<GLGame> mActivity;
        AdHandler(GLGame activity) {
            mActivity = new WeakReference<GLGame>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            GLGame activity = mActivity.get();
            switch(msg.what){
            case 0:
                if (activity != null) {
                    activity.showInterstitial();
                }
                break;
            case 1:
                if (activity != null) {
                    activity.prepareInterstitial();
                }
                break;
            }

            return;
        }
    };
    Handler handler =new AdHandler(this);
    /////////////////////////////inter-ad

    //ad
    static InterstitialAd interstitial;
    static AdRequest adRequest;
    AdView adView;
    //////////////////////////////// //ad

    GLSurfaceView glView;
    GLGraphics glGraphics;
    Audio audio;
    Input input;
    FileIO fileIO;
    Screen screen;
    GLGameState state = GLGameState.Initialized;
    Object stateChanged = new Object();
    long startTime = System.nanoTime();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        /////////////////////////////calculate and normalize the view size
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

        float density = displaymetrics.densityDpi/160f;
        int adpix = (int)( 50*density);
        int navvarpix = (int)( 25*density);
        int heightSubAd = displaymetrics.heightPixels -navvarpix-adpix;

        int ratioWidth=10;
        int ratioHeight=16;
        boolean isWidthLong = displaymetrics.widthPixels/(float)heightSubAd > ratioWidth/(float)ratioHeight;
        int width = isWidthLong ? heightSubAd * ratioWidth / ratioHeight : displaymetrics.widthPixels;
        int height = isWidthLong ? heightSubAd : displaymetrics.widthPixels * ratioHeight/ratioWidth;

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height);
        lp.setMargins((displaymetrics.widthPixels-width)/2, 0, 0, (displaymetrics.widthPixels-width)/2);
        ///////////////////////////// //calc

        glView = new GLSurfaceView(this);
        glView.setLayoutParams(lp);
        glView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
        glView.setRenderer(this);

        adView = new AdView(this, AdSize.BANNER, "MY_NUMBER");
        lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, adpix);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        adView.setLayoutParams(lp);

        RelativeLayout layout = new RelativeLayout(this);
        layout.setBackgroundColor(Color.BLACK);
        layout.setId(0);
        layout.addView(glView);
        layout.addView(adView);
        adView.loadAd(new AdRequest());

        setContentView(layout);

        /////////////////////////////////request inter-ad
        interstitial = new InterstitialAd(this, "MY_NUMBER");
        adRequest = new AdRequest();
        adRequest.addTestDevice("MY_NUMBER");
        adRequest.addTestDevice("MY_NUMBER");
        interstitial.loadAd(adRequest);
        /////////////////////////////////inter-ad

        glGraphics = new GLGraphics(glView);
        fileIO = new AndroidFileIO(getAssets());
        audio = new AndroidAudio(this);
        input = new AndroidInput(this, glView, 1, 1);
    }

    public void onResume() {
        super.onResume();
        glView.onResume();
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        glGraphics.setGL(gl);

        synchronized(stateChanged) {
            if(state == GLGameState.Initialized)
                screen = getStartScreen();
            state = GLGameState.Running;
            screen.resume();
            startTime = System.nanoTime();
        }
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        GLGameState state = null;

        synchronized(stateChanged) {
            state = this.state;
        }

        if(state == GLGameState.Running) {
            float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;
            startTime = System.nanoTime();

            screen.update(deltaTime);
            screen.present(deltaTime);
        }

        if(state == GLGameState.Paused) {
            screen.pause();
            synchronized(stateChanged) {
                this.state = GLGameState.Idle;
                stateChanged.notifyAll();
            }
        }

        if(state == GLGameState.Finished) {
            screen.pause();
            screen.dispose();
            synchronized(stateChanged) {
                this.state = GLGameState.Idle;
                stateChanged.notifyAll();
            }
        }
    }

    @Override
    public void onPause() {
        synchronized(stateChanged) {
            if(isFinishing())
                state = GLGameState.Finished;
            else
                state = GLGameState.Paused;
            while(true) {
                try {
                    stateChanged.wait();
                    break;
                } catch(InterruptedException e) {
                }
            }
        }
        glView.onPause();
        super.onPause();
    }

    public GLGraphics getGLGraphics() {
        return glGraphics;
    }

    @Override
    public Input getInput() {
        return input;
    }

    @Override
    public FileIO getFileIO() {
        return fileIO;
    }

    @Override
    public Graphics getGraphics() {
        throw new IllegalStateException("We are using OpenGL!");
    }

    @Override
    public Audio getAudio() {
        return audio;
    }

    @Override
    public void setScreen(Screen screen) {
        if (screen == null)
            throw new IllegalArgumentException("Screen must not be null");

        this.screen.pause();
        this.screen.dispose();
        screen.resume();
        screen.update(0);
        this.screen = screen;
    }

    @Override
    public Screen getCurrentScreen() {
        return screen;
    }

    @Override
    public Handler getHandler(){
        return handler;
    }

    private void showInterstitial(){
        if(interstitial.isReady()){
            interstitial.show();
        }
    }

    private void prepareInterstitial(){
        interstitial.loadAd(adRequest);
    }

}

thank you for your kindness!


text:
Q: jQuery: wait to perform a task until an animation finished I have a div which is placed in any pages. When you click on this div, it will be closed by using jquery checking on its css class:
$('.content-box-header').click(function
() {
    $(this).parent().children('.content-box-content').slideFadeToggle(200);
}

In several pages, I need to set that div with a specific ID in order to perform some tasks after that div closed. For example:
$('#divleft').live('click', function
(e) {    runTask(); }

The above sample is trigger on that div with the specific ID = divleft.
The problem is that, I would like to check something ONLY after the div is really closed, but in my current situation, runTask() is performed before the div is closed.
SO my question is that how could the method runTask(); is delayed after the div is really closed?
Thanks in advance!!!!

A: I think what you are looking for is .queue(). See the documentation here: http://api.jquery.com/queue/
You can call this on a set of matched elements to get some information about the remaining effects to be run. So in your case you could do something like this:
$('#divleft').live('click', function (e) {
    runTaskAfterAnimation()
});

function runTaskAfterAnimation() {
    if ($('.content-box-content').queue('fx').length == 0) {
        runTask();
    } else {
        setTimeout(runTaskAfterAnimation, 10);
    }
}

View a demonstration here: http://jsfiddle.net/LeHHj/2/
This time it definitely works ;)

A: In your case, just use
$('.content-box-header').click(function () { $(this).parent().children('.content-box-content').slideFadeToggle(200, function() { runTask(); }); }

A: You can store the function on the div using jQuery's data() method.
This lets you set an 'afterClick' function on your element:
$('.content-box-header').click(function () {
    var $this = $(this);
    $this.parent().children('.content-box-content').slideUp(200, function () {
        var after = $this.data('afterClick');
        if (after) after();
    });
});

$('#divleft').data('afterClick', function () { runTask(); });

A: You need to check if the item you are wanting to runTask() on is :animated and if so 'register' a callback (via .data()) for when it's done
.live('click', doRunTask);

doRuntask = function() {
 if ($(this).is(':animated'))
  $(this).data('afterAnimation', runTask);
 else
  runTask();
});

$('.content-box-header').click(function () {
 $(this).parent().children('.content-box-content').slideFadeToggle(200, function() {
  var cb = $(this).data('afterAnimation');
  cb && cb();
 });
}


text:
Q: Why am I getting [object HTML ParagraphElement] Returned instead of my number I have a silly fiddle that I am stuck with, I am trying to take the beginning number and double it every time the x2 button is hit. Instead of this behavior I am getting [object HTML ParagraphElement] returned instead. I am re-learning JavaScript so I am trying to work with just JavaScript, no frameworks etc...

var inputVal = document.getElementById("input").value;
var inputEl = document.getElementById("input");
var doubleButton = function () {
  var sum = 0;
  Number(input);
  sum = input + input;
  inputEl.value = input;
  inputEl.innerText = input;
}
var boom = function () {
  alert("BOOM!!!!! Dont you know you should never press the big red  button")
}
document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
document.getElementById("btnRed").addEventListener("click", boom, false);

Enter a number and click the x2 button to have it doubled

5

<button id="btnAdd">x2</button>

<button class="redBtn" id="btnRed">BIG RED BUTTON</button>

here is the link to my actual fiddle http://jsfiddle.net/jpb4815/uynfc1ky/16/
Why is my code returning object and not the number, I thought that I had taken care of that with the number function by converting the input from a string to a number. I have tried a variety of different settings in fiddler the onload, no wrap in body. I have changed the code a multitude of times. I could do it in jQuery but I really want just plain vanilla JavaScript.

A: Try  this:
(function () {
            var inputEl = document.getElementById("input");
            var doubleButton = function () {
                var sum = 0;
                input = Number(inputEl.textContent);
                sum = input + input;
                inputEl.textContent = sum;

            }
            var boom = function () {
                alert("BOOM!!!!! Dont you know you should never press the big red  button")
            }
            document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
            document.getElementById("btnRed").addEventListener("click", boom, false);

        }());

A: First your input variable is not instantiated. I'm surprised that passed muster. Here's a bit on that.
So, where to get the initial value? Since a p tag doesn't have a value property, I'm pulling the p tag id'd as input, retrieving the innerHTML property, and running the result through parseInt.
Also, pull document.getElementById into your function so the button will have what it needs each time it's called.
And finally, sum was summed but not assigned to your output.
JSFiddle
(function () {
    var doubleButton = function () {
        var inputEl = document.getElementById("input");
        var inputVal = inputEl.innerHTML;
        var input = parseInt(inputVal, 10);
        var sum = input + input;
        inputEl.innerText = sum;

    }
    var boom = function () {
        alert("BOOM!!!!! Dont you know you should never press the big red button")
    }
    document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
    document.getElementById("btnRed").addEventListener("click", boom, false);
}());


text:
Q: Raycast hitting the wrong Object I have a problem with my Raycast/BulletHole in my FireRaycast() Function.
If I shoot, it doesnt spawn my Hitsparks and BulletHoles on the hitted Raycast Position (Position where the bullet impacts). If they spawn, they spawn in the space in front of my weapon. (see pic) In this case, the console debug log tells me that I hit the FPSController...?!?
Do anybody have a solution for that?
I want that it always hits walls or the bottom and so on..
function FireRaycast() {

var hit : RaycastHit;

if (Physics.Raycast(shootPoint.position, shootPoint.transform.forward, hit, range)) {

   Debug.Log(hit.transform.name + " FOUND!");

   var hitParticleEffect = Instantiate(hitParticles, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));

   var bulletHole : GameObject= Instantiate(bulletImpact, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));

  Destroy(hitParticleEffect, 1f);
  Destroy(bulletHole, 2f);

}
}
Heres an ingame screenshot:

Thank u guys!


text:
Q: Angular - issue assigning json file to class I'm just wondering if you could help me fix this issue I'm having with assigning an interface from my json file. I am getting the ts error of json file is not assignable to type Data. 'data' is declared as a type of Data in the .ts file.
  this.data = '../assets/data.json';

  export interface Data {
      millers: Miller[];
  }

  export interface Miller {
      name: string;
      address: string;
      farms: Farm[];
  }

  export interface Farm {
     code: string;
     name: string;
     harvest: string;
     type: string;
     paddocks: Paddock[];
  }

  export interface Paddock {
     code: string;
     area: string;
     owner: string;
  }

  {
  "millers": [
    {
      "name": "Britney Houston",
      "address": "Summit Street Haena",
      "farms": [
        {
          "code": "deserunt840",
          "name": "Artiq",
          "harvest": "2012-06-26",
          "type": "Cane",
          "paddocks": [
            {
              "code": "do318",
              "area": 965
            },

A: EDIT:
You can read JSON file using requirejs. Check this question for more details: Angular 5 Service to read local .json file.

this.data = '../assets/data.json';
This is your issue. All you're doing on this line assigning a String value to this.data. And as you mentioned this.data is of type Data, not string. Hence the error
Now, coming back to your issue, you cannot read data from JSON file (As far as I know.). If you have to, convert that JSON file into a .ts file and export your data from that file. then you can import it and assign to this.data or any other property

A: As commented you're assigning a string value to a property that you've declared of type Data.
To fix it:

*

*Make sure you have the following in architect.build.options in angular.json:

"assets": [
  "src/favicon.ico",
  "src/assets",
],

*Create a millers.json file in src/assets.

*Import HttpClientModule in your Module and add it to the imports array.

*Inject HttpClient as a dependency in your Component and then use it's get method to call the .json which is sort of exposed as an API file:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({...})
export class AppComponent {
  data;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('../assets/millers.json')
      .subscribe(res => console.log(res));
  }
}

HEre's a Sample StackBlitz for your ref.


text:
Q: set a particular option in a select box using jquery I'm unable to perform the desired event.
  <?php
    include_once 'includes/db.php';
        $result = mysql_query('SELECT country,code FROM countries') or die(mysql_error());

        echo '<select id="CountryCode">';
        echo '<option value="Select">Select</option>';
        while ($row = mysql_fetch_array($result))
        {
           echo '<option value=$row["country"]>'.$row['country'].'</option>';
        }
        echo '<option value="Other">Other</option>';
        echo '</select>';
    ?>
<input id="country" type="hidden" value="IN"/>
<script>
$(function()
{
$('#CountryCode').val($('#country').val());
});
</script>

Everything works fine. But the desired item is not selected in the select box

A: You need to set the Attribute "selected" of the option to "selected". Try this (untested):
$("#CountryCode").val($('#country').val()).attr('selected','selected');

A: The echo in your while() loop should look like this:
echo '<option value="'.$row["country"].'">'.$row['country'].'</option>';

Your string above was printing a literal $row["country"] instead of the value that it contained.


text:
Q: use specgram in axes in GUI matlab I create a matlab gui and have some element in it with some axes. I plot one of my desire plot in ploter1 ( first axes ) using
plot(handles.ploter1,xx); title(handles.ploter1,'Waveform');

and it is ok,but I want use specgram and plot specgram result in another axes by I dont know how can do it :(
I test
specgram(wav,N,fs,hamming(N/4),round(0.9*N/4));xlabel('time, s');

or
specgram(handles.ploter2,wav,N,fs,hamming(N/4),round(0.9*N/4));xlabel('time, s');

but  return me error or nothing !!!

please help me. thank you very much

A: EDIT
as mentioned in the comments by bdecaf, what should work, is to set the current axes:
axes(handles.ploter2);

now, when using just
spectrogram(x,window,noverlap,F)]

the plot should be on the specified axes. If not, try:
hold on

before!
OLD
specgram or spectogram does not have a parameter for the plot. You have to define it later on.
I suggest to get the result first by:
[S,F,T]=spectrogram(x,window,noverlap,F)]

and then plot it on a specific axes:
plot(handles.ploter2, S,F)

But I am not sure about which parameter you want to plot. Please take a look at the docs.
From the docs:

[S,F,T] = spectrogram(...) returns a vector of frequencies, F, and a vector of times, T, at which the spectrogram is computed. F has length equal to the number of rows of S. T has length k (defined above) and the values in T correspond to the center of each segment.
[S,F,T] = spectrogram(x,window,noverlap,F) uses a vector F of frequencies in Hz. F must be a vector with at least two elements. This case computes the spectrogram at the frequencies in F using the Goertzel algorithm. The specified frequencies are rounded to the nearest DFT bin commensurate with the signal's resolution. In all other syntax cases where nfft or a default for nfft is used, the short-time Fourier transform is used. The F vector returned is a vector of the rounded frequencies. T is a vector of times at which the spectrogram is computed. The length of F is equal to the number of rows of S. The length of T is equal to k, as defined above and each value corresponds to the center of each segment.
[S,F,T] = spectrogram(x,window,noverlap,F,fs) uses a vector F of frequencies in Hz as above and uses the fs sampling frequency in Hz. If fs is specified as empty [], it defaults to 1 Hz.


text:
Q: How to equal the array into zero when no have value in PHP I have data here:
Array
(
[0] => Array
    (
        [SiteID] => 147
        [Amount] => 500.00
        [TransactionType] => D
    )

[1] => Array
    (
        [SiteID] => 147
        [Amount] => 500.00
        [TransactionType] => D
    )

[2] => Array
    (
        [SiteID] => 145
        [Amount] => 500.00
        [TransactionType] => R
    )
)

I'm done computing the reload, redemption and deposit and it's working, but If ever the siteID don't have a transaction of deposit [D] or reload [R ]or redemption [W] it should be equal to 0. my code is here:
   public function computeGHComponents()
    {
      error_reporting (E_ALL^ E_NOTICE);

      foreach ($this->transaction as $t){

          $amount = (float) $t['Amount'];

            if (isset($this->totals[ $t['SiteID'] ][ $t['TransactionType'] ])){
                $this->totals[ $t['SiteID'] ][ $t['TransactionType'] ] += (float) $amount;
            } else {
                 $this->totals[ $t['SiteID'] ][ $t['TransactionType'] ] = (float) $amount;
            }
        }

     foreach($this->totals as $key => $value)

        {
          $this->result[$key] = array("Deposit"=>$value['D'], "Redemption"=>$value['W'], "Reload"=>$value['R']);

       }
     print_r($this->result);

    }

The result should be shown like this:
 Array
 (
[147] => Array
    (
        [Deposit] => 1000
        [Redemption] => 0
        [Reload] => 0
    )

[145] => Array
    (
        [Deposit] => 0
        [Redemption] => 500.00
        [Reload] => 0
    )

 )

Thanks in advance and Please guide me in proper way.

A: The description is vague, there is information missing in the question.
So this is kind of a blind shot, it might be what you ask but it might as well not:
In the assignment inside the last foreach, you can add 0 as a default value:
$this->result[$key] = array(
  "Deposit"    => array_key_exists('D',$value) ? $value['D'] : 0,
  "Redemption" => array_key_exists('W',$value) ? $value['W'] : 0,
  "Reload"     => array_key_exists('R',$value) ? $value['R'] : 0
);

A: I would focus on doing just one loop.
foreach ($this->transaction as $key => $t){

   $amount = $t['Amount'];

   // set up the array with each postion equal to zero
   $tranTypes = array("Deposit"= 0, "Redemption"=> 0 , "Reload"= 0);

   $transaction = $t['TransactionType'];

   switch($transaction){
     case "D":
        $tranTypes['Deposit'] = $amount;
     break;

     case "R":
         $tranTypes['Redemption'] = $amount;
     break;

     case "W":
         $tranTypes['Reload'] = $amount;
     break;

     }

    $this->result[$key] = $transaction;
}

OR THIS
 foreach($this->totals as $key => $value)

    {

     $this->result[$key]['Deposit']    = isset($value['D']) ? $value['D'] : 0;
     $this->result[$key]['Redemption'] = isset($value['W']) ? $value['W'] : 0;
     $this->result[$key]['Reload']     = isset($value['R']) ? $value['R'] : 0;
    }


text:
Q: Rejection probability given true $\mu$, for a hypothesis test of normal distribution $\sim N(\mu, 1)$ I am testing the hypothesis: $H_0: \mu \leq 1$ against $H_1: \mu>1$. I've found the UMP test, which rejects the null hypothesis based on $ \bar{x}$:
reject when $$\bar{x} \geq \left(\dfrac{1.65}{\sqrt{n}}\right)+1.$$
I'm at a loss to find rejection probability given true $\mu$. At first I thought that it would be based on the CDF of the normal distribution (denote $F_{\mu}$ as CDF associated with $\sim N(\mu,1)$:
$$R(\mu) = 1-F_{\mu}\left(\dfrac{1.65}{\sqrt{n}} + 1 \right).$$
However, this is clearly incorrect since it is based on the CDF of drawing only one observation (i.e., $n=1$).

How do I solve this? Maybe there is a CDF that takes $n$ into account in some way?

A: I assume that the level of the test is $\alpha = 0.05$, hence the critical value for a one-sided test is $$z_\alpha^* = \Phi^{-1}(0.95) \approx 1.64485.$$  Then the rejection region as stated is correct.
The probability of rejecting $H_0$ given $\mu$ is therefore
$$\Pr\left[\bar x \ge \frac{z_\alpha^*}{\sqrt{n}} + 1 \,\Bigl| \,\mu\right],$$ and since $\bar x$ is now normally distributed with mean $\mu$ and variance $1/n$, we compute this probability with the usual standardization technique:
$$\begin{align}
\Pr\left[\bar x \ge \frac{z_\alpha^*}{\sqrt{n}} + 1 \,\Bigl| \,\mu\right]
&= \Pr\left[\frac{\bar x - \mu}{\sqrt{1/n}} \ge \frac{1}{\sqrt{1/n}}\left( \frac{z_\alpha^*}{\sqrt{n}} + 1 - \mu \right) \, \Bigl| \, \mu \right] \\
&= \Pr\left[Z \ge z_\alpha^* + (1-\mu)\sqrt{n}\right] \\
&= \Phi\left((\mu-1)\sqrt{n} - z_{\alpha}^*\right),
\end{align}$$
where $\Phi$ is the standard normal CDF.  Notice how once we standardized and wrote $Z$, we can drop the conditional statement, since that step is valid precisely when the conditional assumption is true (i.e., $(\bar x - \mu)\sqrt{n}$ is standard normal, given that $\mu$ is the true mean).
So for instance, for a sample size of $n = 16$ and $\alpha = 0.05$, for a true mean of $\mu = 2$, the rejection probability will be approximately $$\Phi\left((2-1)\sqrt{16} - 1.64485\right) = \Phi(2.35515) \approx 0.990742.$$  Our formula makes intuitive sense:  The larger $\mu$ is, the larger the quantity $(\mu - 1)\sqrt{n} - z_\alpha^*$ and thus the more likely we are to reject $H_0$; similarly, the larger the sample size, the more precision we have for the sample mean reflecting the true value $\mu$, so if $\mu < 1$, increasing $n$ makes the rejection probability smaller, and if $\mu > 1$, increasing $n$ makes the rejection probability larger.  Finally $z_\alpha^*$, being fixed for a given level $\alpha$, is a constant chosen such that when $\mu = 1$, the rejection probability is equal to the Type I error.


text:
Q: How can i "merge" rows groupby having same values in Pandas dataframe? link to table
The name of my dataframe is df.
I want to combine the rows having the same Borough and same PostalCode with Neighborhood separated by commas. But I'm not able to get it. Can anyone please help me with it?

A: you have to first group by the two first column and then apply a transform for joining the result.
df['Neighborhood ']= df.groupby(['PostalCode ','Borough'])['Neighboudhood'].transform(lambda x: ','.join(x))
df = df.drop_duplicates()

A: You can use this:
df = df.groupby(['PostalCode','Borough'])['Neighbourhood'].agg(','.join)

output sample for the two rows:
CR0  Croydon    Addington,Addiscombe


text:
Q: How to return in the last tabs in javascript (Angular Material) with a button? My code summary
I want if I click on "go back content", I return at the content tabs 1;
<mat-tab-group mat-stretch-tabs>
    <mat-tab label="content 1">
        ........
    </mat-tab>
    <mat-tab label="content 2">
        <button mat-raised-button (click)=""> go Back content 1</button>
    </mat-tab>
</mat-tab-group>

A: You can bind the current selected tab's index to a variable and then set that variable when needed, like this:
<mat-tab-group mat-stretch-tabs [selectedIndex]="selectedIndex">
    <mat-tab label="content 1">
        ........
    </mat-tab>
    <mat-tab label="content 2">
        <button mat-raised-button (click)="selectedIndex = 0"> go Back content 1</button>
    </mat-tab>
</mat-tab-group>

You can read more here.

A: Try this:
<mat-tab-group mat-stretch-tabs [(selectedIndex)]="selectedTab">
    <mat-tab label="content 1">

one

    </mat-tab>
    <mat-tab label="content 2">

two

       <button mat-raised-button (click)="openContentOne()"> go Back content 1</button>
   </mat-tab>
</mat-tab-group>

and in your ts:
selectedTab = 0;
openContentOne() {
    this.selectedTab = 0;
}


text:
Q: UITextField missing copy|paste menu after selectall In my project, I have several UITextFields in different views, such as UITableviewcell contains UITextfield, in a simple view, and so on.
I have a problem in my project. When I touch the UItextfield, input some text, and then do a longclick, it will show a menu select|selectall. When I click select, all the text is selected, but after selectall, it can't show the copy|paste menu. Why?
This phenomena does not always appear. Does anyone know what could cause this?


text:
Q: How to change desktop background image on windows with c++? How to change the desktop background image on Windows?
Right now, I found this solution:
SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, (PVOID*)desktop_image_file, SPIF_SENDCHANGE);

It works fine, but after a restart, the image is gone. How to save it permanently?

A: You need to include the SPIF_UPDATEINIFILE flag:

SPIF_UPDATEINIFILE
Writes the new system-wide parameter setting to the user profile.

SystemParametersInfoA(..., SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);


text:
Q: Cannot use the following command: "heroku create" heroku create error
I'm trying to learn ruby on rail and I followed the heroku steps to the t.
when I enter "heroku create" i get the error message in the img.

A: I had the same error on Windows. I guess my installed version of the Heroku CLI was outdated because all I did was uninstall and reinstall the Heroku CLI and everything is working again.


text:
Q: Could not install NuGet package MPI.NET 1.3.0 in MS Visual Studio 2017 I am trying to install NuGet package MPI.NET 1.3.0 to MS Visual Studio 2017 C# project. I am getting the following error:

Could not install package 'MPI.NET 1.3.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

I have tried to create C# projects in different versions of .NET Framework, but it would not install. On the official GitHub site for this package (MPI.NET GitHub repository) it is written that the package is updated for .NET 4.0. I have tried creating 4.0 and lower projects, but no success.
Help anyone?

A: Looking at the packages available on nuget.org, version 1.3.0 targets .NET 4.6.2, whereas version 1.2.0 targets .NET 4.0. So if you try to install version 1.2.0 of the package into your project, you should be okay. It sounds like the GitHub documentation needs to be updated to reflect this new reality.
(Personally I would bump the major version number for a change like this, given that it's not necessarily backwardly compatible for existing users, but semantic versioning is less cut and dried than it sometimes sounds.)


text:
Q: Accessing Netbeans Code Completion Variable List Programmatically I have a working educational Java-palette Module for Netbeans that helps first-year students learn the basics of programming without needing to worry so much about syntax.
When a student drags an item from the palette, they get a popup that allows them to fill-in the details of the code to be dropped, such as variable names or values. I have ComboBoxes that list all the variables in the document.  For the Java version of the palette, I simply used JavaParser to get a list of the variables, method names, classes, etc.
Now, I'm doing a version of this palette for C++ students.  This time around, I'd rather not use JavaParser, javacc, ANTLR, etc as it seems like overkill. NetBeans already has the list I need when you hit Ctrl+space, but I can't find a way to access the list from a form. Geertjan has a great tutorial on using code completion in a JEditorPane
 which addresses implementing your own code completion provider which brings me back to square one.
And this page suggests that NetBeans is simply grabbing a list of variables from the debugger stack.  The debugger API doesn't suggest any straight forward methods for asking for a variable list that I could discern.
Any suggestion on using Netbeans APIs to grab a list of variables from a C++ source file, rather than resorting to a parser?


text:
Q: Instrumentation test fail randomly with multidexing enabled In my android app I have multidexing enabled. The app runs fine on emulators. I am using robotium for testing the app. But when I execute instrumentation test cases, sometimes the test passes, but mostly they also fail after system reboot. There is no code change between the time it passes and fails.
Default gradle configuration:
android {
        defaultConfig {
        applicationId "com.example.androidapp"
        minSdkVersion 16
        targetSdkVersion 23
        multiDexEnabled true
        testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
        testProguardFile "proguard-test.txt"
    }
}

Also adding dependencies for test:
androidTestCompile fileTree(dir: 'libs', include:'robotium-solo-5.3.0.jar')

androidTestCompile ('com.android.support:multidex-instrumentation:1.0.1') {
         exclude group: 'com.android.support', module: 'multidex' }

In AndroidManifest.xml I have mentioned the application tag as:
<application
        android:name="StartupActivity"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" ...../>

I have extended "android.support.multidex.MultiDexApplication" in StartupActivity. The times when the instrumentation test cases fall I get the following error:
INSTRUMENTATION_RESULT: shortMsg=java.lang.IllegalAccessError
INSTRUMENTATION_RESULT: longMsg=java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
INSTRUMENTATION_CODE: 0

The error message in logcat is:
W/dalvikvm﹕ Class resolved by unexpected DEX: Lcom/example/androidapp/StartupActivity;(0xa695df08):0x9910e000 ref [Landroid/support/multidex/MultiDexApplication;] Landroid/support/multidex/MultiDexApplication;(0xa695df08):0x99a2c000
W/dalvikvm﹕ (Lcom/example/androidapp/StartupActivity; had used a different Landroid/support/multidex/MultiDexApplication; during pre-verification)
W/dalvikvm﹕ Unable to resolve superclass of Lcom/example/androidapp/StartupActivity; (540)
W/dalvikvm﹕ Link of class 'Lcom/example/androidapp/StartupActivity;' failed
D/AndroidRuntime﹕ Shutting down VM
W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa628c288)

The test class looks somewhat like:
public class HelloActivityTest extends ActivityInstrumentationTestCase2<HelloActivity> {
private Solo solo;
public HelloActivityTest() {
    super(HelloActivityTest.class);
}
  @Override
  public void setUp() throws Exception {
    setActivityInitialTouchMode(false);
    solo = new Solo(getInstrumentation(), getActivity());
  }

  public void test1() {}

  public void test2() {}

}

I am running the test case as an android test. I am unable to understand which dependency is messing up the code. Besides this, random failures of code are skeptical. Please help.

A: Found a solution for the same, that is setting dex verification and optimization parameters. You could also set dalvik.vm.dexopt-flags to v=n to have the framework pass -Xverify:none -Xdexopt:verified to disable verification.
Execute:
adb shell setprop dalvik.vm.dexopt-flags v=n,o=v
adb shell stop installd
adb shell start installd

Had to wait for a few seconds after executing the commands. Instrumentation test with multidexing run smoothly post that.

A: For gradle plugin 1.5.0 you could use this workaround in your build.gradle:
// Workaround for Multidex bug in gradle-android-plugin
// Replace Multidex dependency with some dummy dependency to avoid dex problems
// @see https://code.google.com/p/android/issues/detail?id=194609
project.getConfigurations().all { config ->
    if (config.name.contains("AndroidTest")) {
        config.resolutionStrategy.eachDependency { DependencyResolveDetails details ->
            if (details.requested.name == "multidex") {
                details.useTarget("de.felixschulze.teamcity:teamcity-status-message-helper:1.2")
            }
        }
    }
}

A: In case you're using gradle plugin above 1.4.0-beta3. Multi-Dex support was added to gradle plugin, which means that multidex and  multidex-instrumentation dependencies are already included and you don't have to specify them explicitly. Unfortunately, it seems to be buggy on pre-Lollipop devices, looks like different versions of MultiDexApplication are used for the target and test application. As a result Instrumentation fails to run and logcat gives you something similar to this:
W/dalvikvm: Class resolved by unexpected DEX: Lcom/example/dexproof/App;(0x43893f90):0x64d46000 ref [Landroid/support/multidex/MultiDexApplication;] Landroid/support/multidex/MultiDexApplication;(0x43893f90):0x5de01000
W/dalvikvm: (Lcom/example/dexproof/App; had used a different Landroid/support/multidex/MultiDexApplication; during pre-verification)
W/dalvikvm: Unable to resolve superclass of Lcom/example/dexproof/App; (457)
W/dalvikvm: Link of class 'Lcom/example/dexproof/App;' failed
E/AndroidRuntime: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation

The solution would be to use 1.3.1 gradle plugin and be careful to explicitly specify multidex and  multidex-instrumentation (in case you also need this) dependencies of the same version. You also probably want to use AndroidJUnitRunner, since it has built-in multi-dex support.
Feel free to star the related issue: https://code.google.com/p/android/issues/detail?id=194609


text:
Q: Using an array of custom objects Let's say I've created an array of objects SpecialResource via
ArrayList<SpecialResource> masterRes = new ArrayList<SpecialResource>();
masterRes.add(0, new SpecialResource(3,5,0,"Foo Bar"));
.........etc etc many more adds...

Let's say SpecialResource has a method calledgetMax()
How would I reference the getMax method of array index 0?  Every permutation I've guessed at is giving syntax errors. masterRes<0>.getMax(), masterRes(0).getMax(), etc.

A: Well, actually, it's not an array, but a collection. And, in order to retrieve its items by index, you must use the get method:
masterRes.get(0).getMax();

A: masterRes.get(0).getMax();

Java/Android API document will help you.
http://androidappdocs.appspot.com/reference/java/util/ArrayList.html


text:
Q: HBase row write fails due to NoColumnFamily though I have added it This may be a standard asynchronous operation issue. Adding Column Family through HBaseAdmin.addColumnFamily is asynchronous. Now I need to add rows after adding this columnFamily and this is throwing me error of NoColumnFamily. How can I defer adding rows till columnFamily is added other than just checking if columnFamily exists.

A: If you want to add a column family. You will need to:  1. Disable Table 2. Add column Family 3. Enable Table. Then only you will be able to write data to that column family. After following above 3 steps there is no uncertainty about existence of that column family.


text:
Q: Get notified when a third party app is launched for the first time I want to get notified when 3rd party apps are opened by the user for the first time.
My app is a system app, so I can request system permissions.
I know I can do this by polling data such as the app's cache and seeing that it is larger than 0, but is there some other way to do that without polling? (for example, via BroadcastReceiver)

A: As per my knowledge, you don't get any broadcast when you launch any application for the first time.
However you can check for Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY which will be set if the application has been launched from history. This will not fully solve your problem but will be just a case to check if in future you find a way to detect first application launch.


text:
Q: unable to save the input of the value I'm new to reactjs, unable to import body object in another component?
Could you please help me in importing the body object in the compose component. I'm unable to display the content of the body.

A: As you have provided value and onChange here,
<Editor label='Body' name="body" value={this.state.body} onChange={this.changeHandler}/>

But in Editor component you have not provided value and onChange to ReactQuill, you should do this,
<ReactQuill
   theme='snow'
   modules={this.modules}
   formats={this.formats}
   className='Editor'
   value={this.props.value}        // provide value passed as props from parent component
   onChange={this.props.onChange}  // provide onChange passed as props from parent component
/>

Note: I think you should have separate change handler for your Editor component, because ReactQuill directly provides value on change.
<Editor label='Body' name="body" value={this.state.body} onChange={this.changeBodyHandler}/>

And the handler should be this,
changeBodyHandler = (value) => {
   this.setState({
      body: value
   })
}

Simplified Demo

A: You can try this:
changeBodyHandler = (e) => {
   this.setState({
      body: e.target.value
   })
}


text:
Q: Python, text mining, docx to table(CSV) So I'm pretty new to python and probably asking an easy question. I'm looking for a way where I can extract chapter names, section names and text from a docx file and transfer it to a table where in the first row I have the chapter name, the second row the section name, third row the text from the chapter. Another thing I want to add at some point have a new line for each new paragraph of the text. I had the following steps in mind but I doubt sincerely whether it is the right way to go:

*

*Open word document
1.a. Read word document
1.b. Define headings, subheadings, footnotes & headers

*Create new file
2.a. Create table with 9 rows

*Name each row

*Fill in header with predefined text: Legal document
"Part  Title   Chapter Section Subsection Article number   Article text
Article title  Reference"

*Define rankings of the categories
5.a. Give rankings to the table, row 1 contains document name
5.b: row 2 contains chapter name, row 3 section name etc.

*Read word document from start to the first defined ranking
6.a.: Copy the text of the defined ranking
6.b. Append to file the copied text into the correct row
I've looked into docx and xlml but I wonder whether it will give me the result I'm looking for.

A: You'll need the docx and CSV or openpyxl modules. You'll also need effort. Figure out a way to differentiate between the things you want to store in the CSV then throw this detection and storage into a loop that senses and stops when there is nothing more to do. That's the most advice you'll get with this type of question.


text:
Q: Some burning questions on First-order logic from an amateur I'm currently taking an introductory course in Mathematical logic(prerequisites is only advanced calculus) and my lecture notes are based on Enderton's book 'Mathematical Introduction to Logic'
Suppose $\varphi$ is deducible from $\Gamma$ and we are seeking a proof of this fact. There are several cases, one of the which is $\varphi=\forall x \psi$. According to the book, if $x$ should occur free in $\Gamma,$ there will be a variable $y$ such that $\Gamma \vdash \forall y \ \psi ^{x}_{y}$ and $\forall y \ \psi^{x}_{y} \vdash \forall x \ \psi.$
May I know how do we prove that there will be a variable $y$ such that $\Gamma \vdash \forall y \ \psi ^{x}_{y}$ and $\forall y \ \psi^{x}_{y} \vdash \forall x \ \psi \ ?$ The author then refers one to Re-replacement lemma but I can't see how are both related. Could anyone instruct me please?
Thank you.

A: I suppose that you are working with Corollary 24G, page 124, of Herbert Enderton, A Mathematical Introduction to Logic (2nd ed Harcourt - 2001) :

Assume that $\Gamma \vdash \varphi^{x}_{c}$, where the constant symbol $c$ does not occur in $\Gamma$ or in $\varphi$. Then $\Gamma \vdash \forall x \varphi$, and there is a deduction of $\forall x \varphi$ from $\Gamma$ in which $c$ does not occur.

The proof invoks Theorem 24F (Generalization on Constants) [page 123].
The motivation of the Corollary is [page 124] : "We want to apply Theorem 24F in circumstances in which not just any variable will do. In the following version, there is a
variable $x$ selected in advance."
From the hypotheses $\Gamma \vdash \varphi^{x}_{c}$, where the constant symbol $c$ does not occur in $\Gamma$ or in $\varphi$, Theorem 24F gives us a deduction (without $c$) from $\Gamma$ of $\forall y ((\varphi^{x}_{c})^{c}_{y})$ where $y$ does not occur in $\varphi^{x}_{c}$.
But since $c$ does not occur in $\varphi$,

$((\varphi^{x}_{c})^{c}_{y}) = \varphi^{x}_{y}$.

This substitution works, because there are no occurrences of $c$ in the "original" formula $\varphi$; thus, substituting $c$ in place of $x$, and then $y$ in place of $c$, we do not have "unpleasant effects".
Thus, we may conclude that :

$\Gamma \vdash \forall y \varphi^{x}_{y}$ --- (a).

The last step in the proof is to show that :

$\forall y \varphi^{x}_{y} \vdash \forall x \varphi$.

To do this, he invokes Axiom 2 [see page 112] : $\forall y \alpha \rightarrow \alpha^{y}_{t}$.
With $\varphi^{x}_{y}$ in place of $\alpha$ and $x$ in place of $t$, we have as $\alpha^{y}_{t}$ the result $(\varphi^{x}_{y})^{y}_{x}$ , i.e. $\varphi$.

The proof now call for a formal verification through Re-replacement lemma.

Having verified this, we have $\vdash \forall y \varphi^{x}_{y} \rightarrow \varphi$.
Then the following generalization is also an axiom [see page 112] :

$\vdash \forall x (\forall y \varphi^{x}_{y} \rightarrow \varphi )$.

By Axiom 4 ($x$ is not free in $\forall y \varphi^{x}_{y}$), we have :

$\vdash \forall y \varphi^{x}_{y} \rightarrow \forall x \varphi$.

Thus, from (a) above, we may finally conclude :

$\Gamma \vdash \forall x \varphi$.


text:
Q: ReactJS 0.9+ Code Coverage with ES2015 class keyword I have a basic demo app that I've put together and I have successfully been able to write test and get code coverage working.
Except for one minor problem.
All of the code that use the class keyword from ES2015 end up emitting code at the top that looks like this:
/*istanbul ignore next*/'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();var /*istanbul ignore next*/_react = require('react'); /*istanbul ignore next*/var React = _interopRequireWildcard(_react);

It is a very long line, I'll save you the trouble of reading it.
There are a couple of problems.
First, the /*istanbul ignore next*/ should be /* istanbul ignore next */ with a space before and after the comment, otherwise istanbul basically ignores it.
Second, even once you fix that, which I tried doing, there are functions in that string that don't get commented at all with the ignore comment.  I'm assuming because the set of functions all get added at once so only one comment gets applied at the beginning.
My configuration for babel, both in package.json and .babelrc looks like this:
"presets": ["react","es2015"],
"comments": true,
"compact": false

I've also tried adding babel-plugin-transform-runtime as
"plugins": ["transform-runtime"]

both before and after the "presets" line but when I do that, I get errors that indicate the auto mocking is unable to read the metadata.
So, I guess the question is.  Does code coverage with the class keyword work at all in Jest?  If so, what am I missing?  Is there some way of getting transform-runtime working?

A: For anyone coming here in the future, I've figured this out using a combination of:

*

*The tranform-runtime plugin

*Modifying babel-jest

It takes 1000 words to describe the specifics, you can check it out here:
https://davembush.github.io/es2015-code-coverage-and-jest-react-js-unit-testing/


text:
Q: Prevent hover from changing link's height Using Angular, Angular Material, and Angular Flex-Layout, I have created a group of links that are styled like cards or tiles. When the links are not being hovered, an icon and title for the link are shown. When hovered, the icon and title no longer display and are replaced with informational text.
For items with a lot of informational text, this change of state is resulting in a height increase for the items.
I am able to fix this by hard-coding a min-height with pixels. However, if I try to use percent, like 110%, there is no change on the size of the links. The same is true for the div surrounding the links named .container .
Here is an excerpt:

<fa-icon [icon]="faToolbox"></fa-icon>Broken

Is your request causing an impact to a business-critical function, which is impacting daily production?

<fa-icon [icon]="faPuzzlePiece"></fa-icon>Project

Is your request a new product or service?

      Requires and RFI or RFP?

      Requires more than 500 or more internal resource hours

      Necessitates a cost greater then $100,000?

      New banking center or remodel?

      New Partnership, divestiture or branch closure?

I have created an example of this on StackBlitz.
How can I resolve this height-change without hard-coding for pixels?

A: Adding the following to your CSS will prevent the height change on scroll, while using 45% of the viewport height vh
.container{
  height:45vh
}

Also using the following will extend the container 10% beyond the vh for a total of 110%
.container{
  height:110vh
}

Stackblitz
https://stackblitz.com/edit/angular-w1exhe?embed=1&file=src/app/app.component.css

A: If you were looking to adjust css of links, you could add something like this to the a  css:
 max-height:60vh; (or use percentage instead of vh, but set a max-height)
 overflow-y:auto;
 overflow-x:hidden;

Hope this helps.
Example (I set your icon size to 35pt in this)


text:
Q: Sometimes Code Runs and Sometimes it gives error Below is my code to scrape a site using beautiful soup..The code runs fine on windows but has issues on ubuntu. In ubuntu, the code sometimes run and sometimes give error.
The error is below:
Traceback (most recent call last):
  File "Craftsvilla.py", line 22, in <module>
    source =  requests.get(new_url)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 487, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.craftsvilla.com', port=80): Max retries exceeded with url: /shop/01-princess-ayesha-cotton-salwar-suit-for-rudra-house/5601472 (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f6685fc3310>: Failed to establish a new connection: [Errno -2] Name or service not known',))

Below is my code:
import requests
import lxml
from bs4 import BeautifulSoup
import xlrd
import xlwt

file_location = "/home/nitink/Python Linux/BeautifulSoup/Craftsvilla/Craftsvilla.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_index(0)

products = []
for r in range(sheet.nrows):
    products.append(sheet.cell_value(r,0))

book = xlwt.Workbook(encoding= "utf-8", style_compression = 0)
sheet = book.add_sheet("Sheet11", cell_overwrite_ok=True)

for index, url in enumerate(products):
    new_url = "http://www." + url
    source =  requests.get(new_url)
    data = source.content
    soup = BeautifulSoup(data, "lxml")

    sheet.write(index, 0, url)

    try:
        Product_Name = soup.select(".product-title")[0].text.strip()
        sheet.write(index, 1, Product_Name)

    except Exception:
        sheet.write(index, 1, "")

book.save("Craftsvilla Output.xls")

Save the below links as Craftsvilla.xlsx
craftsvilla.com/shop/01-princess-ayesha-cotton-salwar-suit-for-rudra-house/5601472
craftsvilla.com/shop/3031-pista-prachi/3715170
craftsvilla.com/shop/795-peach-colored-stright-salwar-suit/5608295
craftsvilla.com/catalog/product/view/id/5083511/s/dharm-fashion-villa-embroidery-navy-blue-slawar-suit-gown

Note: For some guys the code will run, but try for sometime..the same code would give error..dont know why??..and the same code will never give any error on windows.

A: It looks like you are hitting the site too often and the server rejects your requests. Be a good web-scraping citizen and add a time delay between the consequent requests:
import time

for index, url in enumerate(products):
    new_url = "http://www." + url
    source =  requests.get(new_url)
    data = source.content
    soup = BeautifulSoup(data, "lxml")

    # ...

    time.sleep(1)  # one second delay


text:
Q: jQuery - How to show/hide multiple DIVs with child DIVs I've got a markup as follows (code modified from http://jsfiddle.net/nick_craver/srg6g/):

London & South East

South West, Ireland and Wales

South Central & Home Counties

North England, Northern Ireland & Scotland

Midlands

content london 1

content london 2

content south west 1

content south west 2

content south central 1

content south central 2

content north 1

content north 2

content midlands 1

content midlands 2

And my JavaScript code looks like as follows:
$(".map-box a").click(function(e) {
    $("#areas div").hide();
    $(this.hash).show();
    e.preventDefault();
});
$("#areas div").not("#london, #london div").hide();

When a user clicks on a image, I'd like to hide what's currently displayed and show both  contents associated for that image but this doesn't work.
e.g.,

*

*User clicks on "South West"

*Display both "content south west 1" and "content south west 2"

Would anybody be able to tell me what I'm doing wrong?

A: The problem is the selector on this line:
$("#areas div").hide();

This is selecting and hiding all div elements that are descendants of the "#areas" div, which includes not just the divs with ids like "london", etc., but those divs' children too. Then later when you show a div based on an id like "london" its child divs with the actual content remain hidden.
Try this instead:
$("#areas > div").hide();

And similarly for the line that hides them initially:
$("#areas > div").not("#london, #london div").hide();

That will hide only the divs that are direct children of "#areas". While they are hidden their children will be hidden too, but then when you show one its children will automatically appear with it.
Demo: http://jsfiddle.net/7s5nP/