text:
Q: Credit Card Sized BT receiver, circuitry, eink display and power supply. Possible? New to this forum. Read a bunch of replies to other 'like' questions, seems a lot of you know your stuff. Forgive me if this has already been postulated (don't think it has).
Curious to see if you can fit a BT receiver, the circuitry required to 'deal with the data' and rewrite the magstrip, a power source and possibly an e-ink display into something the size of a credit card (width/height - not necessarily thick).
Essentially, looking to be able to send mag strip rewrite commands to the card via BT from a cell phone or other BT enabled device that has the information required to the 'device' I am trying to assemble. The BT chip only has to be able to receive, not send any info. The magnetic strip has to be credit card thin, but the rest of the device, can be a little thicker.
I know I am reaching here, but would it be possible to also fit an e-ink display, 24 characters wide on the device as well, displaying certain, identifiable information required at the time of usage?

A: Something 2-3mm thick is pretty feasible. Various people have done similar things as "electronic business cards" or "programmable badges".
E-ink is a bit of a pain as it requires suprisingly high voltages compared to 1.8V logic. Normally done with a boost converter, but that's another thing you have to flatten. A regular LCD would be easier.
The self-rewriting magstrip is a serious problem; you might be able to emulate it with a magnetic loop that varies at the right rate.


text:
Q: Pandas dataframe has column title, yet doesn't find the applied filter I have a dataframe with column titles printed below:
Index(['Unnamed: 0', 'material', 'step', 'zaid', 'mass(gm)', 'activity(Ci)',
       'spec.act(Ci/gm)', 'atomden(a/b-cm)', 'atom_frac', 'mass_frac'],
      dtype='object')

If I try to obtain data for only, say step 16, and I perform the command:
print (df[(16 in df['step'] == 16)])

Things work as expected:
           Unnamed: 0  material  step   zaid      mass(gm)  activity(Ci)  spec.act(Ci/gm)  atomden(a/b-cm)     atom_frac     mass_frac
    447           447         1    16  90232  2.034000e-09  2.231000e-16     1.097000e-07     9.311000e-12  2.597000e-10  3.048000e-10
    448           448         1    16  92233  2.451000e-08  2.362000e-10     9.636000e-03     1.117000e-10  3.116000e-09  3.672000e-09
    449           449         1    16  92234  4.525000e-05  2.813000e-07     6.217000e-03     2.053000e-07  5.728000e-06  6.780000e-06
    450           450         1    16  92235  1.640000e-01  3.544000e-07     2.161000e-06     7.408000e-04  2.067000e-02  2.457000e-02
    451           451         1    16  92236  1.553000e-02  1.004000e-06     6.467000e-05     6.987000e-05  1.949000e-03  2.327000e-03
    ...           ...       ...   ...    ...           ...           ...              ...              ...           ...           ...
    37781       37781        10    16  67165  5.941000e-05  0.000000e+00     0.000000e+00     1.195000e-08  3.311000e-07  2.785000e-07
    37782       37782        10    16  68166  4.205000e-05  0.000000e+00     0.000000e+00     8.411000e-09  2.330000e-07  1.971000e-07
    37783       37783        10    16  68167  1.804000e-05  0.000000e+00     0.000000e+00     3.586000e-09  9.934000e-08  8.457000e-08
    37784       37784        10    16  68168  7.046000e-06  0.000000e+00     0.000000e+00     1.393000e-09  3.857000e-08  3.303000e-08
    37785       37785        10    16  68170  7.317000e-07  0.000000e+00     0.000000e+00     1.429000e-10  3.958000e-09  3.430000e-09

However if I now want to grab data for just the zaid 92235 (which clearly exists as it is displayed in the step 16 results above), according to the command:
print (df[(92235 in df['zaid'] == 92235)])

I get the following error:
Traceback (most recent call last):
  File "/Users/jack/Library/Python/3.7/lib/python/site-packages/pandas/core/indexes/base.py", line 2890, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: False

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "get_pincell_isos.py", line 57, in <module>
    print (df[(92235 in df['zaid'] == 92235)])
  File "/Users/jack/Library/Python/3.7/lib/python/site-packages/pandas/core/frame.py", line 2975, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/Users/jack/Library/Python/3.7/lib/python/site-packages/pandas/core/indexes/base.py", line 2892, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: False

It apparently can't find "92235", even though I know it exists (shown above) and the data is stored as an int64, the same type as the values in "step".  This is illustrated by printing all values from "step" and "zaid".
print (df['step'])
print (df['zaid'])

gives the following results:
0         0
1         0
2         0
3         0
4         0
         ..
37781    16
37782    16
37783    16
37784    16
37785    16
Name: step, Length: 37786, dtype: int64
0        90230
1        90231
2        90232
3        90233
4        90234
         ...
37781    67165
37782    68166
37783    68167
37784    68168
37785    68170
Name: zaid, Length: 37786, dtype: int64

I hope I'm missing something obvious.  I've tried any number of ways to try to cross-section the 'zaid' column data and no attempts have been successful at recognizing any of the values associated with 'zaid'.
Thanks!

A: Try df[df['zaid'] == 92235]. Try the below code in any ipython console
import pandas as pd

data=data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
             'year': [2000, 2001, 2002, 2001, 2002, 2003],
             'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
df = pd.DataFrame(data)
df['state'] == 'Nevada'
df[df['state'] == 'Nevada']

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to deploy existant apache sling repository on tomcat? I have a sling repository and I'm using sling luanchpad 6.0 jar to startup the sling instance.
How can I deploy this sling instance -containing application, contents and bundles- on an apache tomcat?
Thanks in advance.

A: Use the Sling launchpad war file instead of the jar file.


text:
Q: Javascript Bookmarklet I've coded a bookmarklet that opens a new window at a certain URL and sends some variables to a PHP using GET.
The problem is I need to have it load the same php and send the same variables but inside a div this time.
Could anyone point me in the right direction please?

A: Client Side - JavaScript & jQuery
jQuery provides a GET operation using AJAX, for example $.get("test.php"); See Ajax/Query.get docs for more info: arguments, examples, etc.
The version to send GET variables is $.get("test.php", { name: "John", time: "2pm" } ); jQuery is an API layer on top of regular JavaScript that simply wraps the lower-level features and expresses them in a somewhat cross-browser compatible way.
Server Side - PHP
This w3schools page shows a sample of a PHP page picking up GET data from an AJAX call:
<?php
$name=$_GET["name"]; // John
$time=$_GET["time"]; // 2pm


text:
Q: Detect encoding and make everything UTF-8 I'm reading out lots of texts from various RSS feeds and inserting them into my database.
Of course, there are several different character encodings used in the feeds, e.g. UTF-8 and ISO 8859-1.
Unfortunately, there are sometimes problems with the encodings of the texts. Example:

*

*The "ß" in "Fußball" should look like this in my database: "Ÿ". If it is a "Ÿ", it is displayed correctly.

*Sometimes, the "ß" in "Fußball" looks like this in my database: "ß". Then it is displayed wrongly, of course.

*In other cases, the "ß" is saved as a "ß" - so without any change. Then it is also displayed wrongly.
What can I do to avoid the cases 2 and 3?
How can I make everything the same encoding, preferably UTF-8? When must I use utf8_encode(), when must I use utf8_decode() (it's clear what the effect is but when must I use the functions?) and when must I do nothing with the input?
How do I make everything the same encoding? Perhaps with the function mb_detect_encoding()? Can I write a function for this? So my problems are:

*

*How do I find out what encoding the text uses?

*How do I convert it to UTF-8 - whatever the old encoding is?

Would a function like this work?
function correct_encoding($text) {
    $current_encoding = mb_detect_encoding($text, 'auto');
    $text = iconv($current_encoding, 'UTF-8', $text);
    return $text;
}

I've tested it, but it doesn't work. What's wrong with it?

A: You first have to detect what encoding has been used. As you're parsing RSS feeds (probably via HTTP), you should read the encoding from the charset parameter of the Content-Type HTTP header field. If it is not present, read the encoding from the encoding attribute of the XML processing instruction. If that's missing too, use UTF-8 as defined in the specification.

Here is what I probably would do:
I'd use cURL to send and fetch the response. That allows you to set specific header fields and fetch the response header as well. After fetching the response, you have to parse the HTTP response and split it into header and body. The header should then contain the Content-Type header field that contains the MIME type and (hopefully) the charset parameter with the encoding/charset too. If not, we'll analyse the XML PI for the presence of the encoding attribute and get the encoding from there. If that's also missing, the XML specs define to use UTF-8 as encoding.
$url = 'http://www.lr-online.de/storage/rss/rss/sport.xml';

$accept = array(
    'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
    'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
    'Accept: '.implode(', ', $accept['type']),
    'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($curl);
if (!$response) {
    // error fetching the response
} else {
    $offset = strpos($response, "\r\n\r\n");
    $header = substr($response, 0, $offset);
    if (!$header || !preg_match('/^Content-Type:\s+([^;]+)(?:;\s*charset=(.*))?/im', $header, $match)) {
        // error parsing the response
    } else {
        if (!in_array(strtolower($match[1]), array_map('strtolower', $accept['type']))) {
            // type not accepted
        }
        $encoding = trim($match[2], '"\'');
    }
    if (!$encoding) {
        $body = substr($response, $offset + 4);
        if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $body, $match)) {
            $encoding = trim($match[1], '"\'');
        }
    }
    if (!$encoding) {
        $encoding = 'utf-8';
    } else {
        if (!in_array($encoding, array_map('strtolower', $accept['charset']))) {
            // encoding not accepted
        }
        if ($encoding != 'utf-8') {
            $body = mb_convert_encoding($body, 'utf-8', $encoding);
        }
    }
    $simpleXML = simplexml_load_string($body, null, LIBXML_NOERROR);
    if (!$simpleXML) {
        // parse error
    } else {
        echo $simpleXML->asXML();
    }
}

A: Your encoding looks like you encoded into UTF-8 twice; that is, from some other encoding, into UTF-8, and again into UTF-8. As if you had ISO 8859-1, converted from ISO 8859-1 to UTF-8, and treated the new string as ISO 8859-1 for another conversion into UTF-8.
Here's some pseudocode of what you did:
$inputstring = getFromUser();
$utf8string = iconv($current_encoding, 'utf-8', $inputstring);
$flawedstring = iconv($current_encoding, 'utf-8', $utf8string);

You should try:

*

*detect encoding using mb_detect_encoding() or whatever you like to use

*if it's UTF-8, convert into ISO 8859-1, and repeat step 1

*finally, convert back into UTF-8

That is presuming that in the "middle" conversion you used ISO 8859-1. If you used Windows-1252, then convert into Windows-1252 (latin1). The original source encoding is not important; the one you used in flawed, second conversion is.
This is my guess at what happened; there's very little else you could have done to get four bytes in place of one extended ASCII byte.
The German language also uses ISO 8859-2 and Windows-1250 (Latin-2).

A: A really nice way to implement an isUTF8-function can be found on php.net:
function isUTF8($string) {
    return (utf8_encode(utf8_decode($string)) == $string);
}

A: Detecting the encoding is hard.
mb_detect_encoding works by guessing, based on a number of candidates that you pass it. In some encodings, certain byte-sequences are invalid, an therefore it can distinguish between various candidates. Unfortunately, there are a lot of encodings, where the same bytes are valid (but different). In these cases, there is no way to determine the encoding; You can implement your own logic to make guesses in these cases. For example, data coming from a Japanese site might be more likely to have a Japanese encoding.
As long as you only deal with Western European languages, the three major encodings to consider are utf-8, iso-8859-1 and cp-1252. Since these are defaults for many platforms, they are also the most likely to be reported wrongly about. Eg. if people use different encodings, they are likely to be frank about it, since else their software would break very often. Therefore, a good strategy is to trust the provider, unless the encoding is reported as one of those three. You should still doublecheck that it is indeed valid, using mb_check_encoding (note that valid is not the same as being - the same input may be valid for many encodings). If it is one of those, you can then use mb_detect_encoding to distinguish between them. Luckily that is fairly deterministic; You just need to use the proper detect-sequence, which is UTF-8,ISO-8859-1,WINDOWS-1252.
Once you've detected the encoding you need to convert it to your internal representation (UTF-8 is the only sane choice). The function utf8_encode transforms ISO-8859-1 to UTF-8, so it can only used for that particular input type. For other encodings, use mb_convert_encoding.

A: The interesting thing about mb_detect_encoding and mb_convert_encoding is that the order of the encodings you suggest does matter:
// $input is actually UTF-8

mb_detect_encoding($input, "UTF-8", "ISO-8859-9, UTF-8");
// ISO-8859-9 (WRONG!)

mb_detect_encoding($input, "UTF-8", "UTF-8, ISO-8859-9");
// UTF-8 (OK)

So you might want to use a specific order when specifying expected encodings. Still, keep in mind that this is not foolproof.

A: If you apply utf8_encode() to an already UTF-8 string, it will return garbled UTF-8 output.
I made a function that addresses all this issues. It´s called Encoding::toUTF8().
You don't need to know what the encoding of your strings is. It can be Latin1 (ISO 8859-1), Windows-1252 or UTF-8, or the string can have a mix of them. Encoding::toUTF8() will convert everything to UTF-8.
I did it because a service was giving me a feed of data all messed up, mixing UTF-8 and Latin1 in the same string.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding;  // It's namespaced now.

$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);

$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);

Download:
https://github.com/neitanod/forceutf8
I've included another function, Encoding::fixUFT8(), which will fix every UTF-8 string that looks garbled.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding;  // It's namespaced now.

$utf8_string = Encoding::fixUTF8($garbled_utf8_string);

Examples:
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");

will output:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football

I've transformed the function (forceUTF8) into a family of static functions on a class called Encoding. The new function is Encoding::toUTF8().

A: Working out the character encoding of RSS feeds seems to be complicated.  Even normal web pages often omit, or lie about, their encoding.
So you could try to use the correct way to detect the encoding and then fall back to some form of auto-detection (guessing).

A: mb_detect_encoding:
echo mb_detect_encoding($str, "auto");

Or
echo mb_detect_encoding($str, "UTF-8, ASCII, ISO-8859-1");

I really don't know what the results are, but I'd suggest you just take some of your feeds with different encodings and try if mb_detect_encoding works or not.
auto is short for "ASCII,JIS,UTF-8,EUC-JP,SJIS". It returns the detected charset, which you can use to convert the string to UTF-8 with iconv.
<?php
function convertToUTF8($str) {
    $enc = mb_detect_encoding($str);

    if ($enc && $enc != 'UTF-8') {
        return iconv($enc, 'UTF-8', $str);
    } else {
        return $str;
    }
}
?>

I haven't tested it, so no guarantee. And maybe there's a simpler way.

A: You need to test the character set on input since responses can come coded with different encodings.
I force all content been sent into UTF-8 by doing detection and translation using the following function:
function fixRequestCharset()
{
  $ref = array(&$_GET, &$_POST, &$_REQUEST);
  foreach ($ref as &$var)
  {
    foreach ($var as $key => $val)
    {
      $encoding = mb_detect_encoding($var[$key], mb_detect_order(), true);
      if (!$encoding)
        continue;
      if (strcasecmp($encoding, 'UTF-8') != 0)
      {
        $encoding = iconv($encoding, 'UTF-8', $var[$key]);
        if ($encoding === false)
          continue;
        $var[$key] = $encoding;
      }
    }
  }
}

That routine will turn all PHP variables that come from the remote host into UTF-8.
Or ignore the value if the encoding could not be detected or converted.
You can customize it to your needs.
Just invoke it before using the variables.

A: This cheatsheet lists some common caveats related to UTF-8 handling in PHP:
http://developer.loftdigital.com/blog/php-utf-8-cheatsheet
This function detecting multibyte characters in a string might also prove helpful (source):

function detectUTF8($string)
{
    return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
        )+%xs',
    $string);
}

A: A little heads up. You said that the "ß" should be displayed as "Ÿ" in your database.
This is probably because you're using a database with Latin-1 character encoding or possibly your PHP-MySQL connection is set wrong, this is, P believes your MySQL is set to use UTF-8, so it sends data as UTF-8, but your MySQL believes PHP is sending data encoded as ISO 8859-1, so it may once again try to encode your sent data as UTF-8, causing this kind of trouble.
Take a look at mysql_set_charset. It may help you.

A: It's simple: when you get something that's not UTF-8, you must encode that into UTF-8.
So, when you're fetching a certain feed that's ISO 8859-1 parse it through utf8_encode.
However, if you're fetching an UTF-8 feed, you don't need to do anything.

A: I know this is an older question, but I figure a useful answer never hurts. I was having issues with my encoding between a desktop application, SQLite, and GET/POST variables. Some would be in UTF-8, some would be in ASCII, and basically everything would get screwed up when foreign characters got involved.
Here is my solution. It scrubs your GET/POST/REQUEST (I omitted cookies, but you could add them if desired) on each page load before processing. It works well in a header. PHP will throw warnings if it can't detect the source encoding automatically, so these warnings are suppressed with @'s.
//Convert everything in our vars to UTF-8 for playing nice with the database...
//Use some auto detection here to help us not double-encode...
//Suppress possible warnings with @'s for when encoding cannot be detected
try
{
    $process = array(&$_GET, &$_POST, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = $v;
                $process[] = &$process[$key][@mb_convert_encoding($k,'UTF-8','auto')];
            } else {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = @mb_convert_encoding($v,'UTF-8','auto');
            }
        }
    }
    unset($process);
}
catch(Exception $ex){}

A: harpax' answer worked for me.  In my case, this is good enough:
if (isUTF8($str)) {
    echo $str;
}
else
{
    echo iconv("ISO-8859-1", "UTF-8//TRANSLIT", $str);
}

A: I was checking for solutions to encoding since ages, and this page is probably the conclusion of years of search! I tested some of the suggestions you mentioned and here are my notes:
This is my test string:

this is a "wròng wrìtten" string bùt I nèed to pù 'sòme'  special
chàrs to see thèm, convertèd by fùnctìon!! & that's it!

I do an INSERT to save this string on a database in a field that is set as utf8_general_ci
The character set of my page is UTF-8.
If I do an INSERT just like that, in my database, I have some characters probably coming from Mars...
So I need to convert them into some "sane" UTF-8. I tried utf8_encode(), but still aliens chars were invading my database...
So I tried to use the function forceUTF8 posted on number 8, but in the database the string saved looks like this:

this is a "wròng wrìtten" string bùt I nèed to pù 'sòme' special
chà rs to see thèm, convertèd by fùnctìon!! & that's it!

So collecting some more information on this page and merging them with other information on other pages I solved my problem with this solution:
$finallyIDidIt = mb_convert_encoding(
  $string,
  mysql_client_encoding($resourceID),
  mb_detect_encoding($string)
);

Now in my database I have my string with correct encoding.
NOTE:
Only note to take care of is in function mysql_client_encoding!
You need to be connected to the database, because this function wants a resource ID as a parameter.
But well, I just do that re-encoding before my INSERT so for me it is not a problem.

A: After sorting out your PHP scripts, don't forget to tell MySQL what charset you are passing and would like to receive.
Example: set the character to UTF-8
Passing UTF-8 data to a Latin 1 table in a Latin 1 I/O session gives those nasty birdfeets. I see this every other day in OsCommerce shops. Back and fourth it might seem right. But phpMyAdmin will show the truth. By telling MySQL what charset you are passing, it will handle the conversion of MySQL data for you.
How to recover existing scrambled MySQL data is another question. :)

A: Get the encoding from headers and convert it to UTF-8.
$post_url = 'http://website.domain';

/// Get headers ///////////////////////////////////////////////
function get_headers_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_HEADER,         true);
    curl_setopt($ch, CURLOPT_NOBODY,         true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);

    $r = curl_exec($ch);
    return $r;
}

$the_header = get_headers_curl($post_url);

/// Check for redirect ////////////////////////////////////////
if (preg_match("/Location:/i", $the_header)) {
    $arr = explode('Location:', $the_header);
    $location = $arr[1];

    $location = explode(chr(10), $location);
    $location = $location[0];

    $the_header = get_headers_curl(trim($location));
}

/// Get charset ///////////////////////////////////////////////
if (preg_match("/charset=/i", $the_header)) {
    $arr = explode('charset=', $the_header);
    $charset = $arr[1];

    $charset = explode(chr(10), $charset);
    $charset = $charset[0];
}

///////////////////////////////////////////////////////////////////
// echo $charset;

if($charset && $charset != 'UTF-8') {
    $html = iconv($charset, "UTF-8", $html);
}

A: Ÿ is Mojibake for ß.  In your database, you may have one of the following hex values (use SELECT HEX(col)...) to find out):

*

*DF if the column is "latin1",

*C39F if the column is utf8 -- OR -- it is latin1, but "double-encoded"

*C383C5B8 if double-encoded into a utf8 column

You should not use any encoding/decoding functions in PHP; instead, you should set up the database and the connection to it correctly.
If MySQL is involved, see: Trouble with UTF-8 characters; what I see is not what I stored

A: if(!mb_check_encoding($str)){
    $str = iconv("windows-1251", "UTF-8", $str);
}

It helped for me

A: When you try to handle multi languages, like Japanese and Korean, you might get in trouble.
mb_convert_encoding with the 'auto' parameter doesn't work well. Setting mb_detect_order('ASCII,UTF-8,JIS,EUC-JP,SJIS,EUC-KR,UHC') doesn't help since it will detect EUC-* wrongly.
I concluded that as long as input strings comes from HTML, it should use 'charset' in a meta element. I use Simple HTML DOM Parser because it supports invalid HTML.
The below snippet extracts the title element from a web page. If you would like to convert the entire page, then you may want to remove some lines.
<?php
require_once 'simple_html_dom.php';

echo convert_title_to_utf8(file_get_contents($argv[1])), PHP_EOL;

function convert_title_to_utf8($contents)
{
    $dom = str_get_html($contents);
    $title = $dom->find('title', 0);
    if (empty($title)) {
        return null;
    }
    $title = $title->plaintext;
    $metas = $dom->find('meta');
    $charset = 'auto';
    foreach ($metas as $meta) {
        if (!empty($meta->charset)) { // HTML5
            $charset = $meta->charset;
        } else if (preg_match('@charset=(.+)@', $meta->content, $match)) {
            $charset = $match[1];
        }
    }
    if (!in_array(strtolower($charset), array_map('strtolower', mb_list_encodings()))) {
        $charset = 'auto';
    }
    return mb_convert_encoding($title, 'UTF-8', $charset);
}

A: This version is for the German language, but you can modify the $CHARSETS and the $TESTCHARS.
class CharsetDetector
{
    private static $CHARSETS = array(
        "ISO_8859-1",
        "ISO_8859-15",
        "CP850"
    );

    private static $TESTCHARS = array(
        "€",
        "ä",
        "Ä",
        "ö",
        "Ö",
        "ü",
        "Ü",
        "ß"
    );

    public static function convert($string)
    {
        return self::__iconv($string, self::getCharset($string));
    }

    public static function getCharset($string)
    {
        $normalized = self::__normalize($string);
        if(!strlen($normalized))
            return "UTF-8";
        $best = "UTF-8";
        $charcountbest = 0;
        foreach (self::$CHARSETS as $charset)
        {
            $str = self::__iconv($normalized, $charset);
            $charcount = 0;
            $stop = mb_strlen($str, "UTF-8");

            for($idx = 0; $idx < $stop; $idx++)
            {
                $char = mb_substr($str, $idx, 1, "UTF-8");
                foreach (self::$TESTCHARS as $testchar)
                {
                    if($char == $testchar)
                    {
                        $charcount++;
                        break;
                    }
                }
            }

            if($charcount > $charcountbest)
            {
                $charcountbest = $charcount;
                $best = $charset;
            }
            //echo $text . "<br />";
        }
        return $best;
    }

    private static function __normalize($str)
    {
        $len = strlen($str);
        $ret = "";
        for($i = 0; $i < $len; $i++)
        {
            $c = ord($str[$i]);
            if ($c > 128) {
                if (($c > 247))
                    $ret .= $str[$i];
                elseif
                    ($c > 239) $bytes = 4;
                elseif
                    ($c > 223) $bytes = 3;
                elseif
                    ($c > 191) $bytes = 2;
                else
                    $ret .= $str[$i];

                if (($i + $bytes) > $len)
                    $ret .= $str[$i];
                $ret2 = $str[$i];
                while ($bytes > 1)
                {
                    $i++;
                    $b = ord($str[$i]);
                    if ($b < 128 || $b > 191)
                    {
                        $ret .= $ret2;
                        $ret2 = "";
                        $i += $bytes-1;
                        $bytes = 1;
                        break;
                    }
                    else
                        $ret2 .= $str[$i];
                    $bytes--;
                }
            }
        }
        return $ret;
    }

    private static function __iconv($string, $charset)
    {
        return iconv ($charset, "UTF-8", $string);
    }
}

A: I had the same issue with phpQuery (ISO-8859-1 instead of UTF-8) and this hack helped me:
$html = '<?xml version="1.0" encoding="UTF-8" ?>' . $html;

mb_internal_encoding('UTF-8'), phpQuery::newDocumentHTML($html, 'utf-8'), mbstring.internal_encoding and other manipulations didn't take any effect.

A: I found a solution at http://deer.org.ua/2009/10/06/1/:
class Encoding
{
    /**
     * http://deer.org.ua/2009/10/06/1/
     * @param $string
     * @return null
     */
    public static function detect_encoding($string)
    {
        static $list = ['utf-8', 'windows-1251'];

        foreach ($list as $item) {
            try {
                $sample = iconv($item, $item, $string);
            } catch (\Exception $e) {
                continue;
            }
            if (md5($sample) == md5($string)) {
                return $item;
            }
        }
        return null;
    }
}

$content = file_get_contents($file['tmp_name']);
$encoding = Encoding::detect_encoding($content);
if ($encoding != 'utf-8') {
    $result = iconv($encoding, 'utf-8', $content);
} else {
    $result = $content;
}

I think that @ is a bad decision and made some changes to the solution from deer.org.ua.

A: For Chinese characters, it is common to be encoded in the GBK encoding. In addition, when tested, the most voted answer doesn't work. Here is a simple fix that makes it work as well:
function toUTF8($raw) {
    try{
        return mb_convert_encoding($raw, "UTF-8", "auto");
    }catch(\Exception $e){
        return mb_convert_encoding($raw, "UTF-8", "GBK");
    }
}

Remark: This solution was written in 2017 and should fix problems for PHP in those days. I have not tested whether latest PHP already understands auto correctly.

A: Try without 'auto'
That is:
mb_detect_encoding($text)

instead of:
mb_detect_encoding($text, 'auto')

More information can be found here: mb_detect_encoding

A: Try to use this... every text that is not UTF-8 will be translated.
function is_utf8($str) {
    return (bool) preg_match('//u', $str);
}

$myString = "Fußball";

if(!is_utf8($myString)){
    $myString = utf8_encode($myString);
}

// or 1 line version ;)
$myString = !is_utf8($myString) ? utf8_encode($myString) : trim($myString);


text:
Q: Use complex numbers to produce the equilateral triangle as illustrated below with its center at the origin and one point at (3, 4). enter image description here

thanks very much!

A: Hint: The unknown coordinates of the second and third point are those of the first point rotated around the origin by 120 resp. 240 degrees. In the complex numbers, a rotation around the origin by $\theta$ is a multiplication by $\exp(i\theta)$.


text:
Q: Let $M,N$ be isomorphic as $\mathbf{Z}[G]$-mods, are they isomorphic as $\mathbf{Z}[H]$-mods, where $HSo I have recently been looking at the isomorphisms of $\mathbf{Z}[G]$-mods ($G$ finite), and noticed that a couple of my examples saw them isomorphic as $\mathbf{Z}[H]$-mods also, where $H$ is a subgroup of $G$. I was wondering if there is any general results for when this holds, such as when $H$ is a normal subgroup perhaps?

A: It holds without any condition on $H$, actually. Suppose $f : M \to N$ is an isomorphism of $\mathbb{Z}[G]$-modules. In other words, $f$ is bijective, additive and $G$-equivariant (ie. $f(g \cdot m) = g \cdot f(m)$ for all $g \in G$, $m \in M$). Then $f$ is also $H$-equivariant: $f(h \cdot m) = h \cdot f(m)$ for all $h \in H$, $m \in M$. It's still additive, so it's a morphism of $\mathbb{Z}[H]$-modules; and it's bijective, so it's an isomorphism.

A more general fact holds. If $\phi : A \to B$ is a ring morphism, and $M$ is a $B$-module, let $\phi^* M$ be the same module viewed as an $A$-module through $\phi$. Then if $f : M \to N$ is an isomorphism of $B$-modules, the induced map $\phi^* M \to \phi^* N$ (on the level of sets it's the same map) is an isomorphism of $A$-modules, with the same proof as before. You can also view it as a purely formal result: $M \mapsto \phi^* M$ is a functor, and thus carries isomorphisms to isomorphisms.


text:
Q: Should a custom event have get methods? I created some custom events in a desktop application and gave it some get methods in order to grab the data that is associated with the event. It seems odd to be calling 'get' methods on an event. Is this bad programming practice, should I make the event properties public instead?
Here is my custom event...
package classes.events
{
import flash.events.Event;

public class ListItemClickedEvent extends Event
{
    public static var PROJECT_CHOSEN:String = "project_chosen";
    private var projectName:String;
    private var projectLabel:String;
    private var projectFolder:String;

    public function ListItemClickedEvent(type:String, bubbles:Boolean = true,
                                    cancelable:Boolean = false, pName:String = null,
                                    pLabel:String = null, pFolder:String = null){
        super(type, bubbles, cancelable);
        projectName = pName;
        projectLabel = pLabel;
        projectFolder = pFolder;
    }

    override public function clone():Event{
        return new ListItemClickedEvent(type, bubbles, cancelable);
    }

    public function getProjectName():String{
        return projectName;
    }
    public function getProjectLabel():String{
        return projectLabel;
    }
    public function getProjectFolder():String{
        return projectFolder;
    }

}

}

A: Flex events like ListEvent or MenuEvent simply use public variables, but feel free to use any access practice you like: getter functions, properties or public variables. It's your class and you can use your own style.


text:
Q: How to prove that if $\int_L \vec{F}(\vec{x})\cdot d\vec{x}$ exists, then integral on separate curve exists? From wiki I found the very basic definition of line integral on vector:
For any partition $P=\{\vec{x}_1,...,\vec{x}_{m+1}\}$ separate $L$, any pick of points $\vec{\xi}_i\in \vec{x}_i\vec{x}_{i+1}$, the limit $\lim_{\lambda\to0}\sum_{i=1}^n \vec{F}(\vec{\xi}_i)\cdot\Delta \vec{x}_i$ always converge to the same value, then we can say
$$\lim_{\lambda\to0}\sum_{i=1}^n \vec{F}(\vec{\xi}_i)\cdot\Delta \vec{x}_i=\int_L \vec{F}(\vec{x})\cdot d\vec{x}$$
Based on that I tried to prove the existence of $\int_{L_1} \vec{F}(\vec{x})\cdot d\vec{x},\int_{L_2} \vec{F}(\vec{x})\cdot d\vec{x}$ (where $L_1\cap L_2=\varnothing \land L_1\cup L_2=L$). However, it is a little bit hard for me and I only can prove it based on $\vec{F}(\vec{x})$ is a continues function.
So I would like to ask for a prove that do not base on that condition. Or if the condition is needed, an example that do not satisfy.
Thanks a lot!!

The following is a list of some definitions and assumptions, in order to better describe my question:

*

*$L$ is a curve in Euclid Space $\mathbb{R}^n$ and is rectifiable.

*$\vec{F}(\vec{x})=\begin{cases}f_1(\vec{x})\\...\\f_n(\vec{x})\end{cases},\vec{x}\in R^n$ is a $\mathbb{R}^n\to \mathbb{R}^n$ function

*$P=\{\vec{x}_1,...,\vec{x}_{m+1}\}$ saperate $L$ into $n$ parts

*$\Delta \vec{x}_i=\vec{x}_{i+1}-\vec{x}_i=\begin{cases}\Delta x_{i(1)}\\...\\\Delta x_{i(n)}\end{cases}$

*$|\Delta \vec{x}_i|=\sqrt{\sum_{j=1}^n\left(\Delta x_{i(j)}\right)^2}$ which is the chord length of $\vec{x}_i\vec{x}_{i+1}$

*$\Delta s_i$ donate the arc length of $\vec{x}_i\vec{x}_{i+1}$

*$\vec{\xi}_i\in \vec{x}_i\vec{x}_{i+1}$

*$\lambda=\max(\Delta s_i)$

A: I'll leave the proof that persuaded myself here, since I'm a beginner, anyone who would willing to look into it and find any mistake are very welcome.

Part 1
Since $\int_L\vec{F}(\vec{x})\cdot d\vec{x}$ exists, we have the following conditions:

*

*$\vec{F}(\vec{x})$ have definition on $L$ since $L$ is close set, $\vec{F}(\vec{x})$ is limited

*$\forall\epsilon>0,\exists\delta,\forall\lambda<\delta$ for any partion $P$ and pick of points $\vec{\xi}_i$, we have  $\left|\sum_{i=1}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-I\right|<\frac{\epsilon_1}{2}$

*$\lim_{\lambda\to0}\sum_{i=1}^m \vec{F}(\vec{x}_i)\cdot\Delta \vec{x}_i=I$
Obviously there will include partitions that separates $L_1,L_2$ on $\vec{x}_k\in P$.
Therefore we have $\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-I\right|<\epsilon$
and also $\lim_{\lambda\to0}\sum_{i=1}^n \vec{F}(\vec{x}_i)\cdot\Delta \vec{x}_i=\lim_{\lambda\to0}\left\{\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i\right\}=I$
Where we define the first part of the sum is from $L_1$ and the second part is from $L_2$

Part 2
Now we assume that $\lim_{\lambda\to0}\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i$ does not converge.
List the assumption as $\exists\epsilon_1>0,\forall\delta>0,\exists\lambda_1<\delta$ exists partition and pick of points  $\exists(P^1,\vec{\xi}^1_i)$
That for all $A\in\mathbb{R}$ we have $\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A\right|>\epsilon_1$ for $L_1$

Part 3
Then we use the condition from Part 1 and
set $\epsilon=\frac{\epsilon_1}{2}$
Therefore we get $\delta>$ that $\forall\lambda<\delta$ we have $\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-I\right|<\frac{\epsilon_1}{2}$
According to Part 2 there is a partition and pick of points that makes $\forall A\Rightarrow\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A\right|>\epsilon_1$
We make $L_1$ follow the above partition and pick of points, $L_2$ can be any partition and pick of points as long as $\lambda<\delta$
Thus we derive:
\begin{aligned}
\because&\frac{\epsilon_1}{2}>\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-I\right|\\
=&\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-(I-A)\right|\\
\geq&\left|\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A\right|-\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-(I-A)\right|\right|\\
\therefore&-\frac{\epsilon_1}{2}<\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-(I-A)\right|-\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A\right|<\frac{\epsilon_1}{2}\\
\because&\left|\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-A\right|>\epsilon_1\\
\therefore&\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-(I-A)\right|>\frac{\epsilon_1}{2}
\end{aligned}
Note that the above condition only used the specific partition and pick of points of $L_1$. For $L_2$, despite of the partition and pick of points the result holds. Also dispute the value of $A$, the result holds.

Part 4
Using condition 1 of Part 1, we define $\left|\vec{F}(\vec{x})\right|\leq M$ thus we have $\left|\vec{F}(\vec{x})\cdot\Delta\vec{x}\right|\leq m\left|\vec{F}(\vec{x})\right|\left|\Delta\vec{x}\right|\leq nM\left|\Delta\vec{x}\right|$
While $n$ is the dimension of $\vec{F}(\vec{x})$
Therefore, we have  $\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i\right|\leq\sum_{i=k}^{m}\left|\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i\right|<nMl_2$ where $l_2$ is the length of $L_2$ since $L$ is rectifiable.
We construct a partition of $P=\{\vec{x}_k,...,\vec{x}_{m+1}\}$ separate $L_2$ equally on length into $m-k$ parts and pick of points $\vec{\xi}_i$ are the middle points of arc $\vec{x}_i\vec{x}_{i+1}$ on length.
Then donate $S_m=\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i,m>k$, with the previous proof we know that S_m is limited series.
Using Bolzano-Weierstrass theorem that there must be a sub-series that converges.
Donate $S_{m_u}$ that have $\lim_{u\to\infty}S_{m_u}=B$
This means that $\forall\epsilon>0,\exists U,\forall u>U\Rightarrow\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-B\right|<\epsilon$

Part 5
From Part 4 we set $\epsilon=\frac{\epsilon_1}{2}$ then we exists $U_1$
we set $u=\max\left(U_1,\left[\frac{l}{\delta}\right]+1\right)$ then obviously we have $\left|\sum_{i=k}^{n}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-B\right|<\frac{\epsilon_1}{2}$
From Part 3 we know that for any partition, pick of points, and $A$,
as long as $\lambda=l\div u\leq l\div \left(\left[\frac{l}{\delta}\right]+1\right)<\delta$, for $L_2$ we have $\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-(I-A)\right|>\frac{\epsilon_1}{2}$
We pick $A=I-B$ then have $\lambda<\delta$, for $L_2$ we have $\left|\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i-B\right|>\frac{\epsilon_1}{2}$
Which result an contradiction.
Thus $\lim_{\lambda\to0}\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i,\lim_{\lambda\to0}\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i$ both converge despite of partition and pick of points.
It is also easy to prove that they would converge into the same value by for any partition and pick of points $\lim_{\lambda\to0}\left\{\sum_{i=1}^{k-1}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i+\sum_{i=k}^{m}\vec{F}(\vec{\xi}_i)\cdot\Delta\vec{x}_i\right\}$ always converge to $I$.
Thus it persuaded me that the existence are proved.


text:
Q: Pagination in HeterogeneousRecyclerview I am unable to used pagination in HeterogeneousRecyclerview.it contents horizontal and vertical recycleview. I want to use pagination in VerticalRecycleview endless. When I try to do that it will not satisfy conditon.I will return visibleItemCount,totalItemCount and firstVisibleItemPosition that will not help to load more data. Please suggest me.
Recycle view:
 val recyclerView = findViewById<RecyclerView>(R.id.rvMain)
        val adapter = MainAdapter(this, getObject())
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)
        recycleViewScroll(recyclerView)

 private fun getObject(): ArrayList<Any> {
        jsonHelper?.readHorizontalItemsJSON()?.get(0)?.let { objects.add(it) }
        jsonHelper?.readVerticalItemsJSON()?.get(0)?.let { objects.add(it) }
        jsonHelper?.readHorizontalItemsJSON()?.get(0)?.let { objects.add(it) }
        return objects as ArrayList<Any>
    }

private fun recycleViewScroll(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val visibleItemCount = recyclerView.layoutManager!!.childCount
                val totalItemCount = recyclerView.layoutManager!!.itemCount
                val firstVisibleItemPosition =
                    (recyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                val lastpositionView = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                //val lastpositionView = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                println("dsfdsfdsfdfd----->" + visibleItemCount + "," + totalItemCount + "," + firstVisibleItemPosition!! +","+lastpositionView)

              if (!isLoading && !isLastPage) {//
                     if (visibleItemCount + firstVisibleItemPosition!! >= totalItemCount && firstVisibleItemPosition!! >= 0 && totalItemCount >= PAGE_SIZE) {
                         loadMoreItems()
                     }
                 }

            }
        })
    }

}`

Adapter:

class MainAdapter(private val context: Context, private val items: ArrayList<Any>?=null) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val jsonHelper = JsonHelper(context)

    //this method returns the number according to the Vertical/Horizontal object
    override
    fun getItemViewType(position: Int): Int {
        if (items?.get(position) is HorizontalModel)
            return HORIZONTAL
        return if (items?.get(position) is VerticalModel) VERTICAL else -1
    }

    override
    fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(context)
        val view: View
        val holder: RecyclerView.ViewHolder
        when (viewType) {
            HORIZONTAL -> {
                view = inflater.inflate(R.layout.layout_horizontal_recycler_view, parent, false)
                holder = HorizontalViewHolder(view)
            }
            VERTICAL -> {
                view = inflater.inflate(R.layout.layout_vertical_recycler_view, parent, false)
                holder = VerticalViewHolder(view)
            }
            else -> {
                view = inflater.inflate(R.layout.layout_horizontal_recycler_view, parent, false)
                holder = HorizontalViewHolder(view)
            }
        }
        return holder
    }

    override
    fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder.itemViewType == HORIZONTAL)
            horizontalView(holder as HorizontalViewHolder)
        else if (holder.itemViewType == VERTICAL)
            verticalView(holder as VerticalViewHolder)
    }

    private fun horizontalView(holder: HorizontalViewHolder) {
        val adapter = HorizontalAdapter(context, jsonHelper.readHorizontalItemsJSON()!!)
        holder.recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        holder.recyclerView.adapter = adapter
    }

    private fun verticalView(holder: VerticalViewHolder) {
        val adapter = VerticalAdapter(context, jsonHelper.readVerticalItemsJSON()!!)
        holder.recyclerView.layoutManager = LinearLayoutManager(context)
        holder.recyclerView.adapter = adapter
    }

    override
    fun getItemCount(): Int {
        return items?.size ?:0
    }

    inner class HorizontalViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        internal var recyclerView: RecyclerView = itemView.findViewById(R.id.rvHorizontal)
    }

    inner class VerticalViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        internal var recyclerView: RecyclerView = itemView.findViewById(R.id.rvVertical)
    }
}


text:
Q: Is the nullset-indexed union of slices a nullset? Let $A$ be a Borel-measurable subset of $\mathbb{R}^n$, and denote by $A_t:=\{u\in \mathbb{R}^{n-1} \mid (t,u)\in A\}$ ($t\in\mathbb{R}$) the $t$-slices of $A$.
If $N$ is a Lebesgue nullset of $\mathbb{R}$, can we conclude that the subset
$$
A_N \, := \, \bigcup_{t\in N}(t,A_t) \quad \text{of } \ \ A
$$
is a Lebesgue nullset of $\mathbb{R}^n$? [If necessary, it may be assumed that $A$ is compact.]
(This is not a homework question.)

A: Yes. This easily follows from Fubini's theorem (or, even easier, from Tonelli's theorem).


text:
Q: Perform actions once anchor element is clicked I am having a webpage load another webpage inside an iframe that takes up the entire screen. I have 2 div's that are on top of each other. These divs are actually anchors that direct to a new url (an action). What I am trying to do is once any of the divs is clicked, to initiate an onclick event that will go to the url specified in that anchor href, and then reload the initial index.html page. My class is working on a local enviroment to teach us a thing called clickjacking. Below is my current html.
The issue im having is I can have the anchor click go to the url I want, but then I am no longer in my index.html. Is it possible to open the referenced link in a new window, close the new window once its loaded and then refresh the index.html page. Once that is done to hide the div that was clicked since the "second" div is hidden behind the top most clickable div.

</script>

TLDR:

*

*Load iframe in webpage

*click on anchor div on page that directs to a new url

*load that url, once loaded go back to the index.html (all in one tab) (step 1)

*hide the anchor div that was selected-- allowing second anchor to be
clicked

Thank you for your help.

A: It looks like you might need to "fake" the onclick if you want to have an onclick action work on the page you are on. You will need to modify the parameters, but here is a code that I have used:
    $(function() {
    // find out what our query parameters contain.
    var query = location.search;

    // isolate the position of the equal sign.
    var equalIndex = query.indexOf('=');
    // extract the image's id.
    var imageId = query.substring(equalIndex + 1);

    // click on the appropriate image.
    $('#' + imageId).click();
    });

The comments explain what each step of the code performs. In my case, I needed the page to load and then force the onclick using the unique image ids. In your case, you will need to tie it to your unique div. I hope that this helps you get started.


text:
Q: Reducer not fetching the initial state in redux I am building a 'to do list' application in react and redux.
I've built several reducers in the course of development such as 'buckets', 'todos' etc.
The 'buckets' reducer seems to pick up the initialState of the app just fine while the other reducers don't (they console empty arrays).
I can't figure out why.
My index.js file
import todoApp from './reducers/index.js';
import App from './components/App';
import React from 'react';
import {render} from 'react-dom';
import {createStore} from 'redux';
import {Provider} from 'react-redux';

const initialState = {
    buckets: [
        {
            name: 'Test Bucket',
            id: 0,
            visibilityFilter: "SHOW_ALL",
            todos: [
                {
                    id: 0,
                    text: "This is a test",
                    completed: true
                },
                {
                    id: 1,
                    text: "Random entry",
                    completed: true
                },
                {
                    id: 2,
                    text: 'Another random entry',
                    completed: false
                }
            ]
        },
        {
            name: 'Default',
            id: 1,
            visibilityFilter: "SHOW_ALL",
            todos: [
                {
                    id: 0,
                    text: "Alpha Beta Gamma",
                    completed: true
                },
                {
                    id: 1,
                    text: "Lorem Ipsum",
                    completed: true
                },
                {
                    id: 2,
                    text: 'Something Something',
                    completed: false
                }
            ]
        },
    ]
};

let store = createStore(todoApp, initialState);

render(
    <Provider store={store}>
            <App />
    </Provider>,
    document.querySelector("#root")
);

My Reducers file
import { VisibilityFilters } from '../actions/index.js';
import {combineReducers} from 'redux';

function buckets(state = [], action) {
  console.log('buckets',state);
  switch (action.type) {
    case 'ADD_BUCKET': {
      return [...state, {
        name: action.text,
        id: action.id,
        visibilityFilter: "SHOW_ALL",
        todos: []
      }];
    }

    default: {
      return state;
    }
  }
}

function todos(state = [], action) {
  console.log('todos',state);
  switch (action.type) {
    case 'ADD_TODO': {
      return [...state, {
        text: action.text,
        completed: false,
        id: action.id
      }];
    }

    case 'TOGGLE_TODO': {
      return state.map((todo, id) => {
        if (id === action.id) {
          return Object.assign({}, todo, {
            completed: !todo.completed
          });
        }

        return todo;
      });
    }

    default: {
      return state;
    }
  }
}

function visibilityFilter(state = VisibilityFilters.SHOW_ALL, action) {
  console.log('visibilityFilter',state);
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER': {
      return action.filter;
    }

    default: {
      return state
    }
  }
}

let todoApp = combineReducers({
  visibilityFilter,
  todos,
  buckets
});

export default todoApp;

My github repo: https://github.com/iamrkcheers/ToDoList
Any help is appreciated.
Thank You.


text:
Q: Why am I getting a 500 Error when using PayPal uses IPN to WooCommerce? I'm using WooCommerce version 3.3.5 and I'm trying to get the IPN to work so that my orders get updated.
I added https://example.com/?wc-api=WC_Gateway_Paypal  as my notification URL in PayPal.
I'm currently getting a 500 error "PayPal IPN Request Failure" when the order is processed.
What am I doing wrong or what do I have to do to fix this problem.
Thanks in Advance


text:
Q: linq union merging sublists Given a list of objects as follows:
Instance
 - InstanceID

Version
 - VersionID
 - List<Instance> Instances

Activity
 - ActivityID
 - List<Version> Versions

I want to produce a list like this:
Activity
 - ActivityID
 - List<Instance> Instances

currently stuck at:
(from activity in activities
 select new {
            activity.ActivityID,
            VersionGroup = (from version in activity.Versions
                            group version by version.ActivityID into versionGroup
                            select versionGroup)
            })

Just not sure how to get to the instance level.
(from activity in activities
 select new { activity.ActivityID,
              Instances = activity.ActivityVersions.SelectMany(v => v.ActivityInstances).AsEnumerable() });

A: You can use the SelectMany method to flatten a sublist:
var result = activities.Select(a => new
{
    a.ActivityId,
    Instances = a.Versions.SelectMany(v => v.Instances)
                          .GroupBy(i => i.InstanceID)
                          .Select(grp => grp.First())
                          .ToList()
});

You can relpace the GroupBy logic with a Distinct with a custom IEqualityComparer<Instance>:
var result = activities.Select(a => new
{
    a.ActivityId,
    Instances = a.Versions.SelectMany(v => v.Instances)
                          .Distinct(new InstanceComparer())
                          .ToList()
});

class InstanceComparer : IEqualityComparer<Instance>
{

    public bool Equals(Instance x, Instance y)
    {
        return x.InstanceID == y.InstanceID;
    }

    public int GetHashCode(Instance obj)
    {
        return obj.InstanceID.GetHashCode();
    }
}

I haven't done the null check but they are trivial. This is, of course, assuming this is LINQ to Object as there is no tags that says otherwise.


text:
Q: How to ignore a character in split method My file has the data in this format:
Name,Sal,Address,Location
Mike,"£10,732",xxxxxx,GBR
Bob,"£6,450",xxxxxxx,Fra
Arthur,"£8,320",xxxxx,Spa
James,"£7,423",xxxxxxxxxxxx,IRE

I need to read this data into a string array. In my new file I need to write Name,Sal and Location columns only. Here is my code:
    Dim ioReader As New System.IO.Streamreader("C:\old.csv")
    ioLines="Name,Sal,Location"
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    While Not ioLine = ""
        ioLine = ioFile.ReadLine
        Dim values As String()
        If ioLine <> "" Then
            values = ioLine.Split(",")
            Dim outPut as string=values(0) & values(1) & values(3)
            ioLines += System.Environment.NewLine & outPut
        EndIf

When I am splitting the above data, the sal column values which already contains "," is splitting into 2 cells. I want to keep the sal column value as a single cell by ignoring "," in between numbers. Any suggestions please?

A: Looks like you are parsing CSV, if yes you can use
Microsoft.VisualBasic.FileIO.TextFieldParser

e.g.
Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","c}
        MyReader.HasFieldsEnclosedInQuotes = True
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
    Try
        currentRow = MyReader.ReadFields()
        ' Include code here to handle the row.
    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
        MsgBox("Line " & ex.Message &
        " is invalid.  Skipping")
    End Try
End While
End Using

A: Quick and dirty solution:
Dim outPut as string=values(0) & values(1) & "," & values(2) & values(5)

The input file is not proper CSV - the fields with , should be escaped (surrounded with "):
Name,Sal,Address,Location
Mike,"£10,732",xxxxxx,GBR
Bob,"£6,450",xxxxxxx,Fra
Arthur,"£8,320",xxxxx,Spa
James,"£7,423",xxxxxxxxxxxx,IRE

And I wouldn't use string.Split but a CSV parser - you could use the TextFieldParser class.

A: Another quick and dirty...
using System.Text.RegularExpressions;

private void Test(){
    Regex rex = new Regex(@"(?<!£\d*),");
    string[] s = rex.Split(@"Name,Sal,Address,Location Mike,£10,732,xxxxxx,GBR Bob,£6,450,xxxxxxx,Fra Arthur,£8,320,xxxxx,Spa James,£7,423,xxxxxxxxxxxx,IRE");
}

The regex will not split on comma preceeded by a pound-sign and digits. However this will only allow for one comma in the currency and so £10,342,234 will break it...


text:
Q: How do I return argument(s) as string in javascript? I'm trying to make a function which can return argument(s) when it's called.
example( fooObject.foo[1] );
//return "fooObject.foo[1]"

example( fooFunc("foo",42) );
//return "fooFunc(\"foo\",42)"

like this.
I found out that I can get each arguments by using "arguments" method in the function, but cannot find the way to make the argument into the string.

A: This is not possible. A function is called with the values of its arguments, not the expressions that formed them. There is no way to access the code of the expressions as strings.

A: what you are asking depends on how you define your function,
its very simply
function(a){return a}

whatever you passed in you will get out


text:
Q: What is the word for thinking philosophically about life? I want to complete this sentence:

Here we stand, around ten or fifteen years ago, when I started _____ about life.

The thinking is not necessarily focused on one particular topic. The closet word to think I found is meditate, but it too focuses on "religious or spiritual purposes or as a method of relaxation".

A: I would use contemplate, and simply drop the word "about":

Here we stand, around ten or fifteen years ago, when I started contemplating life.

A: To philosophise:

to talk for a long time about subjects such as the meaning of life:

*

*Students, she complained, had nothing better to do than spend whole days philosophizing about the nature of truth.

(Cambridge Dictionary)
Also
speculate conveys a more general and wider sense of thinking about something:

*

*to meditate on or ponder a subject :  reflect

(M-W)

A: muse (MWD)

to become absorbed in thought; especially :  to think about something carefully and thoroughly musing about what might have been

A:
Here we stand, around ten or fifteen years ago, when I started thinking
   existentially about life.

If something is existential, it has to do with human existence. If you wrestle with big questions involving the meaning of life, you may be having an existential crisis. (vocabulary.com)

A: Philosophize, or philosophise, is probably the most suited to this task especially since it consists of the word and a suffix
http://www.thefreedictionary.com/philosophize

Here we stand, around ten or fifteen years ago, when I started philosophising about life.

A: contemplation:

deep reflective thought:

*

*he would retire to his room for study or contemplation.

(Mac OS Dictionary)

A: There are still many options :

Cogitate -  to think over.
Perpend - to reflect on carefully.

A: One choice would be ruminating. See ruminate defined by Oxford dictionary as

Think deeply about something.

A: To ponder

to think or consider especially quietly, soberly, and deeply

Used in your sentence, it would probably work best as "pondering life," rather than "pondering about life."

A: I would consider saying you began to "wax philosophical."

Wax philosophical - To take on a quality or state of thinking or talking of deep subjects such as the meaning of life.

Is there any other way you can "wax" as you do when you "wax philosophical"?

A: Metaphysics is, per Merriam-Webster,

a (1) :  a division of philosophy that is concerned with the fundamental nature of reality and being and that includes ontology, cosmology, and often epistemology
  (2) :  ontology 2
b :  abstract philosophical studies :  a study of what is outside objective experience

which I think may be what you are trying to get at in your description of "thinking philosophically about life". If so, you can use the verb metaphysicize:

-ed/-ing/-s
  :  to engage in metaphysical speculation

You wouldn't even need to use the last two words of your sentence; you could simply say

Here we stand, around ten or fifteen years ago, when I started metaphysicizing/to metaphysicize.

You don't need to say "about life" since the word on its own includes thinking philosophically about life, the universe, and everything.
On the other hand, if you don't so much mean that you started thinking deep thoughts about life but rather that you became more philosophical about life, in the sense

2 :  characterized by the attitude of a philosopher; specifically :  calm or unflinching in the face of trouble, defeat, or loss

then you may want to use a longer phrase like "to become more philosophical" or "to be more contemplative" or "to attain serenity".

A: Apart from ponder and contemplate, I would say you could use mull -

Think about (something) deeply and at length.
"She began to mull over the various notions to life"

It gives a feeling of serious contemplation which could be expected when one is thinking about topics like the one you have described.


text:
Q: How do I reference a vector from a map's value? #include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
  vector<string> examplevector {"one", "two", "three"};
  map<string, vector<string>> examplemap {{"vector1", examplevector}};

  examplemap["vector1"][0] = "eight";

  cout << examplemap["vector1"][0] << endl; // prints "eight"
  cout << examplevector[0] << endl; // prints "one". I was expecting "eight".

}

Is there a way to alter the values within examplevector via examplemap["vector1"]?

A: No, C++ does not work this way, this is not how objects work in C++. This is how objects work in Java and C#, but C++ is not Java or C#. Objects that are stored in some container, a vector, a map, or any other container, are distinct objects of their own and have nothing to do with any other object.
map<string, vector<string>> examplemap {{"vector1", examplevector}};

This effectively makes a copy of the examplevector and stores it in the map. Changes to the object in the map have no effect on the original examplevector. Similarly:
string abra="cadabra";

std::vector<std::string> examplevector{"hocuspocus", abra};

// ...
examplevector[1]="abracadabra";

This modifies the object in the vector. abra is still cadabra.
It's possible to store a map or a container of pointers, or perhaps std::reference_wrappers. Then, modify the pointed-to object, or wrapped reference, will modify the underlying object. But that introduces its own kind of complexity, in terms of managing the lifetime of all objects, correctly.

A: If you want to alter the values of examplevector via your map you should declare your map as a map of strings associated to vector pointers, therefore you can alter the original vector using its reference in the map.
Adapting your code, it will become like:
#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
  vector<string>* examplevector = new vector<string>({"one", "two", "three"});
  map<string, vector<string>*> examplemap = {{"vector1", examplevector}};

  examplemap["vector1"]->at(0) = "eight";

  cout << examplemap["vector1"]->at(0) << endl; // prints "eight"
  cout << examplevector->at(0) << endl; // prints "eigth", as expected.

}


text:
Q: Bundling 2 .exe's together in a C# application I want to write an application that launches another app using Process.Start , but that app is a .exe, can I bundle that into my C# app without it being outside in a folder? I want to make it so my app doesn't need to install at all, so can it be in the app?

A: Not entirely sure if I understand, but do you mean so you can ship it and send it around as a single .exe (rather than zipping it all up)?
Could you embed the .exe in as an embedded resource and have your own .exe put it in some temporary files?

A: You want to make two exe's look like one exe?
There is no reasonable way to do this.  Are you using someone else's program and don't want people to know?


text:
Q: How to add custom classes to more than one separate menu's a link in wordpress? Here is a link to my website: website
I have placed the following code to this document in /wp-includes/nav-menu-template.php
Towards the end of the code are several lines that start with $item_output. In particular, you want to look at this piece:
$item_output .= '';

Because this line determines the output for the beginning of the link html. I have changed it to something like this:
$item_output .= '';

Then all your links in the menu will have class="btn btn-warning btn-block" added to them.

That said, it doesn't allow a custom class for each menu and I several menus that don't need the class="btn btn-warning btn-block" inside of the a link. (or at least I don't know how to code it). This is an issue for me.
Does anyone know how to code this request?
For those asking why would you want to do this? I want to have my main (top) menu links to be buttons.
Here is the function I'm using to call the menu:

<?php

$defaults = array(

'theme_location'  => '',

'menu'            => 'main-nav',

    'container'       => 'ul',

'container_class'    => 'nav navbar-nav',

    'before'          => '',

'after'           => '',

'menu_class'      => '',

'menu_id'         => 'menu',

'echo'            => true,

'fallback_cb'     => 'wp_page_menu',

'link_before'     => '',

'link_after'      => '',

'items_wrap'      => '
%3$s
',

'depth'           => 0,

'walker'          => ''

);

wp_nav_menu( $defaults );

?>

A: Just use CSS to style your #nav li block.
This is quick, but would make your links into buttons.
    #nav li {
        list-style: none;
        background: #F00;
        width: 120px;
        margin-right: 60px;
        padding: 10px;
        text-align: center;
}

you can add a hover class too like #nav li:hover


text:
Q: How to solve DLL load failed:A dynamic link library (DLL) initialisation routine failed. of Tensorflow? I am using Python 3.7.3 and pip version 20.1 and I installed tensorflow 2.0 using pip. I've successfully installed tensorflow. But when I try to run import tensorflow as tf it shows error as ImportError: DLL load failed: A dynamic link library (DLL) initialisation routine failed.
Failed to load the native TensorFlow runtime.
I've gone through the link provided along with the error but couldn't find this particular type of error. If Anyone has faced this typeof error and solved it please help me solve too.
>>> import tensorflow as tf
Traceback (most recent call last):
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialisation routine failed.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 98, in <module>
    from tensorflow_core import *
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Aayush\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialisation routine failed.

Failed to load the native TensorFlow runtime.

A: New version of tensorflow (for example I am using tensorflow v2.2) windows installation needs Microsoft Visual C++ 2019 Redistributable
https://www.tensorflow.org/install/source_windows#install_visual_c_build_tools_2019
After you have install Microsoft Visual C++ Redistributable for Visual Studio 2019 from https://visualstudio.microsoft.com/downloads/ under the section Other Tools and Frameworks, you will be able to run it.


text:
Q: How to export the whole page or html content with Highcharts not just the chart? hi all my chart is exporting fine with highcharts i m getting the chart for my php project
but the problem is
that i am looking to import html content or the whole page along with the chart not just the chart
is it possible to do ??
can any one help me
or show here is a sample fiddle http://jsfiddle.net/YBXdq/
i need to export the text below the chart has well

A: You can try to print the page , or make a pdf using php file functions to get the desired html content .
or you can try the method told by baba to get the image :)

A: There are so many direct and indirect way to achieve this

*

*Use HTML Canvas : http://html2canvas.hertzen.com/

*Using wkhtmltoimage
Example
  exec('wkhtmltoimage --quality 50 http://www.bbc.com bbc.jpg');

*

*Using wkhtmltopdf + ImageMagic
-- Convert the web page to pdf using wkhtmltopdf
-- Convert pdf to jpg  using ImageMagic
Example
exec("convert a.pdf a.jpg");

*

*Use PHP imagegrabwindow and imagegrabscreen
Example
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://localhost");

/* Still working? */
while ($browser->Busy) {
    com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();

header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);

Advance Examples
-- Also See Get Website Screenshots Using PHP
For Possible Issues : Getting imagegrabscreen to work

*

*use Webshort and call it from php using exec if you have python installed

Example
exec("python webshot.py https://example.com/webshot/php example.png");

*

*Download and use Website Thumbnail Generator
Example
webthumb.php?url=http://www.google.com&x=150&y=150

*

*Use boxcutter
Example
exec('boxcutter -f image.png');

*

*Capture Screenshots in PHP with GrabzIt
Example
$grabzIt = new GrabzItClient("APPLICATION KEY", "APPLICATION SECRET");
$id = $grabzIt->TakePicture("http://www.google.com", "http://www.example.com/GrabzItHandler.php");

*

*using wimg.ca
Example with this current page
  http://wimg.ca/https://stackoverflow.com/questions/10328457/how-to-export-the-whole-page-or-html-content-with-highcharts-not-just-the-chart/10330701#10330701

*

*TimThumb – PHP Image Resizer
Example
 timthumb.php?src=http://www.google.com/&webshot=1

I think have given more than enough example

A: i  found a simple workaround for exporting charts (printing)
and
i didn't use any plugin just little plain old css and some javascript
which in my case is
i wanted to print the chart with some specific html content of the page
or in my case i wanted to remove header , footer and left menu
i dint wanted to show buttons or unecessary content
and just show the page content , description table and chart
so here is i how i achieved it.
> CSS :-

<style type="text/css">
@media print{
@page
        {
            size: auto;   /* auto is the initial value */
            margin: 0mm;  /* this affects the margin in the printer settings */
        }
  body{ background-color:#FFFFFF; background-image:none; color:#000000 }
  .navimainbg{ display:none;}
  .printhide{ display:none;}
  .usercontent-footer{ display:none;}
  .linkBTN{ display:none;}
  .userheader{ display:none;}
  .user-profile-left{ display:none;}
  #userbgcontent{ width:100%;}
}
</style>

We are focussing on the print css here which we implied when the page is printed
acess the divs or portions of the page which you dont want ot be printed via their class or id depending upon your usage
for example
i didnt wanted to display the button
 .linkBTN{ display:none;}

which can be simply called via javascript.
Javascript :->

<script type="text/javascript">

function printpage()
{

window.print()
}

<script type="text/javascript">

we can invoke the print function to print the page minus elements we dont want to print with the page via click of a button by calling function in my case "printpage" as you can
see this button will also not display while printing as printhide class display is set to none while priting
<input title="Print a Printer Friendly Page" class ="printhide" type="button" value="Print this page" onclick="printpage()">

isnt is it a simple way to print chart other than highcharts printing if you want to print more
only con is that sometime the image will slide down when you want to show it along with some conetent due to lack of size to render an image . it will shift to next page . other than its tested working .


text:
Q: Change format input type='date' from mm-dd-yyyy to dd-mm-yyyy Laravel I am trying to change date format in laravel from mm-dd-yyy to dd-mm-yyyy
<input type="date" class="form-control" name="joining_date" id="joining_date" required>

I tried even to put timezone="[[timezone]]" but nothing changes.

A: Convert that date in controller before feeding to database like this :
$originalDate = $request->joining_date;
$newDate = date("dd-mm-YYYY", strtotime($originalDate));

Or if you want to show in view the same date
{{ date("dd-mm-YYYY", strtotime($date_from_controller)); }}

if you want to pre populate input field then
<input type="date" class="form-control" name="joining_date" id="joining_date" value="{{ date("dd-mm-YYYY", strtotime($date_from_controller)); }}" required>

if you want to change the format of input date then
<input type="text" name="input" placeholder="dd-mm-yyyy" required pattern="(?:30))|(?:(?:0[13578]|1[02])-31))/(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])/(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])">

Hope this helps you.

A: Carbon::createFromFormat('mm-dd-yyy', $input)
  ->format('dd-mm-yyyy'); `

A: You should try this:
$date =  date('d-m-Y', strtotime($request->date));

A: date_create_from_format('mm-dd-yyy', $input)->format('dd-mm-yyyy');


text:
Q: Swift - subview of UICollectionReusableView doesn't fit with width I have a UICollectionViewController with a UICollectionReusableView (header).
In this UICollectionReusableView, I have a subview (in pink).

I have set some constraints to give to the subview, a full screen width.
It's working perfectly for the background img (in black). However, concerning the subview, it's working only with the iPhone 6 dimensions (it's too large for iPhone 5s and not enough for iPhone 6 plus for example). I really don't know why it's working for the background image and not for this subview. The pink subview is "Radius View on Top" and the image in the background is "Ban img".
I have tried to code this in the UICollectionReusableView's awakeFromNib()
let width = UIScreen.main.bounds.size.width
self.widthConstraintRadiusView.constant = width

Edit
I have found something:

I can see that the subview has the right width, but it's not stretched? How is it possible? What do I have to understand?

Edit 2
If I use the function roundCorners on the subview, it's not working:
func roundCorners(_ corners:UIRectCorner, radius: CGFloat) {
      let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
      let mask = CAShapeLayer()
      mask.path = path.cgPath
      self.layer.mask = mask
   }

radiusViewOnTop.roundCorners([.topLeft,.topRight], radius: 7)

How could I keep the function and have the right width?

A: With your latest edit I know why it's not working, and it's a simple fix.
Your view is being sized properly, but the mask you are adding is the wrong size.
You designed your interface with the iPhone 6 size, and those are the dimensions the view is loaded with. After that it performs a layout pass on your view to update the size to whatever the actual size should be.
However, you are probably calling the round corners method on awakeFromNib or something similar, which happens after the view is loaded but before the size is updated.
The fix is simple, override layoutSubviews, call super first and then call the roundCorners: method.


text:
Q: Unexpected results with SELECT INTO I've got a table valued function created in MSSQL that takes in 2 paramateres
1. End Date
2. Number of weeks to go back
to generate a table of dates with the week start date.
The PERIOD table simply is a table with 1 column (called pPeriod) with all the dates between '19971229' and '20201231'
CREATE FUNCTION [dbo].[Get_Week_Rank]
(
    -- Add the parameters for the function here
    @PERIOD_END DATETIME,
    @NUM_WEEKS INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT A.PPERIOD TY_PPERIOD, B.PPERIOD TY_PWKSTART, DATEADD(YY, -1, A.PPERIOD) LY_PPERIOD, DATEADD(YY, -1, B.PPERIOD) LY_PWKSTART, B.CRNK WEEK_RANK  FROM (
        SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY PPERIOD) CRNK FROM PERIODS
            WHERE PPERIOD BETWEEN DATEADD(WW, @NUM_WEEKS - 1, @PERIOD_END)  + 1 AND @PERIOD_END
        ) AS A
        JOIN (
            SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY CRNK % 7) CRNK FROM (
                SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY PPERIOD) CRNK FROM PERIODS
                    WHERE PPERIOD BETWEEN DATEADD(WW, @NUM_WEEKS, @PERIOD_END)  +  1 AND @PERIOD_END
                ) AS A
                WHERE CRNK % 7 = 1
            ) AS B ON (A.CRNK - 1)/7 = B.CRNK
)

I noticed then when @NUM_WEEKS is between -1 and -130, the results are correct when running this query:
SELECT * INTO #WEEKS FROM GET_WEEK_RANK('20160401', -104)
SELECT * FROM #WEEKS ORDER BY 1

However, any number below -130 (eg -156, -208), the returned results are all wrong.
Wrong results
You can see that TY_PWKSTART is all jumbled up and not in sync with TY_PPERIOD.
If I run the query directly, the results return fine:
SELECT * FROM GET_WEEK_RANK('20160401', -140)

What could be the issue? I am using Microsoft SQL Server 2014
EDIT: Posting images of results
As you can see, both queries essentially do the same thing, but the results returned are different. The order of pWkStart in the first query when using SELECT INTO is wrong.
Wrong results:
SELECT * INTO #WEEK_WRONG FROM GET_WEEK_RANK('20160410', -140)
SELECT * FROM #WEEK_WRONG ORDER BY 1

Correct results:
CREATE TABLE #WEEK_CORRECT (TY_PPERIOD DATETIME, TY_PWKSTART DATETIME, LY_PPERIOD DATETIME, LY_PWKTART DATETIME, WEEK_RANK INT)
INSERT INTO #WEEK_CORRECT
SELECT * FROM GET_WEEK_RANK('20160410', -140)
SELECT * FROM #WEEK_CORRECT ORDER BY 1

EDIT2:
Turns out that my initial query was producing unexpected results. I've fixed my query and managed to get consistent results from SELECT INTO and INSERT INTO.
Just sharing the code here:
CREATE FUNCTION [dbo].[Get_Week_Rank]
(
    @PERIOD_END DATETIME,
    @NUM_WEEKS INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT A.PPERIOD TY_PPERIOD, B.PPERIOD TY_PWKSTART, DATEADD(YY, -1, A.PPERIOD) LY_PPERIOD, DATEADD(YY, -1, B.PPERIOD) LY_PWKSTART, B.CRNK + 1 WEEK_RANK  FROM (
            SELECT PPERIOD, (ROW_NUMBER() OVER (ORDER BY PPERIOD)-1)/7 CRNK FROM PERIODS
                WHERE PPERIOD BETWEEN DATEADD(WW, @NUM_WEEKS, @PERIOD_END)  + 1 AND @PERIOD_END
        ) AS A
        JOIN (
            SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY PPERIOD)-1 CRNK FROM (
                SELECT PPERIOD , ROW_NUMBER() OVER (PARTITION BY CRNK ORDER BY CRNK) CRNK FROM (
                    SELECT PPERIOD, (ROW_NUMBER() OVER (ORDER BY PPERIOD)-1)/7 CRNK FROM PERIODS
                        WHERE PPERIOD BETWEEN DATEADD(WW, @NUM_WEEKS, @PERIOD_END)  +  1 AND @PERIOD_END
                    ) AS A
                ) AS A
                WHERE CRNK = 1
            ) AS B ON A.CRNK = B.CRNK
)

A: This part of your query is broken:
SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY CRNK % 7) CRNK FROM (
    ...
) AS A
WHERE CRNK % 7 = 1

Since the where clause establishes that CRNK % 7 is equal to 1, the ROW_NUMBER() expression is free to assign row numbers in any order1. I would guess that you still would want to assign row numbers in the order in which PPERIOD or CRNK values work, and so the expression should instead by:
SELECT PPERIOD, ROW_NUMBER() OVER (ORDER BY CRNK) CRNK FROM (
    ...
) AS A
WHERE CRNK % 7 = 1

1Since you haven't provided enough expressions in the ORDER BY for row numbers to be assigned unambiguously, there's no guarantee on the values assigned to each row.


text:
Q: How to find discretezation error of NDSolve Is there a way to find out how large the truncation, round-off, and other errors that occur from discretizing a differential equation are while using the default settings in NDSolve? Or would I have to explicitly ask Mathematica to solve the problem using 4th order Runge-Kutta, Adams, etc and find the errors myself.
I did find this link: http://reference.wolfram.com/mathematica/howto/CheckTheResultsOfNDSolve.html
helpful, but I am wondering what other methods are available.


text:
Q: Switching between browsers using Linktext in Selenium This is how you can switch  browsers pages using linkText in Selenium as below

A:   public class locatorsPractice {

  public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.gecko.driver","/path");
    WebDriver driver =new FirefoxDriver();
    driver.manage().window().maximize();
    driver.navigate().to("https://browser url");

    String strMainWindowHandle=driver.getWindowHandle();
    System.out.println("Window title"+driver.getTitle());

    driver.findElement(By.linkText("Google")).click();
    Set <String> strHandles=driver.getWindowHandles();
    for (String handle:strHandles) {
        driver.switchTo().window(handle);
        String strTitle=driver.getTitle();
        if(strTitle.equalsIgnoreCase("Google")) {
            System.out.println(driver.getTitle());
            driver.manage().window().maximize();
            Thread.sleep(2000);
            driver.close();
        }
    }
    }}


text:
Q: How to concat all values from a row into a single varchar in SQL? I want to know if there is a way to concatenate all fields in a row, in a single NVARCHAR field.
Say, if I have a table like this:
FieldA             FieldB                FieldC
---------------------------------------------------------
Abc                 Bcd                    123
Cde                 Def                    234
                        ...

Is there a way to get either a table with a single column, with the concatenated values, like:
Field
-------------
AbcBcd123
CdeDef234
  ...

Or this same operation but for a single row?, and then I could just iterate over the rows some other way and do the operation on each row separately.
The number of fields in this table is always variable, it could be three, like in this example, or all the way to around 100 columns, that's why I don't do something like simply:
SELECT
    CONCAT(t.FieldA, t.FieldB, t.FieldC)
FROM
    TestTable t

A: Please try the following solution.
It will work for any table with any number of columns. It just needs a primary key column.
It is based on XML and XQuery. No need for any dynamic SQL.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, ColA VARCHAR(10), ColB CHAR(3), ColC INT);
INSERT INTO @tbl (ColA, ColB, ColC) VALUES
('Abc', 'Bcd', 123),
('Cde', 'Def', 234);
-- DDL and sample data population, end

SELECT p.*
    , result = c.query('/root/*[not(local-name()="ID")]/text()').value('.', 'VARCHAR(MAX)')
FROM @tbl AS p
CROSS APPLY (SELECT * FROM @tbl AS c WHERE p.ID = c.ID
        FOR XML PATH(''), TYPE, ROOT('root')) AS t1(c);

Output
+----+------+------+------+-----------+
| ID | ColA | ColB | ColC |  result   |
+----+------+------+------+-----------+
|  1 | Abc  | Bcd  |  123 | AbcBcd123 |
|  2 | Cde  | Def  |  234 | CdeDef234 |
+----+------+------+------+-----------+


text:
Q: Intranet, no Internet after switch to static IP on OS X I have a Linksys WRT54GS and have two machines on my network connecting wirelessly. DHCP is enabled, and is granting IP addresses in the .100-120 range. The one machine is a laptop running Ubuntu 10.04 and it is working via DHCP, IP address .103.
The second machine, OS X 10.4, I set to a static IP in order to allow port forwarding from the router, as per these instructions: http://portforward.com/networking/static-Mac10.4.htm. It's grabbing an IP address outside of the DHCP range; .13.
Since I did so, the Mac can see the local network, and I can access the router config from it, but all traffic outside of my LAN is blocked for that machine. I see no settings indicating any sort of filter or rules that would block web access.
Where did I go wrong?

A: When manually configuring the 10.4 machine, did you enter the subnet mask and the router's address correctly?
When testing off-network connectivity, did you try connecting to things by IP address or just by name? Because maybe you forgot to enter a valid DNS server address on your 10.4 client, and since it's not getting that information via DHCP anymore, it doesn't know who to ask when it needs to look up the IP address for a given hostname.

A: Are you trying to use the "DHCP with Manual IP" setup available in OS X's Network system preferences? I personally have never gotten that to work properly. Make sure you're configuring TCP/IP "Manually" and copying all of the addresses (Including DNS) from what would be distributed by DHCP except for the IP address.
Something else I would recommend, not as a fix but as an advanced alternative, would be to set up your router to do some static DHCP: distribute a predetermined IP address to the 10.4 machine based on the MAC address of its ethernet interface. You probably can't do this with the stock firmware on that router, but that router is well known in the community to be a good candidate for alternative firmware such as DD-WRT. I personally have had great success with Tomato, which is very lightweight and easy to use, while drastically expanding on the limited feature set of Linksys stock firmware.


text:
Q: Simple.Data Sqlite Insert returns Null Im using Simple.Data to insert data into an Sqlite database. I read on the wiki that Insert returns the inserted data. I need to get the latest rowID (identity). But I get Null instead.
Using the Stable version from NuGet.
var db = Database.OpenFile("Database.db");
var x = db.Scan.Insert(Name:"Test", Description:"test", CreationDate:DateTime.Now, DocumentDate:DateTime.Now, ModifiedDate:DateTime.Now);

DB schema:
CREATE TABLE Scan (
    ID           INTEGER         PRIMARY KEY,
    Name         NVARCHAR( 50 )  NOT NULL,
    Description  TEXT,
    CreationDate DATETIME        NOT NULL,
    DocumentDate DATETIME        NOT NULL,
    ModifiedDate DATETIME        NOT NULL
);

Does this even work for SQLite? If not whats the best way to retrieve the rowID of the inserted record?

A: Had the same "issue".
The problem lies within your schema.
You have to add identity to your primary key column:
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,

Then you get back the row and you can i.e. create a new object with it:
var x = db.Scan.Insert(Name:"Test", Description:"test", CreationDate:DateTime.Now, DocumentDate:DateTime.Now, ModifiedDate:DateTime.Now);
return new Scan { ID = (int)x.ID, Name = x.Name, ... }

From the Wiki:

If you have an IDENTITY column defined on your table, then the Insert
  methods will all return a copy of the record fetched from the
  database, so all defaulted values are set. In 0.4, support for other
  ways of fetching the inserted row will be added.


text:
Q: Print Table with List Variable From Entities in MVC I've not worked MVC for a long time; I'm a fresh guy to this. So, I have these two entities:
// Entity Worker

[Display(Name = "ID")]
public Int32 Id { get; set; }

[Display(Name = "Número")]
public Int32 Numero { get; set; }

[Display(Name = "Nome")]

// Entity Lottery

public Int32 Id { get; set; }

[Display(Name = "Tipo")]
public String Tipo { get; set; }

[Display(Name = "Data")]
public DateTime Data { get; set; }

[Display(Name = "Observações")]
public List<Worker> FuncionariosSorteados { get; set; }

So, for each lottery entity, I will have a List of workers. I am passing the values to the View by the controller, like this:
public ActionResult Details(int id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Lottery lottery = service.FindLottery(id);
    if (sorteio == null)
    {
        return HttpNotFound();
    }
    return View(lottery);
}

Where the service is my Repository for the connection to database (in this case he do a search by ID on database to get the right lottery.
Here my doubt begin, if I want to do a table for the lotteries, I can do it doing (using Lottery model)
@foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Tipo)

                @Html.DisplayFor(modelItem => item.Data)

                @Html.DisplayFor(modelItem => item.Observacoes)

    }

But how I can do the same for the public List<Worker> FuncionariosSorteados? I just want to print the public List<Worker> FuncionariosSorteados in a GridMvc table, but through the model I cant have access to it!

A: I believe you need to iterate through the list within the foreach loop you already created. Something like this:
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Tipo)

            @Html.DisplayFor(modelItem => item.Data)

            @Html.DisplayFor(modelItem => item.Observacoes)

    @foreach(var w in Model.FuncionariosSorteados )
    {

        @Html.DisplayFor(w => w.Id)
        @Html.DisplayFor(w => w.Numero)

    }

}

A: I'm confused because in your action, you're pulling a single lottery record and passing that to your view, but in your view, you're iterating through what appears to be an IEnumerable<Lottery>.
Since you'd have no issues accessing FuncionariosSorteados off of a Model of type Lottery, I'm assuming the view is actually using IEnumerable<Lottery>. For an enumerable, you have to iterate over the list and access the properties on the individual items. For example:
@model IEnumerable<Lottery>

@Model.FuncionariosSorteados

@foreach (var lottery in Model)
{
    @lottery.FuncionariosSorteados
}

A: For your second entity you could create it like this:
Entitie Lottery
public Lottery( )
{
  FuncionariosSorteados = new List <Worker>();
  }
public Int32 Id { get; set; }
[Display(Name = "Tipo")]
public    String Tipo { get; set; }
[Display(Name = "Data")]
public DateTime Data { get; set; }
 [Display(Name = "Observações")]
 public virtual List<Worker> FuncionariosSorteados { get; set; }

And thenin your view you can use a foreach loup to iterate inside the lists


text:
Q: How to use Rsync in terminal? I use windows 10 and install mvware to run centOS 6.5.
I try with rsync in terminal.
         rsync -avz + source + dest

        ===>>>>  rsync -avz /John/ServerA/* /John/ServerB/

the file and directory are transfered, but when I edit config.txt file in ServerA (source) the serverB (Dest) not change. means it not synchronized.
please, give me expert.
Thank you.


text:
Q: Cascading to a auto completing text box I have a web page where the user will enter their address. They will select their country and region in cascading drop down lists. I would like to provide an auto completing textbox for their city, but I want to be context sensitive to the country and region selections. I would have just used another cascading drop down list, however the number of cities exceeds the maximum number of list items.
Any suggestions or cool code spinets out there that may help me out?

A: I just found the following blog post that looks at least close to what you want.
They manage it using the following javascript functions:
    function initCascadingAutoComplete() {
        var moviesAutoComplete = $find('autoCompleteBehavior1');
        var actorsAutoComplete = $find('autoCompleteBehavior2');
        actorsAutoComplete.set_contextKey(moviesAutoComplete.get_element().value);
        moviesAutoComplete.add_itemSelected(cascade);

        // setup initial state of second flyout
        if (moviesAutoComplete.get_element().value) {
            actorsAutoComplete.get_element().disabled = false;
        } else {
            actorsAutoComplete.get_element().disabled = true;
            actorsAutoComplete.get_element().value = "";
        }
    }

    function cascade(sender, ev) {
        var actorsAutoComplete = $find('autoCompleteBehavior2');
        actorsAutoComplete.set_contextKey(ev.get_text());
        actorsAutoComplete.get_element().value = '';
        if (actorsAutoComplete.get_element().disabled) {
            actorsAutoComplete.get_element().disabled = false;
        }
    }
    Sys.Application.add_load(initCascadingAutoComplete);

Calling the cascade function on the add_itemSelected method of the parent control for the cascading behaviour.
They cascade the contents of one auto complete extender into another, rather than taking a cascading drop down list, but hopefully you can reuse some of the ideas.