text:
Q: "Error calling Driver#connect" using Hibernate This is my cfg.xml file:

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=hiber;</property>
    <property name="connection.username">Costi-PC\Costi</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="model.User" />

User class and Main class:
@Entity
    public class User {

        @Id
        private int userId;
        private String userName;

        public int getUserId() {..}
        public void setUserId(int userId) {..}
        public String getUserName() {..}
        public void setUserName(String userName) {..}

    }

    public class Main {

        public static void main(String[] args) {
           User user = new User();
           user.setUserId(1);
           user.setUserName("Costi");

           AnnotationConfiguration configuration = new AnnotationConfiguration();
           configuration.configure();

           SessionFactory sessionFactory = configuration.buildSessionFactory();

           Session session = sessionFactory.openSession();
           session.beginTransaction();
           session.save(user);
           session.getTransaction().commit();
           session.close();

           sessionFactory.close();

}

When I run the program i get this error:
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:132)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
    at main.Main.main(Main.java:23)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
    ... 14 more

I'm using sql server 2008.
I tried different types of cfg configuration  but none seems to work.
I believe the problem is from connection.url. I tried to change the port (1433) but nothing.
Can anyone tell what's the problem ?

A: I have Faced Same issue just i have changed the Version on mysql  server connector than works fine
    <!-- commented as it was not make to connect
       <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.34</version>
       </dependency>
   -->

added latest version of mysql connector
   <!-- added latest version of mysql connector -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>

A: I know this post is almost 2 years old, but for me the questions gave me, for me, the right answer. And because people with the same question are getting this post from Google. I thought, lets add my story.
Same thing, same problem. And for me the answer was that SQL Server didn't accept connections from the outside. The tcp/ip network client configuration is standard disabled.
So it was for me a hint in the right direction.

A: I changed the version of MySql like,
From 5.1.8
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.8</version>
    </dependency>

To 8.0.19
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>

It works for me.
Thank you.

A: Use This with all Permission of DB
 <property name="hibernate.connection.url">jdbc:mysql://ip:3306/dbname</property><property name="hibernate.connection.username">*******</property>
     <property name="hibernate.connection.password">*******</property>

A: Try going to the command line and see if sqlserver is indeed listening to that port. On windows this would be the command:
netstat -nao | findstr 1433

Then see if the PID is Sql Server as expected in the windows (Ctr+Alt+Delete) process list.
If the server is running, try to connect to it using a SQL client GUI, see here for examples.  When you can connect to the database from an external client successfully, try again from the Java program.
Try to see also if your local firewall settings to see if the firewall is the cause for the error, although by default firewalls do not block  localhost - have a look at this answer.

A: Check you Sid in

hibernate.cfg.xml file

For Oracle Express Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

For Oracle Enterprise Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>

A: the error is due to AnnotationConfiguration and making session by it.
you can try this solution:
@Autowired
SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ce);

A: I also face same problem due to some dependency issue. i solve my problem to change sql depenedency which is compatible to my current version of sql server in pom.xml file.

A: I had a same error when migrating from jTDS1.2.8 to mssql-jdbc and for me it helped removing the port number and specifying the named instance in the connection URL within hibernate.cfg.xml
From:
<property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME:1433;databaseName=mydbname;instanceName=MYINSTANCENAME;</property>

To:
  <property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME;instanceName=MYINSTANCENAME;databaseName=mydbname;</property>

Reference: https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017
When using Named and Multiple SQL Server Instances, to use a JDBC URL property, do the following:
jdbc:sqlserver://localhost;instanceName=instance1;integratedSecurity=true;<more properties as required>;

A: if you are using a virtual server or server that is not updated the time zone should update it.
SQL CONSOLE:
SET GLOBAL time_zone = '+3:00';

A: Wrong username or a password in a config hibernate file "hibernate.cfg.xml"

A: Please make sure that the database with which you are trying to connect has already been created in the database with the same name.

A: If you're using Hibernate 4, try switching to Hibernate 5.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.10.Final</version>
</dependency>

This helped me resolve the error.


text:
Q: Command with or without parameter How to define a command
\def\hello{Hello world!}

that can be called with no parameter:
\hello

or with a parameter:
\hello{3}

but that won't be displayed anyway (3 shouldn't be displayed, it's an internal number I'll maybe use later, but for now, it should not be displayed)

A: As pointed out by Steven B. Segletes in a comment,
\newcommand\hello[1][]{Hello world!\gdef\savearg{#1}}

works and saves the optional argument. If the optional argument is not required, then
\newcommand\hello[1][]{Hello World}

is the solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML5 Audio m4a Is it possible to play m4a music files using html5 audio? If that is not possible do you know of any flash player that can play m4a outside JWPlayer, I need a free one.

A: Any Flash player should be able to play MP4 content - this capability is coded into Flash, not the player product built on top of it.
JPlayer is a nice free player that uses HTML5 where it can, and falls back on Flash when it can't.

A: You can use Soundmanager2 which can use Flash fallback if HTML5 does not natively support M4A.
http://www.schillmania.com/projects/soundmanager2/
M4A should be supported by the browsers from companies who support MPEG-4 video and are the licensees of MPEG4-LA patents (Microsoft, Apple).


text:
Q: Match single word length between spaces On a text, I need to match single words with the same length, in order to fill an array. The words could be made of non-word characters and number, but not spaces.
For example, this string:
    A string with a number 100%, and a website www.mysite.org.
using this syntax
    \s[\w\d\W]{6}(?= )
at length of 6, it founds 3 matches but including _with_a which is made of two words (I use underscore to mark the whitespaces). Instead the result should be only string, and number.
Consider that the length number will be increased in a loop in order to catch all text but spaces, and then fill the array.
So, the resulting matches for the previous string, should be:

at 1 should match: A a a
at 3 should match: and
at 4 should match: with
at 5 should match: 100%,
at 6 should match: string number
at 7 should match: website
at 15 should match: www.mysite.org.

A: You can use this regex:
(?:^| )(\S{3})(?= |$)

and grab matched group #1.
RegEx Demo


text:
Q: Getting Output names of Processing algorithms via PyQGIS Calling the results of Processing algorithms in order to plot them to the screen differs depending on the provider used.
An example with QGIS provider:
tmpggis = processing.runalg("qgis:reprojectlayer",vektor,"EPSG:4326",None)
out = tmpggis["OUTPUT"]
qgisLyr = QgsRasterLayer(out, "Orfeo")
QgsMapLayerRegistry.instance().addMapLayer(qgisLyr)

So, for QGIS it is: ["OUTPUT"]    - capital letters
For GRASS it is: ["output"]   - lower case letters
What is the Output name for other providers such as Orfeo Toolbox, SAGA, etc.?

A: It may also depend on the algorithm. For example, the Ordinary Kriging from SAGA returns two outputs (VARIANCE and PREDICTION), but other SAGA algorithm outputs are called OUTPUT. So, you cannot just use a single output name for all algorithms in a provider.
However, there is a way to get output parameter names from any Processing algorithm. We can define the following function (for instance in the QGIS Python console):
import processing

def getAlgOutputNames( algName ):
    for output in processing.Processing.getAlgorithm(algName).outputs:
        print output.name

You can call the function in this way, giving it algorithm names you're interested in:
>>> getAlgOutputNames("grass7:v.surf.idw")
output
>>> getAlgOutputNames("qgis:creategrid")
OUTPUT
>>> getAlgOutputNames("saga:ordinarykriging")
PREDICTION
VARIANCE
>>> getAlgOutputNames("gdalogr:clipvectorsbypolygon")
OUTPUT_LAYER
>>> getAlgOutputNames("lidartools:lasmerge")
OUTPUT_LASLAZ
>>> getAlgOutputNames("taudem:dinfinityavalancherunout")
-rz
-dfs
>>>getAlgOutputNames("otb:radiometricindices")
-out

Note: Remember that you can get algorithm names calling processing.alglist() from the QGIS Python console.


text:
Q: POP3 and IMAP: Setup Gmail & Zoho I wish to use Gmail to handle all of my email needs. Sending, reading, deleting, moving, forwarding etc.. I have a domain with an email at Zoho user@mydomain.com, this is working well.
I've always been confused with POP3 and IMAP regarding which server/client does what. Reading What's the difference between POP3 and IMAP for e-mail? hasen't really made me any smarter.
Here is a flow of the email from user@mydomain.com which I would like:

Incoming email(to: user@mydomain.com) -> Zoho inbox(user@mydomain.com)
  -> Gmail account(user@gmail.com) -> Android client/Web browser

I also would like to send:

Android client/Web browser -> Gmail account(user@gmail.com) -> Zoho
  account(user@mydomain.com) -> Send email(from: user@mydomain.com)

I would also like to setup so that via Gmail I can send emails via user@mydomain.com.
You can say that Gmail is central. How would I set this up? I am guessing it is better to use IMAP as POP3 is old. I would also like to keep copies on Zoho that are not affected by Gmail, so if I delete a message on Gmail that went to user@mydomain.com it would not delete on Zoho (use Zoho as a backup).
What should be the IMAP/POP3 server in this case?
Zoho
POP Configuration details:

*

*Incoming server: pop.zoho.com, Port: 995, SSL

*Outgoing server: smtp.zoho.com, Port: 465, SSL

IMAP Configuration details:

*

*Incoming server: imap.zoho.com, Port: 993, SSL

*Outgoing server: smtp.zoho.com, Port: 465, SSL

Gmail
Incoming Mail (IMAP) Server - Requires SSL

*

*imap.gmail.com
Port: 993
Requires SSL:Yes

Outgoing Mail (SMTP) Server - Requires TLS

*

*smtp.gmail.com
Port: 465 or 587
Requires SSL: Yes
Requires authentication: Yes
Use same settings as incoming mail server

Incoming vs. Outgoing on Zoho

*

*Incoming: Does this mean when Gmail pushes from it's outgoing server to Zohos incoming server?

*Outgoing: Zoho to push from its outgoing server to Gmails incoming server?

Incoming vs. Outgoing on Gmail

*

*Incoming: Does this mean from my Android client/web browser to push to
Gmails incoming server?

*Outgoing: Gmail outgoing server to push to Zohos incoming server?

What do I do in Zoho and what do I do in Gmail?

A: This isn't really a server configuration question. Set Gmail to retrieve email from your Zoho account via pop3 and to send mail through Zoho's SMTP server. That's it.


text:
Q: XML code is not working I'm trying to make a chatbox using PHP, AJAX and JS. There is no syntax error here, but the browser is not showing desired output.  In "message loading please wait," no replacement is happening.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>chat box</title>

<form name="form1">
Enter your chat name:<input type="text" name="uname" />

Your Message:<textarea name="msg" ></textarea>
send

Loading chatlog please wait...

Insert .php code is
<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];

$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
mysql_query("INSERT INTO msg ('usernmae',msg') Values  ('$uname','$msg')");
$result1=mysql_query("SELECT * FROM msg ORDER by id desc");
while($extract= mysql_fetch_array($result1)){
echo $extract['username'].":".$extract['msg']."
";

}

?>

A: In this line:
if(XMLHttp.readystate==1 && XMLHttp.status==200)    {

Try to change readystate to 4. According documentation:

0: request not initialized
  1: server connection established
  2: request received
  3: processing request
  4: request finished and response is ready


text:
Q: Spring security: In 3.1, bypass security filter for only 'GET' requests I want my service to perform authentication only for incoming POST/PUT/DELETE requests and bypass it for any GET requests. Spring versions less than 3.1,  had the 'filters="none"' attribute which could be used to bypass all security filters for a specific URL pattern. In 3.1, 'filters="none"' was deprecated and the alternate solution was to use 'security="none"' attribute for "http" element. This does not support configuration based on type of request coming in (GET/PUT/POST/DELETE).
I am using Spring 3.1.1 and the current config is as below:
<!-- Just un-comment any resource if you don't want authentication to be done on them -->
<http pattern="/base/version" security="none"/>

<!-- Secure resources -->
<http create-session='stateless' entry-point-ref="tokenAuthenticationEntryPoint">
  <custom-filter position="PRE_AUTH_FILTER" ref="tokenAuthenticationFilter" />
  <intercept-url pattern="/v1/abc/**" method="GET" filters="none"/>  //This doesn't work currently
  <intercept-url pattern="/v1/abc/**" method="POST" access="ROLE_USER"/>
  <intercept-url pattern="/v1/abc/**" method="PUT" access="ROLE_USER"/>
  <intercept-url pattern="/v1/abc/**" method="DELETE" access="ROLE_USER"/>
  <intercept-url pattern="/**" access="ROLE_USER" />
</http>

How can I bypass the security filters for pattern="/v1/abc/**" method="GET" in Spring 3.1?

A: I found a way to get around the problem - Using Expression-Based Access Control, I used access="permitAll" which configures authorization without disabling filters.
<!-- Just un-comment any resource if you don't want authentication to be done on them -->
<http pattern="/base/version" security="none"/>

<!-- Secure resources -->
<http create-session='stateless' entry-point-ref="tokenAuthenticationEntryPoint" use-    expressions="true">
  <custom-filter position="PRE_AUTH_FILTER" ref="tokenAuthenticationFilter" />
  <intercept-url pattern="/v1/abc/**" method="GET" access="permitAll"/>
  <intercept-url pattern="/v1/abc/**" method="POST" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/v1/abc/**" method="PUT" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/v1/abc/**" method="DELETE" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
</http>


text:
Q: How to install numpy py3.4 when numpy py2.7 is already installed? I've googled this for a long time to no avail, I hope someone can point out a fix.
I've installed both Python 2.7 and 3.4 along with various packages for Python 2.7 such as matplotlib and numpy.  I'm trying to install matplotlib and its dependencies into Python 3.4.  I'm on Windows 7 (64 bit), the numpy package comes from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
When I right-click to install the numpy py3.4 version, I get the message "Python 3.4 required which was not found in the registry".  How do I proceed?  Thanks very much.


text:
Q: What is proper way to copy this vector char array into a String I'm attempting to use a C API that returns a void** (an array of data arrays) that may consist of any number of each different type (double, long, short, custom struct ... )  The API works okay for all but arrays char arrays.
// a simplified API prototype
void READHISTORY( long id                  // ID in custom database
                , short numFields          // number of fields
                , const timestruct* oldest // oldest time to look up
                , const timestruct* newest // newest time to look up
                , long maxRetVals          // the size of each data array
                , const short DataTypes[]  // types[] length numFields
                , void* theData[]          // pointers to data arrays
                , short* numReturned       // number of returned values
)

To set up the main read, the database is read to see how many fields and their custom defined types.
#define MAXVALS (2048)
long id = 20L;
short vals;  // number of vals returned
tstruct oldest = {2017,1,1,0,0,0};
tstruct newest = {2018,1,1,0,0,0};
int numFields;
std::vector<short> datatypes;

GETFIELDS(id, &numFields, datatypes);  // API to get the number and types of fields
std::vector<void*> values;

for(int i=0; i<numFields; i++) {
    datatypes.push_back(DataTypes[i]);
    switch (DataTypes[i]) { // want the arrays created dynamically
       case -1: // time
          values.push_back(new tstruct[MAXVALS]);break;
       case -2: // short
          values.push_back(new short[MAXVALS]);break;
       case -3: // long
          values.push_back(new long[MAXVALS]);break;
       case -4: // double
          values.push_back(new double[MAXVALS]);break;
       default: // positive numbers are char array length
          values.push_back(new char[DataTypes[i]][MAXVALS]);
    }
}

The READHISTORY call is working and returns data, however I'm getting an exception error for the array of char arrays.
// call the API to get data into the individual data arrays
READHISTORY(id, numFields, &oldest, &newest, MAXVALS, datatypes.data(), values.data(), &vals);

for (int i=0; i<vals ; i++) {
  for(int j=0; j< datatypes.size(); j++) {
    switch(datatypes[j]) {
      case -1: tstruct tval = static_cast<tstruct*>(values[1])[i];   break; // works fine
      case -2: short sval = static_cast<short*>(values[j])[i];       break; // works fine
      case -3: long lval = static_cast<long*>(values[j])[i];         break; // works fine
      case -4: double dval = static_cast<double*>(values[j])[i];     break; // works fine
      ...

      default:
        int len = datatypes[j]; // positive datatypes are the char array length
        char* nchar = new char[len+1];

        // attempting to copy the char gets an access violation is here.
        strncpy(nchar, static_cast<char**>(values[j])[i], len);

        nchar[len+1] = '\0';
        String^ nstr = gcnew String(nchar);
        delete nchar;
        // do something with nstr and so on...
      }
   }
}

Unhandled exception: System.AccessViolationException: Attempted to read or write protected memory.
What am I doing wrong?

A: You are using the wrong constructor to create your vectors:
std::vector<short> values(numFields);

This creates a vector containing numFields null pointers. You later append dynamically allocated arrays, but the null pointers will still be the first elements which READHISTORY will try to use.
Instead just default-construct empty vectors:
std::vector<short> values;


text:
Q: How many words in the lines? I'm learning.
The line containe 3 words in I 'm learning.
echo "i'm learning" |wc -w
2

wc can't count  accurately.
echo "i'm here !" |wc -w
3

Does character ! belong  word in english??
There are tow lines :450th and 805th line in rime.txt.

450:     And now 'twas like all instruments,
  805:      'Tis sweeter far to me

How many words in the two lines?
And now 'twas like all instruments, contains 6 words?
'Tis sweeter far to me contains 5 words?
sample txt--rime.txt

A: "I'm" is one word, not two.
Wikipedia offers these indicators for the boundary between words:

*

*Potential pause --- In English it is not possible to pause in the middle of a contraction.

*Indivisibility --- In English it is not possible to add additional words in the middle of a contraction without first replacing it with its uncontracted multi-word form.

*Phonetic boundaries --- English does not have specific phonetic markers for the beginning and ends of words, so this does not apply to English.

*Orthographic boundaries --- English orthography indicates separations between words with spaces. No spaces are present in a contraction.

A: If you are on a *nix system, including Mac OSX

wc

will give you the word count as the second number, the first is the number of lines, the third number is the character count.


text:
Q: Scrolling performance I have an example that contains some elements. When i scroll so fast elements not showing and slowly loaded. Is this bug or any other problem ?
My html structure:

  This is site header

          Hello World

I created a example. Here is the link. You need to check it with a mobile device.

A: It's not bug. When you are trying to laod image in browser, for the first time, the browser will cache the image for faster laoding in next time. So for the first time it will take some time. If you want to load it faster try to use small size with good pixel ratio image (i.e compressed) , it will load faster when compared to normal one.
If you want read more about browser caching use this link.
Use Chrome lighthouse to check the static data performance(i.e images), check here.
let me know if this works


text: Q: Global Keyboard and Mouse Listener in Chrome OS I'm still learning about developing of Chrome APP. I want to ask if there's a way to monitor or check for keypress and mouseclick event listener outside of the chrome app?


text:
Q: Docker stack memory reservation I'm using both memory reservations and limits in my Docker stack. There is something I haven't found clearly stated in the Docker documentation. Let's say I have a service with the following resource limits and reservations:
deploy:
  replicas: 1
  resources:
    limits:
      memory: 2g
    reservations:
      memory: 2g

Does this mean that 2GB of the RAM of the machine will be exclusive reserved to this service and can't be used by others?. There are some services that have memory spikes but don't use their memory most of the time so I would like to have other containers use that memory space now and then.

A: reserve-memory switch is a configuration for cgroup. You can read answer for your question.
reserve-memory is not guaranteed hard memory reservation for your container in the system. It's a guarantee that the container will not be started if haven't enough memory for a run.


text:
Q: awk keep column value 0 when two columns have value 0 I have infile.txt file with multiple columns and rows like this:
infile.txt
2020  01  13  00  28.5833  77.2000  979  0        282.6  284.3  285.4  0     0
2020  01  13  00  28.5833  77.2000  925  469.578  290.4  296.9  297.7  3.6   5.1
2020  01  13  00  28.5833  77.2000  909  613.987  290.8  298.8  299.5  4.7   3.3
2020  01  13  00  28.5833  77.2000  850  1169.4   288    301.6  303.1  9.3   0
2020  01  13  00  28.5833  77.2000  700  2776.28  279    308.9  309.6  0     7.1
2020  01  13  00  28.5833  77.2000  500  5561.01  258.1  314.6  314.8  14.2  11.9

and, I want to perform some column-based calculation as follows:
awk '{R=0; if($12) R=(('$g'/'$theta_vs')*($11-'$theta_vs')*($8-'$z_s'))/(($12^2)+($13^2)); print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,R }' > test.txt

This work perfect and keep R=0 when $12!=0 but this provides an output value 0 when $12==0 as follows:
outputfile:
2020  01  13  00  28.5833  77.2000  979  0        282.6  284.3  285.4  0     0     0
2020  01  13  00  28.5833  77.2000  925  469.578  290.4  296.9  297.7  3.6   5.1   5.08926
2020  01  13  00  28.5833  77.2000  909  613.987  290.8  298.8  299.5  4.7   3.3   9.01363
2020  01  13  00  28.5833  77.2000  850  1169.4   288    301.6  303.1  9.3   0     8.21755
2020  01  13  00  28.5833  77.2000  700  2776.28  279    308.9  309.6  0     7.1   0
2020  01  13  00  28.5833  77.2000  500  5561.01  258.1  314.6  314.8  14.2  11.9  16.3555

I want to keep R=0 when both $12 && $13 is 0.
How can I make it?
Thank you

A: Could you please try following.
awk -v G="$g" -v theta="$theta_vs" -v z="$z_s" '{R=0; if($12 || $13) R=((G/theta)*($11-theta)*($8-z))/(($12^2)+($13^2)); print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,R }' Input_file

In case your lines have only 13 fields then as per Ed sir's suggestion adding following.
awk -v G="$g" -v theta="$theta_vs" -v z="$z_s" '{R=0; if($12 || $13) R=((G/theta)*($11-theta)*($8-z))/(($12^2)+($13^2)); print $0,R }' Input_file

A: Change
if ($12)

to
if ($12 || $13)

This will assign R if either of them is non-zero, and leave it at 0 if both of them are zero.


text:
Q: Suppress wc -l in data.table's fread I am reading in chunks if a large file (~30 GB) and have noticed that most of time is taken by performing a line count on the entire file.
Read 500000 rows and 49 (of 49) columns from 28.250 GB file in 00:01:09
   4.510s (  7%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
  53.890s ( 79%) Count rows (wc -l)
   0.010s (  0%) Column type detection (first, middle and last 5 rows)
   0.120s (  0%) Allocation of 500000x49 result (xMB) in RAM
   9.780s ( 14%) Reading data
   0.000s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.000s (  0%) Coercing data already read in type bumps (if any)
   0.060s (  0%) Changing na.strings to NA
  68.370s        Total

Is it possible to specify that fread not do a full rowcount every time I read a chunk or is this a necessary step?
EDIT:
Here is the exact command I am running:
fread(pfile, skip = 5E6, nrows = 5E5, sep = "\t", colClasses = rpColClasses, na.strings = c("NA", "N/A", "NULL"), head = FALSE, verbose = TRUE)

A: I'm not sure if you can "turn off" the wc -l command in fread.  That withstanding I do have two answers for you.
Answer 1:  Use the Unix command split to break the large data set into chunks before calling fread.  I find that knowing a bit of Unix goes a long way when handling big data sets (i.e. data that does not fit into RAM).
split -b 1m myfile.csv #breaks your file into 1mb chunks.

Answer 2: Using connections.  This approach unfortunately does not work with fread.  Check out my previous post to understand what I mean by using connections.  Strategies for reading in CSV files in pieces?


text:
Q: Which prime numbers is this inequality true for? Inequality
What values of $n$ satisfy the following inequality?

$$2(n-2) < p_n\prod_{i=3}^n \left(\frac{p_i-1}{p_i}\right)$$

Where $p$ are prime numbers and the notation $p_i$ indicates the $i$-th prime number.

See also, for some comments/answers for this
(https://mathoverflow.net/questions/234793/the-values-of-n-which-satisfy-an-inequality-about-prime-numbers/234840?noredirect=1#comment581295_234840)

A: Take $n=10$ and $p_3=5,\ldots ,p_{10}={29}$. Then $2(n-2)=16$, but
$$
p_n\prod_{i=3}^n \frac{p_i-1}{p_i}=29\cdot \frac{5-1}{5}\cdot \frac{7-1}{7}\cdot \frac{11-1}{11}\cdot \frac{13-1}{13}\cdot \frac{17-1}{17}\cdot
\frac{19-1}{19}\cdot \frac{23-1}{23}\cdot \frac{29-1}{29}=13.741408409869844787061101504499000797,
$$
and $16<13.74\cdots $ is false. The infinite product (see here) is
$$
\displaystyle\prod_{i=1}^\infty\left(1-\dfrac{1}{p_i}\right)=\dfrac{1}{\zeta(1)},
$$
so that
$$
\prod_{i=3}^{\infty} \frac{p_i-1}{p_i}=0.
$$
I suppose that there are only a few $n$ where the inequality is true, i.e., for $n\le 5$.

A: This is more of a long comment than an answer, but it might offer some insight beyond what's already in Dietrich Burde's answer.
Let's rewrite the OP's inequality with a slight shift in index and then some rearrangement of terms:
$$\begin{align}
2(n-1)\lt p_{n+1}\prod_{k=3}^{n+1}\left(p_k-1\over p_k\right)
&=p_{n+1}\left(4\over5\right)\left(6\over7\right)\left(10\over11\right)\cdots\left(p_{n+1}-1\over p_{n+1}\right)\\
&=4\left(6\over5\right)\left(10\over7\right)\cdots\left(p_{n+1}-1\over p_n\right)\\
&=3\left(1+{1\over3}\right)\left(1+{1\over5}\right)\left(1+{1\over7}\right)\cdots\left(1+{(p_{n+1}-p_n)-1\over p_n}\right)
\end{align}$$
This suggests an equivalent form for the OP's question:

What values of $n$ satisfy the inequality
$${2\over3}(n-1)\lt\prod_{k=1}^n\left(1+{g_k-1\over p_k}\right)$$
where $g_k=p_{k+1}-p_k$ is the gap to the next prime?

Note that including the prime $p_1=2$ has no effect, since $1+{g_1-1\over p_1}=1+{0\over2}=1$.  Note also that if the terms in the product were just $1+{g_k\over p_k}$, then the product would telescope down to $p_{n+1}\over2$, which is certainly greater than ${2\over3}(n-1)$.  Even if we just drop the $-1$ from the numerator $g_k-1$ for $k$ beyond some (fixed) value $N$, the inequality would reduce to something of the form ${2\over3}(n-1)\lt C_N{p_{n+1}\over p_N}$, which would eventually be satisfied, since $p_n\sim n\log n$.  So for the inequality to fail for most $n\gt5$, which is Dietrich's concluding supposition, the subtraction of $1$ from $g_k$ must continue to be significant, which suggests that a definitive answer must be based on some analysis of the prevalence of relatively small gaps between primes.

A: Write $x = p_n$, so that this inequality can be written in the form
\[2(\pi(x) - 2) < x \prod_{5 \leq p \leq x}\left(1 - \frac{1}{p}\right).\]
That is, the right-hand side is
\[3x \prod_{p \leq x} \left(1 - \frac{1}{p}\right).\]
By Mertens' third theorem, this is asymptotic to
\[\frac{3 e^{-\gamma_0} x}{\log x}\]
as $x \to \infty$, where $\gamma_0$ is the Euler-Mascheroni constant. In particular, $3 e^{-\gamma_0} \approx 1.68$.
On the other hand, the prime number theorem implies that the left-hand side is asymptotic to
\[\frac{2x}{\log x}\]
as $x \to \infty$. So the inequality is false for all sufficiently large $x$ (or equivalently, for all sufficiently large primes $p_n$). With a little extra effort, one can work out for which $x$ this inequality is first false, as in GH from MO's answer on MathOverflow.


text:
Q: Simple VB.Net Wrapper for Ghostscript Dll I love Ghostscript.  You can use it to convert pdf's to graphics files, split and/or merge pdf files, make thumbnails, and a whole bunch of other stuff.  And, it's free, open-source software!
There are scads of posts on web sites on how to use Ghostscript from the command line for all sorts of platforms.  But, I could never find a simple vb.net dll wrapper that used the Ghostscript dll (gsdll32.dll) instead of starting a process to run the Ghostscript command line app.
So, I came up with this code.  I am posting it here in hopes that others can avoid the frustration I felt looking for something simple and straight forward.  It avoids those goofy arrays of byte array objects you see in some code.  It has minimal error handling, but that can be added to suit your application.
Put this code in a module named "GhostscriptDllLib".
Option Explicit On
Imports System.Runtime.InteropServices

'--- Simple VB.Net wrapper for Ghostscript gsdll32.dll

'    (Tested using Visual Studio 2010 and Ghostscript 9.06)

Module GhostscriptDllLib

  Private Declare Function gsapi_new_instance Lib "gsdll32.dll" _
    (ByRef instance As IntPtr, _
    ByVal caller_handle As IntPtr) As Integer

  Private Declare Function gsapi_set_stdio Lib "gsdll32.dll" _
    (ByVal instance As IntPtr, _
    ByVal gsdll_stdin As StdIOCallBack, _
    ByVal gsdll_stdout As StdIOCallBack, _
    ByVal gsdll_stderr As StdIOCallBack) As Integer

  Private Declare Function gsapi_init_with_args Lib "gsdll32.dll" _
    (ByVal instance As IntPtr, _
    ByVal argc As Integer, _
    <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.LPStr)> _
    ByVal argv() As String) As Integer

  Private Declare Function gsapi_exit Lib "gsdll32.dll" _
    (ByVal instance As IntPtr) As Integer

  Private Declare Sub gsapi_delete_instance Lib "gsdll32.dll" _
    (ByVal instance As IntPtr)

  '--- Run Ghostscript with specified arguments

  Public Function RunGS(ByVal ParamArray Args() As String) As Boolean

    Dim InstanceHndl As IntPtr
    Dim NumArgs As Integer
    Dim StdErrCallback As StdIOCallBack
    Dim StdInCallback As StdIOCallBack
    Dim StdOutCallback As StdIOCallBack

    NumArgs = Args.Count

    StdInCallback = AddressOf InOutErrCallBack
    StdOutCallback = AddressOf InOutErrCallBack
    StdErrCallback = AddressOf InOutErrCallBack

    '--- Shift arguments to begin at index 1 (Ghostscript requirement)

    ReDim Preserve Args(NumArgs)
    System.Array.Copy(Args, 0, Args, 1, NumArgs)

    '--- Start a new Ghostscript instance

    If gsapi_new_instance(InstanceHndl, 0) <> 0 Then
      Return False
      Exit Function
    End If

    '--- Set up dummy callbacks

    gsapi_set_stdio(InstanceHndl, StdInCallback, StdOutCallback, StdErrCallback)

    '--- Run Ghostscript using specified arguments

    gsapi_init_with_args(InstanceHndl, NumArgs + 1, Args)

    '--- Exit Ghostscript

    gsapi_exit(InstanceHndl)

    '--- Delete instance

    gsapi_delete_instance(InstanceHndl)

    Return True

  End Function

  '--- Delegate function for callbacks

  Private Delegate Function StdIOCallBack(ByVal handle As IntPtr, _
    ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer

  '--- Dummy callback for standard input, standard output, and errors

  Private Function InOutErrCallBack(ByVal handle As IntPtr, _
    ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer

    Return 0

  End Function

End Module

The gsdll32.dll file must be where Windows can find it, best in "\Windows\System32" (or "\Windows\SysWOW64" on a 64-bit machine) or in the same folder as your assembly.  It's not the type of dll that has to be registered (in fact, it cannot be registered).
You can then run Ghostscript using a parameter array like this (this sample converts a pdf file to a high quality png file):
Dim PdfFilePath As String = "<Your pdf file path>"
Dim PngFilePath As String = "<Your png file path>"

RunGS("-q", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=png16m", _
  "-r600", _"-dDownScaleFactor=6", "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4", _
  "-sPAPERSIZE=letter", "-sOutputFile=" & PngFilePath, PdfFilePath)

Or you can run the code using a string array like this (better if arguments are generated dynamically at run time):
Dim PdfFilePath As String = "<Your pdf file path>"
Dim PngFilePath As String = "<Your png file path>"

Dim Args() As String = {"-q", "-dNOPAUSE", "-dBATCH", "-dSAFER", _
  "-sDEVICE=png16m", "-r600", "-dDownScaleFactor=6", "-dTextAlphaBits=4", _
  "-dGraphicsAlphaBits=4", "-sPAPERSIZE=letter", _
  "-sOutputFile=" & PngFilePath, PdfFilePath}

RunGS(Args)

Notes:

*

*Do not enclose input or output file names (paths) in quotes as you
would for the  command line application

*Do not escape back-slashes (i.e. "c:path\file.pdf" is ok, "c:path\\file.pdf" is not)

*Do not use the Ghostscript "-o" switch; use "sOutputFile="


text:
Q: How to get distance by road through Google Map API I want to get distance by road by foot and by car in my app.I have already got distance by line but now I want the exact distance. I have read to enable billing for google account for API key and I have done that. Now I couldn't understand he code I have seen multiple and tried them but can't understand how to use the API available at google guide. Sometimes the app crashes and sometime it gives nothing in response.
On priority what I want to do is to get the exact distance only it can be on foot or on vehicle any. Any help will be very grateful
The last code which I tried but its doing nothing
origin = new LatLng(currentLat, currentLong);
                    dest = new LatLng(donarLat, donarLong);
                    String url = getDirectionsUrl();
                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);

 private String getDirectionsUrl() {
        // Origin of route
        String str_origin = "origin=" + currentLat + "," + currentLong;
        // Destination of route
        String str_dest = "destination=" + donarLat + "," + donarLong;
        // Sensor enabled
        String sensor = "sensor=false";
        // Building the parameters to the web service
        String key = "key=" + "**********NR9TxLUwXyeq0jwV6k************";
        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + key;
        // Output format
        String output = "json";
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

        return url;
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
            // Connecting to url
            urlConnection.connect();
            // Reading data from url
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();
            br.close();
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
        @Override
        protected ArrayList<String> doInBackground(String... urlList) {
            try {
                ArrayList<String> returnList = new ArrayList<String>();
                for (String url : urlList) {
                }
                return returnList;
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
                return null; // Failed, return null
            }
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(ArrayList<String> results) {
            super.onPostExecute(results);

            ParserTask parserTask = new ParserTask();

            for (String url : results) {
                parserTask.execute(url);
            }

        }
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
        // Parsing the data in non-ui thread
        @Override
        protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
            try {
                ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();

                // for (String url : jsonData) {
                for (int i = 0; i < jsonData.length; i++) {
                    JSONObject jObject = new JSONObject(jsonData[i]);

                    DirectionsJSONParser parser = new DirectionsJSONParser();

                    routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
                }
                return routes;
            } catch (Exception e) {
                Log.d("Background task", e.toString());
                return null; // Failed, return null
            }
        }

        @Override
        protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
            if (result.size() < 1) {
                Toast.makeText(DonarList.this, "No Points", Toast.LENGTH_LONG).show();
                return;
            }

            for (int i = 0; i < result.size(); i++) {

                List<HashMap<String, String>> path = result.get(i);
                String distance = "No distance";

                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);

                    if (j == 0) {
                        distance = point.get("distance");
                        continue;
                    }
                }

                Log.d("Distance: ", distance);
                Toast.makeText(DonarList.this, "Your Distance ya hy :" + distance, Toast.LENGTH_SHORT).show();

            }


text:
Q: How to accurately fetch Unix permissions a user has on a given fs object? This is the logic I have now:
  int getInodePermissions(final int uid, final int[] gids, final fsObject inode)
  {
     final int inodeOwner = getOwner(inode);
     final int inodeGroup = getGroup(inode);
     final int inodeMode = getMode(inode);

     int perm;
     if (uid == inodeOwner) {
         perm = (inodeMode >> 6) & 7;
     } else if (isUserInGroup(inodeGroup, gids)) {
        perm = (inodeMode >> 3) & 7;
     } else {
        perm = inodeMode & 7;
     }
     return perm;
  }

But I just realized that if we have e.g. x bit as owner and w bit as group, we should you get both x and w.  I tried looking up some tutorials but they explain individual access not combinations of different groups. Could some either direct me to such a description or list all cases so I can make sure I'm not missing any.

A:
if we have e.g. x bit as owner and w bit as group, we should you get both x and w

Nope!  If you are the owner, you get the owner permissions, not the group permissions, even if you are also in the group.  For example:
> touch example.file

Presuming example.file did not already exist, if you have a normal umask, the file's permissions will be 664, with your eponymous group as the group.  Now:
> sudo chmod 077 example.file
> echo whatever >> example.file
bash: example.file: Permission denied

Even though you are in the group and the group has rwx permission, you are denied because you are the owner, and the owner has no permissions.
So, what you already have is correct!


text:
Q: Understanding use of CloudFormation cfn-signal From the AWS docs
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-signal.html

A common usage pattern is to use cfn-init and cfn-signal together. The
  cfn-signal call uses the return status of the call to cfn-init (using
  the $? shell construct). If the application fails to install, the
  instance will fail to create and the stack will rollback.

Below is my stack
{
    "AWSTemplateFormatVersion" : "2010-09-09",

    "Description" : "AWS CloudFormation Sample Template EC2InstanceWithSecurityGroupSample: Create an Amazon EC2 instance running the Amazon Linux AMI. The AMI is chosen based on the region in which the stack is run. This example creates an EC2 security group for the instance to give you SSH access. **WARNING** This template creates an Amazon EC2 instance. You will be billed for the AWS resources used if you create a stack from this template.",

    "Parameters" : {
      "KeyName": {
        "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance",
        "Type": "AWS::EC2::KeyPair::KeyName",
        "ConstraintDescription" : "Must be the name of an existing EC2 KeyPair."
      },

      "InstanceType" : {
        "Description" : "WebServer EC2 instance type",
        "Type" : "String",
        "Default" : "t2.micro",
        "AllowedValues" : [ "t1.micro", "t2.nano", "t2.micro", "t2.small", "t2.medium", "t2.large", "m1.small", "m1.medium",
                            "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge",
                            "m3.2xlarge", "m4.large", "m4.xlarge", "m4.2xlarge", "m4.4xlarge", "m4.10xlarge", "c1.medium", "c1.xlarge",
                            "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge",
                            "c4.8xlarge", "g2.2xlarge", "g2.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge",
                            "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "d2.xlarge", "d2.2xlarge", "d2.4xlarge", "d2.8xlarge"]
  ,
        "ConstraintDescription" : "Must be a valid EC2 instance type."
      },

      "SSHLocation" : {
        "Description" : "The IP address range that can be used to SSH to the EC2 instances",
        "Type": "String",
        "MinLength": "9",
        "MaxLength": "18",
        "Default": "0.0.0.0/0",
        "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
        "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x."
     }
    },

    "Mappings" : {
      "AWSInstanceType2Arch" : {
        "t1.micro"    : { "Arch" : "PV64"   }, "t2.nano"     : { "Arch" : "HVM64"  }, "t2.micro"    : { "Arch" : "HVM64"  },
        "t2.small"    : { "Arch" : "HVM64"  }, "t2.medium"   : { "Arch" : "HVM64"  }, "t2.large"    : { "Arch" : "HVM64"  },
        "m1.small"    : { "Arch" : "PV64"   }, "m1.medium"   : { "Arch" : "PV64"   }, "m1.large"    : { "Arch" : "PV64"   },
        "m1.xlarge"   : { "Arch" : "PV64"   }, "m2.xlarge"   : { "Arch" : "PV64"   }, "m2.2xlarge"  : { "Arch" : "PV64"   },
        "m2.4xlarge"  : { "Arch" : "PV64"   }, "m3.medium"   : { "Arch" : "HVM64"  }, "m3.large"    : { "Arch" : "HVM64"  },
        "m3.xlarge"   : { "Arch" : "HVM64"  }, "m3.2xlarge"  : { "Arch" : "HVM64"  }, "m4.large"    : { "Arch" : "HVM64"  },
        "m4.xlarge"   : { "Arch" : "HVM64"  }, "m4.2xlarge"  : { "Arch" : "HVM64"  }, "m4.4xlarge"  : { "Arch" : "HVM64"  },
        "m4.10xlarge" : { "Arch" : "HVM64"  }, "c1.medium"   : { "Arch" : "PV64"   }, "c1.xlarge"   : { "Arch" : "PV64"   },
        "c3.large"    : { "Arch" : "HVM64"  }, "c3.xlarge"   : { "Arch" : "HVM64"  }, "c3.2xlarge"  : { "Arch" : "HVM64"  },
        "c3.4xlarge"  : { "Arch" : "HVM64"  }, "c3.8xlarge"  : { "Arch" : "HVM64"  }, "c4.large"    : { "Arch" : "HVM64"  },
        "c4.xlarge"   : { "Arch" : "HVM64"  }, "c4.2xlarge"  : { "Arch" : "HVM64"  }, "c4.4xlarge"  : { "Arch" : "HVM64"  },
        "c4.8xlarge"  : { "Arch" : "HVM64"  }, "g2.2xlarge"  : { "Arch" : "HVMG2"  }, "g2.8xlarge"  : { "Arch" : "HVMG2"  },
        "r3.large"    : { "Arch" : "HVM64"  }, "r3.xlarge"   : { "Arch" : "HVM64"  }, "r3.2xlarge"  : { "Arch" : "HVM64"  },
        "r3.4xlarge"  : { "Arch" : "HVM64"  }, "r3.8xlarge"  : { "Arch" : "HVM64"  }, "i2.xlarge"   : { "Arch" : "HVM64"  },
        "i2.2xlarge"  : { "Arch" : "HVM64"  }, "i2.4xlarge"  : { "Arch" : "HVM64"  }, "i2.8xlarge"  : { "Arch" : "HVM64"  },
        "d2.xlarge"   : { "Arch" : "HVM64"  }, "d2.2xlarge"  : { "Arch" : "HVM64"  }, "d2.4xlarge"  : { "Arch" : "HVM64"  },
        "d2.8xlarge"  : { "Arch" : "HVM64"  }
      }
  ,
      "AWSRegionArch2AMI" : {
        "us-east-1"        : {"PV64" : "ami-2a69aa47", "HVM64" : "ami-97785bed", "HVMG2" : "ami-0a6e3770"},
        "us-west-2"        : {"PV64" : "ami-7f77b31f", "HVM64" : "ami-f2d3638a", "HVMG2" : "ami-ee15a196"},
        "us-west-1"        : {"PV64" : "ami-a2490dc2", "HVM64" : "ami-824c4ee2", "HVMG2" : "ami-0da4a46d"},
        "eu-west-1"        : {"PV64" : "ami-4cdd453f", "HVM64" : "ami-d834aba1", "HVMG2" : "ami-af8013d6"},
        "eu-west-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-403e2524", "HVMG2" : "NOT_SUPPORTED"},
        "eu-west-3"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-8ee056f3", "HVMG2" : "NOT_SUPPORTED"},
        "eu-central-1"     : {"PV64" : "ami-6527cf0a", "HVM64" : "ami-5652ce39", "HVMG2" : "ami-1d58ca72"},
        "ap-northeast-1"   : {"PV64" : "ami-3e42b65f", "HVM64" : "ami-ceafcba8", "HVMG2" : "ami-edfd658b"},
        "ap-northeast-2"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-863090e8", "HVMG2" : "NOT_SUPPORTED"},
        "ap-northeast-3"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-83444afe", "HVMG2" : "NOT_SUPPORTED"},
        "ap-southeast-1"   : {"PV64" : "ami-df9e4cbc", "HVM64" : "ami-68097514", "HVMG2" : "ami-c06013bc"},
        "ap-southeast-2"   : {"PV64" : "ami-63351d00", "HVM64" : "ami-942dd1f6", "HVMG2" : "ami-85ef12e7"},
        "ap-south-1"       : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-531a4c3c", "HVMG2" : "ami-411e492e"},
        "us-east-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-f63b1193", "HVMG2" : "NOT_SUPPORTED"},
        "ca-central-1"     : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-a954d1cd", "HVMG2" : "NOT_SUPPORTED"},
        "sa-east-1"        : {"PV64" : "ami-1ad34676", "HVM64" : "ami-84175ae8", "HVMG2" : "NOT_SUPPORTED"},
        "cn-north-1"       : {"PV64" : "ami-77559f1a", "HVM64" : "ami-cb19c4a6", "HVMG2" : "NOT_SUPPORTED"},
        "cn-northwest-1"   : {"PV64" : "ami-80707be2", "HVM64" : "ami-3e60745c", "HVMG2" : "NOT_SUPPORTED"}
      }

    },

    "Resources" : {
      "EC2Instance" : {
        "Type" : "AWS::EC2::Instance",
        "Metadata" : {
          "AWS::CloudFormation::Init" : {
              "configSets" : {
                  "InstallAndRun" : [ "config1", "config2" ]
              },
              "config1" : {
                  "packages" : {
                      "yum" : {
                          "httpd" : []
                      }
                  },
                  "files" : {
                      "/var/www/html/index.html" : {
                          "mode" : "000644",
                          "owner" : "apache",
                          "group" : "apache",
                          "source" : "https://s3.amazonaws.com/pcr-docs/index.html"
                      }
                  }
              },
              "config2" : {
                  "services" : {
                      "sysvinit" : {
                          "httpd" : {
                              "enabled" : "true",
                              "ensureRunning" : "true",
                              "packages" : { "yum" : ["httpd"] }
                          }
                      }
                  }
              }
          }
      },
        "Properties" : {
          "InstanceType" : { "Ref" : "InstanceType" },
          "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
          "KeyName" : { "Ref" : "KeyName" },
          "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                            { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
          "UserData" : { "Fn::Base64" :
                              { "Fn::Join" : ["", [
                                 "#!/bin/bash -xe\n",
                                 "yum update -y aws-cfn-bootstrap\n",
                                 "# Install the files and packages from the metadata\n",
                                 "/opt/aws/bin/cfn-init -v ",
                                 "         --stack ", { "Ref" : "AWS::StackName" },
                                 "         --resource EC2Instance ",
                                 "         --configsets InstallAndRun ",
                                 "         --region ", { "Ref" : "AWS::Region" }, "\n",
                                 "# Signal the status from cfn-init\n",
                                 "/opt/aws/bin/cfn-signal -e $? ",
                                 "         --stack ", { "Ref" : "AWS::StackName" },
                                 "         --resource EC2Instance ",
                                 "         --region ", { "Ref" : "AWS::Region" }, "\n"
                              ]]}
                      }
        }
      },

      "InstanceSecurityGroup" : {
        "Type" : "AWS::EC2::SecurityGroup",
        "Properties" : {
          "GroupDescription" : "Enable SSH access via port 22",
          "SecurityGroupIngress" : [
            { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"} },
            { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : { "Ref" : "SSHLocation"} }
           ]
        }
      }
    },

    "Outputs" : {
      "InstanceId" : {
        "Description" : "InstanceId of the newly created EC2 instance",
        "Value" : { "Ref" : "EC2Instance" }
      },
      "AZ" : {
        "Description" : "Availability Zone of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "AvailabilityZone" ] }
      },
      "PublicDNS" : {
        "Description" : "Public DNSName of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicDnsName" ] }
      },
      "PublicIP" : {
        "Description" : "Public IP address of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicIp" ] }
      }
    }
  }

It creates the EC2 Instance and runs the cfn-init defined as Instance Metadata, Installs the httpd and copies the index.html file to /var/www/html/index.html
Although stack created the EC2 Instance and reached to CREATE_COMPLETE state, but when I check the System Logs for the Instance from EC2 console. I see an error on cfn-signal , looks like Cloudformation stack was already reached to CREATE_COMPLETE state hence signaling after CREATE_COMPLETE doesn't make sense
Updated:
  aws-cfn-bootstrap.noarch 0:1.4-30.21.amzn1

Complete!
+ /opt/aws/bin/cfn-init -v --stack EC2-cfn-init --resource EC2Instance --configsets InstallAndRun --region us-east-1
+ /opt/aws/bin/cfn-signal -e 0 --stack EC2-cfn-init --resource EC2Instance --region us-east-1
ValidationError: Stack arn:aws:cloudformation:us-east-1:472821263165:stack/EC2-cfn-init/1f08fc80-a148-11e8-9779-500c28b3e2d2 is in CREATE_COMPLETE state and cannot be signaled
Aug 16 11:34:04 cloud-init[2680]: util.py[WARNING]: Failed running /var/lib/cloud/instance/scripts/part-001 [1]

Also If I remove the cfn-signal altogether and just cfn-init to run the Init Metadata script it works the same, stack reaches to CREATE_COMPLETE after creating the Instance.
Again from the docs

You use the cfn-signal script in conjunction with a CreationPolicy or
  an Auto Scaling group with a WaitOnResourceSignals update policy. When
  AWS CloudFormation creates or updates resources with those policies,
  it suspends work on the stack until the resource receives the
  requisite number of signals or until the timeout period is exceeded.

But I'm not clear on when and how we should use cfn-signal?

A: I was missing the CreationPolicy with my cfn-signal, since I was not using CreationPolicy to wait for Bootstrapping on EC2 Instance to complete and Cloudformation stack was already reached to CREATE_COMPLETE state, signaling success after stack was already reached to CREATE_COMPLETE was giving error. I attached the CreationPolicy on EC2 resource so that Cloudformation waits for 1 signal within 5 minutes before proceeding with stack. This solved the problem.
Below is the updated stack with CreationPolicy
{
    "AWSTemplateFormatVersion" : "2010-09-09",

    "Description" : "AWS CloudFormation Sample Template EC2InstanceWithSecurityGroupSample: Create an Amazon EC2 instance running the Amazon Linux AMI. The AMI is chosen based on the region in which the stack is run. This example creates an EC2 security group for the instance to give you SSH access. **WARNING** This template creates an Amazon EC2 instance. You will be billed for the AWS resources used if you create a stack from this template.",

    "Parameters" : {
      "KeyName": {
        "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance",
        "Type": "AWS::EC2::KeyPair::KeyName",
        "ConstraintDescription" : "Must be the name of an existing EC2 KeyPair."
      },

      "InstanceType" : {
        "Description" : "WebServer EC2 instance type",
        "Type" : "String",
        "Default" : "t2.micro",
        "AllowedValues" : [ "t1.micro", "t2.nano", "t2.micro", "t2.small", "t2.medium", "t2.large", "m1.small", "m1.medium",
                            "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge",
                            "m3.2xlarge", "m4.large", "m4.xlarge", "m4.2xlarge", "m4.4xlarge", "m4.10xlarge", "c1.medium", "c1.xlarge",
                            "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge",
                            "c4.8xlarge", "g2.2xlarge", "g2.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge",
                            "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "d2.xlarge", "d2.2xlarge", "d2.4xlarge", "d2.8xlarge"]
  ,
        "ConstraintDescription" : "Must be a valid EC2 instance type."
      },

      "SSHLocation" : {
        "Description" : "The IP address range that can be used to SSH to the EC2 instances",
        "Type": "String",
        "MinLength": "9",
        "MaxLength": "18",
        "Default": "0.0.0.0/0",
        "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
        "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x."
     }
    },

    "Mappings" : {
      "AWSInstanceType2Arch" : {
        "t1.micro"    : { "Arch" : "PV64"   }, "t2.nano"     : { "Arch" : "HVM64"  }, "t2.micro"    : { "Arch" : "HVM64"  },
        "t2.small"    : { "Arch" : "HVM64"  }, "t2.medium"   : { "Arch" : "HVM64"  }, "t2.large"    : { "Arch" : "HVM64"  },
        "m1.small"    : { "Arch" : "PV64"   }, "m1.medium"   : { "Arch" : "PV64"   }, "m1.large"    : { "Arch" : "PV64"   },
        "m1.xlarge"   : { "Arch" : "PV64"   }, "m2.xlarge"   : { "Arch" : "PV64"   }, "m2.2xlarge"  : { "Arch" : "PV64"   },
        "m2.4xlarge"  : { "Arch" : "PV64"   }, "m3.medium"   : { "Arch" : "HVM64"  }, "m3.large"    : { "Arch" : "HVM64"  },
        "m3.xlarge"   : { "Arch" : "HVM64"  }, "m3.2xlarge"  : { "Arch" : "HVM64"  }, "m4.large"    : { "Arch" : "HVM64"  },
        "m4.xlarge"   : { "Arch" : "HVM64"  }, "m4.2xlarge"  : { "Arch" : "HVM64"  }, "m4.4xlarge"  : { "Arch" : "HVM64"  },
        "m4.10xlarge" : { "Arch" : "HVM64"  }, "c1.medium"   : { "Arch" : "PV64"   }, "c1.xlarge"   : { "Arch" : "PV64"   },
        "c3.large"    : { "Arch" : "HVM64"  }, "c3.xlarge"   : { "Arch" : "HVM64"  }, "c3.2xlarge"  : { "Arch" : "HVM64"  },
        "c3.4xlarge"  : { "Arch" : "HVM64"  }, "c3.8xlarge"  : { "Arch" : "HVM64"  }, "c4.large"    : { "Arch" : "HVM64"  },
        "c4.xlarge"   : { "Arch" : "HVM64"  }, "c4.2xlarge"  : { "Arch" : "HVM64"  }, "c4.4xlarge"  : { "Arch" : "HVM64"  },
        "c4.8xlarge"  : { "Arch" : "HVM64"  }, "g2.2xlarge"  : { "Arch" : "HVMG2"  }, "g2.8xlarge"  : { "Arch" : "HVMG2"  },
        "r3.large"    : { "Arch" : "HVM64"  }, "r3.xlarge"   : { "Arch" : "HVM64"  }, "r3.2xlarge"  : { "Arch" : "HVM64"  },
        "r3.4xlarge"  : { "Arch" : "HVM64"  }, "r3.8xlarge"  : { "Arch" : "HVM64"  }, "i2.xlarge"   : { "Arch" : "HVM64"  },
        "i2.2xlarge"  : { "Arch" : "HVM64"  }, "i2.4xlarge"  : { "Arch" : "HVM64"  }, "i2.8xlarge"  : { "Arch" : "HVM64"  },
        "d2.xlarge"   : { "Arch" : "HVM64"  }, "d2.2xlarge"  : { "Arch" : "HVM64"  }, "d2.4xlarge"  : { "Arch" : "HVM64"  },
        "d2.8xlarge"  : { "Arch" : "HVM64"  }
      }
  ,
      "AWSRegionArch2AMI" : {
        "us-east-1"        : {"PV64" : "ami-2a69aa47", "HVM64" : "ami-97785bed", "HVMG2" : "ami-0a6e3770"},
        "us-west-2"        : {"PV64" : "ami-7f77b31f", "HVM64" : "ami-f2d3638a", "HVMG2" : "ami-ee15a196"},
        "us-west-1"        : {"PV64" : "ami-a2490dc2", "HVM64" : "ami-824c4ee2", "HVMG2" : "ami-0da4a46d"},
        "eu-west-1"        : {"PV64" : "ami-4cdd453f", "HVM64" : "ami-d834aba1", "HVMG2" : "ami-af8013d6"},
        "eu-west-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-403e2524", "HVMG2" : "NOT_SUPPORTED"},
        "eu-west-3"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-8ee056f3", "HVMG2" : "NOT_SUPPORTED"},
        "eu-central-1"     : {"PV64" : "ami-6527cf0a", "HVM64" : "ami-5652ce39", "HVMG2" : "ami-1d58ca72"},
        "ap-northeast-1"   : {"PV64" : "ami-3e42b65f", "HVM64" : "ami-ceafcba8", "HVMG2" : "ami-edfd658b"},
        "ap-northeast-2"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-863090e8", "HVMG2" : "NOT_SUPPORTED"},
        "ap-northeast-3"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-83444afe", "HVMG2" : "NOT_SUPPORTED"},
        "ap-southeast-1"   : {"PV64" : "ami-df9e4cbc", "HVM64" : "ami-68097514", "HVMG2" : "ami-c06013bc"},
        "ap-southeast-2"   : {"PV64" : "ami-63351d00", "HVM64" : "ami-942dd1f6", "HVMG2" : "ami-85ef12e7"},
        "ap-south-1"       : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-531a4c3c", "HVMG2" : "ami-411e492e"},
        "us-east-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-f63b1193", "HVMG2" : "NOT_SUPPORTED"},
        "ca-central-1"     : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-a954d1cd", "HVMG2" : "NOT_SUPPORTED"},
        "sa-east-1"        : {"PV64" : "ami-1ad34676", "HVM64" : "ami-84175ae8", "HVMG2" : "NOT_SUPPORTED"},
        "cn-north-1"       : {"PV64" : "ami-77559f1a", "HVM64" : "ami-cb19c4a6", "HVMG2" : "NOT_SUPPORTED"},
        "cn-northwest-1"   : {"PV64" : "ami-80707be2", "HVM64" : "ami-3e60745c", "HVMG2" : "NOT_SUPPORTED"}
      }

    },

    "Resources" : {
      "EC2Instance" : {
        "Type" : "AWS::EC2::Instance",
        "Metadata" : {
          "AWS::CloudFormation::Init" : {
              "configSets" : {
                  "InstallAndRun" : [ "config1", "config2" ]
              },
              "config1" : {
                  "packages" : {
                      "yum" : {
                          "httpd" : []
                      }
                  },
                  "files" : {
                      "/var/www/html/index.html" : {
                          "mode" : "000644",
                          "owner" : "apache",
                          "group" : "apache",
                          "source" : "https://s3.amazonaws.com/pcr-docs/index.html"
                      }
                  }
              },
              "config2" : {
                  "services" : {
                      "sysvinit" : {
                          "httpd" : {
                              "enabled" : "true",
                              "ensureRunning" : "true",
                              "packages" : { "yum" : ["httpd"] }
                          }
                      }
                  }
              }
          }
      },
        "Properties" : {
          "InstanceType" : { "Ref" : "InstanceType" },
          "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
          "KeyName" : { "Ref" : "KeyName" },
          "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                            { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
          "UserData" : { "Fn::Base64" :
                              { "Fn::Join" : ["", [
                                 "#!/bin/bash -xe\n",
                                 "yum update -y aws-cfn-bootstrap\n",
                                 "# Install the files and packages from the metadata\n",
                                 "/opt/aws/bin/cfn-init -v ",
                                 "         --stack ", { "Ref" : "AWS::StackName" },
                                 "         --resource EC2Instance ",
                                 "         --configsets InstallAndRun ",
                                 "         --region ", { "Ref" : "AWS::Region" }, "\n",
                                 "# Signal the status from cfn-init\n",
                                 "/opt/aws/bin/cfn-signal -e $? ",
                                 "         --stack ", { "Ref" : "AWS::StackName" },
                                 "         --resource EC2Instance ",
                                 "         --region ", { "Ref" : "AWS::Region" }, "\n"
                              ]]}
                      }
        },
        "CreationPolicy": {
          "ResourceSignal": {
            "Count": "1",
            "Timeout": "PT5M"
          }
        }
      },

      "InstanceSecurityGroup" : {
        "Type" : "AWS::EC2::SecurityGroup",
        "Properties" : {
          "GroupDescription" : "Enable SSH access via port 22",
          "SecurityGroupIngress" : [
            { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"} },
            { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : { "Ref" : "SSHLocation"} }
           ]
        }
      }
    },

    "Outputs" : {
      "InstanceId" : {
        "Description" : "InstanceId of the newly created EC2 instance",
        "Value" : { "Ref" : "EC2Instance" }
      },
      "AZ" : {
        "Description" : "Availability Zone of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "AvailabilityZone" ] }
      },
      "PublicDNS" : {
        "Description" : "Public DNSName of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicDnsName" ] }
      },
      "PublicIP" : {
        "Description" : "Public IP address of the newly created EC2 instance",
        "Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicIp" ] }
      }
    }
  }


text:
Q: Reading elevation data from WMS response? I am trying to get elevation data from the tile received from USGS server.
I query the data using Image Format image/Png. When I read the data I get color values.
I need to know how to read the elevation values from it.
Is there any documentation or sample available?

A: WMS returns an image of your data, if you want to use it as data then you need a WCS.

A: In a nutshell, you can't. As @iant says, WMS is just imagery that is designed to be displayed on your screen. To get the actual data, you'd need a WCS. If USGS doesn't supply that, then your options are limited.
You could make a guess at a pixel's height value if you know the range over which the greyscale covers. For instance, it might be [0-1000] metres, which means that each shade of grey in a 256-colour image covers a height of 1000/256 ~= 4 metres. So you'd just need to multiply the grey value you get by that number to get an approximate height. But unless your horizontal resolution is quite large, a 4 metre vertical resolution would be a noticeable stair-step.
Also, as WMS is designed to produce pretty maps rather than analysable data, you are likely going to get all sorts of other cruft such as place names, roads, and contour lines, that will throw your calculations right off.
If I were you, I'd investigate where they got their source data from to generate these WMS tiles. If its fairly low resolution, it's probably based on SRTM data, which you can get for free for (almost) anywhere on the earth.
Either that, or petition the USGS to provide a WCS server of the data you want, but I wouldn't hold your breath!


text:
Q: How to retrieve deleted code but still keeping the new code? So, I have this case of merge commit:
           --D--E--
          /        \
--A--B--C-          ---H---
          \        /
           --F--G--

Where :

*

*Commit A, B, and C is in develop branch

*Commit D, E is in feature branch

*Commit F, G is in develop branch, merged from another feature branch

*Commit H is merge feature into develop
The problem is, when i merged feature into develop, we lost some code introduced before the branch, for example :
Before the branch (A, B, C and before that), in file Z we have :
Code 1
Code 2

In feature branch (D, E), the committer removed Code 2 , he also added Code 3 so the file becomes :
Code 1
Code 3

In develop branch (F, G), Code 4 is added so the file becomes :
Code 1
Code 2
Code 4

Now after the merge (H), the file becomes :
Code 1
Code 3
Code 4

But the merge deleted Code 2 because it was deleted in feature.
What I want :
Code 1
Code 2
Code 3
Code 4

The merge didn't show any conflict for this file.
So how do I keep the old code while still having the new code?
One thing to note is that I have pushed this merge to the remote repo.

A: Before I get into all the details below, if you're just asking how to find the deleted code (relatively) easily, you can run git diff on the merge base and the two commits.  This is the same set of diffs that git merge merged.  To find the merge base, use git merge-base:
$ merge=1234567...   # or some other way to locate the merge commit
$ git merge-base --all ${merge}^1 ${merge}^2

Ideally, this prints out just one commit ID, which is the merge base.  You can then git diff that hash ID against ${merge}^1 (the merge's first-parent) and ${merge}^2 (the merge's second parent).

As Tim Biegeleisen noted in a comment, your diagram does not quite seem to match your text.  Fortunately, from the text we can describe a much simpler situation, where problems arise from separate files' interactions.  The effect is the same, but the setup is easier:
       A   <-- branch1
      /
...--*
      \
       B   <-- branch2

Here we have one commit A on branch1 and a different commit B on branch2, both descending from a common base branch whose tip commit is *.  (We only really need to care that commit * exists, for the upcoming merge.)
Suppose that in the merge base, there is a function prepare() defined in shared.py that is not actually used anywhere.  It was meant for use in branch1, and is now used in branch1 from work.py.  But the author of commit B in branch2 decided to delete prepare() precisely because it was never used.
You now wish to combine commits A and B, perhaps as a new commit on branch1:
$ git checkout branch1
$ git merge branch2

Git compares commit * to commit A: this says, among other things, "add call to prepare in file work.py".  This is no problem for Git, because commit B does not even touch file work.py.
Git then compares commit * to commit B: this says, among other things, "remove call to prepare from file shared.py".  This is no problem for Git either, because commit A does not touch this part of shared.py (and maybe even does not touch shared.py at all).
The result is a new merge commit:
       A---C   <-- branch1
      /   /
...--*   /
      \ /
       B   <-- branch2

Git is a tool (pun maybe not intended), not a solution
It is your job, as the person doing the merge, to tell whether Git got the merge right.  Git will get this merge wrong, in part because whoever wrote commit B did the wrong thing.  If you simply run git merge and push the result because the merge succeeded, that's your mistake right there, and you will need to recover from it.  We'll get to this in a moment, but first, let's look at ways to avoid or correct the mistake early.
Test thoroughly
This is not perfect but has the advantage of being easy to do by computer.  If there are good tests, you can do the git merge and then run the tests.  If the tests fail, you know something is wrong with the merge—so stop using it, and go back and fix it.
Scan the merge manually
This catches more errors, but also misses more errors, because it can catch problems that are not being tested-for, but relies on fallible humans.
If you spot a problem this way that does not show up during testing, you may be able to write an automated test to detect it.  If that does not take too long, that's a good idea.
Options for fixing the problem before pushing
Since the merge is not used anywhere, you can just un-make it:
$ git reset --hard HEAD^

which discards the merge (commit C) so that branch1 points to A again.  We do not need to keep the index or work-tree either, since Git made the merge in a fully automated manner.  We now must decide how to fix the problem.
Option 1: restore the missing code on branch2
$ git checkout branch2
... edit shared.py to restore the code ...
$ git add shared.py; git commit

This gives us:
       A      <-- branch1
      /
...--*
      \
       B--C   <-- branch2

where a merge to create D on branch1 will again succeed, but not remove the necessary code.  We can re-merge and re-test.
Option 2: do the merge but don't commit it:
$ git merge --no-commit branch2

Now we can fix up shared.py, git add it, and commit.  This option is fast, but a little bit dirty, because we now have a merge commit that has a manual fixup from a problem not seen by Git itself.  If the problem is found through automated testing, and we consistently use automated testing, and for some reason we have to repeat this merge in the future, we'll re-discover the problem.  If we also comment on this in the merge message, that's probably sufficient.
This option does have the advantage that we did not have to add another commit to branch2.
There's a slight variant of Option 1 that is more work than either, but may be the best of all for some cases (those where disturbing branch2 is a problem): make a new branch with the fixed version of B, and merge that, so that we get:
       A---D   <-- branch1
      /   /
...--*   C     <-- fixed-branch2
      \ /
       B       <-- branch2

Option 3: Fixing things after-the-fact
Of course, what we have now is that the merge has been pushed (or published).  Retracting published merges is even harder than retracting published regular (non-merge) commits, because reverting a merge sets us up to have a different but related failure on subsequent merges.  So we can just leave the "bad" version out there and simply make a fix and push that:
       A---C--D   <-- branch1
      /   /
...--*   /
      \ /
       B   <-- branch2

Commit D, which we make as the new tip of branch1, just puts back the missing function—the same as we would do if we were fixing branch2 directly.
This leaves C behind as a "broken commit".  That's basically just the way things are: people have that commit it; people are using it; so we're kind of stuck with it.  It causes headaches later if/when we go to use git bisect to find a problem, since commit C doesn't really work, but the only alternative is to can get everyone else to scrub the broken commit C from their repositories—in which case, you can "rewrite history" to pretend you used one of the first two options in the first place.
(Fortunately git bisect can deal with broken commits—and if you are going to preserve history, you can use git notes to annotate these commits for automation during bisections.  See http://xkcd.com/974/ for details. :-) )


text:
Q: Deleting user account triggers deletion of another nodes Db structure:
--followers
  -followedUser1
   -user1
  -followedUser2
   -user1
   -user2
--users
  -user1
   -followed
    -followedUser1
    -followedUser2
  -user2(followedUser1)
   -followed
    -followedUser2
  -user3(followedUser2)

Everytime user follows(onCreate) & unfollows(onDelete) under followers/{followedUser}/{followerUser} path, it triggers function which increment or derement count and assigning or detaching posts from follower. It's working via fanout method, and there're no problems. Now, worse part comes when some user deletes account completely together with detaching his followers from himself(because his account will be a ghost), i've set trigger onDelete to indicate whenever it'll happen, then iterating through this user's (i.e.user3) followers removes himself from corresponding followers plus his account, it looks like this then:
--followers
  -followedUser1
   -user1
  -followedUser2
   -user1
   -user2
--users
  -user1
   -followed
    -followedUser1
  -user2(followedUser1)

Now, problematic part - when promise returns i'd like to also remove whole follower/followedUser2(because it's a ghost now) path but... there is a trigger which unfortunately executes for every follower under(onDelete).  So, is there any chance to remove path above(levelup) deletetion trigger without triggering children itself? Or any other approach would be great, thanks
edit: Dont get me wrong, it'll work but if number of followers under followedUser would be "a lot" server will die after 100... trigger

A: At this time, there is no way to filter what deletion events will trigger the function, so you are correct, the function will be triggered once for each user the deleted user was following. I recognize this is one of many use cases where such functionality would be useful, so if you get a chance, please fill out a feature request here.

A: It looks like your multiple-update problem can be fixed with a multi-location updates
In very quickly hacked together and not tested typescript:
export const cleanupFollowers = functions.auth.user().onDelete(event => {
  const user = event.data.userId;
  const followersNode = admin.database().ref(`followers/${user}`);
  const followers = _.keys(await followersNode.once('value'));

  // Every follower also has a reverse node for this user. Get the list of keys:
  const reverseNodesToDelete = followers.map(follower => `followers/${follower}/${user}`);
  // Model this update as a map of deep key -> null to delete all at once
  let cleanup = _.keyBy(reverseNodesToDelete, null);
  // add one more update: deleting full node for the deleted user.
  cleanup[`followers/${user}`] = null;

  // do all deletions as one database request:
  return admin.database().ref().update(cleanup);
 }

Note that this will still fire your counting function, but that should be fine to run in parallel. It probably makes your app simpler to have each invariant captured separately.


text:
Q: Plot do predict para modelo Gamlss ajustado Como faço para fazer e plotar o predict para este modelo Gamlss ajustado?
Meu modelo está apresentado abaixo.
mod<- gamlss(cbind(nfr, nv-nfr)~tt+tr1+d2+d3+random(as.factor(p ))+random(as.factor(id))+random(as.factor(no)),
        data=ta, family = "BI")

A: Seguindo o exemplo do livro "Flexible Regression and Smoothing Using GAMLSS in R", o plot dos valores preditos, ajustados, pode ser feito seguindo o exemplo abaixo.
library(gamlss)
library(dplyr)
library(ggplot2)
data(film90)

# plot das observacoes
plot(lborev1~lboopen, data = film90, col = "lightblue")

model <- gamlss(lborev1~pb(lboopen), data = film90, family = NO)

# plot das observacoes + valores ajustados
plot(lborev1~lboopen, col = "lightgreen", data = film90)
lines(fitted(model)[order(film90$lboopen)]~
        film90$lboopen[order(film90$lboopen)], col = "red", lwd = 2)

film90 <- film90 %>%
  dplyr::mutate(lb2 = lboopen^2,
                lb3 = lboopen^3)
model2 <- gamlss(lborev1~lboopen + lb2 + lb3, data=film90, family=NO)

plot(lborev1~lboopen, col = "lightgreen", data = film90)
lines(fitted(model2)[order(film90$lboopen)]~
        film90$lboopen[order(film90$lboopen)], col = "grey10", lwd = 2)

{
  plot(lborev1~lboopen, col = "lightgreen", data = film90)
  lines(fitted(model)[order(film90$lboopen)]~
          film90$lboopen[order(film90$lboopen)], col = "red", lwd = 2)
  lines(fitted(model2)[order(film90$lboopen)]~
          film90$lboopen[order(film90$lboopen)], col = "grey10", lwd = 2)
}

Também é possível plotar utilizando o ggplot2.
ggplot2::ggplot(film90) +
  geom_point(aes(x = lboopen, y = lborev1), col = "lightgreen", alpha = 0.5) +
  geom_line(aes(x = film90$lboopen[order(film90$lboopen)],
                y = fitted(model)[order(film90$lboopen)]), col = "red") +
  geom_line(aes(x = film90$lboopen[order(film90$lboopen)],
                y = fitted(model2)[order(film90$lboopen)]), col = "black") +
  scale_y_continuous(limits = c(4, 20),
                     expand = c(0, 0)) +
  theme_minimal()

Como seu exemplo não é totalmente reproduzível, adaptei um pouco este do livro. Mas acredito que você não terá problemas para adaptar ao seu caso.
term.plot(model2, pages = 1, partial = T)

Maiores exemplos de emprego do term.plot() podem ser encontradas aqui ou aqui..


text:
Q: Web api open oauth(DotNetOpenAuth) mvc 4 There is an amazing feature in mvc 4 internet application template which can easily integrate with facebook twitter and google. But there is no such feature in web api template.
How can I easily integrate DotNetOpenAuth with web api?
Is there a tutorial?

A: MVC is a browser-facing web site. WebAPI is for programmatic access by some client other than a browser web page (although it may be javascript running in the browser). So OpenID or OAuth login flows that require browser redirects don't make sense for WebAPI. Not directly anyway.
What does seem to apply is that you want your WebAPI to be authorized, and to know what user they represent. The common case then is for WebAPI to act as an OAuth 2 resource server, accepting access tokens that were issued by an authorization server that does accept Facebook, Twitter and Google to log in users before minting these access tokens.
There are several WebAPI samples that do this. Here's one.


text:
Q: Identity column Stored Procedure
CREATE PROCEDURE [dbo].[Insert_Customer]
@id int,
@FName  varchar(50) ,
@MName  varchar(50) ,
@LName  varchar(50) ,
@Age    int ,
@Citizen varchar(50),
@Gender varchar(50) ,
@DOB    varchar(50) ,
@Status varchar(50) ,
@Nationality    varchar(50) ,

@Country    varchar(50) ,
@State  varchar(50) ,
@City   varchar(50) ,
@Address    varchar(MAX)    ,
@Pin    varchar(50) ,
@AccNo int IDENTITY (100,1),
@Branch varchar(50) ,

@IDProof    varchar(50) ,
@IDNo   varchar(50) ,
@IDName varchar(50) ,
@DOI    varchar(50) ,
@Date datetime
AS
BEGIN

Insert into tbl_Customer1
values(@id,@FName,@MName,@LName,@Age,@Citizen,@Gender,@DOB,@Status,@Nationality)

Insert into tbl_Customer2
values(@id,@Country,@State,@City,@Address,@Pin,@accno ,@Branch)

Insert into tbl_Customer3
values(@id,@IDProof,@IDNo,@IDName,@DOI,@Date)

END

Here the error is

Msg 156, Level 15, State 1, Procedure Insert_Customer, Line 28
  Incorrect syntax near the keyword 'IDENTITY'.
  Msg 137, Level 15, State 2, Procedure Insert_Customer, Line 42
  Must declare the scalar variable "@accno".
  Msg 137, Level 15, State 2, Procedure Insert_Customer, Line 44
  Must declare the scalar variable "@IDProof".

A: You cannot declare INT IDENTITY  variable / parameter. If particular column defined as IDENTITY column, you don't have to add it's value insert statement. If you don't specify column value, identity number automatically will set.

A: @AccNo int IDENTITY (100,1),

you cant set a parameter as identity.
Why do you need it in the first place?
This should be only on your table.
Can you explain why do you need it so we can help you?


text:
Q: SQLITE error Unable to open file I want to create a database for an app in the data directory. I tried to use
try{
        String path = "/data/data/"+context+"/database/Einkaufsliste.sqlite";
        database = SQLiteDatabase.openOrCreateDatabase(path,null);
    }

But I get always the following exception:
unable to open database file
Logcat gives the following result:

04-10 19:55:09.387: E/SqliteDatabaseCpp(554):
  sqlite3_open_v2("/data/data/at.einkaufsliste/database/Einkaufsliste.sqlite",
  &handle, 6, NULL) failed 04-10 19:55:09.527: E/SQLiteDatabase(554):
  Failed to open the database. closing it. 04-10 19:55:09.527:
  E/SQLiteDatabase(554):
  android.database.sqlite.SQLiteCantOpenDatabaseException: unable to
  open database file 04-10 19:55:09.527: E/SQLiteDatabase(554):     at
  android.database.sqlite.SQLiteDatabase.dbopen(Native Method) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1013)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  at.einkaufsliste.Database.createOrOpen(Database.java:33) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  at.einkaufsliste.Database.(Database.java:23) 04-10 19:55:09.527:
  E/SQLiteDatabase(554):    at
  at.einkaufsliste.MainActivity.onCreate(MainActivity.java:50) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  android.app.Activity.performCreate(Activity.java:4465) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.app.ActivityThread.access$600(ActivityThread.java:123) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  android.os.Handler.dispatchMessage(Handler.java:99) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  android.os.Looper.loop(Looper.java:137) 04-10 19:55:09.527:
  E/SQLiteDatabase(554):    at
  android.app.ActivityThread.main(ActivityThread.java:4424) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  java.lang.reflect.Method.invokeNative(Native Method) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  java.lang.reflect.Method.invoke(Method.java:511) 04-10 19:55:09.527:
  E/SQLiteDatabase(554):    at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  04-10 19:55:09.527: E/SQLiteDatabase(554):    at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-10
  19:55:09.527: E/SQLiteDatabase(554):  at
  dalvik.system.NativeStart.main(Native Method)

I set the permission EXTERNAL Storage and the group permisson.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<permission-group android:name="android.permission-group.STORAGE"></permission-group>

What is wrong with this usage?

A:
What is wrong with this usage?

NEVER HARDCODE PATHS. /data/data is wrong for many users. Use getDatabasePath() to get the location where a database file should go on internal storage. This will also fix your problems with using string concatenation to build a path.
That would give you:
try {
    database = SQLiteDatabase.openOrCreateDatabase(getDatabasePath("Einkaufsliste.sqlite"), null);
}

assuming that this code is called from a method in a subclass of Context. Otherwise, you will need to arrange to call getDatabasePath() on a Context.

I set the permission EXTERNAL Storage

If by this you mean that you have WRITE_EXTERNAL_STORAGE, that does not matter here, as you are not putting the database on external storage

and the group permisson

I have no idea what that means, sorry.
Also, please consider using SQLiteOpenHelper, to be able to handle database schema changes over time.


text:
Q: Actions on Google V2 webhook external api acces In Actions on Google V1 I could easily parse info to and back from the api with the webhook,
but V2 has a different aproach, It skipped request() functions and only process the conv.tell/conv.ask.
V1 code:
function helpIntent (app) {
        request(API_URL, { json: true }, function (error, response, body) {
              console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
              var msg = body.response;
              app.tell(msg);
        });
}

V2 code:
app.intent('help', (conv) => {
      request(API_URL, { json: true }, function (error, response, body) {
           console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
           var msg = body.response;
           conv.close(msg);
      })
});

So how to make conv.close(msg) was called correctly in V2 code?

A: The issue is that request is an asynchronous operation. With the latest version of the actions-on-google library, if you have an asynchronous call inside your handler, you must return a Promise. Otherwise, when the handler ends, the async function will still be pending, and the code that triggers the handler doesn't know this, so it will return a response immediately.
The easiest way to do this is to use the request-promise-native package instead of the request package. This might make your code look something like this:
app.intent('help', (conv) => {
  var rp = require('request-promise-native');

  var options = {
    uri: API_URL,
    json: true // Automatically parses the JSON string in the response
  };

  return rp(options)
    .then( response => {
      // The response will be a JSON object already. Do whatever with it.
      console.log( 'response:', JSON.stringify(response,null,1) );
      var value = response.msg;
      return conv.close( value );
    });
};


text:
Q: Kendo Grid Filter Suggestion List Html Encoded Is there a way that we can html decode the selection list of the kendo grid filter? Please see my sample output. I want to output a not encoded value. By the way the "ü" value in the picture corresponds to 'ü'.

A: I got it working, you just need to declare a template in Filter Cell.
Code in the backend razor:
.Filterable(f => f
    .Cell( c => c.Template("testFilterTemplate")
)

Code in JS:
testfilterTemplate: function testfilterTemplate(container) {
    container.element.kendoAutoComplete({
        filter: 'contains',
        dataSource: container.dataSource,
        dataTextField: 'testfield',
        valuePrimitive: true,
        template: function kendoAutoCompleteTemplate(data) {
            return data.testfield ? htmlDecode(data.testfield) : '';
        },
        select: function kendoAutoCompleteSelect(e) {
            var dataItem = this.dataItem(e.item.index());
            dataItem.testfield = htmlDecode(dataItem.testfield);
        }
    });


text:
Q: How to put execution time limit on g++? I use the following to compile my C++ Program.
g++ filename.cpp -o filename.o
Then I take an input file and direct the output to the another file.
filename.o < in.txt > out.txt
However sometimes the code goes into an infinite loop and I am not able to stop it (I force quit the .o from Activity Monitor).
What is want it to put an execution limit time on the program so that after it it automatically stops executing. Is there any way to this?
Something like:- g++ filename.cpp -o filename.o [execution_limit_here=10.0s]
Edit:- I am creating an Atom Package and users will compile and execute their code for a particular set of input files, using a simple key combination.
So I can't predict beforehand if the code will go into an infinite loop.

A:
g++ filename.cpp -o filename.o

Very bad taste (even if it could work). By convention *.o files are object files, not executables, but in your compilation command, the fileno.o is the executable output (i.e. produced by g++) by compilation and linking. Read about invoking GCC.
I guess you are on Linux or POSIX (e.g. MacOSX, Android...)
I recommend
  g++ -Wall -Wextra -g filename.cpp -o filename

In that command, we ask for all warnings and debug info, and the executable is named filename (without a confusing .o suffix).
Standard C++ does not know about time limits, but POSIX (so Linux and MacOSX) does, and I recommend using setrlimit(2) with RLIMIT_CPU. That should be coded in the application (you could call setrlimit early in your main).
Otherwise, code a shell like program (or use some shell script with ulimit) to run your executable with some CPU limit and/or use timeout(1).
See also time(7) to understand the various notions of time.
But you really should debug your program (using the gdb debugger to understand its behavior) to always avoid infinite loops. Perhaps you could use some timer facilities (e.g. setitimer(2) and catch the SIGALRM signal(7); read also signal-safety(7)) and/or query in your loops the elapsed real or CPU time (and check it against some threshold).

A: First of all I'd recommend putting printouts on your program so you can figure out why it's getting stuck in an infinite loop, and if you only want to have a time limit you could set a starting time with clock() (from ctime) and after each iteration compare the current time with the starting time point.

A: You could use timeout command while running the executable command
timeout 5 ./a.out

This command will only run the given command (in this case executable) for 5 seconds