问:
PhpMyAdmin SQL query to return multiple records on inner joined tables with count
I have two tables in a database, 'invoices' and 'customers'. I am trying to create a query which displays a list of customers that have placed
two or more orders. The following statements work if I only look at a single customer (in this case customer with id 'C120').

```<code>SELECT `invoices`.date,`customers`.name FROM `invoices`
INNER JOIN `customers`
ON `invoices`.cust_id=`customers`.cust_id
WHERE `invoices`.cust_id = 'C120'
HAVING COUNT(`invoices`.date) >=2;
</code>```

However I would like a view of all customers meeting the search criteria.

I have tried using LIKE in the following form:

```<code>WHERE (`customers`.`cust_id` LIKE 'C%')
</code>```

(all customer ids are four characters beginning with 'C') but all this does is return the first customer in 'customers' which dosen't even satisfy the >= 2 condition.Also tried

```<code>WHERE `invoices`.cust_id = 'C*'
</code>```

which returns an empty set.

I have run out of ideas and would appreciate some help, thanks.

The customer table is as follows:

```<code>cust_id     name
C100    Bloggs
C110    Pekkonen
C120    Finklefluffle
</code>```

The invoice table is:

```<code>date    cust_id     amount
2017-10-09  C100    27.78
2017-11-28  C110    409.66
2017-10-17  C110    2729.3
2017-10-09  C120    2.66
2017-11-06  C110    300
2017-11-21  C120    59.65
</code>```

What I want the reult to be is:

```<code>C110 Pekkonen
C120 Finklefluffle
</code>```

or even better

```<code>C110 Pekkonen 3
C120 Finklefluffle 2
</code>```

What I get with

```<code>WHERE (`customers`.`cust_id` LIKE 'C%')
</code>```

is completely wrong:

```<code>C100    Bloggs
</code>```

and what I get with

```<code>WHERE `invoices`.cust_id = 'C*'
</code>```

is 'empty data set' .. also incorrect.

答:
You may try this</p>

```<code>    SELECT `customers`.cust_id , `customers`.name, count(*) FROM `invoices`
    INNER JOIN `customers`
    ON `invoices`.cust_id=`customers`.cust_id
    GROUP BY `customers`.cust_id , `customers`.name
    HAVING COUNT(`invoices`.date) >=2;
</code>```

Body:
I have two tables in a database, 'invoices' and 'customers'. I am trying to create a query which displays a list of customers that have placed
two or more orders. The following statements work if I only look at a single customer (in this case customer with id 'C120').

SELECT `invoices`.date,`customers`.name FROM `invoices`
INNER JOIN `customers`
ON `invoices`.cust_id=`customers`.cust_id
WHERE `invoices`.cust_id = 'C120'
HAVING COUNT(`invoices`.date) >=2;

However I would like a view of all customers meeting the search criteria.

I have tried using LIKE in the following form:

WHERE (`customers`.`cust_id` LIKE 'C%')

(all customer ids are four characters beginning with 'C') but all this does is return the first customer in 'customers' which dosen't even satisfy the >= 2 condition.Also tried

WHERE `invoices`.cust_id = 'C*'

which returns an empty set.

I have run out of ideas and would appreciate some help, thanks.

The customer table is as follows:

cust_id     name
C100    Bloggs
C110    Pekkonen
C120    Finklefluffle

The invoice table is:

date    cust_id     amount
2017-10-09  C100    27.78
2017-11-28  C110    409.66
2017-10-17  C110    2729.3
2017-10-09  C120    2.66
2017-11-06  C110    300
2017-11-21  C120    59.65

What I want the reult to be is:

C110 Pekkonen
C120 Finklefluffle

or even better

C110 Pekkonen 3
C120 Finklefluffle 2

What I get with

WHERE (`customers`.`cust_id` LIKE 'C%')

is completely wrong:

C100    Bloggs

and what I get with

WHERE `invoices`.cust_id = 'C*'

is 'empty data set' .. also incorrect.

Body:
You may try this

    SELECT `customers`.cust_id , `customers`.name, count(*) FROM `invoices`
    INNER JOIN `customers`
    ON `invoices`.cust_id=`customers`.cust_id
    GROUP BY `customers`.cust_id , `customers`.name
    HAVING COUNT(`invoices`.date) >=2;


来源: stackexchange

问:
Facebook graph API - get custom profile picture size
I'm trying to get the logged in user's profile picture for a canvas app, but I would like to have it in a specific size.

Is this possible and, if so, how?

Currently I'm using the following:

```<code>graph.facebook.com/{user's FB ID}/picture?type=square
</code>```

This gives me a 50px by 50px image. There are also options to use type=normal and type=large to give large image size, but these are not square images, and also not the exact size I am looking for.

To be specific, is there a way to get a member's profile picture in size 80px by 80px directly from Facebook, without downloading a larger image and downsizing/cropping on my end?

答:
https://graph.facebook.com/[[[[insertusersfbid]]]]/picture?type=large
 Is what i fall back to...
https://graph.facebook.com/[[[[insertusersfbid]]]]/picture?width=2000&height=2000
 Is when i want to muck with the image.
If the user does not have an uploaded profilepicture; now fb returns the gender based default pic...
I hope this helps someone else :)</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the logged in user's profile picture for a canvas app, but I would like to have it in a specific size.

Is this possible and, if so, how?

Currently I'm using the following:

graph.facebook.com/{user's FB ID}/picture?type=square

This gives me a 50px by 50px image. There are also options to use type=normal and type=large to give large image size, but these are not square images, and also not the exact size I am looking for.

To be specific, is there a way to get a member's profile picture in size 80px by 80px directly from Facebook, without downloading a larger image and downsizing/cropping on my end?


问:
What is the code for Autocomplete in a ComboBox Using C# and Access 2017?
I want to make Autocomplete in a ComboBox Using C# and Access 2017.So I used this code... But i can not understand what the mean of "&lt"and "&gt". There are some errors with these places. Please help me to fix this error.</p>

```<code>private void Autocomplete()
    {
        string query;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
        //opening connection
        con.Open();
        try
       {
        //initialize a new instance of sqlcommand
         OleDbCommand cmd = new OleDbCommand();
        //set a connection used by this instance of sqlcommand
         cmd.Connection = con;
         //set the sql statement to execute at the data source
         cmd.CommandText = query;

          OleDbDataAdapter da = new OleDbDataAdapter();
         //set the sql statement or stored procedure to execute at the data source
         da.SelectCommand = cmd;
         //initialize a new instance of DataTable
         DataTable dt=new DataTable ();
         //add or resfresh rows in the certain range in the datatable to match those in the data source.
         da.Fill(dt);

         foreach (DataRow r in dt.Rows)
         {
         //getting all rows in the specific field|Column
         var rw = r.Field < string >("IMEI");

         //Set the properties of a combobox to make it auto suggest.
         comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
         comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
         //adding all rows into the combobox
         comboBox1.AutoCompleteCustomSource.Add(rw);

         }
        }
         catch (Exception ex)
         {
          //catching error
          MessageBox.Show(ex.Message);
         }
         //release all resources used by the component
         da.Dispose();
         //clossing connection
         con.Close();
    }
</code>```

答:
< = less than

> = greater than

```<code>var rw = r.Field < string >("IMEI");
</code>```

becomes

```<code>var rw = r.Field<string>("IMEI");
</code>```

Body:
I want to make Autocomplete in a ComboBox Using C# and Access 2017.So I used this code... But i can not understand what the mean of "&lt"and "&gt". There are some errors with these places. Please help me to fix this error.

private void Autocomplete()
    {
        string query;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
        //opening connection
        con.Open();
        try
       {
        //initialize a new instance of sqlcommand
         OleDbCommand cmd = new OleDbCommand();
        //set a connection used by this instance of sqlcommand
         cmd.Connection = con;
         //set the sql statement to execute at the data source
         cmd.CommandText = query;

          OleDbDataAdapter da = new OleDbDataAdapter();
         //set the sql statement or stored procedure to execute at the data source
         da.SelectCommand = cmd;
         //initialize a new instance of DataTable
         DataTable dt=new DataTable ();
         //add or resfresh rows in the certain range in the datatable to match those in the data source.
         da.Fill(dt);

         foreach (DataRow r in dt.Rows)
         {
         //getting all rows in the specific field|Column
         var rw = r.Field < string >("IMEI");

         //Set the properties of a combobox to make it auto suggest.
         comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
         comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
         //adding all rows into the combobox
         comboBox1.AutoCompleteCustomSource.Add(rw);

         }
        }
         catch (Exception ex)
         {
          //catching error
          MessageBox.Show(ex.Message);
         }
         //release all resources used by the component
         da.Dispose();
         //clossing connection
         con.Close();
    }

Body:
&lt; = less than

&gt; = greater than

var rw = r.Field &lt; string &gt;("IMEI");

becomes

var rw = r.Field<string>("IMEI");


问:
Structured Data (schema.org) - openingHours for EducationalOrganization
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

```<code><div itemscope itemtype="http://schema.org/EducationalOrganization" class="ce_text address block">
    <div class="text_container">
        <p>
            <span>
                <strong itemprop="name"><?php echo $this->field('company')->value(); ?></strong><br>
            </span>
        <p itemscope itemtype="http://schema.org/PostalAddress" itemprop="address">
            <span itemprop="streetAddress">
                <?php echo $this->field('street')->value(); ?><br>
            </span>
            <span itemprop="postalCode">
                <?php echo $this->field('zipcode')->value(); ?>
            </span>
            <span itemprop="addressLocality">
                <?php echo $this->field('place')->value(); ?>
            </span>
        </p>
        <p>
            Aus dem Ausland: <span itemprop="telephone"><?php echo $this->field('phone_foreign')->value(); ?></span><br>
            Fax: <span itemprop="telephone"><?php echo $this->field('fax')->value(); ?></span>
        </p>
        <p itemscope itemtype="??????"> <!-- What type can I use here? -->
            <strong>Öffnungszeiten:</strong><br>
            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?><br>
            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>
        </p> <!-- Öffnungszeiten Ende -->
    </div>
</div>
</code>```

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

```<code>    <div itemscope itemtype="http://schema.org/Service">
        <strong>Öffnungszeiten:</strong><br>
        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?><br>
        Freitag: <?php echo $this->field('fri')->value(); ?>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>
        </div>
    </div>
</code>```

答:
Apply the element contactPoint with the extension for the
property ContactPoint.

Next, select and apply  the element hoursAvailable with the
extension for the property OpeningHoursSpecification.

Create something similar:

Name of Organization

Opening hours

     <meta itemprop="hoursAvailable" content="Mo,Tu,We,Th,Fr,Sa,Su 09:00-14:00">

Normally open daily <time datetime="09:00">9am</time>-<time datetime="14:00">2pm</time>

```

Check the structured data on this Google tool and set the required data. Hope this helps.

Body:
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

                <?php echo $this->field('company')->value(); ?>

                <?php echo $this->field('street')->value(); ?>

                <?php echo $this->field('zipcode')->value(); ?>

                <?php echo $this->field('place')->value(); ?>

            Aus dem Ausland: <?php echo $this->field('phone_foreign')->value(); ?>

            Fax: <?php echo $this->field('fax')->value(); ?>

            Öffnungszeiten:

            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?>

            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

        Öffnungszeiten:

        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?>

        Freitag: <?php echo $this->field('fri')->value(); ?>

            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>

Body:
Apply the element contactPoint with the extension for the
property ContactPoint.

Next, select and apply  the element hoursAvailable with the
extension for the property OpeningHoursSpecification.

Create something similar:

<main itemscope itemtype="http://schema.org/EducationalOrganization">
<h1 itemprop="name">Name of Organization</h1>
<section itemprop=contactPoint itemscope itemtype=http://schema.org/ContactPoint>
  <h2>Opening hours</h2>
     <meta itemprop="hoursAvailable" content="Mo,Tu,We,Th,Fr,Sa,Su 09:00-14:00">
    <p>Normally open daily <time datetime="09:00">9am</time>-<time datetime="14:00">2pm</time></p>
</section>
</main>

Check the structured data on this Google tool and set the required data. Hope this helps.


问:
Symfony2: change APC to xcache
Because a Bug in APC, i had to use another Cache-Drive. I removed APC and installed xcache. config.php says Your configuration looks good to run Symfony.

I got the following error on request:

```<code>PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'Unable to use ApcClassLoader as APC is not enabled.' in /var/.../app/bootstrap.php.cache:1039
Stack trace:
#0 /var/.../web/app.php(11): Symfony\\Component\\ClassLoader\\ApcClassLoader->__construct('sf2', Object(Composer\\Autoload\\ClassLoader))
#1 {main}
thrown in /var/...app/bootstrap.php.cache on line 1039
</code>```

How do I tell Symfony to use xcache instead of APC?

答:
You didn't define the use statement for XCache:</p>

```<code>use Symfony\Component\ClassLoader\XcacheClassLoader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\ClassLoader\XcacheClassLoader;
</code>```

Title: Symfony2: change APC to xcache

Body:
Because a Bug in APC, i had to use another Cache-Drive. I removed APC and installed xcache. config.php says Your configuration looks good to run Symfony.

I got the following error on request:

PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'Unable to use ApcClassLoader as APC is not enabled.' in /var/.../app/bootstrap.php.cache:1039
Stack trace:
#0 /var/.../web/app.php(11): Symfony\\Component\\ClassLoader\\ApcClassLoader->__construct('sf2', Object(Composer\\Autoload\\ClassLoader))
#1 {main}
thrown in /var/...app/bootstrap.php.cache on line 1039

How do I tell Symfony to use xcache instead of APC?

Body:
You didn't define the use statement for XCache:

use Symfony\Component\ClassLoader\XcacheClassLoader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\ClassLoader\XcacheClassLoader;


问:
PL/SQL Program that uses a Cursor to Rank
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment. </p>

```<code>CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;
</code>```

<p>I'm trying to get an output like this: </p>

```<code>Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL
</code>```

答:
I have executed the similar one for emp table. You can change it for students table :

1.Without rank over function :

```<code>SELECT x.ranking,ename,sal
FROM  emp e,
    (
SELECT e2.empno, COUNT(*) AS
      ranking
FROM  emp e1,emp e2 WHERE e1.sal<=e2.sal
       GROUP BY  e2.empno
)x

WHERE e.empno=x.empno
ORDER BY sal
</code>```

2.With Rank over function :

```<code>SELECT  RANK () OVER (ORDER BY  sal DESC ) AS ranking ,empno,ename,sal

FROM emp
</code>```

Note: If there are ties, you can use DENSE_RANK

```<code>SELECT  DENSE_RANK () OVER (ORDER BY  sal DESC ) AS ranking ,empno,ename,sal

FROM emp
</code>```

Body:
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment.

CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;

I'm trying to get an output like this:

Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL

Body:
I have executed the similar one for emp table. You can change it for students table :

1.Without rank over function :

SELECT x.ranking,ename,sal
FROM  emp e,
    (
SELECT e2.empno, COUNT(*) AS
      ranking
FROM  emp e1,emp e2 WHERE e1.sal<=e2.sal
       GROUP BY  e2.empno
)x

WHERE e.empno=x.empno
ORDER BY sal

2.With Rank over function :

SELECT  RANK () OVER (ORDER BY  sal DESC ) AS ranking ,empno,ename,sal

FROM emp

Note: If there are ties, you can use DENSE_RANK

SELECT  DENSE_RANK () OVER (ORDER BY  sal DESC ) AS ranking ,empno,ename,sal

FROM emp


问:
How can I use Jar produced by mvn package in another Jenkins declarative pipeline stage?
I'm trying to build CI/CD pipeline with Jenkins for Maven project. I can't seem to find any decent examples on how to use .jar file produced by mvn package in another Jenkins declarative pipeline stage. I need the jar file to make an docker-image before uploading it to docker-registry. Here's my relevant parts of jenkinsfile:

```<code>pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}
</code>```

Dockerfile:

```<code>#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]
</code>```

EDIT 1----------------------------------------------------------------------:

Laszlos answer did the trick, as I noticed that my .jar file was under different name than dockerfile assumed.
Here is my working final jenkinsfile:

```<code>pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                unstash 'targetfiles'
                sh 'ls -l -R'
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}
</code>```

And modified dockerfile:

```<code>#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
#ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
ADD target/AdWordsProducer-1.0-SNAPSHOT.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]
</code>```

答:
You can use the same dockerfile for all stages and just install docker cmd on it and mount the docker.sock to it.

Add this to the Dockerfile:

```<code>RUN apt-get update && \
    apt-get install -y apt-transport-https ca-certificates curl software-properties-common && \
    curl -fsSL https://download.docker.com/linux/centos/gpg | apt-key add - && \
    add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/centos trusty stable" && \
    apt-get update && \
    apt-get install -y docker-ce
</code>```

And run set the Jenkinsfile like this:

```<code>pipeline {
    agent {
       docker {
         image 'maven:3-alpine'
         args '-u root -v /root/.m2:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock'
       }
    }
    stage('Build Jar'){
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {

      steps {
            script{
                sh 'docker build image-name:test'
            }
      }
    }
}
</code>```

Body:
I'm trying to build CI/CD pipeline with Jenkins for Maven project. I can't seem to find any decent examples on how to use .jar file produced by mvn package in another Jenkins declarative pipeline stage. I need the jar file to make an docker-image before uploading it to docker-registry. Here's my relevant parts of jenkinsfile:

pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}

Dockerfile:

#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]

EDIT 1----------------------------------------------------------------------:

Laszlos answer did the trick, as I noticed that my .jar file was under different name than dockerfile assumed.
Here is my working final jenkinsfile:

pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                unstash 'targetfiles'
                sh 'ls -l -R'
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}

And modified dockerfile:

#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
#ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
ADD target/AdWordsProducer-1.0-SNAPSHOT.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]

Body:
You can use the same dockerfile for all stages and just install docker cmd on it and mount the docker.sock to it.

Add this to the Dockerfile:

RUN apt-get update && \
    apt-get install -y apt-transport-https ca-certificates curl software-properties-common && \
    curl -fsSL https://download.docker.com/linux/centos/gpg | apt-key add - && \
    add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/centos trusty stable" && \
    apt-get update && \
    apt-get install -y docker-ce

And run set the Jenkinsfile like this:

pipeline {
    agent {
       docker {
         image 'maven:3-alpine'
         args '-u root -v /root/.m2:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock'
       }
    }
    stage('Build Jar'){
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {

      steps {
            script{
                sh 'docker build image-name:test'
            }
      }
    }
}


问:
Break up a SQL Server 2008 query into batches
I'm trying to prepare some data for deletion by a 3rd party, and unfortunately they can only process data in batches of 2000 records.  I have 100k records and may need to divide-and-export this data several more times, so I'd like to automate the process somehow.

Is there a reasonably easy way to do this using SQL Server 2008?  I'm not running a complex query -- it's not too far off from SELECT PKID FROM Sometable ORDER BY PKID -- and while I can probably do this using a cursor, I'd like to know if there's a better way.

答:
```<code>SET NOCOUNT ON;

CREATE TABLE [dbo].[SyncAudit] ( PkId INT, BatchNumber INT)

DECLARE  @batchsize INT
    ,@rowcount INT
    ,@batchcount INT
    ,@rootdir VARCHAR(2048)
    ,@saveas VARCHAR(2048)
    ,@query VARCHAR(2048)
    ,@bcpquery VARCHAR(2048)
    ,@bcpconn VARCHAR(64)
    ,@bcpdelim VARCHAR(2)

SET     @rootdir    = '\\SERVER1\SHARE1\FOLDER\'
SET     @batchsize  = 2000
SET     @bcpdelim   = '|'
SET     @bcpconn    = '-T' -- Trusted
--SET       @bcpconn    = '-U <username> -P <password>' -- SQL authentication

SELECT  @rowcount   = COUNT(1),
    @batchcount = CEILING(COUNT(1)/@batchsize) FROM <@TableName, string, 'SomeTable'>

SELECT [BatchSize] = @BatchSize, [BatchCount] = @Batchcount

INSERT INTO SyncAudit
SELECT
 <@TableKey, string, 'PKField'>
 ,groupnum = NTILE(@batchcount) OVER ( ORDER BY <@TableKey, string, 'PKField'>)
FROM
<@TableName, string, 'SomeTable'>

WHILE (@batchcount > 0)
BEGIN

SET @saveas = @rootdir + 'batchnumber-' + cast(@batchcount as varchar) + '.txt'
SET @query = '  SELECT  [<@TableName, string, 'SomeTable'>].*
                FROM    [' + db_name() + '].[dbo].[<@TableName, string, 'SomeTable'>]
                JOIN    [' + db_name() + '].[dbo].[SyncAudit]
                            ON  [<@TableName, string, 'SomeTable'>].<@TableKey, string, 'PKField'> = [SyncAudit].PkId
                            AND [SyncAudit].BatchNumber = ' + cast(@batchcount as varchar) + ''

SET @bcpquery = 'bcp "' + replace(@query, char(10), '') + '" QUERYOUT "' + @saveas + '" -c -t^' + @bcpdelim + ' ' + @bcpconn + ' -S ' + @@servername
EXEC master..xp_cmdshell @bcpquery

--EXEC (@query)

SET @batchcount = @batchcount -1
END

DROP TABLE [dbo].[SyncAudit] -- or leave for reference
</code>```

ContentLicense: CC BY-SA 2.5


问:
GoogleMaps, Reverse geocode, return street_address
I have a form that allows the user to create a new marker on the Google Map, with an infoWindow containing info the user provides.  One field allows the user to enter a description of the location (i.e. "Buds Burgers on Sonoma in Vallejo") and a marker will be created with the exact same info in what I have labeled as "Location.address".  My goal is to reverse geocode the given coordinates and output the street address for any location provided. I am able to console.log the lat and lng so I know that I can access them, I just haven't been able to figure out how do I use them.

location.rb

```<code>create_table "locations", force: :cascade do |t|
    t.string   "location_name"
    t.string   "location_address"
    t.string   "location_description"
    t.float    "lat"
    t.float    "lng"
    t.datetime "created_at",           null: false
    t.datetime "updated_at",           null: false
  end
</code>```

The script running on my map page:

```<code><script>
    map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(37.725685, -122.156830),
                mapTypeId: google.maps.MapTypeId.ROADMAP
                });

      var places = <%= @locations.to_json.html_safe %>
      var infowindow = new google.maps.InfoWindow();
      var marker, i;
      for (i = 0; i < places.length; i++) {
        marker = new google.maps.Marker({
        position: new google.maps.LatLng(places[i].lat, places[i].lng),
        map: map
        });
        var lat = (places[i].lat);
        var lng = (places[i].lng);

        console.log(" lat: " +  places[i].lat + " " + "lng: " + places[i].lng);
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(places[i].location_name + "   <br />  " + places[i].location_description  + "    <br />     " + places[i].location_address);
            infowindow.open(map, marker);
          }
        })(marker, i));
      }
</script>
</code>```

Form:

```<code> <%= form_for @location, :html => { :class => "form-inline" } do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :location_name %><br />

  <%= f.label "Description or Discount Offered" %>:
  <%= f.text_field :location_description %><br />

  <%= f.label :address %>:
  <%= f.text_field :location_address %><br />

  <%= f.submit "Create New Location"%>
 <% end %>
</code>```

I am at my wits end.  Help please.

Thank you.

答:
I am not familiar with Ruby-on-Rails but I can definitely help you in Google Maps API. Let's just use coordinates places[i].lat and places[i].lng since you said in your post that you can log their values.

You wanted to Reverse Geocode the coordinates you acquired.

Reverse geocoding
  is the process of converting geographic coordinates into a
  human-readable address.

Let's start by creating a new Geocoder instance.

```<code>var geocoder = new google.maps.Geocoder();
</code>```

This means that a new instance of Geocoder Object has been created using variable "geocoder". You can now use Geocoder's geocode method.

In Reverse Geocoding, geocode method accepts 2 arguments - location, and callback. You need to use "location" parameter and supply a comma-separated latitude/longitude or you can simply use new google.maps.LatLng(lat, lng) object. The value of this should be the coordinates you acquired.

```<code>geocoder.geocode( { 'location' : new google.maps.LatLng(places[i].lat, places[i].lng) }, callback );
</code>```

On the other hand, the callback arguments need two arguments as well. The first is for the result, and the other is for the status. You can name the arguments, whatever you want. This is where most of our logic will be implemented.

```<code>function(results, status) {
   if ( status === 'OK' ) {
   }
}
</code>```

In the callback function, there's should be a condition that checks if the returned status is 'OK'. If so, the results arguments will return an array of results. There's a note in Reverse Geocoding documentation:

The reverse geocoder often returns more than one result.  Geocoded
  addresses are not just postal addresses, but any way to geographically
  name a location.

You can get the formatted address under results[0].formatted_address. You can also get address_components such as "street_number", "route", "locality", and "country" and append it to the DOM. I recommend using an external library using JQuery to make DOM manipulation easier. You can do something like this:

```<code>function(results, status) {
   if ( status === 'OK' ) {
   $('div#street_name').html('<p>'+results[0].formatted_address.+'</p>');
   }
}
</code>```

The whole code looks something like this:

```<code>var geocoder = new google.maps.Geocoder();

geocoder.geocode( { 'location' : new google.maps.LatLng(places[i].lat, places[i].lng) }, function(results, status) {
   if ( status === 'OK' ) {
   $('div#street_name').html('<p>'+results[0].formatted_address.+'</p>');
   }
});
</code>```

Hope this helps and happy coding!

Body:
I have a form that allows the user to create a new marker on the Google Map, with an infoWindow containing info the user provides.  One field allows the user to enter a description of the location (i.e. "Buds Burgers on Sonoma in Vallejo") and a marker will be created with the exact same info in what I have labeled as "Location.address".  My goal is to reverse geocode the given coordinates and output the street address for any location provided. I am able to console.log the lat and lng so I know that I can access them, I just haven't been able to figure out how do I use them.

location.rb

create_table "locations", force: :cascade do |t|
    t.string   "location_name"
    t.string   "location_address"
    t.string   "location_description"
    t.float    "lat"
    t.float    "lng"
    t.datetime "created_at",           null: false
    t.datetime "updated_at",           null: false
  end

The script running on my map page:

Form:

 <%= form_for @location, :html => { :class => "form-inline" } do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :location_name %>

  <%= f.label "Description or Discount Offered" %>:
  <%= f.text_field :location_description %>

  <%= f.label :address %>:
  <%= f.text_field :location_address %>

  <%= f.submit "Create New Location"%>
 <% end %>

I am at my wits end.  Help please.

Thank you.

Body:
I am not familiar with Ruby-on-Rails but I can definitely help you in Google Maps API. Let's just use coordinates places[i].lat and places[i].lng since you said in your post that you can log their values.

You wanted to Reverse Geocode the coordinates you acquired.

Reverse geocoding
  is the process of converting geographic coordinates into a
  human-readable address.

Let's start by creating a new Geocoder instance.

var geocoder = new google.maps.Geocoder();

This means that a new instance of Geocoder Object has been created using variable "geocoder". You can now use Geocoder's geocode method.

In Reverse Geocoding, geocode method accepts 2 arguments - location, and callback. You need to use "location" parameter and supply a comma-separated latitude/longitude or you can simply use new google.maps.LatLng(lat, lng) object. The value of this should be the coordinates you acquired.

geocoder.geocode( { 'location' : new google.maps.LatLng(places[i].lat, places[i].lng) }, callback );

On the other hand, the callback arguments need two arguments as well. The first is for the result, and the other is for the status. You can name the arguments, whatever you want. This is where most of our logic will be implemented.

function(results, status) {
   if ( status === 'OK' ) {
   }
}

In the callback function, there's should be a condition that checks if the returned status is 'OK'. If so, the results arguments will return an array of results. There's a note in Reverse Geocoding documentation:

The reverse geocoder often returns more than one result.  Geocoded
  addresses are not just postal addresses, but any way to geographically
  name a location.

You can get the formatted address under results[0].formatted_address. You can also get address_components such as "street_number", "route", "locality", and "country" and append it to the DOM. I recommend using an external library using JQuery to make DOM manipulation easier. You can do something like this:

function(results, status) {
   if ( status === 'OK' ) {
   $('div#street_name').html('<p>'+results[0].formatted_address.+'</p>');
   }
}

The whole code looks something like this:

var geocoder = new google.maps.Geocoder();

geocoder.geocode( { 'location' : new google.maps.LatLng(places[i].lat, places[i].lng) }, function(results, status) {
   if ( status === 'OK' ) {
   $('div#street_name').html('<p>'+results[0].formatted_address.+'</p>');
   }
});

Hope this helps and happy coding!


问:
CABasicAnimation: From left to right
With the following piece of code, I am able to animate a CALayer from left to right

```<code>let imageLayer = CALayer()
imageLayer.frame = CGRect(x: 0, y: 500, width: 100, height: 70)
imageLayer.contents = UIImage(named: "first_image")?.cgImage

let animation = CABasicAnimation()
animation.keyPath = "position.x"
animation.fromValue = 100
animation.toValue = 300
animation.duration = 3
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = true
animation.repeatCount = 2
imageLayer.add(animation, forKey: "basic")

self.view.layer.addSublayer(imageLayer)
</code>```

What I am trying to do is, in

Cycle: 1 - "first_image" will move from left to right

and in

Cycle: 2 - "second_image" (this is another image) will move from left
  to right like previous cycle.

Here Cycle: 1 + Cycle: 2 is actually a single animation and I want this animation to happen for a number of times. How to achieve this?
Any assistance would be appreciated.

答:
As you required left to right & vice versa animation, You can also use UIView.anima.. for animation.

```<code>     let testViewTowardsLeft = UIView(frame: CGRect(x: 0, y: 150, width: 50, height: 50))
    testViewTowardsLeft.backgroundColor = .red
    view.addSubview(testViewTowardsLeft)
    UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
        testViewTowardsLeft.frame = CGRect(x: 100, y: 150, width: 50, height: 50)

    }, completion: nil)

    let testViewTowardsRight = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
    testViewTowardsRight.backgroundColor = .red
    view.addSubview(testViewTowardsRight)
    UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
        testViewTowardsRight.frame = CGRect(x: 0, y: 100, width: 50, height: 50)

    }, completion: nil)
</code>```

Title: CABasicAnimation: From left to right

Body:
With the following piece of code, I am able to animate a CALayer from left to right

let imageLayer = CALayer()
imageLayer.frame = CGRect(x: 0, y: 500, width: 100, height: 70)
imageLayer.contents = UIImage(named: "first_image")?.cgImage

let animation = CABasicAnimation()
animation.keyPath = "position.x"
animation.fromValue = 100
animation.toValue = 300
animation.duration = 3
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = true
animation.repeatCount = 2
imageLayer.add(animation, forKey: "basic")

self.view.layer.addSublayer(imageLayer)

What I am trying to do is, in

Cycle: 1 - "first_image" will move from left to right

and in

Cycle: 2 - "second_image" (this is another image) will move from left
  to right like previous cycle.

Here Cycle: 1 + Cycle: 2 is actually a single animation and I want this animation to happen for a number of times. How to achieve this?
Any assistance would be appreciated.

Body:
As you required left to right & vice versa animation, You can also use UIView.anima.. for animation.

     let testViewTowardsLeft = UIView(frame: CGRect(x: 0, y: 150, width: 50, height: 50))
    testViewTowardsLeft.backgroundColor = .red
    view.addSubview(testViewTowardsLeft)
    UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
        testViewTowardsLeft.frame = CGRect(x: 100, y: 150, width: 50, height: 50)

    }, completion: nil)

    let testViewTowardsRight = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
    testViewTowardsRight.backgroundColor = .red
    view.addSubview(testViewTowardsRight)
    UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
        testViewTowardsRight.frame = CGRect(x: 0, y: 100, width: 50, height: 50)

    }, completion: nil)


问:
How to replace Roboto with a font that I downloaded
I've already put my downloaded Montserrat font-pack inside my public/dist/fonts/ directory, how will I replace Roboto as my font.</p>

答:
Depends on your font, you would need to put the css that changes the original font after the materialize css file in your html

```<code>* {
  font-family: 'Montserrat';
}
</code>```

if it doesn't work, just simply add !important at the end, it will be working.

Body:
Depends on your font, you would need to put the css that changes the original font after the materialize css file in your html

* {
  font-family: 'Montserrat';
}

if it doesn't work, just simply add !important at the end, it will be working.


问:
How to resolve git's "not something we can merge" error
I just encountered a problem when merging a branch into master in git. First, I got the branch name by running git ls-remote. Let's call that branch "branch-name". I then ran git merge branch-name command and got the following result:

```<code>fatal: branch-name - not something we can merge
</code>```

How do I resolve this error?

答:
For me the problem occured when I tried this:

```<code>git merge -s ours --no-commit --allow-unrelated-histories <remote name>/develop
</code>```

So actually I should have written master instead of develop,because master was the branch name of Subtree,not my actual branch.

Body:
I just encountered a problem when merging a branch into master in git. First, I got the branch name by running git ls-remote. Let's call that branch "branch-name". I then ran git merge branch-name command and got the following result:

fatal: branch-name - not something we can merge

How do I resolve this error?

Body:
For me the problem occured when I tried this:

git merge -s ours --no-commit --allow-unrelated-histories <remote name>/develop

So actually I should have written master instead of develop,because master was the branch name of Subtree,not my actual branch.


问:
Add jitter to grouped box plot using markers in R plotly
I'd like the interactive (that means they can be selected with box/lasso selection) jittered points to be displayed on the grouped boxplot. I came out of this question: Add jitter to box plot using markers in plotly. I want exactly the same but the boxplots should be grouped.

I made a boxplot but the points are all mixed up:

```<code>dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(IC)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

When I try making the X axis grouped by factor (so that each combination is a level) I cannot make my boxplot grouped:

```<code>dat <- dat %>%
  mutate(gene_x_covariate = as.factor(
    paste0(get(facet_title), "-", gene)))

dat %>%
  plot_ly(x = ~as.numeric(gene_x_covariate),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

When I try to mix the variables on X axis, I get the points away from the boxplots:

```<code>dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none"
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

Any ideas?

答:
You could create a ggplot2 object and then make it interactive using ggplotly() function.</p>

```<code>library(dplyr)
library(ggplot2)
library(plotly)

dat <- data.frame(xval = sample(100,1000,replace = TRUE),
              group1 = as.factor(sample(c("a","b","c"),1000,replace = TRUE)),
              group2 = as.factor(sample(c("g1","g2","g3","g4"),1000, replace = TRUE)))

p <- dat %>% ggplot(aes(x=group2, y=xval, fill=group1)) +
              geom_boxplot() + geom_jitter() + facet_grid(~group2)

ggplotly(p) %>% layout(boxmode = 'group')
</code>```

Body:
I'd like the interactive (that means they can be selected with box/lasso selection) jittered points to be displayed on the grouped boxplot. I came out of this question: Add jitter to box plot using markers in plotly. I want exactly the same but the boxplots should be grouped.

I made a boxplot but the points are all mixed up:

dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(IC)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

When I try making the X axis grouped by factor (so that each combination is a level) I cannot make my boxplot grouped:

dat <- dat %>%
  mutate(gene_x_covariate = as.factor(
    paste0(get(facet_title), "-", gene)))

dat %>%
  plot_ly(x = ~as.numeric(gene_x_covariate),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

When I try to mix the variables on X axis, I get the points away from the boxplots:

dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none"
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

Any ideas?

Body:
You could create a ggplot2 object and then make it interactive using ggplotly() function.

library(dplyr)
library(ggplot2)
library(plotly)

dat <- data.frame(xval = sample(100,1000,replace = TRUE),
              group1 = as.factor(sample(c("a","b","c"),1000,replace = TRUE)),
              group2 = as.factor(sample(c("g1","g2","g3","g4"),1000, replace = TRUE)))

p <- dat %>% ggplot(aes(x=group2, y=xval, fill=group1)) +
              geom_boxplot() + geom_jitter() + facet_grid(~group2)

ggplotly(p) %>% layout(boxmode = 'group')


问:
DBCC CHECKIDENT Sets Identity to 0
I'm using this code to reset the identity on a table:

```<code>DBCC CHECKIDENT('TableName', RESEED, 0)
</code>```

This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item inserted will have an ID of 0.

Any ideas?

EDIT: After researching I found out I didn't read the documentation properly - "The current identity value is set to the new_reseed_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new_reseed_value as the identity. Otherwise, the next row inserted will use new_reseed_value + 1. "

答:
See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx

This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)

ContentLicense: CC BY-SA 4.0

Title: DBCC CHECKIDENT Sets Identity to 0

Body:
I'm using this code to reset the identity on a table:

DBCC CHECKIDENT('TableName', RESEED, 0)

This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item inserted will have an ID of 0.

Any ideas?

EDIT: After researching I found out I didn't read the documentation properly - "The current identity value is set to the new_reseed_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new_reseed_value as the identity. Otherwise, the next row inserted will use new_reseed_value + 1. "

OwnerDisplayName: SQLMenace


问:
is this GWT modules structure ok?

Description

I have a Parent GWT project that uses the gwt-maven-plugin. This project is split into 2 sub-projects: Domain and WebApp and each project contains pom.xml files. I'd like to split the domain code from GWT client code.

Parent project

/Parent

/Parent/pom.xml

Domain project

[1] I think of of it as the server-side part of the application that runs on the server

/Parent/Domain

/Parent/Domain/pom.xml

.../beans/PersonBean.java

.../dao/PersonDAO.java

.../services/PersonService.java

.../util/DateUtil.java

.../gwt/client/GWTPersonService.java

.../gwt/server/GWTPersonServiceImpl.java

.../gwt/shared/GWTPersonDTO.java -- a DTO(Data Transfer Object)

WebApp project

[2] I think of it as the client-side of the application that runs in the web browser.

Parent/WebApp

Parent/WebApp/pom.xml

.../gwt/client/PersonUI.java

.../gwt/util/GWTUtility.java - this is a utility class called by GWT components, it is not used on the server

.../webapp/WEB-INF/web.xml

.../webapp/Page.css

.../webapp/Page.html

Sequence diagram

PersonUI will call GWTPersonService's methods which calls PersonService(I need this separation because PersonService.java will be called by non-GWT clients as well).

PersonService will call PersonDAO which uses and returns PersonBean instances. Then, PersonBean gets converted to GWTPersonDTO and sent to the client by GWTPersonServiceImpl.

Questions (edited)

In which project should I put the shared GWT code that normally lives under /shared folder?

Does it make sense to have GWTPersonServiceImpl.java and GWTPersonService.java in the domain project? My reason is that since all servlets live on the server, and the domain is for server-side then those classes should be in the Domain project.

Should I move GWTUtility.java inside Domain project?

Does it make sense to use DTO's? Is there any way to make it more straight-forward: i.e. use directly the PersonBean?

Is it possible to run this scenario in GWT Developer mode using maven? How easy is it to configure?

If you have any modifications/additions to the above scenario, please post them - or even better if you have already done an app it would help much to know how you did to solve this separation.

Thank you!

答:
I would put the shared code in a third project on which both Domain and WebApp can depend.

Since GWTPersonServiceImpl is a servlet and runs on the server, not the client, it belongs in Domain.

What function does GWTUtility perform? If it is only used on the client, it belongs in WebApp; if it is only used on the server then it belongs in Domain; if it is used on both then it probably belongs in a third project on which both WebApp and Domain depend.

You can use a complex type as long as it (and its constituent types) implements either of com.google.gwt.user.client.rpc.IsSerializable or (with limitations) java.io.Serializable. See the GWT development guide for details. In any case, as designed, any serialized type in your project probably belongs in a module upon which both Domain and WebApp depend.

Yes.

Title: is this GWT modules structure ok?


问:
How to get value in array in asp-classic
The array contents are like this ..

```<code> str = "penalty: 6, ord: 1, ot: 0, fe: 7, rs: 7"
</code>```

Arrays can be 3 ~ 10 depending on the situation.

How do you put variables in this way?

```<code>aa = 6

bb = 1

cc = 0

dd = 7

ee = 7
</code>```

I tried this, but it does not work anymore.

```<code> str_arr=Split(str,",")
 if_num=UBound(str_arr)
 redim str_arr1(if_num)
 For k=0 To eval(if_num)
   str_arr1(k)=Split(str_arr(k),":")
  name = str_arr1(k)(0)
  num = str_arr1(k)(1)
Next
</code>```

答:
What you  need is the Split() VBScript method, and store the results in a Dictionary object.

I wrote a generic function that takes a raw string, main separator, and sub separator which returns such a Dictionary object, that you can iterate to see the values:

Function DoubleSplit(rawValue, mainSeparator, subSeparator)
    Dim oResult, arrMainParts, arrSubParts
    Dim x, curMainPart

    'using Dictionary as key/value collection
    Set oResult = Server.CreateObject("Scripting.Dictionary")

    'split raw value by the main separator
    arrMainParts = Split(rawValue, mainSeparator)

    'iterate over main parts, split each by the sub separator
    For x=0 To UBound(arrMainParts)
        curMainPart = arrMainParts(x)
        arrSubParts = Split(curMainPart, subSeparator)
        If UBound(arrSubParts)=1 Then
            'adding to result only if there are both key and value
            oResult(arrSubParts(0)) = arrSubParts(1)
        End If

        'prevent memory leaks
        Erase arrSubParts
    Next

    'prevent memory leaks
    Erase arrMainParts

    'assign function return value
    Set DoubleSplit = oResult
End Function
```

<p>Usage example, using the data given in the question:</p>

<pre class="lang-vbs prettyprint-override"><code>Dim str, myDictionary, key
str = "penalty: 6, ord: 1, ot: 0, fe: 7, rs: 7"
Set myDictionary = DoubleSplit(str, ", ", ": ")
For Each key In myDictionary.Keys
    Response.Write("Name is " & key & ", value is: " & myDictionary(key) & "<br />")
Next

'prevent memory leaks
Set myDictionary = Nothing
</code>```

Body:
The array contents are like this ..

 str = "penalty: 6, ord: 1, ot: 0, fe: 7, rs: 7"

Arrays can be 3 ~ 10 depending on the situation.

How do you put variables in this way?

aa = 6

bb = 1

cc = 0

dd = 7

ee = 7

I tried this, but it does not work anymore.

 str_arr=Split(str,",")
 if_num=UBound(str_arr)
 redim str_arr1(if_num)
 For k=0 To eval(if_num)
   str_arr1(k)=Split(str_arr(k),":")
  name = str_arr1(k)(0)
  num = str_arr1(k)(1)
Next

Body:
What you  need is the Split() VBScript method, and store the results in a Dictionary object.

I wrote a generic function that takes a raw string, main separator, and sub separator which returns such a Dictionary object, that you can iterate to see the values:

Function DoubleSplit(rawValue, mainSeparator, subSeparator)
    Dim oResult, arrMainParts, arrSubParts
    Dim x, curMainPart

    'using Dictionary as key/value collection
    Set oResult = Server.CreateObject("Scripting.Dictionary")

    'split raw value by the main separator
    arrMainParts = Split(rawValue, mainSeparator)

    'iterate over main parts, split each by the sub separator
    For x=0 To UBound(arrMainParts)
        curMainPart = arrMainParts(x)
        arrSubParts = Split(curMainPart, subSeparator)
        If UBound(arrSubParts)=1 Then
            'adding to result only if there are both key and value
            oResult(arrSubParts(0)) = arrSubParts(1)
        End If

        'prevent memory leaks
        Erase arrSubParts
    Next

    'prevent memory leaks
    Erase arrMainParts

    'assign function return value
    Set DoubleSplit = oResult
End Function

Usage example, using the data given in the question:

Dim str, myDictionary, key
str = "penalty: 6, ord: 1, ot: 0, fe: 7, rs: 7"
Set myDictionary = DoubleSplit(str, ", ", ": ")
For Each key In myDictionary.Keys
    Response.Write("Name is " & key & ", value is: " & myDictionary(key) & "<br />")
Next

'prevent memory leaks
Set myDictionary = Nothing


问:
Mailgun webhook POST body seems empty
I'am trying to handle http post message from Mailgun bounce webhook. When sending it to Mailgun's Postbin service all data is found of course. But I'm now sending that POST to my localhost server for development purposes and all I get is empty json array. I use Test Webhook.

Intent is to keep this simple as possible besides our main service. That for I started using nodejs/expressjs to create stand alone webservice to work as relay to receive POST messages of email bounces from Mailgun and inform admins about bounced email addresses.

Now I can't figure why I don't get the same data as is visible in Postbin.

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mailgun = require('mailgun-js')({apiKey: 'key-...', domain: 'mymailgundomain.com'});

app.use(bodyParser.urlencoded({
  extended: true
}));

function router(app) {
  app.post('/webhooks/*', function (req, res, next) {
    var body = req.body;

    if (!mailgun.validateWebhook(body.timestamp, body.token, body.signature)) {
      console.error('Request came, but not from Mailgun');
      res.send({ error: { message: 'Invalid signature. Are you even Mailgun?' } });
      return;
    }

    next();
  });

  app.post('/webhooks/mailgun/', function (req, res) {
    // actually handle request here
    console.log("got post message");
    res.send("ok 200");
  });
}

app.listen(5000, function(){
  router(app);
  console.log("listening post in port 5000");
});
</code>```

I'm running this from Mailgun's Test Webhook using url like http://mylocalhostwithpublicip.com:5000/webhooks/mailgun

Code structure is copied from https://github.com/1lobby/mailgun-js. Probably I'm missing something fundamental here as I can't figure it out myself.

答:
I make a custom parser for get data in req.body when the Content-type = 'multipart/alternative'

https://github.com/josemadev/Multiparser/

Title: Mailgun webhook POST body seems empty

Body:
I'am trying to handle http post message from Mailgun bounce webhook. When sending it to Mailgun's Postbin service all data is found of course. But I'm now sending that POST to my localhost server for development purposes and all I get is empty json array. I use Test Webhook.

Intent is to keep this simple as possible besides our main service. That for I started using nodejs/expressjs to create stand alone webservice to work as relay to receive POST messages of email bounces from Mailgun and inform admins about bounced email addresses.

Now I can't figure why I don't get the same data as is visible in Postbin.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mailgun = require('mailgun-js')({apiKey: 'key-...', domain: 'mymailgundomain.com'});

app.use(bodyParser.urlencoded({
  extended: true
}));

function router(app) {
  app.post('/webhooks/*', function (req, res, next) {
    var body = req.body;

    if (!mailgun.validateWebhook(body.timestamp, body.token, body.signature)) {
      console.error('Request came, but not from Mailgun');
      res.send({ error: { message: 'Invalid signature. Are you even Mailgun?' } });
      return;
    }

    next();
  });

  app.post('/webhooks/mailgun/', function (req, res) {
    // actually handle request here
    console.log("got post message");
    res.send("ok 200");
  });
}

app.listen(5000, function(){
  router(app);
  console.log("listening post in port 5000");
});

I'm running this from Mailgun's Test Webhook using url like http://mylocalhostwithpublicip.com:5000/webhooks/mailgun

Code structure is copied from https://github.com/1lobby/mailgun-js. Probably I'm missing something fundamental here as I can't figure it out myself.


问:
Python - Update Dictionary With User Input
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

```<code>while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break
</code>```

When running this code i get the following error:

```<code>Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range
</code>```

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

答:
Your updates is a list with one string which you erase with each new input in your for loop over n . You may want to use append to add new elements in your list.

So your for loop will be

```<code>for i in range(n):
            updates.append(input().split(' '))
</code>```

After having defined updates as a list, earlier in the code.
Plus, using split will make your updates be a list of lists :

```<code>>>> updates
>>> [['John'], ['IT'], ['programmer']]
</code>```

I suggest you to write updates.append(input()) then the output will be ['John', 'IT', 'programmer']

Finally to access those new information, you just have to consider updates as a 1D list.

Hope this is helpful

Body:
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break

When running this code i get the following error:

Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

Body:
Your updates is a list with one string which you erase with each new input in your for loop over n . You may want to use append to add new elements in your list.

So your for loop will be

for i in range(n):
            updates.append(input().split(' '))

After having defined updates as a list, earlier in the code.
Plus, using split will make your updates be a list of lists :

>>> updates
>>> [['John'], ['IT'], ['programmer']]

I suggest you to write updates.append(input()) then the output will be ['John', 'IT', 'programmer']

Finally to access those new information, you just have to consider updates as a 1D list.

Hope this is helpful


问:
How to paint a gradient color in Android on a Canvas with the color changing?
I need to paint the background of my Canvas one color with shading/gradient applied, but each onDraw call I would like to potentially change the color.

I am having trouble doing this without creating a new object each onDraw call. Anyone have any ideas?  If I use drawPaint() and set a new shader() to my paint, then I have created a new shader object and if I create a new GradientDrawable() I have as well.  I want to avoid GC.

I thought I could reuse one GradientDrawable() object and call the .setColor() method, but this just resets any gradient data associated it and paints the drawable as that solid color.

Anyone?

答:
I think what you want to do is this.  Create a LayerDrawable and then insert two Drawables into it.  The first Drawable you insert should have its color set to the color you'd like your background to be and the second should be a Gradient that is set up to be black and transition from alpha 0 to alpha 255.

For more information, see: http://developer.android.com/guide/topics/resources/drawable-resource.html#LayerList


问:
Scala call length() on very long string throws exception: Maximum String literal length exceeded
I wrote a scala solution for HackerRank BigSorting ,
and got RuntimeException in some test case. I tested the input in scastie, it seems the problem is caused by calling length() on a very long string, but the same java solution has no problem, is this a bug?
my solution code is :

```<code>object Solution {
    def stringSort(x:String, y:String):Boolean = {
        var result = true

        if(x.length < y.length){
            result = true
        }else if(x.length > y.length){
            result = false
        }else{
            var founded = false
            var i = 0
            while(i < x.length && !founded){
                var xi = x.charAt(i)
                var yi = y.charAt(i)
                if(xi != yi){
                    result = xi < yi
                    founded = true
                }
                i += 1
            }
        }
        result
    }

    def bigSort(unsorted:Array[String]):Array[String] = {
        return unsorted.sortWith(stringSort)
    }

    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var n = sc.nextInt();
        var unsorted = new Array[String](n);
        for(unsorted_i <- 0 to n-1) {
           unsorted(unsorted_i) = sc.next();
        }
        print(bigSort(unsorted).mkString("\n"))
        // your code goes here
    }
}
</code>```

the exception is

```<code>java.lang.IllegalArgumentException: Maximum String literal length exceeded
    at scala.tools.asm.ByteVector.putUTF8(ByteVector.java:213)
    at scala.tools.asm.ClassWriter.newUTF8(ClassWriter.java:1114)
    at scala.tools.asm.ClassWriter.newString(ClassWriter.java:1582)
    at scala.tools.asm.ClassWriter.newConstItem(ClassWriter.java:1064)
    at scala.tools.asm.MethodWriter.visitLdcInsn(MethodWriter.java:1187)
    at scala.tools.asm.tree.LdcInsnNode.accept(LdcInsnNode.java:71)
    at scala.tools.asm.tree.InsnList.accept(InsnList.java:162)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:820)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:730)
    at scala.tools.asm.tree.ClassNode.accept(ClassNode.java:412)
...
</code>```

java solution

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] unsorted = new String[n];
        for(int i = 0; i < n; i++) unsorted[i] = in.next();

        Arrays.sort(unsorted,new Comparator<String>() {
            @Override
            public int compare(String a, String b)
            {
                return StringAsIntegerCompare(a,b);
            }
        });

        StringBuilder output = new StringBuilder("");
        for(String num : unsorted)
            output.append(num+"\n");
        System.out.println(output);
    }

    static int StringAsIntegerCompare(String s1, String s2)
    {
        if(s1.length() > s2.length()) return 1;
        if(s1.length() < s2.length()) return -1;
        for(int i = 0; i < s1.length(); i++)
        {
            if((int)s1.charAt(i) > (int)s2.charAt(i)) return 1;
            if((int)s1.charAt(i) < (int)s2.charAt(i)) return -1;
        }
        return 0;
    }
}
</code>```

答:
The only substantial difference between Java and Scala code that I can see is that Scala sortWith creates a new array, unlike Arrays.sort (and probably has some intermediate overhead too), so you could be running out of memory. You can instead try

```<code>import scala.math.Ordering
import scala.util.Sorting

val byLength: Ordering[String] = ... // your implementation, similar to Java comparator

Sorting.quickSort(unordered)(byLength) // instead of sortWith, sorts in-place
</code>```

See http://www.scala-lang.org/api/2.12.0/scala/math/Ordering.html and http://www.scala-lang.org/api/2.12.0/scala/util/Sorting$.html for relevant documentation.

Body:
I wrote a scala solution for HackerRank BigSorting ,
and got RuntimeException in some test case. I tested the input in scastie, it seems the problem is caused by calling length() on a very long string, but the same java solution has no problem, is this a bug?
my solution code is :

object Solution {
    def stringSort(x:String, y:String):Boolean = {
        var result = true

        if(x.length < y.length){
            result = true
        }else if(x.length > y.length){
            result = false
        }else{
            var founded = false
            var i = 0
            while(i < x.length && !founded){
                var xi = x.charAt(i)
                var yi = y.charAt(i)
                if(xi != yi){
                    result = xi < yi
                    founded = true
                }
                i += 1
            }
        }
        result
    }

    def bigSort(unsorted:Array[String]):Array[String] = {
        return unsorted.sortWith(stringSort)
    }

    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var n = sc.nextInt();
        var unsorted = new Array[String](n);
        for(unsorted_i <- 0 to n-1) {
           unsorted(unsorted_i) = sc.next();
        }
        print(bigSort(unsorted).mkString("\n"))
        // your code goes here
    }
}

the exception is

java.lang.IllegalArgumentException: Maximum String literal length exceeded
    at scala.tools.asm.ByteVector.putUTF8(ByteVector.java:213)
    at scala.tools.asm.ClassWriter.newUTF8(ClassWriter.java:1114)
    at scala.tools.asm.ClassWriter.newString(ClassWriter.java:1582)
    at scala.tools.asm.ClassWriter.newConstItem(ClassWriter.java:1064)
    at scala.tools.asm.MethodWriter.visitLdcInsn(MethodWriter.java:1187)
    at scala.tools.asm.tree.LdcInsnNode.accept(LdcInsnNode.java:71)
    at scala.tools.asm.tree.InsnList.accept(InsnList.java:162)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:820)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:730)
    at scala.tools.asm.tree.ClassNode.accept(ClassNode.java:412)
...

java solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] unsorted = new String[n];
        for(int i = 0; i < n; i++) unsorted[i] = in.next();

        Arrays.sort(unsorted,new Comparator<String>() {
            @Override
            public int compare(String a, String b)
            {
                return StringAsIntegerCompare(a,b);
            }
        });

        StringBuilder output = new StringBuilder("");
        for(String num : unsorted)
            output.append(num+"\n");
        System.out.println(output);
    }

    static int StringAsIntegerCompare(String s1, String s2)
    {
        if(s1.length() > s2.length()) return 1;
        if(s1.length() < s2.length()) return -1;
        for(int i = 0; i < s1.length(); i++)
        {
            if((int)s1.charAt(i) > (int)s2.charAt(i)) return 1;
            if((int)s1.charAt(i) < (int)s2.charAt(i)) return -1;
        }
        return 0;
    }
}

Body:
The only substantial difference between Java and Scala code that I can see is that Scala sortWith creates a new array, unlike Arrays.sort (and probably has some intermediate overhead too), so you could be running out of memory. You can instead try

import scala.math.Ordering
import scala.util.Sorting

val byLength: Ordering[String] = ... // your implementation, similar to Java comparator

Sorting.quickSort(unordered)(byLength) // instead of sortWith, sorts in-place

See http://www.scala-lang.org/api/2.12.0/scala/math/Ordering.html and http://www.scala-lang.org/api/2.12.0/scala/util/Sorting$.html for relevant documentation.


问:
Did this method 'method' throw this error message?
The ruby code

```<code>class Word < Array
   def g
      puts "JJ"
   end
end

w = Word.new([4, 6])
puts Word.method(:g)
</code>```

produces the following error:

```<code>main.rb:9:in `method': undefined method `g' for class `#<Class:Word>' (NameError)
        from main.rb:9:in `<main>'
</code>```

because g is an instance method for Word, not its class method.

It looks like it is the method method that in fact threw this error message. I wouldn't be able to explain how such an error message could be produced if that were not the case.

Is it in fact the method method that threw this error message?

Here, we are passing the symbol :g to the method Word.method, and waiting for its execution. The ruby interpreter cannot know beforehand that it's gonna be an error, only when the method method checks for the existence of a function with a name similar to the symbol :g can it (the method) decide that an error exists. The console/interpreter cannot know about the error beforehand.

答:
Yes. The description:

```<code>in `method'
</code>```

in the error message means exactly that.

Body:
The ruby code

class Word < Array
   def g
      puts "JJ"
   end
end

w = Word.new([4, 6])
puts Word.method(:g)

produces the following error:

main.rb:9:in `method': undefined method `g' for class `#<Class:Word>' (NameError)
        from main.rb:9:in `'

because g is an instance method for Word, not its class method.

It looks like it is the method method that in fact threw this error message. I wouldn't be able to explain how such an error message could be produced if that were not the case.

Is it in fact the method method that threw this error message?

Here, we are passing the symbol :g to the method Word.method, and waiting for its execution. The ruby interpreter cannot know beforehand that it's gonna be an error, only when the method method checks for the existence of a function with a name similar to the symbol :g can it (the method) decide that an error exists. The console/interpreter cannot know about the error beforehand.

Body:
Yes. The description:

in `method'

in the error message means exactly that.


问:
Why is Perl not printing all regex matches in a multi-line regex?
I have this text (shortened version of my original text):

mytext.txt
  BAHJSBUBGUCYHAGSBUCAGSUCBASBCYHUBXZCZPZHCUIHAUISHCIUJXZJCBZYAUSGHDYUAGWEBWHBHJASBHJASCXZBUYTRTRTRJFUARGAFGOOPWWKBBCAAAABBXHABSDAUSBCZAAAAAAAAACGAFAXHJBJHXZCXZCCZCXZUCAGSUCBASBCYHUBXZCZPZHCUIHAUISHCIUJXZJCBZYAUSGHDYUAGWEBWHBHJASBHJASCXZBUYHABSDAUSZXHJBRRRRRRJFUABGAFGLLPKWAACAAAABBZJHXZXHJBJHXZXHJBJHXJBJHXZCXZCCZCXZUCAGSAJIJICXZIJUAUUISUSJUSSJSJSJAJCXZXCZTTTTTRJFUABGAFGLOPKWABCAAAABBU

My code is the following, which intends to print all of the matches and then save them into a file as well. But I am not getting any matches while I except there to be at least 10 in my original file.

```<code>open(text, "<mytext.txt");

push (@matches,$&) while(<text> =~ m{
    ([TR]{6}
    JFUA
    [ABR]{1}
    GAFG
    ( [LOP]{2,3} )
    [KW]{2,5}
    (??{ $2 =~ tr/LOP/ABC/r })
    AAAABB[UXZ]{1})
    /g
}x);

print "@matches\n";

my $filename = 'results_matches.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "@matches\n";
close $fh;
print "done\n";
</code>```

I have also tried the following code and this also does not work:

```<code>my @matches = <text> =~ m{
        ([TR]{6}
        JFUA
        [ABR]{1}
        GAFG
        ( [LOP]{2,3} )
        [KW]{2,5}
        (??{ $2 =~ tr/LOP/ABC/r })
        AAAABB[UXZ]{1})
        /g
    }x;

print "@matches\n";
</code>```

I have the following code which successfully prints out only one (the first) result. But it fails to print all of the matches.

```<code>if (<text> =~ m{
    ([TR]{6}
    JFUA
    [ABR]{1}
    GAFG
    ( [LOP]{2,3} )
    [KW]{2,5}
    (??{ $2 =~ tr/LOP/ABC/r })
    AAAABB[UXZ]{1})
}x) {print "$1\n";}
</code>```

I have followed the answers in this topic but have not been able to get any of them to work: How can I find all matches to a regular expression in Perl?

答:
By using while <text>, you are reading a new file from the file handle on each iteration of the loop. You need to loops, one iterating over the lines, and the inner loop to iterate over the matches.

```<code>while (my $line = <text>) {
    push @matches, $1 while $line
        =~ m{
            ([TR]{6}
            JFUA
            [ABR]
            GAFG
            ( [LOP]{2,3} )
            [KW]{2,5}
            (??{ $2 =~ tr/LOP/ABC/r })
            AAAABB[UXZ])
        }xg;
}
</code>```

I also removed {1} as it's useless, used $1 instead of $& because $& imposes a performance penatly on all the matching you do in a program; and removed the /g and added the g to the right place (i.e. next to }x).

When testing, I copied'n'pasted the input from here, i.e. I have all the characters in one line. If your input is different, please use the code formatting for it, not quotation.

Body:
I have this text (shortened version of my original text):

mytext.txt
  BAHJSBUBGUCYHAGSBUCAGSUCBASBCYHUBXZCZPZHCUIHAUISHCIUJXZJCBZYAUSGHDYUAGWEBWHBHJASBHJASCXZBUYTRTRTRJFUARGAFGOOPWWKBBCAAAABBXHABSDAUSBCZAAAAAAAAACGAFAXHJBJHXZCXZCCZCXZUCAGSUCBASBCYHUBXZCZPZHCUIHAUISHCIUJXZJCBZYAUSGHDYUAGWEBWHBHJASBHJASCXZBUYHABSDAUSZXHJBRRRRRRJFUABGAFGLLPKWAACAAAABBZJHXZXHJBJHXZXHJBJHXJBJHXZCXZCCZCXZUCAGSAJIJICXZIJUAUUISUSJUSSJSJSJAJCXZXCZTTTTTRJFUABGAFGLOPKWABCAAAABBU

My code is the following, which intends to print all of the matches and then save them into a file as well. But I am not getting any matches while I except there to be at least 10 in my original file.

open(text, "<mytext.txt");

push (@matches,$&) while(<text> =~ m{
    ([TR]{6}
    JFUA
    [ABR]{1}
    GAFG
    ( [LOP]{2,3} )
    [KW]{2,5}
    (??{ $2 =~ tr/LOP/ABC/r })
    AAAABB[UXZ]{1})
    /g
}x);

print "@matches\n";

my $filename = 'results_matches.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "@matches\n";
close $fh;
print "done\n";

I have also tried the following code and this also does not work:

my @matches = <text> =~ m{
        ([TR]{6}
        JFUA
        [ABR]{1}
        GAFG
        ( [LOP]{2,3} )
        [KW]{2,5}
        (??{ $2 =~ tr/LOP/ABC/r })
        AAAABB[UXZ]{1})
        /g
    }x;

print "@matches\n";

I have the following code which successfully prints out only one (the first) result. But it fails to print all of the matches.

if (<text> =~ m{
    ([TR]{6}
    JFUA
    [ABR]{1}
    GAFG
    ( [LOP]{2,3} )
    [KW]{2,5}
    (??{ $2 =~ tr/LOP/ABC/r })
    AAAABB[UXZ]{1})
}x) {print "$1\n";}

I have followed the answers in this topic but have not been able to get any of them to work: How can I find all matches to a regular expression in Perl?

Body:
By using while <text>, you are reading a new file from the file handle on each iteration of the loop. You need to loops, one iterating over the lines, and the inner loop to iterate over the matches.

while (my $line = <text>) {
    push @matches, $1 while $line
        =~ m{
            ([TR]{6}
            JFUA
            [ABR]
            GAFG
            ( [LOP]{2,3} )
            [KW]{2,5}
            (??{ $2 =~ tr/LOP/ABC/r })
            AAAABB[UXZ])
        }xg;
}

I also removed {1} as it's useless, used $1 instead of $& because $& imposes a performance penatly on all the matching you do in a program; and removed the /g and added the g to the right place (i.e. next to }x).

When testing, I copied'n'pasted the input from here, i.e. I have all the characters in one line. If your input is different, please use the code formatting for it, not quotation.


问:
Cannot read input file using ifstream c++
I have an input file "abc.txt" which contains characters seperated by ',' in every line.
While trying to read the file line by line using ifstream, its unable to read the file and I am getting the output on console as "Cannot open input file.".
What am I doing wrong?
The code:-

```<code>void EnterFiles(string filename, int index)
{
    string line;
    vector<string> f1,f2;

    std::ifstream f;

    //prepare f to throw if failbit gets set

    std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
    f.exceptions(exceptionMask);
    try
    {
        f.open(filename);
    }
    catch (std::ios_base::failure& e)
    {
        std::cerr << e.what() << '\n';
    }
    if (!f)
    {
        cout << "Cannot open input file.\n";
    }
    while (getline(f,line) )
    {
        if (index == 0)
        {
            f1.push_back(line);
            cout << line << endl;
        }
        else
        {
            f2.push_back(line);
            cout << line << endl;
        }
    }
    f.close();
}
</code>```

答:
If condition is satisfied every time, thus skipping else part.

provide full or qualified file path (Sometimes it creates problem !!),
Also, include  file (if not !!).

Following is an examples similar to your code, which you refer,
(It is checked by me works like a charm in Linux)

http://cpp-tutorial.cpp4u.com/STL_ifstream.html

Hope, this answer might be of help.

Body:
I have an input file "abc.txt" which contains characters seperated by ',' in every line.
While trying to read the file line by line using ifstream, its unable to read the file and I am getting the output on console as "Cannot open input file.".
What am I doing wrong?
The code:-

void EnterFiles(string filename, int index)
{
    string line;
    vector<string> f1,f2;

    std::ifstream f;

    //prepare f to throw if failbit gets set

    std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
    f.exceptions(exceptionMask);
    try
    {
        f.open(filename);
    }
    catch (std::ios_base::failure& e)
    {
        std::cerr << e.what() << '\n';
    }
    if (!f)
    {
        cout << "Cannot open input file.\n";
    }
    while (getline(f,line) )
    {
        if (index == 0)
        {
            f1.push_back(line);
            cout << line << endl;
        }
        else
        {
            f2.push_back(line);
            cout << line << endl;
        }
    }
    f.close();
}


问:
Too late for the schedule
When Cron with "newsletter_send_all" this job code execute then its status became missed and pass message like below. currently using magento's defalt cron settings with UTC time. My Cron.php executed in every 5 minute. Please help me out on this curios issue.

```<code>    exception 'Mage_Core_Exception' with message 'Too late for the schedule' in /home/test/public_html/app/Mage.php:595
    Stack trace:
    #0 /home/test/public_html/app/code/core/Mage/Cron/Model/Observer.php(293): Mage::throwException('Too late for th...')
    #1 /home/test/public_html/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
    #2 /home/test/public_html/app/code/core/Mage/Core/Model/App.php(1338): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
    #3 /home/test/public_html/app/code/core/Mage/Core/Model/App.php(1317): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
    #4 /home/test/public_html/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
    #5 /home/test/public_html/cron.php(75): Mage::dispatchEvent('default')
    #6 {main}
</code>```

Also made below modification in newslatter module's observer in core for testing purpose but still its not working

```<code>    public function scheduledSend($schedule)
    {
        $countOfQueue  = 1; // default 3 Modified on 14 Nov 17
        $countOfSubscritions = 1; //default 20 Modified on 14 Nov 17

        $collection = Mage::getModel('newsletter/queue')->getCollection()
            ->setPageSize($countOfQueue)
            ->setCurPage(1)
            ->addOnlyForSendingFilter()
            ->load();

        $collection->walk('sendPerSubscriber', array($countOfSubscritions));
    }
</code>```

答:
This happens when the scheduler finds pending jobs that were supposed
  to be scheduled longer than the time configured in
  'system/cron/schedule_lifetime'. By default this value is set to 15
  minutes.

There are two different problems the may result in you seeing this
  error:

Cron isn't configured to run often enough: If you don't trigger cron
  often enough then the tasks start piling up and most likely tasks
  will be too late for schedule at the point when they're being
  executed by the scheduler. Instead of increasing the
  scheduler_lifetime settings you should increase the frequency cron
  is being called to */5 * * * * (every 5 minutes) or even * * * * *
  (every minute).

You have long running cron jobs that will block the execution of
  other jobs: In case you're importing data, indexing products,
  generating reports or doing other long-running jobs via cron (which
  is generally a good idea) other jobs will not be run in parallel
  (unless you're running cron.php instead of cron.sh). This will
  result in these jobs not being executed. Find out which jobs are
  preventing others from running (by looking at the timeline view) and
  run them in a different cron group. (look at this for more
  information and check the features added to version >0.5.0 for an
  easier way to configure and manage cron groups.

source https://github.com/AOEpeople/Aoe_Scheduler/blob/master/doc/faq.md

Title: Too late for the schedule

Body:
When Cron with "newsletter_send_all" this job code execute then its status became missed and pass message like below. currently using magento's defalt cron settings with UTC time. My Cron.php executed in every 5 minute. Please help me out on this curios issue.

    exception 'Mage_Core_Exception' with message 'Too late for the schedule' in /home/test/public_html/app/Mage.php:595
    Stack trace:
    #0 /home/test/public_html/app/code/core/Mage/Cron/Model/Observer.php(293): Mage::throwException('Too late for th...')
    #1 /home/test/public_html/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
    #2 /home/test/public_html/app/code/core/Mage/Core/Model/App.php(1338): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
    #3 /home/test/public_html/app/code/core/Mage/Core/Model/App.php(1317): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
    #4 /home/test/public_html/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
    #5 /home/test/public_html/cron.php(75): Mage::dispatchEvent('default')
    #6 {main}

Also made below modification in newslatter module's observer in core for testing purpose but still its not working

    public function scheduledSend($schedule)
    {
        $countOfQueue  = 1; // default 3 Modified on 14 Nov 17
        $countOfSubscritions = 1; //default 20 Modified on 14 Nov 17

        $collection = Mage::getModel('newsletter/queue')->getCollection()
            ->setPageSize($countOfQueue)
            ->setCurPage(1)
            ->addOnlyForSendingFilter()
            ->load();

        $collection->walk('sendPerSubscriber', array($countOfSubscritions));
    }