问:
Unicode and UTF-8 encoding issue with Scrapy XPath selector text
I'm using Scrapy and Python (as part of a Django project) to scrape a site with German content. I have libxml2 installed as the backend for Scrapy selectors.

If I extract the word 'Hüftsitz' (this is how it is displayed on the site) through selectors, I get: u'H\ufffd\ufffdftsitz' (Scrapy XPath selectors return Unicode strings).

If I encode this into UTF-8, I get: 'H\xef\xbf\xbd\xef\xbf\xbdftsitz'. And if I print that, I get 'H??ftsitz' which isn't correct. I am wondering why this may be happening.

The character-set on the site is set to UTF-8. I am testing the above on a Python shell with sys.getdefaultencoding set to UTF-8. Using the Django application where the data from XPath selectors is written to a MySQL database with UTF-8 character set, I see the same behaviour.

Am I overlooking something obvious here? Any clues or help will be greatly appreciated.

答:
Thanks very much for your answers, John and Steven. Your answers got me thinking differently, which led me to find the source of the problem and also a working solution.

I was working with the following test code:

```<code>import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse

URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"

url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)

handle = url_handler.open(URL)
response = handle.read()
handle.close()

html_response = HtmlResponse(URL).replace(body=response) # Problematic line
hxs = HtmlXPathSelector(html_response)

desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')
</code>```

Inside the Scrapy shell, when I extracted the description data, it came out fine. It gave me reason to suspect something was wrong in my code, because on the pdb prompt, I was seeing the replacement characters in the extracted data.

I went through the Scrapy docs for the Response class and adjusted the code above to this:

```<code>import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse

URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"

url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)

handle = url_handler.open(URL)
response = handle.read()
handle.close()

#html_response = HtmlResponse(URL).replace(body=response)
html_response = HtmlResponse(URL, body=response)
hxs = HtmlXPathSelector(html_response)

desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')
</code>```

The change I made was to replace the line html_response = HtmlResponse(URL).replace(body=response) with html_response = HtmlResponse(URL, body=response). It is my understanding that the replace() method was somehow mangling the special characters from an encoding point of view.

If anyone would like to chip in with any details of what exactly the replace() method did wrong, I'd very much appreciate the effort.

Thank you once again.

Body:
Thanks very much for your answers, John and Steven. Your answers got me thinking differently, which led me to find the source of the problem and also a working solution.

I was working with the following test code:

import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse

URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"

url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)

handle = url_handler.open(URL)
response = handle.read()
handle.close()

html_response = HtmlResponse(URL).replace(body=response) # Problematic line
hxs = HtmlXPathSelector(html_response)

desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')

Inside the Scrapy shell, when I extracted the description data, it came out fine. It gave me reason to suspect something was wrong in my code, because on the pdb prompt, I was seeing the replacement characters in the extracted data.

I went through the Scrapy docs for the Response class and adjusted the code above to this:

import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse

URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"

url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)

handle = url_handler.open(URL)
response = handle.read()
handle.close()

#html_response = HtmlResponse(URL).replace(body=response)
html_response = HtmlResponse(URL, body=response)
hxs = HtmlXPathSelector(html_response)

desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')

The change I made was to replace the line html_response = HtmlResponse(URL).replace(body=response) with html_response = HtmlResponse(URL, body=response). It is my understanding that the replace() method was somehow mangling the special characters from an encoding point of view.

If anyone would like to chip in with any details of what exactly the replace() method did wrong, I'd very much appreciate the effort.

Thank you once again.


来源: stackexchange

问:
Can you configure what resources to monitor or does Stackdriver Logging automatically display all resources in use?
I'm interested in viewing logs in Stackdriver Logging using the filter: role_name:roles/owner

However, I can see that the IAM Role resource is not in the list of monitored resources. (This list refers to the first drop down box in Stackdriver Logging>Logs)

I understand from this documentation that there are many monitored resources.

I would like to know if these resources can be configured to be monitored (i.e. logged) or if Stackdriver logging automatically displays a list of resources in use by the project.

In the latter case, I would conclude that the resource IAM Role has not been configured to be monitored.

答:
Any monitored resource for which there is an associated log entry will be presented in the menu.

Keep in mind that you can always switch to the advanced filter mode in the viewer and provide the filter (assuming you're looking for "iam_role" resources) as

```<code>resource.type = "iam_role"
</code>```

It's not clear what question you're trying to answer by filtering on role_name. If you're looking for policy changes related to the role, they are recorded against the "project" resource type. You could look for

```<code>protoPayload.@type="type.googleapis.com/google.cloud.audit.AuditLog"
protoPayload.request.policy.bindings.role="roles/viewer"
</code>```

You can also query for actions taken by a particular user, like

```<code>protoPayload.@type="type.googleapis.com/google.cloud.audit.AuditLog"
protoPayload.authenticationInfo.principalEmail="user@example.com"
</code>```

FWIW, It is possible to exclude logs, which might cause the resource not to be presented if all of the associated logs are excluded, but this isn't allowed for the default-enabled audit logs.

ContentLicense: CC BY-SA 4.0

Body:
Any monitored resource for which there is an associated log entry will be presented in the menu.

Keep in mind that you can always switch to the advanced filter mode in the viewer and provide the filter (assuming you're looking for "iam_role" resources) as

resource.type = "iam_role"

It's not clear what question you're trying to answer by filtering on role_name. If you're looking for policy changes related to the role, they are recorded against the "project" resource type. You could look for

protoPayload.@type="type.googleapis.com/google.cloud.audit.AuditLog"
protoPayload.request.policy.bindings.role="roles/viewer"

You can also query for actions taken by a particular user, like

protoPayload.@type="type.googleapis.com/google.cloud.audit.AuditLog"
protoPayload.authenticationInfo.principalEmail="user@example.com"

FWIW, It is possible to exclude logs, which might cause the resource not to be presented if all of the associated logs are excluded, but this isn't allowed for the default-enabled audit logs.


问:
lumen5.8 Validator's "required_without" work unexpectedly
In my project, i use lumen 5.8(I create my project by "lumen new test" command ). And i use validation's(Illuminate\Support\Facades\Validator) required_without to validate my request parameters. But "required_without " didnot work correctly.

```<code>$fields = [
    'Field_1'     =>  'required_without: Field_2 | int',
    'Field_2'     =>  'required_without: Field_1 | int',
];

$validator = Validator::make($args, $fields);
if ($validator->fails()) {
    echo "Validate parameters fail. [Error] " . json_encode($validator->errors()) . "\n";
}
</code>```

1、if request data is：
{
  "Field_1": 1
}

--actually reuslt:
"Validate parameters fail. [Error] {"Field_2":["The field 2 field is required when field 1 is not present."]}

--expected reuslt: no error, because Field_1 field is set to 1, Field_2 is no need to be set.

2、if request data is：
{
  "Field_2": 2
}

--actually reuslt:
Validate parameters fail. [Error] {"Field_1":["The field 1 field is required when field 2 is not present."]}

--expected reuslt: no error

3、if request data is：
{
  "Field_1": 1,
  "Field_2": 2
}

--actually reuslt: no error

--expected reuslt: no error

答:
I believe you should file this as a bug in the Lumen source project.

https://github.com/laravel/lumen-framework/issues

Body:
In my project, i use lumen 5.8(I create my project by "lumen new test" command ). And i use validation's(Illuminate\Support\Facades\Validator) required_without to validate my request parameters. But "required_without " didnot work correctly.

$fields = [
    'Field_1'     =>  'required_without: Field_2 | int',
    'Field_2'     =>  'required_without: Field_1 | int',
];

$validator = Validator::make($args, $fields);
if ($validator->fails()) {
    echo "Validate parameters fail. [Error] " . json_encode($validator->errors()) . "\n";
}

1、if request data is：
{
  "Field_1": 1
}

--actually reuslt:
"Validate parameters fail. [Error] {"Field_2":["The field 2 field is required when field 1 is not present."]}

--expected reuslt: no error, because Field_1 field is set to 1, Field_2 is no need to be set.

2、if request data is：
{
  "Field_2": 2
}

--actually reuslt:
Validate parameters fail. [Error] {"Field_1":["The field 1 field is required when field 2 is not present."]}

--expected reuslt: no error

3、if request data is：
{
  "Field_1": 1,
  "Field_2": 2
}

--actually reuslt: no error

--expected reuslt: no error


问:
How to print over a current line, using the python logging module
I am writing a program with multiple threads, thus for logging information I use the python logging module. However I have parts of application where I would like to display how much is a thread is waiting for execution in the same line which is overwritten each time. I do not want multiple lines to show in the log.

I tried to use the sys.stdout.flush() function. Unfortunately it doesn't work.

My current code:

```<code>def log_flush(message, start, stop):
    import logging, sys
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-10s) %(message)s',
                        )
    time = stop - start
    logging.debug((str(message) + str(time)))
    sys.stdout.write('\r')
    sys.stdout.flush()

for i in range(0, 5):
    log_flush("Time taken: ", 0, i)
</code>```

My expected output is (after execution is finished):

```<code>(MainThread) Time taken: 4
</code>```

While currently the script outputs:

```<code>(MainThread) Time taken: 0
(MainThread) Time taken: 1
(MainThread) Time taken: 2
(MainThread) Time taken: 3
(MainThread) Time taken: 4
</code>```

答:
You can print backspaces, like this:

```<code>import time, sys

t = 0
while True:
    print('Seconds passed:', t, end='')
    sys.stdout.flush()
    time.sleep(1)
    t += 1
    print('\b'*20, end='')
</code>```

Body:
I am writing a program with multiple threads, thus for logging information I use the python logging module. However I have parts of application where I would like to display how much is a thread is waiting for execution in the same line which is overwritten each time. I do not want multiple lines to show in the log.

I tried to use the sys.stdout.flush() function. Unfortunately it doesn't work.

My current code:

def log_flush(message, start, stop):
    import logging, sys
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-10s) %(message)s',
                        )
    time = stop - start
    logging.debug((str(message) + str(time)))
    sys.stdout.write('\r')
    sys.stdout.flush()

for i in range(0, 5):
    log_flush("Time taken: ", 0, i)

My expected output is (after execution is finished):

(MainThread) Time taken: 4

While currently the script outputs:

(MainThread) Time taken: 0
(MainThread) Time taken: 1
(MainThread) Time taken: 2
(MainThread) Time taken: 3
(MainThread) Time taken: 4

Body:
You can print backspaces, like this:

import time, sys

t = 0
while True:
    print('Seconds passed:', t, end='')
    sys.stdout.flush()
    time.sleep(1)
    t += 1
    print('\b'*20, end='')


问:
Python keyerror 'sapi5'
One question of this type is previously asked but is not very helpful. I am using version Python3.6 in Windows 10 OS. I am getting an error, KeyError: 'sapi5' and During handling of the above exception, another exception occurred.
My code is:

import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices)
```

<p>And here is the stack trace:</p>

``` File "c:/Users/farhe/OneDrive/Desktop/PYTHON/jarvis/ai.py.py", line 2, in <module>
    engine = pyttsx3.init(sapi5)
NameError: name 'sapi5' is not defined
```

What should I do?

答:
From the Github README:

If you recieve errors such as No module named win32com.client, No module named win32, or No module named win32api, you will need to additionally install pypiwin32.

Title: Python keyerror 'sapi5'

Body:
One question of this type is previously asked but is not very helpful. I am using version Python3.6 in Windows 10 OS. I am getting an error, KeyError: 'sapi5' and During handling of the above exception, another exception occurred.
My code is:

import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices)

And here is the stack trace:

 File "c:/Users/farhe/OneDrive/Desktop/PYTHON/jarvis/ai.py.py", line 2, in <module>
    engine = pyttsx3.init(sapi5)
NameError: name 'sapi5' is not defined

What should I do?


问:
How create database and tables, and fill them with data? I got error
I want to create a database inside its table and fill it with data.
To do this, I write the following code, but it turns out an error:

```<code><?php

$json = json_decode(file_get_contents("categories.json"), true)['categories'];
foreach ($json as $elem) {
    print_r($elem);
}

$link = mysqli_connect('localhost', 'root', '');

$sql = "DROP DATABASE cats";
mysqli_query($link, $sql);

$sql = "CREATE DATABASE cats";
mysqli_query($link, $sql);

$sql = "CREATE TABLE cats.categories (id INT NOT NULL AUTO_INCREMENT, id_category INT, name VARCHAR(255), alias VARCHAR(255))";
mysqli_query($link, $sql);
$sql = "CREATE TABLE cats.category_child (id INT NOT NULL AUTO_INCREMENT, id_category INT, id_child INT)";
mysqli_query($link, $sql);

foreach ($json as $elem) {
    $stmt = mysqli_prepare($link, "INSERT INTO cats.categories (id_category, name, alias) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($stmt, "iss", $elem['id'], $elem['name'], $elem['alias']);
    mysqli_stmt_execute($stmt);
    var_dump(mysqli_error($link));
    mysqli_stmt_close($stmt);

}

?>
</code>```

var_dump(mysqli_error($link)) prints: string(37) "Table 'cats.categories' doesn't exist"
What am I doing wrong?

答:
On second thought, this doesn't work:

```<code>CREATE TABLE categories (
    id INT NOT NULL AUTO_INCREMENT,
    id_category INT,
    name VARCHAR(255),
    alias VARCHAR(255)
);
</code>```

I think the error is pretty self-explanatory:

Incorrect table definition; there can be only one auto column and it must be defined as a key

However, it might not be totally clear what to do for someone learning SQL.  You can phrase it as:

```<code>CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    id_category INT,
    name VARCHAR(255),
    alias VARCHAR(255)
);
</code>```

By the way, kudos for using parameters!

Body:
I want to create a database inside its table and fill it with data.
To do this, I write the following code, but it turns out an error:

<?php

$json = json_decode(file_get_contents("categories.json"), true)['categories'];
foreach ($json as $elem) {
    print_r($elem);
}

$link = mysqli_connect('localhost', 'root', '');

$sql = "DROP DATABASE cats";
mysqli_query($link, $sql);

$sql = "CREATE DATABASE cats";
mysqli_query($link, $sql);

$sql = "CREATE TABLE cats.categories (id INT NOT NULL AUTO_INCREMENT, id_category INT, name VARCHAR(255), alias VARCHAR(255))";
mysqli_query($link, $sql);
$sql = "CREATE TABLE cats.category_child (id INT NOT NULL AUTO_INCREMENT, id_category INT, id_child INT)";
mysqli_query($link, $sql);

foreach ($json as $elem) {
    $stmt = mysqli_prepare($link, "INSERT INTO cats.categories (id_category, name, alias) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($stmt, "iss", $elem['id'], $elem['name'], $elem['alias']);
    mysqli_stmt_execute($stmt);
    var_dump(mysqli_error($link));
    mysqli_stmt_close($stmt);

}

?>

var_dump(mysqli_error($link)) prints: string(37) "Table 'cats.categories' doesn't exist"
What am I doing wrong?

Body:
On second thought, this doesn't work:

CREATE TABLE categories (
    id INT NOT NULL AUTO_INCREMENT,
    id_category INT,
    name VARCHAR(255),
    alias VARCHAR(255)
);

I think the error is pretty self-explanatory:

Incorrect table definition; there can be only one auto column and it must be defined as a key

However, it might not be totally clear what to do for someone learning SQL.  You can phrase it as:

CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    id_category INT,
    name VARCHAR(255),
    alias VARCHAR(255)
);

By the way, kudos for using parameters!


问:
how to encode api URL using base64 in laravel?
how to encode URL using base64 in laravel?

I need something like this:

original URL: http://localhost/dashboard/api/test/

encode URL: http://localhost/dashboard/YXBpL3Rlc3Qv

答:
I've found this piece of code which helped me, I'm just looking for something that removes "=" from base64 string so here :-

```<code><?php
    function base64url_encode($data) {
      return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    function base64url_decode($data) {
      return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
    }
?>
</code>```

Example :-

```<code>dump(rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '='));
$encodedString = rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '=');
dd(base64_decode(str_pad(strtr($encodedString, '-_', '+/'), strlen($encodedString) % 4, '=')));
</code>```

I hope this helps someone.

ContentLicense: CC BY-SA 3.0

Body:
I've found this piece of code which helped me, I'm just looking for something that removes "=" from base64 string so here :-

<?php
    function base64url_encode($data) {
      return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    function base64url_decode($data) {
      return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
    }
?>

Example :-

dump(rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '='));
$encodedString = rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '=');
dd(base64_decode(str_pad(strtr($encodedString, '-_', '+/'), strlen($encodedString) % 4, '=')));

I hope this helps someone.


问:
Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

```<code>/Controller/Action?id=11112&value=4444
</code>```

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

```<code> $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }
</code>```

答:
```<code>var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
</code>```

Sample here

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

Updated code to account for no '?':

```<code>var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
</code>```

Sample here

Body:
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

/Controller/Action?id=11112&value=4444

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }

Body:
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

Sample here

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

Updated code to account for no '?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

Sample here


问:
Angular 5 Promise waiting to long for back end answer gets undefined
I'm sending a POST request from front-end within a Promise using Angular 5 and the problem is that back-end service takes to long to answer and, even though the script keeps going on Java back-end, promise's results shows up as "undefined", kind of like it has a timeout on waiting.

It is expected this backend service to take a while to answer. So, I intend to show to user that request stills not completed. To do so, I would need the Promised to keep on waiting a few more moments on the service's answer.

Chrome's console show this

```<code>Loader Started - HTTP request: /api/example/exampleService

POST https://localhost:4200/api/example/exampleService net::ERR_SPDY_PROTOCOL_ERROR
Http failure response for (unknown url): 0 Unknown Error
Loader Finished - HTTP request: /api/example/exampleService
</code>```

答:
You could increase your timeout using a pipe in Angular:</p>

```<code>this.http.post(API_URL, {headers: HEADER})
            .pipe(
                timeout(3000) //3 seconds
            );
</code>```

Body:
I'm sending a POST request from front-end within a Promise using Angular 5 and the problem is that back-end service takes to long to answer and, even though the script keeps going on Java back-end, promise's results shows up as "undefined", kind of like it has a timeout on waiting.

It is expected this backend service to take a while to answer. So, I intend to show to user that request stills not completed. To do so, I would need the Promised to keep on waiting a few more moments on the service's answer.

Chrome's console show this

Loader Started - HTTP request: /api/example/exampleService

POST https://localhost:4200/api/example/exampleService net::ERR_SPDY_PROTOCOL_ERROR
Http failure response for (unknown url): 0 Unknown Error
Loader Finished - HTTP request: /api/example/exampleService

Body:
You could increase your timeout using a pipe in Angular:

this.http.post(API_URL, {headers: HEADER})
            .pipe(
                timeout(3000) //3 seconds
            );


问:
What module is the unnamed package part of in Java?
I think that the unnamed package is part of the unnamed module, however I can't be sure as I can't find any answers online, so I posted my question here.

From https://docs.oracle.com/javase/tutorial/java/package/createpkgs.html:

If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages.

*Edit: The answer is that the unnamed package is part of the unnamed module

答:
It is in a (the) unnamed module.

According to the Java 11 edition of the JLS 7.4.2

The host system must associate ordinary compilation units in an unnamed package with an unnamed module (§7.7.5), not a named module.

This is more authoritative than the Java Tutorial.


问:
Flutter connect real device
I am running Windows 10 home edition and every time I launch an AVD the machine slows down considerably.

Is it possible for flutter to connect to a real device such that when I run my app during development its rendered on an actual device and not the virtual devices. If so would hot reloading still be allowed?

答:
To prepare to run and test your Flutter app on an Android device, you’ll need an Android device running Android 4.1 (API level 16) or higher.

Enable Developer options and USB debugging on your device.

Install the Google USB Driver

Using a USB cable, plug your phone into your
computer. If prompted on your device, authorize your computer to
access your device.

In the terminal, run the flutter devices command
to verify that Flutter recognizes your connected Android device.

You get full instructions and more information here: Flutter Docs

Title: Flutter connect real device


问:
Handle time from different timezone and store into mysql
I making a website with facebook,
the bad thing is.. there is too many timezone and hard to convert into UTC.
my server is using UTC as default setting,
may i know how could i manage it in more generic way, to convert difference time zone into UTC time, and display it into preset timezone setting ?

additionally, may i know how could i store this into mysql database with php ?

2011-04-10T08:13:30+0000

答: Use gmdate() function, it formats the time in UTC.


问:
Unable to search single number and comma separated string in same query
I am trying to search on specific scenario from last 8 hours but unable to sort it out.

I need to get records from single table where I need to match a comma separated string against two columns.

-Both columns contain single values like 1 or comma separated values like 1,2,3

I need to get records where minimum one AND condition matches for both columns either for single value or comma separated value.

Here is my query

```<code>SELECT specialities, ids_origin, id, latitude, longitude
FROM `ep_restaurant`
where `specialities` in (2,4,5,32) and `ids_origin` in (106,154,3)
</code>```

The record is fetching

http://prntscr.com/ntiao7

But it is matching when both columns have same whole set of comma separated values, I also need to get all of those where even single values from both columns match like 2,6 or 2,154 or whole comma separated string like (2,4,5,32) and (106,154,3) matched..

It is not my own database so i cannot change it. Please help me .Thanks.

答:
MySQL has a useful function for such must-avoid use-case.

For example, if you have specialities table:

```<code>SELECT r.id, latitude, longitude, r.specialities
  FROM ep_restaurant r
  WHERE exists( SELECT 1
                  FROM specialities s
                  WHERE find_in_set(s.id, r.specialities)
                    AND s.id in(2,6)
              )
     OR exists( SELECT 1
                  FROM <Origins Table> o
                  WHERE find_in_set(o.<Column Id>, r.ids_origin)
                    AND o.<Column Id> in(106,154)
              )
</code>```

Body:
I am trying to search on specific scenario from last 8 hours but unable to sort it out.

I need to get records from single table where I need to match a comma separated string against two columns.

-Both columns contain single values like 1 or comma separated values like 1,2,3

I need to get records where minimum one AND condition matches for both columns either for single value or comma separated value.

Here is my query

SELECT specialities, ids_origin, id, latitude, longitude
FROM `ep_restaurant`
where `specialities` in (2,4,5,32) and `ids_origin` in (106,154,3)

The record is fetching

http://prntscr.com/ntiao7

But it is matching when both columns have same whole set of comma separated values, I also need to get all of those where even single values from both columns match like 2,6 or 2,154 or whole comma separated string like (2,4,5,32) and (106,154,3) matched..

It is not my own database so i cannot change it. Please help me .Thanks.

Body:
MySQL has a useful function for such must-avoid use-case.

For example, if you have specialities table:

SELECT r.id, latitude, longitude, r.specialities
  FROM ep_restaurant r
  WHERE exists( SELECT 1
                  FROM specialities s
                  WHERE find_in_set(s.id, r.specialities)
                    AND s.id in(2,6)
              )
     OR exists( SELECT 1
                  FROM <Origins Table> o
                  WHERE find_in_set(o.<Column Id>, r.ids_origin)
                    AND o.<Column Id> in(106,154)
              )


问:
Bad accuracy when prediction happens
After I trained my model for the toxic challenge at Keras the accuracy of the prediction is bad. I'm not sure if I'm doing something wrong, but the accuracy during the training period was pretty good ~0.98.

How I trained

```<code>import sys, os, re, csv, codecs, numpy as np, pandas as pd
import matplotlib.pyplot as plt
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation
from keras.layers import Bidirectional, GlobalMaxPool1D
from keras.models import Model
from keras import initializers, regularizers, constraints, optimizers, layers

train = pd.read_csv('train.csv')

list_classes = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]
y = train[list_classes].values
list_sentences_train = train["comment_text"]

max_features = 20000
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(list_sentences_train))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)

maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

inp = Input(shape=(maxlen, ))

embed_size = 128
x = Embedding(max_features, embed_size)(inp)
x = LSTM(60, return_sequences=True,name='lstm_layer')(x)
x = GlobalMaxPool1D()(x)
x = Dropout(0.1)(x)
x = Dense(50, activation="relu")(x)
x = Dropout(0.1)(x)
x = Dense(6, activation="sigmoid")(x)

model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

batch_size = 32
epochs = 2
print(X_t[0])
model.fit(X_t,y, batch_size=batch_size, epochs=epochs, validation_split=0.1)

model.save("m.hdf5")
</code>```

This is how I predict

```<code>model = load_model('m.hdf5')

list_sentences_train = np.array(["I love you Stackoverflow"])

max_features = 20000
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(list_sentences_train))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)

maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

print(X_t)

print(model.predict(X_t))
</code>```

Output

[[  1.97086316e-02   9.36032447e-05   3.93966911e-03   5.16672269e-04
      3.67353857e-03   1.28102733e-03]]

答:
In inference (i.e. prediction) phase, you should use the same pre-processing steps you have used during training of the model. Therefore, you should not create a new Tokenizer instance and fit it on your test data. Rather, if you want to be able to do prediction later with the same model, besides the model you must also save all the statistics you obtained from the training data like the vocabulary in Tokenizer instance. Therefore it would be like this:

```<code>import pickle

# building and training of the model as you have done ...

# store all the data we need later: model and tokenizer
model.save("m.hdf5")
with open('tokenizer.pkl', 'wb') as handler:
    pickle.dump(tokenizer, handler)
</code>```

And now in prediction phase:

```<code>import pickle

model = load_model('m.hdf5')
with open('tokenizer.pkl', 'rb') as handler:
    tokenizer = pickle.load(handler)

list_sentences_train = ["I love you Stackoverflow"]

# use the the same tokenizer instance you used in training phase
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

print(model.predict(X_t))
</code>```

Title: Bad accuracy when prediction happens

Body:
After I trained my model for the toxic challenge at Keras the accuracy of the prediction is bad. I'm not sure if I'm doing something wrong, but the accuracy during the training period was pretty good ~0.98.

How I trained

import sys, os, re, csv, codecs, numpy as np, pandas as pd
import matplotlib.pyplot as plt
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation
from keras.layers import Bidirectional, GlobalMaxPool1D
from keras.models import Model
from keras import initializers, regularizers, constraints, optimizers, layers

train = pd.read_csv('train.csv')

list_classes = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]
y = train[list_classes].values
list_sentences_train = train["comment_text"]

max_features = 20000
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(list_sentences_train))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)

maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

inp = Input(shape=(maxlen, ))

embed_size = 128
x = Embedding(max_features, embed_size)(inp)
x = LSTM(60, return_sequences=True,name='lstm_layer')(x)
x = GlobalMaxPool1D()(x)
x = Dropout(0.1)(x)
x = Dense(50, activation="relu")(x)
x = Dropout(0.1)(x)
x = Dense(6, activation="sigmoid")(x)

model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

batch_size = 32
epochs = 2
print(X_t[0])
model.fit(X_t,y, batch_size=batch_size, epochs=epochs, validation_split=0.1)

model.save("m.hdf5")

This is how I predict

model = load_model('m.hdf5')

list_sentences_train = np.array(["I love you Stackoverflow"])

max_features = 20000
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(list_sentences_train))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)

maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

print(X_t)

print(model.predict(X_t))

Output

[[  1.97086316e-02   9.36032447e-05   3.93966911e-03   5.16672269e-04
      3.67353857e-03   1.28102733e-03]]

Body:
In inference (i.e. prediction) phase, you should use the same pre-processing steps you have used during training of the model. Therefore, you should not create a new Tokenizer instance and fit it on your test data. Rather, if you want to be able to do prediction later with the same model, besides the model you must also save all the statistics you obtained from the training data like the vocabulary in Tokenizer instance. Therefore it would be like this:

import pickle

# building and training of the model as you have done ...

# store all the data we need later: model and tokenizer
model.save("m.hdf5")
with open('tokenizer.pkl', 'wb') as handler:
    pickle.dump(tokenizer, handler)

And now in prediction phase:

import pickle

model = load_model('m.hdf5')
with open('tokenizer.pkl', 'rb') as handler:
    tokenizer = pickle.load(handler)

list_sentences_train = ["I love you Stackoverflow"]

# use the the same tokenizer instance you used in training phase
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

print(model.predict(X_t))


问:
IE7: background-img on multipleline text
On a anchor-tag with a url to a external site we have a little icon that indicates that this is a link to a external site. Now this Icon is included via a additional span-element around the link-text and displayed via CSS background-image with position 100% 50% to always be at the end of the text and a padding-right for the text-gap between link and the following text

now this works fine in every browser — as long as the link-text is not longer than 1 line … if it is on multiple lines, the whole thing works still fine everywhere, except IE7 (IE6 is not supported by the project)… IE7 displays the Icon at the end of the first line and a few pixels to the bottom, instead of at the end of the link-/span-text on the second or third line…

Sometimes a picture says more than 1000 words: http://img859.imageshack.us/i/spdexternalerror.jpg/

HTML-Code: Link-Text to multiple lines

CSS to the span-element: {background: url(/#/icon-new-window.png) no-repeat center right; padding-right: 14px;}

答: adding zoom:1 CSS property resolves this problem at most situations


问:
Adaptation textarea to contenteditable
I have a script that displays smiles in a textarea.

I would like to know how to adapt it to work with a contenteditable instead of a textarea.

To see the full script : https://pastebin.com/HavdikMj

thank you so much

```<code>            // EMOJI CLICK EVENT
            $( document ).off( "click", "."  + emojiContainer +  " section .emojione" );
            $( document ).on( "click", "."  + emojiContainer +  " section .emojione",
                function()
                {
                    var caretPos = activeEl.selectionStart;
                    var textAreaTxt = $( activeEl ).val();
                    var txtToAdd;
                    if( settings.type=="shortcode" )
                    {
                        txtToAdd = $( this ).attr( "title" ) + " ";
                    }else{
                        txtToAdd = $( this ).attr( "alt" ) + " ";
                    }

                    $( activeEl ).val( textAreaTxt.substring( 0, caretPos ) + txtToAdd + textAreaTxt.substring( caretPos ) );
                    $( activeEl ).focus();
                    activeEl.selectionStart = caretPos + txtToAdd.length;
                    activeEl.selectionEnd = caretPos + txtToAdd.length;
                }
            );
        };
</code>```

答:
The problem is that the emojione textarea picker relies on the selectionStart and selectionEnd properties of the textarea element. Both aren't available for a div. Furthermore the picker gets & sets the text inside the textarea using element.val() which also doesn't work with divs.

There's hope though it isn't too easy.

We need to enhance the HTMLDivElement with selectionStart and selectionEnd properties

```<code>HTMLDivElement.prototype.selectionStart = 0;
HTMLDivElement.prototype.selectionEnd = 0;
</code>```

Get the values for those properties using the Selection API

```<code>function update(e) {
  var caret = window.getSelection().anchorOffset;
  e.target.selectionStart = caret;
  e.target.selectionEnd = caret + window.getSelection().focusOffset;
}
</code>```

Apply the values as soon as the user either clicks or moves the keys inside a div

```<code>['mousedown', 'mouseup', 'keydown', 'keyup'].forEach(function(evt) {
  document.getElementById("theDiv").addEventListener(evt, update);
});
</code>```

Finally rewrite the on click function you've posted to make it aware of divs and if it's a div set & get the text using element.firstChild.data instead of element.val()

```<code>  $(document).on("click", "." + emojiContainer + " section .emojione",
    function() {
      var textAreaTxt;
      var caretPos = activeEl.selectionStart;
      if (activeEl.constructor.name == "HTMLDivElement") {
        textAreaTxt = activeEl.firstChild.data;

      } else {
        textAreaTxt = $(activeEl).val();
      }
      var txtToAdd;
      if (settings.type == "shortcode") {
        txtToAdd = $(this).attr("title") + " ";
      } else {
        txtToAdd = $(this).attr("alt") + " ";
      }
      if (activeEl.constructor.name == "HTMLDivElement") {
        activeEl.firstChild.data = textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos);
      } else {
        $(activeEl).val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
      }
      $(activeEl).focus();
      activeEl.selectionStart = caretPos + txtToAdd.length;
      activeEl.selectionEnd = caretPos + txtToAdd.length;
    }
  );
</code>```

Here's a working example. Please note I had to remove a lot of the emojis because of a 30000 chars per post limit. This doesn't affect the functionality though.

(function($) {
  $.fn.emojionePicker = function(options) {
    var emojiContainer = "emojionepicker",
      activeEl;

    // DEFAULT SETTINGS
    var settings = $.extend({
      pickerTop: 5, // Picker top margin
      pickerRight: 5, // Picker right margin
      type: "shortcode", // What to send to textarea, valid values are "shortcode" and "unicode"

    }, options);

    var $el = this;

    // EMOJI LIST
    var emojiList = {
      people: {
        header: ":smiley:",
        content: ":grinning: :grin: :joy: :rofl: :smiley: :smile: :sweat_smile: :laughing: :wink: :blush: :yum: :sunglasses: :heart_eyes: :kissing_heart: :kissing: :kissing_smiling_eyes: :kissing_closed_eyes: :relaxed: :slight_smile: :hugging: :thinking: :neutral_face: :expressionless: :no_mouth: :rolling_eyes: :smirk: :persevere: :disappointed_relieved: :open_mouth: :zipper_mouth: :hushed: :sleepy: :tired_face: :sleeping: :relieved: :nerd: :stuck_out_tongue: :stuck_out_tongue_winking_eye: :stuck_out_tongue_closed_eyes: :drooling_face: :unamused: :sweat: :pensive: :confused: :upside_down: :money_mouth: :astonished: :frowning2: :slight_frown: :confounded: :disappointed: :worried: :triumph: :cry: :sob: :frowning: :anguished: :fearful: :weary: :grimacing: :cold_sweat: :scream: :flushed: :dizzy_face: :rage: :angry: :innocent: :cowboy: :clown: :lying_face: :mask: :thermometer_face: :head_bandage: :nauseated_face: :sneezing_face: :smiling_imp: :imp: :japanese_ogre: :japanese_goblin: :skull: :ghost: :alien: :robot: :poop: :smiley_cat: :smile_cat: :joy_cat: :heart_eyes_cat: :smirk_cat: :kissing_cat: :scream_cat: :crying_cat_face: :pouting_cat: :boy: :boy_tone1: :boy_tone2: :boy_tone3: :boy_tone4: :boy_tone5: :girl: :girl_tone1: :girl_tone2: :girl_tone3: :girl_tone4: :girl_tone5: :man: :man_tone1: :man_tone2: :man_tone3: :man_tone4: :man_tone5: :woman: :woman_tone1: :woman_tone2: :woman_tone3: :woman_tone4: :woman_tone5: :older_man: :older_man_tone1: :older_man_tone2: :older_man_tone3: :older_man_tone4: :older_man_tone5: :older_woman: :older_woman_tone1: :older_woman_tone2: :older_woman_tone3: :older_woman_tone4: :older_woman_tone5: :baby: :baby_tone1: :baby_tone2: :baby_tone3: :baby_tone4: :baby_tone5: :angel: :angel_tone1: :angel_tone2: :angel_tone3: :angel_tone4: :angel_tone5: :cop: :cop_tone1: :cop_tone2: :cop_tone3: :cop_tone4: :cop_tone5: :spy: :spy_tone1: :spy_tone2: :spy_tone3: :spy_tone4: :spy_tone5: :guardsman: :guardsman_tone1: :guardsman_tone2: :guardsman_tone3: :guardsman_tone4: :guardsman_tone5: :construction_worker: :construction_worker_tone1: :construction_worker_tone2: :construction_worker_tone3: :construction_worker_tone4: :construction_worker_tone5: :man_with_turban: :man_with_turban_tone1: :man_with_turban_tone2: :man_with_turban_tone3: :man_with_turban_tone4: :man_with_turban_tone5: :person_with_blond_hair: :person_with_blond_hair_tone1: :person_with_blond_hair_tone2: :person_with_blond_hair_tone3: :person_with_blond_hair_tone4: :person_with_blond_hair_tone5: :santa: :santa_tone1: :santa_tone2: :santa_tone3: :santa_tone4: :santa_tone5: :mrs_claus: :mrs_claus_tone1: :mrs_claus_tone2: :mrs_claus_tone3: :mrs_claus_tone4: :mrs_claus_tone5: :princess: :princess_tone1: :princess_tone2: :princess_tone3: :princess_tone4: :princess_tone5: :prince: :prince_tone1: :prince_tone2: :prince_tone3: :prince_tone4: :prince_tone5: :bride_with_veil: :bride_with_veil_tone1: :bride_with_veil_tone2: :bride_with_veil_tone3: :bride_with_veil_tone4: :bride_with_veil_tone5: :man_in_tuxedo: :man_in_tuxedo_tone1: :man_in_tuxedo_tone2: :man_in_tuxedo_tone3: :man_in_tuxedo_tone4: :raised_hands_tone1: :raised_hands_tone2: :raised_hands_tone3: :raised_hands_tone4: :raised_hands_tone5: :pray: :pray_tone1: :pray_tone2: :pray_tone3: :pray_tone4: :pray_tone5: :handshake: :handshake_tone1: :handshake_tone2: :handshake_tone3: :handshake_tone4: :handshake_tone5: :nail_care: :nail_care_tone1: :nail_care_tone2: :nail_care_tone3: :nail_care_tone4: :nail_care_tone5: :ear: :ear_tone1: :ear_tone2: :ear_tone3: :ear_tone4: :ear_tone5: :nose: :nose_tone1: :nose_tone2: :nose_tone3: :nose_tone4: :nose_tone5: :footprints: :eyes: :eye: :tongue: :lips: :kiss: :zzz: :eyeglasses: :dark_sunglasses: :necktie: :shirt: :jeans: :dress: :kimono: :bikini: :womans_clothes: :purse: :handbag: :pouch: :school_satchel: :mans_shoe: :athletic_shoe: :high_heel: :sandal: :boot: :crown: :womans_hat: :tophat: :mortar_board: :helmet_with_cross: :lipstick: :ring: :closed_umbrella: :briefcase:".split(" ")
      },
      nature: {
        header: ":four_leaf_clover:",
        content: ":see_no_evil: :hear_no_evil: :speak_no_evil: :sweat_drops: :dash: :monkey_face: :monkey: :gorilla: :dog: :dog2: :poodle: :wolf: :fox: :cat: :cat2: :lion_face: :tiger: :tiger2: :leopard: :horse: :racehorse: :deer: :unicorn: :cow: :ox: :water_buffalo: :cow2: :pig: :pig2: :boar: :pig_nose: :ram: :sheep: :goat: :dromedary_camel: :camel: :elephant: :rhino: :mouse: :mouse2: :rat: :hamster: :rabbit: :rabbit2: :chipmunk: :bat: :bear: :koala: :panda_face: :feet: :turkey: :chicken: :rooster: :hatching_chick: :baby_chick: :hatched_chick: :bird: :penguin: :dove: :eagle: :duck: :owl: :frog: :crocodile: :turtle: :lizard: :snake: :dragon_face: :dragon: :whale: :whale2: :dolphin: :fish: :tropical_fish: :blowfish: :shark: :octopus: :shell: :crab: :shrimp: :squid: :butterfly: :snail: :bug: :ant: :bee: :beetle: :spider: :spider_web: :scorpion: :bouquet: :cherry_blossom: :rosette: :rose: :wilted_rose: :hibiscus: :sunflower: :blossom: :tulip: :seedling: :evergreen_tree: :deciduous_tree: :palm_tree: :cactus: :ear_of_rice: :herb: :shamrock: :four_leaf_clover: :maple_leaf: :fallen_leaf: :leaves: :mushroom: :chestnut: :earth_africa: :earth_americas: :earth_asia: :new_moon: :waxing_crescent_moon: :first_quarter_moon: :waxing_gibbous_moon: :full_moon: :waning_gibbous_moon: :last_quarter_moon: :waning_crescent_moon: :crescent_moon: :new_moon_with_face: :first_quarter_moon_with_face: :last_quarter_moon_with_face: :sunny: :full_moon_with_face: :sun_with_face: :star: :star2: :cloud: :partly_sunny: :thunder_cloud_rain: :white_sun_small_cloud: :white_sun_cloud: :white_sun_rain_cloud: :cloud_rain: :cloud_snow: :cloud_lightning: :cloud_tornado: :fog: :wind_blowing_face: :umbrella2: :umbrella: :zap: :snowflake: :snowman2: :snowman: :comet: :fire: :droplet: :ocean: :jack_o_lantern: :christmas_tree: :sparkles: :tanabata_tree: :bamboo:".split(" ")
      },
      food: {
        header: ":hamburger:",
        content: ":grapes: :melon: :watermelon: :tangerine: :lemon: :banana: :pineapple: :apple: :green_apple: :pear: :peach: :cherries: :strawberry: :kiwi: :tomato: :avocado: :eggplant: :potato: :carrot: :corn: :hot_pepper: :cucumber: :peanuts: :bread: :croissant: :french_bread: :pancakes: :cheese: :meat_on_bone: :poultry_leg: :bacon: :hamburger: :fries: :pizza: :hotdog: :taco: :burrito: :stuffed_flatbread: :egg: :cooking: :shallow_pan_of_food: :stew: :salad: :popcorn: :bento: :rice_cracker: :rice_ball: :rice: :curry: :ramen: :spaghetti: :sweet_potato: :oden: :sushi: :fried_shrimp: :fish_cake: :dango: :icecream: :shaved_ice: :ice_cream: :doughnut: :cookie: :birthday: :cake: :chocolate_bar: :candy: :lollipop: :custard: :honey_pot: :baby_bottle: :milk: :coffee: :tea: :sake: :champagne: :wine_glass: :cocktail: :tropical_drink: :beer: :beers: :champagne_glass: :tumbler_glass: :fork_knife_plate: :fork_and_knife: :spoon:".split(" ")
      },
      objects: {
        header: ":bulb:",
        content: ":skull_crossbones: :love_letter: :bomb: :hole: :shopping_bags: :prayer_beads: :gem: :knife: :amphora: :map: :barber: :frame_photo: :bellhop: :door: :sleeping_accommodation: :bed: :couch: :toilet: :shower: :bathtub: :hourglass: :hourglass_flowing_sand: :watch: :alarm_clock: :stopwatch: :timer: :clock: :thermometer: :beach_umbrella: :balloon: :tada: :confetti_ball: :dolls: :flags: :wind_chime: :ribbon: :gift: :joystick: :postal_horn: :microphone2: :level_slider: :control_knobs: :radio: :iphone: :calling: :telephone: :telephone_receiver: :pager: :fax: :battery: :electric_plug: :computer: :desktop: :printer: :keyboard: :mouse_three_button: :trackball: :minidisc: :floppy_disk: :cd: :dvd: :movie_camera: :film_frames: :projector: :tv: :camera: :camera_with_flash: :video_camera: :vhs: :mag: :mag_right: :microscope: :telescope: :satellite: :candle: :bulb: :flashlight: :izakaya_lantern: :notebook_with_decorative_cover: :closed_book: :book: :green_book: :blue_book: :orange_book: :books: :notebook: :ledger: :page_with_curl: :scroll: :page_facing_up: :newspaper: :shopping_cart: :triangular_flag_on_post: :crossed_flags: :flag_black: :flag_white: :rainbow_flag:".split(" ")
      },
      activity: {
        header: ":football:",
        content: ":space_invader: :levitate: :fencer: :trumpet: :violin: :drum: :clapper: :bow_and_arrow:".split(" ")
      },
      travel: {
        header: ":red_car:",
        content: ":race_car: :motorcycle: :japan: :mountain_snow: :mountain: :volcano: :mount_fuji: :camping: :beach: :desert: :island: :park: :stadium: :classical_building: :construction_site: :homes: :cityscape: :house_abandoned: :house: :house_with_garden: :office: :post_office: :european_post_office: :hospital: :bank: :hotel: :love_hotel: :convenience_store: :school: :department_store: :factory: :japanese_castle: :european_castle: :wedding: :tokyo_tower: :statue_of_liberty: :church: :mosque: :synagogue: :shinto_shrine: :kaaba: :fountain: :tent: :foggy: :night_with_stars: :sunrise_over_mountains: :sunrise: :city_dusk: :city_sunset: :bridge_at_night: :milky_way: :carousel_horse: :ferris_wheel: :roller_coaster: :steam_locomotive: :railway_car: :bullettrain_side: :bullettrain_front: :train2: :metro: :light_rail: :station: :tram: :monorail: :mountain_railway: :train: :bus: :oncoming_bus: :trolleybus: :minibus: :ambulance: :fire_engine: :police_car: :oncoming_police_car: :taxi: :oncoming_taxi: :red_car: :oncoming_automobile: :blue_car: :truck: :articulated_lorry: :tractor: :bike: :scooter: :motor_scooter: :busstop: :motorway: :railway_track: :fuelpump: :rotating_light: :traffic_light: :vertical_traffic_light: :construction: :anchor: :sailboat: :canoe: :speedboat: :cruise_ship: :ferry: :motorboat: :ship: :airplane: :airplane_small: :airplane_departure: :airplane_arriving: :seat: :helicopter: :suspension_railway: :mountain_cableway: :aerial_tramway: :rocket: :satellite_orbital: :stars: :rainbow: :fireworks: :sparkler: :rice_scene: :checkered_flag:".split(" ")
      },
      symbols: {
        header: ":hash:",
        content: ":100: :1234: :eye_in_speech_bubble: :cupid: :heart: :heartbeat: :broken_heart: :two_hearts: :sparkling_heart: :heartpulse: :blue_heart: :green_heart: :yellow_heart: :purple_heart: :black_heart: :gift_heart: :revolving_hearts: :heart_decoration: :heart_exclamation: :anger: :boom: :dizzy: :speech_balloon: :speech_left: :anger_right: :thought_balloon: :white_flower: :globe_with_meridians: :hotsprings: :octagonal_sign: :clock12: :clock1230: :clock1: :clock130: :clock2: :clock230: :clock3: :clock330: :clock4: :clock430: :clock5: :clock530: :clock6: :clock630: :clock7: :clock730: :clock8: :clock830: :clock9: :clock930: :clock10: :clock1030: :clock11: :clock1130: :cyclone: :spades: :hearts: :diamonds: :clubs: :black_joker: :mahjong: :flower_playing_cards: :mute: :speaker: :sound: :loud_sound: :loudspeaker: :mega: :bell: :no_bell: :musical_note: :notes: :chart: :currency_exchange: :heavy_dollar_sign: :atm: :put_litter_in_its_place: :potable_water: :wheelchair: :mens: :womens: :restroom: :baby_symbol: :wc: :passport_control: :customs: :baggage_claim: :regional_indicator_c: :regional_indicator_b: :regional_indicator_a:".split(" ")
      },
      flags: {
        header: ":flag_black:",
        content: ":flag_ac: :flag_ad: :flag_ae: :flag_af: :flag_ag: :flag_ai: :flag_al: :flag_am: :flag_ao: :flag_aq: :flag_ar: :flag_as: :flag_at: :flag_au: :flag_aw: :flag_ax: :flag_az: :flag_ba: :flag_bb: :flag_bd: :flag_be: :flag_bf: :flag_bg: :flag_bh: :flag_bi: :flag_bj: :flag_bl: :flag_bm: :flag_bn: :flag_bo: :flag_bq: :flag_br: :flag_bs: :flag_bt: :flag_bv: :flag_bw: :flag_by: :flag_bz: :flag_ca: :flag_cc: :flag_cd: :flag_cf: :flag_cg: :flag_ch: :flag_ci: :flag_ck: :flag_cl: :flag_cm: :flag_cn: :flag_co: :flag_cp: :flag_cr: :flag_cu: :flag_cv: :flag_cw: :flag_cx: :flag_cy: :flag_cz: :flag_de: :flag_dg: :flag_dj: :flag_dk: :flag_dm: :flag_do: :flag_dz: :flag_ea: :flag_ec: :flag_ee: :flag_eg: :flag_eh: :flag_er: :flag_es: :flag_et: :flag_eu: :flag_fi: :flag_fj: :flag_fk: :flag_fm: :flag_fo: :flag_fr: :flag_ga: :flag_gb: :flag_gd: :flag_ge: :flag_gf: :flag_gg: :flag_gh: :flag_gi: :flag_gl: :flag_gm: :flag_gn: :flag_gp: :flag_gq: :flag_gr: :flag_gs: :flag_gt: :flag_gu: :flag_gw: :flag_gy: :flag_hk: :flag_hm: :flag_hn: :flag_hr: :flag_ht: :flag_hu: :flag_ic: :flag_id: :flag_ie: :flag_il: :flag_im: :flag_in: :flag_io: :flag_iq: :flag_ir: :flag_is: :flag_it: :flag_je: :flag_jm: :flag_jo: :flag_jp: :flag_ke: :flag_kg: :flag_kh: :flag_ki: :flag_km: :flag_kn: :flag_kp: :flag_kr: :flag_kw: :flag_ky: :flag_kz: :flag_la: :flag_lb: :flag_lc: :flag_li: :flag_lk: :flag_lr: :flag_ls: :flag_lt: :flag_lu: :flag_lv: :flag_ly: :flag_ma: :flag_mc: :flag_md: :flag_me: :flag_mf: :flag_mg: :flag_mh: :flag_mk: :flag_ml: :flag_mm: :flag_mn: :flag_mo: :flag_mp: :flag_mq: :flag_mr: :flag_ms: :flag_mt: :flag_mu: :flag_mv: :flag_mw: :flag_mx: :flag_my: :flag_mz: :flag_na: :flag_nc: :flag_ne: :flag_nf: :flag_ng: :flag_ni: :flag_nl: :flag_no: :flag_np: :flag_nr: :flag_nu: :flag_nz: :flag_om: :flag_pa: :flag_pe: :flag_pf: :flag_pg: :flag_ph: :flag_pk: :flag_pl: :flag_pm: :flag_pn: :flag_pr: :flag_ps: :flag_pt: :flag_pw: :flag_py: :flag_qa: :flag_re: :flag_ro: :flag_rs: :flag_ru: :flag_rw: :flag_sa: :flag_sb: :flag_sc: :flag_sd: :flag_se: :flag_sg: :flag_sh: :flag_si: :flag_sj: :flag_sk: :flag_sl: :flag_sm: :flag_sn: :flag_so: :flag_sr: :flag_ss: :flag_st: :flag_sv: :flag_sx: :flag_sy: :flag_sz: :flag_ta: :flag_tc: :flag_td: :flag_tf: :flag_tg: :flag_th: :flag_tj: :flag_tk: :flag_tl: :flag_tm: :flag_tn: :flag_to: :flag_tr: :flag_tt: :flag_tv: :flag_tw: :flag_tz: :flag_ua: :flag_ug: :flag_um: :flag_us: :flag_uy: :flag_uz: :flag_va: :flag_vc: :flag_ve: :flag_vg: :flag_vi: :flag_vn: :flag_vu: :flag_wf: :flag_ws: :flag_xk: :flag_ye: :flag_yt: :flag_za: :flag_zm: :flag_zw:".split(" ")
      }
    };

    // CREATE EMOJI CONTAINER AND LOAD SECTION HEADER
    var createContainer = function(el) {
      $('

').insertAfter(el);

      var navItems = '';
      $.each(emojiList,
        function(k, v) {
          var emoji = emojione.shortnameToImage(v["header"]);
          navItems += '
' + emoji + '
';
        }
      );

      $("." + emojiContainer + " nav").append(navItems);

      $("." + emojiContainer + " nav .tab").click(
        function() {
          loadEmojies($(this).attr("data-tab"));
        }
      );

      // EMOJI CLICK EVENT
      $(document).off("click", "." + emojiContainer + " section .emojione");
      $(document).on("click", "." + emojiContainer + " section .emojione",
        function() {
          var textAreaTxt;
          var caretPos = activeEl.selectionStart;
          if (activeEl.constructor.name == "HTMLDivElement") {
            textAreaTxt = activeEl.firstChild.data;

          } else {
            textAreaTxt = $(activeEl).val();
          }
          var txtToAdd;
          if (settings.type == "shortcode") {
            txtToAdd = $(this).attr("title") + " ";
          } else {
            txtToAdd = $(this).attr("alt") + " ";
          }
          if (activeEl.constructor.name == "HTMLDivElement") {
            activeEl.firstChild.data = textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos);
          } else {
            $(activeEl).val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
          }
          $(activeEl).focus();
          activeEl.selectionStart = caretPos + txtToAdd.length;
          activeEl.selectionEnd = caretPos + txtToAdd.length;
        }
      );
    };

    // GENERATE / CHANGE EMOJI SECTION
    var loadEmojies = function(section) {
      if ($("." + emojiContainer + " section." + section).length > 0) {
        if ($("." + emojiContainer + " .tab[data-tab='" + section + "']").hasClass("active")) {
          return;
        }

        $("." + emojiContainer + " section").fadeOut().promise().done(
          function() {
            $(this).hide();
            $("." + emojiContainer + " section." + section).fadeIn();
            $("." + emojiContainer + " .tab").removeClass("active");
            $("." + emojiContainer + " .tab[data-tab='" + section + "']").addClass("active");
          }
        );

        return;
      }

      if (typeof(emojiList[section]) == "undefined") {
        return;
      }

      var sectionHtml = '';
      $.each(emojiList[section].content,
        function(k, v) {
          sectionHtml += emojione.shortnameToImage(v);
        }
      );

      $('
' + sectionHtml + '
').insertAfter("." + emojiContainer + " nav");

      $("." + emojiContainer + " section").fadeOut().promise().done(
        function() {
          $("." + emojiContainer + " section." + section).fadeIn();
          $("." + emojiContainer + " .tab").removeClass("active");
          $("." + emojiContainer + " .tab[data-tab='" + section + "']").addClass("active");
        }
      );
    };

    // LOAD EMOJIONE
    var init = (function() {
      var script = document.createElement("script"),
        head = document.querySelector("head"),
        style = document.createElement('link');

      script.src = 'https://cdn.jsdelivr.net/emojione/2.2.7/lib/js/emojione.min.js';
      style.type = "text/css";
      style.href = "https://cdn.jsdelivr.net/emojione/2.2.7/assets/css/emojione.min.css";

      head.appendChild(style);
      head.appendChild(script);

      script.onload = function() {
        createContainer($el[0]);

        $.each($el, function(i, el) {
          var picker = $('

').insertAfter(el);

          // SET ACTIVE TEXTAREA
          picker.bind("click", function() {
            activeEl = el;
          });

          var elOffset = $(el).offset();

          picker.css({
            "top": elOffset["top"] + settings.pickerTop + "px",
            "left": $(el).width() + elOffset["left"] - $(".emojionepicker-picker").width() - settings.pickerRight + "px",
          }).show();
        });

        // EMOJI PICKER CLICK EVENT
        $(".emojionepicker-picker").click(
          function() {
            if ($("." + emojiContainer).is(":visible")) {
              $("." + emojiContainer).fadeOut();
              return;
            }

            // LOAD SECTION EMOJIES
            loadEmojies($("." + emojiContainer + " nav div.active").attr("data-tab"));

            var containerH = $("." + emojiContainer).height();
            var containerW = $("." + emojiContainer).width();
            var pickerOffset = $(this).offset();

            var top, left;
            if (pickerOffset["top"] > (containerH - 15)) {
              top = pickerOffset["top"] - containerH - 15;
            } else {
              top = pickerOffset["top"] + $(this).height() + 15;
            }

            if (pickerOffset["left"] > containerW) {
              left = pickerOffset["left"] - containerW + $(this).width();
            } else {
              left = pickerOffset["left"];
            }

            $("." + emojiContainer).css({
              "top": top + "px",
              "left": left + "px",
            }).fadeIn();
          }
        );

        // HIDE EMOJI CONTAINER ON CLICK ANYWHERE OUTSIDE THE ELEMENT
        $(document).on("click",
          function(e) {
            if ($("." + emojiContainer).is(":visible") == false || $(e.target).is(".emojionepicker-picker, .emojione")) {
              return;
            }

            $("." + emojiContainer).fadeOut();
          }
        );
      }
    })();

    return this;
  };
}(jQuery));

HTMLDivElement.prototype.selectionStart = 0;
HTMLDivElement.prototype.selectionEnd = 0;

function update(e) {
  var caret = window.getSelection().anchorOffset;
  e.target.selectionStart = caret;
  e.target.selectionEnd = caret + window.getSelection().focusOffset;
}

['mousedown', 'mouseup', 'keydown', 'keyup'].forEach(function(evt) {
  document.getElementById("theDiv").addEventListener(evt, update);
});

$("#theDiv").emojionePicker();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#theDiv {
  margin-top: 2em;
  height: 75px;
  width: 90%;
  border: 1px solid #000;
}</code>```

<link href="https://www.jqueryscript.net/demo/jQuery-EmojiOne-Based-Emoji-Picker-For-Textarea/dist/emojione.picker.css" rel="stylesheet" type="text/css">

  A contentEditable div

```

Title: Adaptation textarea to contenteditable

Body:
I have a script that displays smiles in a textarea.

I would like to know how to adapt it to work with a contenteditable instead of a textarea.

To see the full script : https://pastebin.com/HavdikMj

thank you so much

            // EMOJI CLICK EVENT
            $( document ).off( "click", "."  + emojiContainer +  " section .emojione" );
            $( document ).on( "click", "."  + emojiContainer +  " section .emojione",
                function()
                {
                    var caretPos = activeEl.selectionStart;
                    var textAreaTxt = $( activeEl ).val();
                    var txtToAdd;
                    if( settings.type=="shortcode" )
                    {
                        txtToAdd = $( this ).attr( "title" ) + " ";
                    }else{
                        txtToAdd = $( this ).attr( "alt" ) + " ";
                    }

                    $( activeEl ).val( textAreaTxt.substring( 0, caretPos ) + txtToAdd + textAreaTxt.substring( caretPos ) );
                    $( activeEl ).focus();
                    activeEl.selectionStart = caretPos + txtToAdd.length;
                    activeEl.selectionEnd = caretPos + txtToAdd.length;
                }
            );
        };

Body:
The problem is that the emojione textarea picker relies on the selectionStart and selectionEnd properties of the textarea element. Both aren't available for a div. Furthermore the picker gets & sets the text inside the textarea using element.val() which also doesn't work with divs.

There's hope though it isn't too easy.

We need to enhance the HTMLDivElement with selectionStart and selectionEnd properties

HTMLDivElement.prototype.selectionStart = 0;
HTMLDivElement.prototype.selectionEnd = 0;

Get the values for those properties using the Selection API

function update(e) {
  var caret = window.getSelection().anchorOffset;
  e.target.selectionStart = caret;
  e.target.selectionEnd = caret + window.getSelection().focusOffset;
}

Apply the values as soon as the user either clicks or moves the keys inside a div

['mousedown', 'mouseup', 'keydown', 'keyup'].forEach(function(evt) {
  document.getElementById("theDiv").addEventListener(evt, update);
});

Finally rewrite the on click function you've posted to make it aware of divs and if it's a div set & get the text using element.firstChild.data instead of element.val()

  $(document).on("click", "." + emojiContainer + " section .emojione",
    function() {
      var textAreaTxt;
      var caretPos = activeEl.selectionStart;
      if (activeEl.constructor.name == "HTMLDivElement") {
        textAreaTxt = activeEl.firstChild.data;

      } else {
        textAreaTxt = $(activeEl).val();
      }
      var txtToAdd;
      if (settings.type == "shortcode") {
        txtToAdd = $(this).attr("title") + " ";
      } else {
        txtToAdd = $(this).attr("alt") + " ";
      }
      if (activeEl.constructor.name == "HTMLDivElement") {
        activeEl.firstChild.data = textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos);
      } else {
        $(activeEl).val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
      }
      $(activeEl).focus();
      activeEl.selectionStart = caretPos + txtToAdd.length;
      activeEl.selectionEnd = caretPos + txtToAdd.length;
    }
  );

Here's a working example. Please note I had to remove a lot of the emojis because of a 30000 chars per post limit. This doesn't affect the functionality though.

(function($) {
  $.fn.emojionePicker = function(options) {
    var emojiContainer = "emojionepicker",
      activeEl;

    // DEFAULT SETTINGS
    var settings = $.extend({
      pickerTop: 5, // Picker top margin
      pickerRight: 5, // Picker right margin
      type: "shortcode", // What to send to textarea, valid values are "shortcode" and "unicode"

    }, options);

    var $el = this;

    // EMOJI LIST
    var emojiList = {
      people: {
        header: ":smiley:",
        content: ":grinning: :grin: :joy: :rofl: :smiley: :smile: :sweat_smile: :laughing: :wink: :blush: :yum: :sunglasses: :heart_eyes: :kissing_heart: :kissing: :kissing_smiling_eyes: :kissing_closed_eyes: :relaxed: :slight_smile: :hugging: :thinking: :neutral_face: :expressionless: :no_mouth: :rolling_eyes: :smirk: :persevere: :disappointed_relieved: :open_mouth: :zipper_mouth: :hushed: :sleepy: :tired_face: :sleeping: :relieved: :nerd: :stuck_out_tongue: :stuck_out_tongue_winking_eye: :stuck_out_tongue_closed_eyes: :drooling_face: :unamused: :sweat: :pensive: :confused: :upside_down: :money_mouth: :astonished: :frowning2: :slight_frown: :confounded: :disappointed: :worried: :triumph: :cry: :sob: :frowning: :anguished: :fearful: :weary: :grimacing: :cold_sweat: :scream: :flushed: :dizzy_face: :rage: :angry: :innocent: :cowboy: :clown: :lying_face: :mask: :thermometer_face: :head_bandage: :nauseated_face: :sneezing_face: :smiling_imp: :imp: :japanese_ogre: :japanese_goblin: :skull: :ghost: :alien: :robot: :poop: :smiley_cat: :smile_cat: :joy_cat: :heart_eyes_cat: :smirk_cat: :kissing_cat: :scream_cat: :crying_cat_face: :pouting_cat: :boy: :boy_tone1: :boy_tone2: :boy_tone3: :boy_tone4: :boy_tone5: :girl: :girl_tone1: :girl_tone2: :girl_tone3: :girl_tone4: :girl_tone5: :man: :man_tone1: :man_tone2: :man_tone3: :man_tone4: :man_tone5: :woman: :woman_tone1: :woman_tone2: :woman_tone3: :woman_tone4: :woman_tone5: :older_man: :older_man_tone1: :older_man_tone2: :older_man_tone3: :older_man_tone4: :older_man_tone5: :older_woman: :older_woman_tone1: :older_woman_tone2: :older_woman_tone3: :older_woman_tone4: :older_woman_tone5: :baby: :baby_tone1: :baby_tone2: :baby_tone3: :baby_tone4: :baby_tone5: :angel: :angel_tone1: :angel_tone2: :angel_tone3: :angel_tone4: :angel_tone5: :cop: :cop_tone1: :cop_tone2: :cop_tone3: :cop_tone4: :cop_tone5: :spy: :spy_tone1: :spy_tone2: :spy_tone3: :spy_tone4: :spy_tone5: :guardsman: :guardsman_tone1: :guardsman_tone2: :guardsman_tone3: :guardsman_tone4: :guardsman_tone5: :construction_worker: :construction_worker_tone1: :construction_worker_tone2: :construction_worker_tone3: :construction_worker_tone4: :construction_worker_tone5: :man_with_turban: :man_with_turban_tone1: :man_with_turban_tone2: :man_with_turban_tone3: :man_with_turban_tone4: :man_with_turban_tone5: :person_with_blond_hair: :person_with_blond_hair_tone1: :person_with_blond_hair_tone2: :person_with_blond_hair_tone3: :person_with_blond_hair_tone4: :person_with_blond_hair_tone5: :santa: :santa_tone1: :santa_tone2: :santa_tone3: :santa_tone4: :santa_tone5: :mrs_claus: :mrs_claus_tone1: :mrs_claus_tone2: :mrs_claus_tone3: :mrs_claus_tone4: :mrs_claus_tone5: :princess: :princess_tone1: :princess_tone2: :princess_tone3: :princess_tone4: :princess_tone5: :prince: :prince_tone1: :prince_tone2: :prince_tone3: :prince_tone4: :prince_tone5: :bride_with_veil: :bride_with_veil_tone1: :bride_with_veil_tone2: :bride_with_veil_tone3: :bride_with_veil_tone4: :bride_with_veil_tone5: :man_in_tuxedo: :man_in_tuxedo_tone1: :man_in_tuxedo_tone2: :man_in_tuxedo_tone3: :man_in_tuxedo_tone4: :raised_hands_tone1: :raised_hands_tone2: :raised_hands_tone3: :raised_hands_tone4: :raised_hands_tone5: :pray: :pray_tone1: :pray_tone2: :pray_tone3: :pray_tone4: :pray_tone5: :handshake: :handshake_tone1: :handshake_tone2: :handshake_tone3: :handshake_tone4: :handshake_tone5: :nail_care: :nail_care_tone1: :nail_care_tone2: :nail_care_tone3: :nail_care_tone4: :nail_care_tone5: :ear: :ear_tone1: :ear_tone2: :ear_tone3: :ear_tone4: :ear_tone5: :nose: :nose_tone1: :nose_tone2: :nose_tone3: :nose_tone4: :nose_tone5: :footprints: :eyes: :eye: :tongue: :lips: :kiss: :zzz: :eyeglasses: :dark_sunglasses: :necktie: :shirt: :jeans: :dress: :kimono: :bikini: :womans_clothes: :purse: :handbag: :pouch: :school_satchel: :mans_shoe: :athletic_shoe: :high_heel: :sandal: :boot: :crown: :womans_hat: :tophat: :mortar_board: :helmet_with_cross: :lipstick: :ring: :closed_umbrella: :briefcase:".split(" ")
      },
      nature: {
        header: ":four_leaf_clover:",
        content: ":see_no_evil: :hear_no_evil: :speak_no_evil: :sweat_drops: :dash: :monkey_face: :monkey: :gorilla: :dog: :dog2: :poodle: :wolf: :fox: :cat: :cat2: :lion_face: :tiger: :tiger2: :leopard: :horse: :racehorse: :deer: :unicorn: :cow: :ox: :water_buffalo: :cow2: :pig: :pig2: :boar: :pig_nose: :ram: :sheep: :goat: :dromedary_camel: :camel: :elephant: :rhino: :mouse: :mouse2: :rat: :hamster: :rabbit: :rabbit2: :chipmunk: :bat: :bear: :koala: :panda_face: :feet: :turkey: :chicken: :rooster: :hatching_chick: :baby_chick: :hatched_chick: :bird: :penguin: :dove: :eagle: :duck: :owl: :frog: :crocodile: :turtle: :lizard: :snake: :dragon_face: :dragon: :whale: :whale2: :dolphin: :fish: :tropical_fish: :blowfish: :shark: :octopus: :shell: :crab: :shrimp: :squid: :butterfly: :snail: :bug: :ant: :bee: :beetle: :spider: :spider_web: :scorpion: :bouquet: :cherry_blossom: :rosette: :rose: :wilted_rose: :hibiscus: :sunflower: :blossom: :tulip: :seedling: :evergreen_tree: :deciduous_tree: :palm_tree: :cactus: :ear_of_rice: :herb: :shamrock: :four_leaf_clover: :maple_leaf: :fallen_leaf: :leaves: :mushroom: :chestnut: :earth_africa: :earth_americas: :earth_asia: :new_moon: :waxing_crescent_moon: :first_quarter_moon: :waxing_gibbous_moon: :full_moon: :waning_gibbous_moon: :last_quarter_moon: :waning_crescent_moon: :crescent_moon: :new_moon_with_face: :first_quarter_moon_with_face: :last_quarter_moon_with_face: :sunny: :full_moon_with_face: :sun_with_face: :star: :star2: :cloud: :partly_sunny: :thunder_cloud_rain: :white_sun_small_cloud: :white_sun_cloud: :white_sun_rain_cloud: :cloud_rain: :cloud_snow: :cloud_lightning: :cloud_tornado: :fog: :wind_blowing_face: :umbrella2: :umbrella: :zap: :snowflake: :snowman2: :snowman: :comet: :fire: :droplet: :ocean: :jack_o_lantern: :christmas_tree: :sparkles: :tanabata_tree: :bamboo:".split(" ")
      },
      food: {
        header: ":hamburger:",
        content: ":grapes: :melon: :watermelon: :tangerine: :lemon: :banana: :pineapple: :apple: :green_apple: :pear: :peach: :cherries: :strawberry: :kiwi: :tomato: :avocado: :eggplant: :potato: :carrot: :corn: :hot_pepper: :cucumber: :peanuts: :bread: :croissant: :french_bread: :pancakes: :cheese: :meat_on_bone: :poultry_leg: :bacon: :hamburger: :fries: :pizza: :hotdog: :taco: :burrito: :stuffed_flatbread: :egg: :cooking: :shallow_pan_of_food: :stew: :salad: :popcorn: :bento: :rice_cracker: :rice_ball: :rice: :curry: :ramen: :spaghetti: :sweet_potato: :oden: :sushi: :fried_shrimp: :fish_cake: :dango: :icecream: :shaved_ice: :ice_cream: :doughnut: :cookie: :birthday: :cake: :chocolate_bar: :candy: :lollipop: :custard: :honey_pot: :baby_bottle: :milk: :coffee: :tea: :sake: :champagne: :wine_glass: :cocktail: :tropical_drink: :beer: :beers: :champagne_glass: :tumbler_glass: :fork_knife_plate: :fork_and_knife: :spoon:".split(" ")
      },
      objects: {
        header: ":bulb:",
        content: ":skull_crossbones: :love_letter: :bomb: :hole: :shopping_bags: :prayer_beads: :gem: :knife: :amphora: :map: :barber: :frame_photo: :bellhop: :door: :sleeping_accommodation: :bed: :couch: :toilet: :shower: :bathtub: :hourglass: :hourglass_flowing_sand: :watch: :alarm_clock: :stopwatch: :timer: :clock: :thermometer: :beach_umbrella: :balloon: :tada: :confetti_ball: :dolls: :flags: :wind_chime: :ribbon: :gift: :joystick: :postal_horn: :microphone2: :level_slider: :control_knobs: :radio: :iphone: :calling: :telephone: :telephone_receiver: :pager: :fax: :battery: :electric_plug: :computer: :desktop: :printer: :keyboard: :mouse_three_button: :trackball: :minidisc: :floppy_disk: :cd: :dvd: :movie_camera: :film_frames: :projector: :tv: :camera: :camera_with_flash: :video_camera: :vhs: :mag: :mag_right: :microscope: :telescope: :satellite: :candle: :bulb: :flashlight: :izakaya_lantern: :notebook_with_decorative_cover: :closed_book: :book: :green_book: :blue_book: :orange_book: :books: :notebook: :ledger: :page_with_curl: :scroll: :page_facing_up: :newspaper: :shopping_cart: :triangular_flag_on_post: :crossed_flags: :flag_black: :flag_white: :rainbow_flag:".split(" ")
      },
      activity: {
        header: ":football:",
        content: ":space_invader: :levitate: :fencer: :trumpet: :violin: :drum: :clapper: :bow_and_arrow:".split(" ")
      },
      travel: {
        header: ":red_car:",
        content: ":race_car: :motorcycle: :japan: :mountain_snow: :mountain: :volcano: :mount_fuji: :camping: :beach: :desert: :island: :park: :stadium: :classical_building: :construction_site: :homes: :cityscape: :house_abandoned: :house: :house_with_garden: :office: :post_office: :european_post_office: :hospital: :bank: :hotel: :love_hotel: :convenience_store: :school: :department_store: :factory: :japanese_castle: :european_castle: :wedding: :tokyo_tower: :statue_of_liberty: :church: :mosque: :synagogue: :shinto_shrine: :kaaba: :fountain: :tent: :foggy: :night_with_stars: :sunrise_over_mountains: :sunrise: :city_dusk: :city_sunset: :bridge_at_night: :milky_way: :carousel_horse: :ferris_wheel: :roller_coaster: :steam_locomotive: :railway_car: :bullettrain_side: :bullettrain_front: :train2: :metro: :light_rail: :station: :tram: :monorail: :mountain_railway: :train: :bus: :oncoming_bus: :trolleybus: :minibus: :ambulance: :fire_engine: :police_car: :oncoming_police_car: :taxi: :oncoming_taxi: :red_car: :oncoming_automobile: :blue_car: :truck: :articulated_lorry: :tractor: :bike: :scooter: :motor_scooter: :busstop: :motorway: :railway_track: :fuelpump: :rotating_light: :traffic_light: :vertical_traffic_light: :construction: :anchor: :sailboat: :canoe: :speedboat: :cruise_ship: :ferry: :motorboat: :ship: :airplane: :airplane_small: :airplane_departure: :airplane_arriving: :seat: :helicopter: :suspension_railway: :mountain_cableway: :aerial_tramway: :rocket: :satellite_orbital: :stars: :rainbow: :fireworks: :sparkler: :rice_scene: :checkered_flag:".split(" ")
      },
      symbols: {
        header: ":hash:",
        content: ":100: :1234: :eye_in_speech_bubble: :cupid: :heart: :heartbeat: :broken_heart: :two_hearts: :sparkling_heart: :heartpulse: :blue_heart: :green_heart: :yellow_heart: :purple_heart: :black_heart: :gift_heart: :revolving_hearts: :heart_decoration: :heart_exclamation: :anger: :boom: :dizzy: :speech_balloon: :speech_left: :anger_right: :thought_balloon: :white_flower: :globe_with_meridians: :hotsprings: :octagonal_sign: :clock12: :clock1230: :clock1: :clock130: :clock2: :clock230: :clock3: :clock330: :clock4: :clock430: :clock5: :clock530: :clock6: :clock630: :clock7: :clock730: :clock8: :clock830: :clock9: :clock930: :clock10: :clock1030: :clock11: :clock1130: :cyclone: :spades: :hearts: :diamonds: :clubs: :black_joker: :mahjong: :flower_playing_cards: :mute: :speaker: :sound: :loud_sound: :loudspeaker: :mega: :bell: :no_bell: :musical_note: :notes: :chart: :currency_exchange: :heavy_dollar_sign: :atm: :put_litter_in_its_place: :potable_water: :wheelchair: :mens: :womens: :restroom: :baby_symbol: :wc: :passport_control: :customs: :baggage_claim: :regional_indicator_c: :regional_indicator_b: :regional_indicator_a:".split(" ")
      },
      flags: {
        header: ":flag_black:",
        content: ":flag_ac: :flag_ad: :flag_ae: :flag_af: :flag_ag: :flag_ai: :flag_al: :flag_am: :flag_ao: :flag_aq: :flag_ar: :flag_as: :flag_at: :flag_au: :flag_aw: :flag_ax: :flag_az: :flag_ba: :flag_bb: :flag_bd: :flag_be: :flag_bf: :flag_bg: :flag_bh: :flag_bi: :flag_bj: :flag_bl: :flag_bm: :flag_bn: :flag_bo: :flag_bq: :flag_br: :flag_bs: :flag_bt: :flag_bv: :flag_bw: :flag_by: :flag_bz: :flag_ca: :flag_cc: :flag_cd: :flag_cf: :flag_cg: :flag_ch: :flag_ci: :flag_ck: :flag_cl: :flag_cm: :flag_cn: :flag_co: :flag_cp: :flag_cr: :flag_cu: :flag_cv: :flag_cw: :flag_cx: :flag_cy: :flag_cz: :flag_de: :flag_dg: :flag_dj: :flag_dk: :flag_dm: :flag_do: :flag_dz: :flag_ea: :flag_ec: :flag_ee: :flag_eg: :flag_eh: :flag_er: :flag_es: :flag_et: :flag_eu: :flag_fi: :flag_fj: :flag_fk: :flag_fm: :flag_fo: :flag_fr: :flag_ga: :flag_gb: :flag_gd: :flag_ge: :flag_gf: :flag_gg: :flag_gh: :flag_gi: :flag_gl: :flag_gm: :flag_gn: :flag_gp: :flag_gq: :flag_gr: :flag_gs: :flag_gt: :flag_gu: :flag_gw: :flag_gy: :flag_hk: :flag_hm: :flag_hn: :flag_hr: :flag_ht: :flag_hu: :flag_ic: :flag_id: :flag_ie: :flag_il: :flag_im: :flag_in: :flag_io: :flag_iq: :flag_ir: :flag_is: :flag_it: :flag_je: :flag_jm: :flag_jo: :flag_jp: :flag_ke: :flag_kg: :flag_kh: :flag_ki: :flag_km: :flag_kn: :flag_kp: :flag_kr: :flag_kw: :flag_ky: :flag_kz: :flag_la: :flag_lb: :flag_lc: :flag_li: :flag_lk: :flag_lr: :flag_ls: :flag_lt: :flag_lu: :flag_lv: :flag_ly: :flag_ma: :flag_mc: :flag_md: :flag_me: :flag_mf: :flag_mg: :flag_mh: :flag_mk: :flag_ml: :flag_mm: :flag_mn: :flag_mo: :flag_mp: :flag_mq: :flag_mr: :flag_ms: :flag_mt: :flag_mu: :flag_mv: :flag_mw: :flag_mx: :flag_my: :flag_mz: :flag_na: :flag_nc: :flag_ne: :flag_nf: :flag_ng: :flag_ni: :flag_nl: :flag_no: :flag_np: :flag_nr: :flag_nu: :flag_nz: :flag_om: :flag_pa: :flag_pe: :flag_pf: :flag_pg: :flag_ph: :flag_pk: :flag_pl: :flag_pm: :flag_pn: :flag_pr: :flag_ps: :flag_pt: :flag_pw: :flag_py: :flag_qa: :flag_re: :flag_ro: :flag_rs: :flag_ru: :flag_rw: :flag_sa: :flag_sb: :flag_sc: :flag_sd: :flag_se: :flag_sg: :flag_sh: :flag_si: :flag_sj: :flag_sk: :flag_sl: :flag_sm: :flag_sn: :flag_so: :flag_sr: :flag_ss: :flag_st: :flag_sv: :flag_sx: :flag_sy: :flag_sz: :flag_ta: :flag_tc: :flag_td: :flag_tf: :flag_tg: :flag_th: :flag_tj: :flag_tk: :flag_tl: :flag_tm: :flag_tn: :flag_to: :flag_tr: :flag_tt: :flag_tv: :flag_tw: :flag_tz: :flag_ua: :flag_ug: :flag_um: :flag_us: :flag_uy: :flag_uz: :flag_va: :flag_vc: :flag_ve: :flag_vg: :flag_vi: :flag_vn: :flag_vu: :flag_wf: :flag_ws: :flag_xk: :flag_ye: :flag_yt: :flag_za: :flag_zm: :flag_zw:".split(" ")
      }
    };

    // CREATE EMOJI CONTAINER AND LOAD SECTION HEADER
    var createContainer = function(el) {
      $('<div class="' + emojiContainer + '"><nav></nav></div>').insertAfter(el);

      var navItems = '';
      $.each(emojiList,
        function(k, v) {
          var emoji = emojione.shortnameToImage(v["header"]);
          navItems += '<div class="tab' + (navItems == "" ? ' active' : '') + '" data-tab="' + k + '" onclick="">' + emoji + '</div>';
        }
      );

      $("." + emojiContainer + " nav").append(navItems);

      $("." + emojiContainer + " nav .tab").click(
        function() {
          loadEmojies($(this).attr("data-tab"));
        }
      );

      // EMOJI CLICK EVENT
      $(document).off("click", "." + emojiContainer + " section .emojione");
      $(document).on("click", "." + emojiContainer + " section .emojione",
        function() {
          var textAreaTxt;
          var caretPos = activeEl.selectionStart;
          if (activeEl.constructor.name == "HTMLDivElement") {
            textAreaTxt = activeEl.firstChild.data;

          } else {
            textAreaTxt = $(activeEl).val();
          }
          var txtToAdd;
          if (settings.type == "shortcode") {
            txtToAdd = $(this).attr("title") + " ";
          } else {
            txtToAdd = $(this).attr("alt") + " ";
          }
          if (activeEl.constructor.name == "HTMLDivElement") {
            activeEl.firstChild.data = textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos);
          } else {
            $(activeEl).val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
          }
          $(activeEl).focus();
          activeEl.selectionStart = caretPos + txtToAdd.length;
          activeEl.selectionEnd = caretPos + txtToAdd.length;
        }
      );
    };

    // GENERATE / CHANGE EMOJI SECTION
    var loadEmojies = function(section) {
      if ($("." + emojiContainer + " section." + section).length > 0) {
        if ($("." + emojiContainer + " .tab[data-tab='" + section + "']").hasClass("active")) {
          return;
        }

        $("." + emojiContainer + " section").fadeOut().promise().done(
          function() {
            $(this).hide();
            $("." + emojiContainer + " section." + section).fadeIn();
            $("." + emojiContainer + " .tab").removeClass("active");
            $("." + emojiContainer + " .tab[data-tab='" + section + "']").addClass("active");
          }
        );

        return;
      }

      if (typeof(emojiList[section]) == "undefined") {
        return;
      }

      var sectionHtml = '';
      $.each(emojiList[section].content,
        function(k, v) {
          sectionHtml += emojione.shortnameToImage(v);
        }
      );

      $('<section class="' + section + '">' + sectionHtml + '</section>').insertAfter("." + emojiContainer + " nav");

      $("." + emojiContainer + " section").fadeOut().promise().done(
        function() {
          $("." + emojiContainer + " section." + section).fadeIn();
          $("." + emojiContainer + " .tab").removeClass("active");
          $("." + emojiContainer + " .tab[data-tab='" + section + "']").addClass("active");
        }
      );
    };

    // LOAD EMOJIONE
    var init = (function() {
      var script = document.createElement("script"),
        head = document.querySelector("head"),
        style = document.createElement('link');

      script.src = 'https://cdn.jsdelivr.net/emojione/2.2.7/lib/js/emojione.min.js';
      style.type = "text/css";
      style.href = "https://cdn.jsdelivr.net/emojione/2.2.7/assets/css/emojione.min.css";

      head.appendChild(style);
      head.appendChild(script);

      script.onload = function() {
        createContainer($el[0]);

        $.each($el, function(i, el) {
          var picker = $('<div class="emojionepicker-picker" data-index="' + i + '"></div>').insertAfter(el);

          // SET ACTIVE TEXTAREA
          picker.bind("click", function() {
            activeEl = el;
          });

          var elOffset = $(el).offset();

          picker.css({
            "top": elOffset["top"] + settings.pickerTop + "px",
            "left": $(el).width() + elOffset["left"] - $(".emojionepicker-picker").width() - settings.pickerRight + "px",
          }).show();
        });

        // EMOJI PICKER CLICK EVENT
        $(".emojionepicker-picker").click(
          function() {
            if ($("." + emojiContainer).is(":visible")) {
              $("." + emojiContainer).fadeOut();
              return;
            }

            // LOAD SECTION EMOJIES
            loadEmojies($("." + emojiContainer + " nav div.active").attr("data-tab"));

            var containerH = $("." + emojiContainer).height();
            var containerW = $("." + emojiContainer).width();
            var pickerOffset = $(this).offset();

            var top, left;
            if (pickerOffset["top"] > (containerH - 15)) {
              top = pickerOffset["top"] - containerH - 15;
            } else {
              top = pickerOffset["top"] + $(this).height() + 15;
            }

            if (pickerOffset["left"] > containerW) {
              left = pickerOffset["left"] - containerW + $(this).width();
            } else {
              left = pickerOffset["left"];
            }

            $("." + emojiContainer).css({
              "top": top + "px",
              "left": left + "px",
            }).fadeIn();
          }
        );

        // HIDE EMOJI CONTAINER ON CLICK ANYWHERE OUTSIDE THE ELEMENT
        $(document).on("click",
          function(e) {
            if ($("." + emojiContainer).is(":visible") == false || $(e.target).is(".emojionepicker-picker, .emojione")) {
              return;
            }

            $("." + emojiContainer).fadeOut();
          }
        );
      }
    })();

    return this;
  };
}(jQuery));

HTMLDivElement.prototype.selectionStart = 0;
HTMLDivElement.prototype.selectionEnd = 0;

function update(e) {
  var caret = window.getSelection().anchorOffset;
  e.target.selectionStart = caret;
  e.target.selectionEnd = caret + window.getSelection().focusOffset;
}

['mousedown', 'mouseup', 'keydown', 'keyup'].forEach(function(evt) {
  document.getElementById("theDiv").addEventListener(evt, update);
});

$("#theDiv").emojionePicker();

#theDiv {
  margin-top: 2em;
  height: 75px;
  width: 90%;
  border: 1px solid #000;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://www.jqueryscript.net/demo/jQuery-EmojiOne-Based-Emoji-Picker-For-Textarea/dist/emojione.picker.css" rel="stylesheet" type="text/css">
<div id="theDiv" contentEditable="true">
  A contentEditable div
</div>


问:
Responsive images with high performance
I'm making a new webiste and I want to configure it to load different image in mobile version.

I saw some solutions that can fit my needs.
My question is what is the best solution for high performance.
What is the solution that will prevent the explorer to load unnecessary contents.

One method is using html5's  element:

```<code><picture>
 <source srcset="img_smallflower.jpg" media="(max-width: 400px)">
 <source srcset="img_flowers.jpg">
  <img src="img_flowers.jpg" alt="Flowers">
</picture>
</code>```

Another method is using css display property:

```<code>.img-responsive.mobile {
  display: none;
}

@media only screen and (max-device-width: 480px) {
  .img-responsive {
    display: none;
  }
  .img-responsive.mobile {
    display: block;
 }
}
<body>
    <img src="img_flowers.jpg" class="img-responsive careerpage">
    <img src="img_smallflower.jpg" class="img-responsive careerpage mobile">  </body>
</code>```

I don't know any other methods.
I would like to know what is the best option for high performance
thank you

答:
All you need to do is to set a few CSS attributes to the img-responsive class, for example:</p>

```<code>.img-responsive {
  width: 100%;
  max-width: 400px;
  height: auto;
}
</code>```

Title: Responsive images with high performance

Body:
I'm making a new webiste and I want to configure it to load different image in mobile version.

I saw some solutions that can fit my needs.
My question is what is the best solution for high performance.
What is the solution that will prevent the explorer to load unnecessary contents.

One method is using html5's  element:

<picture>
 <source srcset="img_smallflower.jpg" media="(max-width: 400px)">
 <source srcset="img_flowers.jpg">

</picture>

Another method is using css display property:

.img-responsive.mobile {
  display: none;
}

@media only screen and (max-device-width: 480px) {
  .img-responsive {
    display: none;
  }
  .img-responsive.mobile {
    display: block;
 }
}

I don't know any other methods.
I would like to know what is the best option for high performance
thank you

Body:
All you need to do is to set a few CSS attributes to the img-responsive class, for example:

.img-responsive {
  width: 100%;
  max-width: 400px;
  height: auto;
}