问:
Goswagger not creating appropriate json spec file
I am trying to create a spec file for the go implementation of petstore example . I tried a go generate in the directory which had doc.go but it did nothing. On further reading, I realised that there should be

//go:generate swagger generate spec -o swagger.json

in doc.go . When I added that it creates a spec file but it doesn't contain the entire specification. This is the .json file that is create on go generate

```<code>{
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "schemes": [
    "http",
    "https"
  ],
  "swagger": "2.0",
  "info": {
    "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec",
    "title": "Petstore API.",
    "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility\ngo:generate swagger generate spec -o swagger.json",
    "contact": {
      "name": "John Doe",
      "url": "http://john.doe.com",
      "email": "john.doe@example.com"
    },
    "license": {
      "name": "MIT",
      "url": "http://opensource.org/licenses/MIT"
    },
    "version": "0.0.1"
  },
  "host": "localhost",
  "basePath": "/v2",
  "paths": {}
}
</code>```

There are no routes/parameters/models mentioned in the spec file. Is this how this is supposed to be? This is an official example from the goswagger repo so I doubt the code is wrong. What should I change to make it work?

答:
The code you want to document needs to be reachable from your main package. That means from the main package its usage needs to be detectable.
So if you have a working server that isn't hooked up through some means of reflection it will generate the right specification.</p>

Body:
I am trying to create a spec file for the go implementation of petstore example . I tried a go generate in the directory which had doc.go but it did nothing. On further reading, I realised that there should be

//go:generate swagger generate spec -o swagger.json

in doc.go . When I added that it creates a spec file but it doesn't contain the entire specification. This is the .json file that is create on go generate

{
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "schemes": [
    "http",
    "https"
  ],
  "swagger": "2.0",
  "info": {
    "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec",
    "title": "Petstore API.",
    "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility\ngo:generate swagger generate spec -o swagger.json",
    "contact": {
      "name": "John Doe",
      "url": "http://john.doe.com",
      "email": "john.doe@example.com"
    },
    "license": {
      "name": "MIT",
      "url": "http://opensource.org/licenses/MIT"
    },
    "version": "0.0.1"
  },
  "host": "localhost",
  "basePath": "/v2",
  "paths": {}
}

There are no routes/parameters/models mentioned in the spec file. Is this how this is supposed to be? This is an official example from the goswagger repo so I doubt the code is wrong. What should I change to make it work?


来源: stackexchange

问:
How to select and count 3 elements in the same column in the same query and show them in three columns?
How can I write one query instead of these three?
Thanks for your answers!       </p>

```<code>    sqlCtx.sql("""Select count(*) as iPhone
    from yahoo
    where source like '%iphone%'
    """).show()

    sqlCtx.sql("""Select count(*) as Android
    from yahoo
    where source like '%android%'
    """).show()

    sqlCtx.sql("""Select count(*) as Web
    from yahoo
    where source like '%Web Client%'
    """).show()
</code>```

答:
You need to try condition for same and add 1 if exists else add 0, Here is Sample:-</p>

```<code>sqlCtx.sql("""
       Select
          sum(if source like '%iphone%', 1, 0) as Iphone,
          sum(if source like '%android%', 1, 0) as Android,
          sum(if source like '%Web Client%', 1, 0) as Web
       from yahoo
   """).show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I write one query instead of these three?
Thanks for your answers!

    sqlCtx.sql("""Select count(*) as iPhone
    from yahoo
    where source like '%iphone%'
    """).show()

    sqlCtx.sql("""Select count(*) as Android
    from yahoo
    where source like '%android%'
    """).show()

    sqlCtx.sql("""Select count(*) as Web
    from yahoo
    where source like '%Web Client%'
    """).show()

Body:
You need to try condition for same and add 1 if exists else add 0, Here is Sample:-

sqlCtx.sql("""
       Select
          sum(if source like '%iphone%', 1, 0) as Iphone,
          sum(if source like '%android%', 1, 0) as Android,
          sum(if source like '%Web Client%', 1, 0) as Web
       from yahoo
   """).show()


问:
How to remove the project name and replace with icon on the navigation bar in android?
I need a customize menu with an icon and 3 navigation buttons. I have already created 3 buttons but I could not replace my project name which is SMILE in here and replace with a icon in my customized navigation bar.

Any help is appreciated.

答:
try this, put it in onCreate()

```<code>getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
</code>```

and you can change label from manifest or use getSupportActionBar().setTitle("") to make title blank

Body:
try this, put it in onCreate()

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);

and you can change label from manifest or use getSupportActionBar().setTitle("") to make title blank


问:
How to ORDER BY one query only in a UNION ALL without subquery
I'm creating a list from unrelated data using UNION ALL in order to be saved to Excel in SQL Server 2008. Only one of the SELECT statements will have an ORDER BY and that is where my issue arises with the following error message

```<code>'The multi-part identifier "p.Category" could not be bound.'
</code>```

This is a simplified working code example that I prefer to the second one below but breaks when uncommenting the first SELECT query:

```<code>CREATE TABLE #People(Category varchar(50), [Name] varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

-- Unrelated data SELECT query
--SELECT 'Best Employee' AS Matrix
--     , 'Alan' AS [Name]
--UNION ALL

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category;

DROP TABLE #People;
</code>```

After some research I found that I could rewrite the query in the following way, which would give me the desired result in this small example but not something that I would consider ideal in my real case. Is there a way to give me the correct result without resorting to sub queries like in the working example below?

```<code>CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT *
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category

    UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category
    FROM #People p
) x
ORDER BY x.Category;

DROP TABLE #People;
</code>```

答:
The ORDER BY doesn't apply to just one SELECT, it applies to the whole result set, to the whole result after all rows are UNIONed. So, you need to include columns that will be used for sorting in each SELECT of the UNION ALL.

For example, the following is wrong syntax, because ORDER BY has to be after the last SELECT of the UNION.

```<code>SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category

UNION ALL

SELECT 'Best Employee' AS Matrix
     , 'Alan' AS [Name]
</code>```

Your second example from the question can be written in a simpler form, without sub-query:

```<code>SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
     , p.Category
FROM #People p

UNION ALL

SELECT 'Best Employee' AS Matrix
     , 'Alan' AS [Name]
     , NULL AS Category  --- or '' AS Category

ORDER BY Category;
</code>```

In any case, the column Category has to be added in each SELECT statement of the UNION. I don't see how you can avoid it.

Body:
I'm creating a list from unrelated data using UNION ALL in order to be saved to Excel in SQL Server 2008. Only one of the SELECT statements will have an ORDER BY and that is where my issue arises with the following error message

'The multi-part identifier "p.Category" could not be bound.'

This is a simplified working code example that I prefer to the second one below but breaks when uncommenting the first SELECT query:

CREATE TABLE #People(Category varchar(50), [Name] varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

-- Unrelated data SELECT query
--SELECT 'Best Employee' AS Matrix
--     , 'Alan' AS [Name]
--UNION ALL

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category;

DROP TABLE #People;

After some research I found that I could rewrite the query in the following way, which would give me the desired result in this small example but not something that I would consider ideal in my real case. Is there a way to give me the correct result without resorting to sub queries like in the working example below?

CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT *
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category

    UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category
    FROM #People p
) x
ORDER BY x.Category;

DROP TABLE #People;

Body:
The ORDER BY doesn't apply to just one SELECT, it applies to the whole result set, to the whole result after all rows are UNIONed. So, you need to include columns that will be used for sorting in each SELECT of the UNION ALL.

For example, the following is wrong syntax, because ORDER BY has to be after the last SELECT of the UNION.

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category

UNION ALL

SELECT 'Best Employee' AS Matrix
     , 'Alan' AS [Name]

Your second example from the question can be written in a simpler form, without sub-query:

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
     , p.Category
FROM #People p

UNION ALL

SELECT 'Best Employee' AS Matrix
     , 'Alan' AS [Name]
     , NULL AS Category  --- or '' AS Category

ORDER BY Category;

In any case, the column Category has to be added in each SELECT statement of the UNION. I don't see how you can avoid it.


问:
Finding cycle of 3 nodes ( or triangles) in a graph
I am working with complex networks. I want to find group of nodes which forms a cycle of 3 nodes (or triangles) in a given graph. As my graph contains about million edges, using a simple iterative solution (multiple "for" loop) is not very efficient.

I am using python for my programming, if these is some inbuilt modules for handling these problems, please let me know.

If someone knows any algorithm which can be used for finding triangles in graphs, kindly reply back.

答:
Assuming its an undirected graph, the answer lies in networkx library of python.
if you just need to count triangles, use:

```<code>import networkx as nx
tri=nx.triangles(g)
</code>```

But if you need to know the edge list with triangle (triadic) relationship, use

```<code>all_cliques= nx.enumerate_all_cliques(g)
</code>```

This will give you all cliques (k=1,2,3...max degree - 1)

So, to filter just triangles i.e k=3,

```<code>triad_cliques=[x for x in all_cliques if len(x)==3 ]
</code>```

The triad_cliques will give a edge list with only triangles.

Body:
Assuming its an undirected graph, the answer lies in networkx library of python.
if you just need to count triangles, use:

import networkx as nx
tri=nx.triangles(g)

But if you need to know the edge list with triangle (triadic) relationship, use

all_cliques= nx.enumerate_all_cliques(g)

This will give you all cliques (k=1,2,3...max degree - 1)

So, to filter just triangles i.e k=3,

triad_cliques=[x for x in all_cliques if len(x)==3 ]

The triad_cliques will give a edge list with only triangles.


问:
Using Accelerate (CLAPACK) to solve an augmented matrix?
Does anyone know what function/method to use in Accelerate (CLAPACK) to solve an augmented matrix such as the one below? Looking for any sample code, links to samples, hints on how to solve the matrix. I've been looking through the documentation but most everything has to do with more complex graphical systems and there are hundreds of seemingly similar methods.</p>

```<code> ____            ____
|                    |
|  4   3  -1   |  2  |
| -2   3   8   |  0  |
|  0   2   6   | -1  |
|____            ____|
</code>```

答:
```<code>#include <Accelerate/Accelerate.h>
#include <stdio.h>

int main(int argc, char *argv[]) {

    /* Dimension of the matrix */
    __CLPK_integer n = 3;

    /* Number of right-hand side vectors to solve for */
    __CLPK_integer nrhs = 1;

    /* Note the ordering of the entries in A.  LAPACK uses "column major"
       ordering as follows:

        0 3 6
        1 4 7
        2 5 8

       This is a Fortran-ism that persists in CLAPACK.                    */
    double A[9] = {4.0, -2.0, 0.0, 3.0, 3.0, 2.0, -1.0, 8.0, 6.0 };

    /* "Leading dimension" of the matrix; most of the time, this is just the
       matrix dimension (but not always; you'll learn about this by the time
       you need to use it. */
    __CLPK_integer lda = 3;

    /* Integer array to hold information about the matrix factorization */
    __CLPK_integer ipiv[3];

    /* Right hand side to solve for */
    double x[3] = { 2.0, 0.0, -1.0 };

    /* Leading dimension of the right hand side vector */
    __CLPK_integer ldb = 3;

    /* Status variable */
    __CLPK_integer info;

    /* Solve the augmented system with a call to dgesv_.  Note that this
       routine will overwrite the contents of the array A with a factored
       form of the matrix.  If you need the original matrix, you need to
       copy it before calling dgesv_.  Note that all the scalar arguments
       are passed as pointers; this too is a Fortran-ism.                 */
    dgesv_(&n, &nrhs, A, &lda, ipiv, x, &ldb, &info);

    /* Handle error conditions */
    if (info)
        printf("Could not solve system; dgesv exited with error %d\n", info);

    /* If no error, print the result */
    else
        printf("Solution is [%f, %f, %f]\n", x[0], x[1], x[2]);

    return 0;
}
</code>```

Compile and run:

```<code> scanon$ gcc solve.c -framework Accelerate
 scanon$ ./a.out
 Solution is [-0.479167, 1.125000, -0.541667]
</code>```

Body:
Does anyone know what function/method to use in Accelerate (CLAPACK) to solve an augmented matrix such as the one below? Looking for any sample code, links to samples, hints on how to solve the matrix. I've been looking through the documentation but most everything has to do with more complex graphical systems and there are hundreds of seemingly similar methods.

 ____            ____
|                    |
|  4   3  -1   |  2  |
| -2   3   8   |  0  |
|  0   2   6   | -1  |
|____            ____|

Body:
#include <Accelerate/Accelerate.h>
#include <stdio.h>

int main(int argc, char *argv[]) {

    /* Dimension of the matrix */
    __CLPK_integer n = 3;

    /* Number of right-hand side vectors to solve for */
    __CLPK_integer nrhs = 1;

    /* Note the ordering of the entries in A.  LAPACK uses "column major"
       ordering as follows:

        0 3 6
        1 4 7
        2 5 8

       This is a Fortran-ism that persists in CLAPACK.                    */
    double A[9] = {4.0, -2.0, 0.0, 3.0, 3.0, 2.0, -1.0, 8.0, 6.0 };

    /* "Leading dimension" of the matrix; most of the time, this is just the
       matrix dimension (but not always; you'll learn about this by the time
       you need to use it. */
    __CLPK_integer lda = 3;

    /* Integer array to hold information about the matrix factorization */
    __CLPK_integer ipiv[3];

    /* Right hand side to solve for */
    double x[3] = { 2.0, 0.0, -1.0 };

    /* Leading dimension of the right hand side vector */
    __CLPK_integer ldb = 3;

    /* Status variable */
    __CLPK_integer info;

    /* Solve the augmented system with a call to dgesv_.  Note that this
       routine will overwrite the contents of the array A with a factored
       form of the matrix.  If you need the original matrix, you need to
       copy it before calling dgesv_.  Note that all the scalar arguments
       are passed as pointers; this too is a Fortran-ism.                 */
    dgesv_(&n, &nrhs, A, &lda, ipiv, x, &ldb, &info);

    /* Handle error conditions */
    if (info)
        printf("Could not solve system; dgesv exited with error %d\n", info);

    /* If no error, print the result */
    else
        printf("Solution is [%f, %f, %f]\n", x[0], x[1], x[2]);

    return 0;
}

Compile and run:

 scanon$ gcc solve.c -framework Accelerate
 scanon$ ./a.out
 Solution is [-0.479167, 1.125000, -0.541667]

ContentLicense: CC BY-SA 2.5


问:
Composer Fails to Install and Update
I was doing the same thing in my server weeks ago, but now I can't. Here's my error output:

composer install

```<code>Loading composer repositories with package information
Installing dependencies (including require-dev)
PHP Fatal error:  Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:974
Stack trace:
#0 [internal function]: Composer\Util\ErrorHandler::handle(2, 'proc_open(): fo...', 'phar:///usr/loc...', 974, Array)
#1 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(974): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#2 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(793): Symfony\Component\Console\Application->getSttyColumns()
#3 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(754): Symfony\Component\Console\Application->getTerminalDimensions()
#4 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(688): Symfony\Component\Console\Application->getTerminalWidth()
#5 phar:///usr/local/bin/com in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php on line 974

Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:974
Stack trace:
#0 [internal function]: Composer\Util\ErrorHandler::handle(2, 'proc_open(): fo...', 'phar:///usr/loc...', 974, Array)
#1 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(974): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#2 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(793): Symfony\Component\Console\Application->getSttyColumns()
#3 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(754): Symfony\Component\Console\Application->getTerminalDimensions()
#4 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(688): Symfony\Component\Console\Application->getTerminalWidth()
#5 phar:///usr/local/bin/com in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php on line 974`
</code>```

答:
To solve this issue, increase the swap memory:</p>

```<code>/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
</code>```

Title: Composer Fails to Install and Update

Body:
I was doing the same thing in my server weeks ago, but now I can't. Here's my error output:

composer install

Loading composer repositories with package information
Installing dependencies (including require-dev)
PHP Fatal error:  Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:974
Stack trace:
#0 [internal function]: Composer\Util\ErrorHandler::handle(2, 'proc_open(): fo...', 'phar:///usr/loc...', 974, Array)
#1 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(974): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#2 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(793): Symfony\Component\Console\Application->getSttyColumns()
#3 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(754): Symfony\Component\Console\Application->getTerminalDimensions()
#4 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(688): Symfony\Component\Console\Application->getTerminalWidth()
#5 phar:///usr/local/bin/com in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php on line 974

Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:974
Stack trace:
#0 [internal function]: Composer\Util\ErrorHandler::handle(2, 'proc_open(): fo...', 'phar:///usr/loc...', 974, Array)
#1 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(974): proc_open('stty -a | grep ...', Array, NULL, NULL, NULL, Array)
#2 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(793): Symfony\Component\Console\Application->getSttyColumns()
#3 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(754): Symfony\Component\Console\Application->getTerminalDimensions()
#4 phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php(688): Symfony\Component\Console\Application->getTerminalWidth()
#5 phar:///usr/local/bin/com in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php on line 974`

Body:
To solve this issue, increase the swap memory:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1


问:
DateTime formatting confusion in Scala
So I have the following data in a .csv file (this is only the first few rows) -

```<code>time                  temp
2015-08-14 00:00:05   30.00
2015-08-14 00:00:15   31.25
2015-08-14 00:00:25   33.45
2015-08-14 00:00:35   34.76
2015-08-14 00:00:45   36.43
</code>```

I then create the following case class  -

```<code>scala> case class Temps(time: org.joda.time.format.DateTimeFormat, temp: String)
</code>```

I then aim to create an RDD by creating the parse function

```<code>scala> def parse(line: String) = {
       val data = line.split(',')
       val time = data(0).????
       val temp= data(1).toString
       Temps(time, temp)
       }
</code>```

So my question is, what do I put where the ??? is above? I'm not entirely sure how to format the DateTime in this scenario.

答:
First, for your Temps's time type should be: org.joda.time.DateTime, DateTimeFormat is a factory for creating DateTimeFormatter(this is used to format time).

Second, you can use DateTimeFormatter.parseDateTime to parse date string to DateTime

so this code maybe should like be:

```<code> case class Temps(time: DateTime, temp: String)

 val dateTimeFormatter = DateTimeFormat.forPattern("yyyy-mm-dd HH:mm:ss")
 def parse(line: String) = {
       val data = line.split(',')
       val time = dateTimeFormatter.parseDateTime(data(0))
       val temp= data(1).toString
       Temps(time, temp)
 }
</code>```

Title: DateTime formatting confusion in Scala

Body:
So I have the following data in a .csv file (this is only the first few rows) -

time                  temp
2015-08-14 00:00:05   30.00
2015-08-14 00:00:15   31.25
2015-08-14 00:00:25   33.45
2015-08-14 00:00:35   34.76
2015-08-14 00:00:45   36.43

I then create the following case class  -

scala> case class Temps(time: org.joda.time.format.DateTimeFormat, temp: String)

I then aim to create an RDD by creating the parse function

scala> def parse(line: String) = {
       val data = line.split(',')
       val time = data(0).????
       val temp= data(1).toString
       Temps(time, temp)
       }

So my question is, what do I put where the ??? is above? I'm not entirely sure how to format the DateTime in this scenario.

Body:
First, for your Temps's time type should be: org.joda.time.DateTime, DateTimeFormat is a factory for creating DateTimeFormatter(this is used to format time).

Second, you can use DateTimeFormatter.parseDateTime to parse date string to DateTime

so this code maybe should like be:

 case class Temps(time: DateTime, temp: String)

 val dateTimeFormatter = DateTimeFormat.forPattern("yyyy-mm-dd HH:mm:ss")
 def parse(line: String) = {
       val data = line.split(',')
       val time = dateTimeFormatter.parseDateTime(data(0))
       val temp= data(1).toString
       Temps(time, temp)
 }


问:
UISearchController Push Segue not finding SourceController
Please, I have tried everything I can google! Image Provided Below!

I have a main 'ProgramTableViewController' which is a TableView that is populated with an Array of data. I have created a UISearchController (SearchResultsTableViewController) that is presented in code on top of the ProgramTableViewController to search through the array. Once I click on a tableview selected row in the SearchResultsTableView for it to Push Segue to a third 'AboutViewController' that is set up to populate all the data from the array to show all the details of said data. When you segue from the ProgramTableViewController to AboutViewController, it works fine. When you try it from the SearchResultsTableViewController is crashes the app with this error code: "Terminating app due to uncaught exception 'NSGenericException', reason: 'Could not find a navigation controller for segue 'aboutViewTwo'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.'"

I have embedded the SearchResultsTableViewController in a Navigation Controller, didn't fix anything. If I modally do the segue, it half works. Doesn't show nav bar or tab bar and fails when you click on some of the buttons in that AboutViewController.

(In ProgramViewController)

pragma mark - Navigation

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"AboutView"] || [segue.identifier isEqualToString:@"AboutView2"]) {

        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        AboutViewController *aboutVwController = [segue destinationViewController];
        EventList *obj  =   [arrayEventList objectAtIndex:selectedRowIndex.row];
        aboutVwController.eventObj  =   obj;
}
}
</code>```

pragma mark - Search Events

```<code>- (UISearchController *)controller {

    if (!_controller) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
        SearchResultsTableViewController *resultsController = [storyboard instantiateViewControllerWithIdentifier:@"SearchResults"];
        _controller = [[UISearchController alloc] initWithSearchResultsController:resultsController];
        _controller.searchResultsUpdater = self;
}
    return _controller;
}
</code>```

pragma mark - Search Results Updater

```<code>-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    self.results = nil;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"eventName contains [cd] %@", self.controller.searchBar.text];
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", self.controller.searchBar.text];
    self.results = [self->arrayEventList filteredArrayUsingPredicate:predicate];
}
- (IBAction)searchButtonPressed:(id)sender {
    [self.navigationController presentViewController:self.controller animated:YES completion:nil];
}
</code>```

(In SearchResultsTableViewController)

pragma mark - Navigation

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"aboutViewTwo"]) {
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        AboutViewController *aboutVwController = [segue destinationViewController];
        EventList *obj  =   [_searchResults objectAtIndex:selectedRowIndex.row];
        aboutVwController.eventObj  =   obj;
}
}
</code>```

Thanks!!!

答:
Change the segue from Push to Modal.

(Or otherwise, embed the source controller of the segue into a UINavigationController.)

You can only use a Push segue within a navigation stack managed by a UINavigationController.

Body:
Please, I have tried everything I can google! Image Provided Below!

I have a main 'ProgramTableViewController' which is a TableView that is populated with an Array of data. I have created a UISearchController (SearchResultsTableViewController) that is presented in code on top of the ProgramTableViewController to search through the array. Once I click on a tableview selected row in the SearchResultsTableView for it to Push Segue to a third 'AboutViewController' that is set up to populate all the data from the array to show all the details of said data. When you segue from the ProgramTableViewController to AboutViewController, it works fine. When you try it from the SearchResultsTableViewController is crashes the app with this error code: "Terminating app due to uncaught exception 'NSGenericException', reason: 'Could not find a navigation controller for segue 'aboutViewTwo'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.'"

I have embedded the SearchResultsTableViewController in a Navigation Controller, didn't fix anything. If I modally do the segue, it half works. Doesn't show nav bar or tab bar and fails when you click on some of the buttons in that AboutViewController.

(In ProgramViewController)

pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"AboutView"] || [segue.identifier isEqualToString:@"AboutView2"]) {

        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        AboutViewController *aboutVwController = [segue destinationViewController];
        EventList *obj  =   [arrayEventList objectAtIndex:selectedRowIndex.row];
        aboutVwController.eventObj  =   obj;
}
}

pragma mark - Search Events

- (UISearchController *)controller {

    if (!_controller) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
        SearchResultsTableViewController *resultsController = [storyboard instantiateViewControllerWithIdentifier:@"SearchResults"];
        _controller = [[UISearchController alloc] initWithSearchResultsController:resultsController];
        _controller.searchResultsUpdater = self;
}
    return _controller;
}

pragma mark - Search Results Updater

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    self.results = nil;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"eventName contains [cd] %@", self.controller.searchBar.text];
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", self.controller.searchBar.text];
    self.results = [self->arrayEventList filteredArrayUsingPredicate:predicate];
}
- (IBAction)searchButtonPressed:(id)sender {
    [self.navigationController presentViewController:self.controller animated:YES completion:nil];
}

(In SearchResultsTableViewController)

pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"aboutViewTwo"]) {
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        AboutViewController *aboutVwController = [segue destinationViewController];
        EventList *obj  =   [_searchResults objectAtIndex:selectedRowIndex.row];
        aboutVwController.eventObj  =   obj;
}
}

Thanks!!!


问:
How do I move an element inside an iframe by jQuery?
I want to copy some elements to an iframe. My code is this:

```<code><div id="some">
  <div id="more">Something</div>
  <input id="inp>
</div>
<iframe id="myframe"></iframe>
</code>```

I am doing this in Javascript to move all elements from some div to the iframe:

```<code>var allElements = $('div').children();
for(i = 0; i < allElements.length; i++)
{
   $(allElements[i]).detach().appendTo($('#myframe'));
}
</code>```

However, it's not working because iframe has its own html and body. So, how can I get to do this?

答:
If you add .contents().find("body"), you will be able to modify the dom.  So:

```<code>var allElements = $('div').children();
for(i = 0; i < allElements.length; i++)
{
   $(allElements[i]).detach().appendTo($('#myframe').contents().find("body"));
}
</code>```

So, check out the jsFiddle:

https://jsfiddle.net/251u04cq/

Body:
I want to copy some elements to an iframe. My code is this:

Something

  <input id="inp>

I am doing this in Javascript to move all elements from some div to the iframe:

var allElements = $('div').children();
for(i = 0; i < allElements.length; i++)
{
   $(allElements[i]).detach().appendTo($('#myframe'));
}

However, it's not working because iframe has its own html and body. So, how can I get to do this?

Body:
If you add .contents().find("body"), you will be able to modify the dom.  So:

var allElements = $('div').children();
for(i = 0; i < allElements.length; i++)
{
   $(allElements[i]).detach().appendTo($('#myframe').contents().find("body"));
}

So, check out the jsFiddle:

https://jsfiddle.net/251u04cq/


问:
parse ruby file for class references
If I have a file model.rb:

```<code>require 'foo.rb'
require 'foo/bar.rb'

class Model
  def self.foo
    Foo.new
  end

  def bar
    Foo::Bar.to_s
  end

  Foo::Bar::Baz.class_does_not_exist
end
</code>```

How could I parse this file to return valid class references? For instance, if Foo and Foo::Bar are defined elsewhere, but Foo::Bar::Baz is not, then I would want something like:

```<code>parse_for_valid_class_references(File.open('model.rb', 'rb'))
# => [Foo, Foo::Bar]
</code>```

答:
One way to do it would be to execute a shell script that runs a separate ruby process, requires the file, checks what constants are added, and prints it.

if you have file 1.rb:

```<code>class Foo; end
</code>```

then you can write this ruby code elsewhere:

```<code>require 'json'
def constants_added_by_file(path)
  cmd = <<-RB
    require 'json'
    consts = Object.constants
    require '#{path}'
    puts((Object.constants - consts).to_json)
  RB
  JSON.parse `ruby -e "#{cmd}"`
end

puts constants_added_by_file('./1.rb')
# => Foo
</code>```

Title: parse ruby file for class references

Body:
If I have a file model.rb:

require 'foo.rb'
require 'foo/bar.rb'

class Model
  def self.foo
    Foo.new
  end

  def bar
    Foo::Bar.to_s
  end

  Foo::Bar::Baz.class_does_not_exist
end

How could I parse this file to return valid class references? For instance, if Foo and Foo::Bar are defined elsewhere, but Foo::Bar::Baz is not, then I would want something like:

parse_for_valid_class_references(File.open('model.rb', 'rb'))
# => [Foo, Foo::Bar]

Body:
One way to do it would be to execute a shell script that runs a separate ruby process, requires the file, checks what constants are added, and prints it.

if you have file 1.rb:

class Foo; end

then you can write this ruby code elsewhere:

require 'json'
def constants_added_by_file(path)
  cmd = <<-RB
    require 'json'
    consts = Object.constants
    require '#{path}'
    puts((Object.constants - consts).to_json)
  RB
  JSON.parse `ruby -e "#{cmd}"`
end

puts constants_added_by_file('./1.rb')
# => Foo


问:
Which commit to use when git commit?
For example, in the beginning, master is in commit01, which is OK, then I merged branch001 which contains 2 commits into master, then became:

```<code>commit04 Merge branch001 into master
commit03 commit from branch001
commit02 commit from branch001
commit01 master commit
</code>```

Then I found that there is a big bug in branch001, so I want to go back to commit01, if I use git revert, which commit should I use?

答:
If you didn't pushed your master then reset local/master with origin/master

```<code>$ git fetch
$ git reset --hard origin/master
</code>```

If already push then revert your merge commit (commit message like Merge branch 'branch-name' of ...)

```<code>$ git log                  # copy the merge-commit-hash
$ git revert <commit-hash> # revert merge commit

$ git push origin HEAD     # push to origin master
</code>```

Title: Which commit to use when git commit?

Body:
For example, in the beginning, master is in commit01, which is OK, then I merged branch001 which contains 2 commits into master, then became:

commit04 Merge branch001 into master
commit03 commit from branch001
commit02 commit from branch001
commit01 master commit

Then I found that there is a big bug in branch001, so I want to go back to commit01, if I use git revert, which commit should I use?

Body:
If you didn't pushed your master then reset local/master with origin/master

$ git fetch
$ git reset --hard origin/master

If already push then revert your merge commit (commit message like Merge branch 'branch-name' of ...)

$ git log                  # copy the merge-commit-hash
$ git revert <commit-hash> # revert merge commit

$ git push origin HEAD     # push to origin master


问:
Angular2 : how to call main component function from a child component
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

```<code>@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}
</code>```

button component html

```<code><div (click)="onBtnClick()">
    <button>btn</button>
</div>
</code>```

browser component

```<code>@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}
</code>```

browser component html

```<code><div>
<h1>browser title</h1>
<cb-button (click)="editCampus()"></cb-button>
</div>
</code>```

and finally in main component i'm including browser component

main-component.ts

```<code>editCampus() {
  alert('clicked');
}
</code>```

html

```<code><topology-browser [campus]="campus"></topology-browser>
</code>```

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

答:
You may try the below. I have not tried this but am guessing it might work. The button component emits an event which is being caught by the main component.

You may also pass data via a common service and injecting that service into the child component and calling a service function which updates a service observable which is subscribed by the main component

Your main component

```<code>@Component({
  template `
    <button-comp (onClick)="mainMethod($event)"></button-comp>
  `,
  directives: [ ButtonComponent ]
})
export class MainComponent {
  (...)

  mainMethod(event) {
    console.log(event)
  }
}
</code>```

your button component

```<code>@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit('hello');
    }
}

button component html

<div (click)="onBtnClick()">
    <button>btn</button>
</div>
</code>```

Body:
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}

button component html

    <button>btn</button>

browser component

@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}

browser component html

browser title

<cb-button (click)="editCampus()"></cb-button>

and finally in main component i'm including browser component

main-component.ts

editCampus() {
  alert('clicked');
}

html

<topology-browser [campus]="campus"></topology-browser>

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

Body:
You may try the below. I have not tried this but am guessing it might work. The button component emits an event which is being caught by the main component.

You may also pass data via a common service and injecting that service into the child component and calling a service function which updates a service observable which is subscribed by the main component

Your main component

@Component({
  template `
    <button-comp (onClick)="mainMethod($event)"></button-comp>
  `,
  directives: [ ButtonComponent ]
})
export class MainComponent {
  (...)

  mainMethod(event) {
    console.log(event)
  }
}

your button component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit('hello');
    }
}

button component html

<div (click)="onBtnClick()">
    <button>btn</button>
</div>


问:
Swift 3.0 - Drawing on imageView with finger
I have been working on being able to draw a red line on an image view using swift 3.0 and have ran across some problems. As you could guess, I am using some code from stack overflow to help me with my first initial attempt at this and am getting a weird bug.

As I drag my finger across the imageview it does draw a red line but for each "frame" it drops all that I drew down further on the screen. So as I draw it looks like the lines I am drawing are falling and then just completely go off screen.

What I am looking for is to be able to simply draw on the image view and instead of everything moving down each frame, I would like it to keep in the same position similar to how it works on all the drawing apps and etc.

Below is all the code:

```<code>@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var fromPoint = CGPoint();
var toPoint = CGPoint.zero
var red: CGFloat = 255.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
{
    UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, false, 0);
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    mainImageView.alpha = opacity
    UIGraphicsEndImageContext()

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false;
    if let touch = touches.first {
        lastPoint = touch.location(in: self.mainImageView)
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true;
    if let touch = touches.first {
        let currentPoint = touch.location(in: mainImageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if(!swiped){
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }
}
</code>```

Thanks for the help guys!

答:
Following code you can Draw the image using touch (Swift 3.0)</p>

```<code>func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
swiped = false
if let touch = touches.first as? UITouch {
    lastPoint = touch.location(in: self.view)
}
 }
 func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {

UIGraphicsBeginImageContext(view.frame.size)
let context = UIGraphicsGetCurrentContext()
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width:     view.frame.size.width, height: view.frame.size.height))

context?.move(to: fromPoint)
context?.addLine(to: toPoint)

context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()

tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = opacity
UIGraphicsEndImageContext()

}

 func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
swiped = true
if let touch = touches.first as? UITouch {
    let currentPoint = touch.location(in: view)
    drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

    lastPoint = currentPoint
}
}
</code>```

Body:
I have been working on being able to draw a red line on an image view using swift 3.0 and have ran across some problems. As you could guess, I am using some code from stack overflow to help me with my first initial attempt at this and am getting a weird bug.

As I drag my finger across the imageview it does draw a red line but for each "frame" it drops all that I drew down further on the screen. So as I draw it looks like the lines I am drawing are falling and then just completely go off screen.

What I am looking for is to be able to simply draw on the image view and instead of everything moving down each frame, I would like it to keep in the same position similar to how it works on all the drawing apps and etc.

Below is all the code:

@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var fromPoint = CGPoint();
var toPoint = CGPoint.zero
var red: CGFloat = 255.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
{
    UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, false, 0);
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    mainImageView.alpha = opacity
    UIGraphicsEndImageContext()

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false;
    if let touch = touches.first {
        lastPoint = touch.location(in: self.mainImageView)
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true;
    if let touch = touches.first {
        let currentPoint = touch.location(in: mainImageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if(!swiped){
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }
}

Thanks for the help guys!

Body:
Following code you can Draw the image using touch (Swift 3.0)

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
swiped = false
if let touch = touches.first as? UITouch {
    lastPoint = touch.location(in: self.view)
}
 }
 func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {

UIGraphicsBeginImageContext(view.frame.size)
let context = UIGraphicsGetCurrentContext()
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width:     view.frame.size.width, height: view.frame.size.height))

context?.move(to: fromPoint)
context?.addLine(to: toPoint)

context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()

tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = opacity
UIGraphicsEndImageContext()

}

 func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
swiped = true
if let touch = touches.first as? UITouch {
    let currentPoint = touch.location(in: view)
    drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

    lastPoint = currentPoint
}
}


问:
F#, implement fold3, fold4, fold_n
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

```<code>// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964
</code>```

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

```<code>let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]
</code>```

My second method is to declare a mutable data, and use List.map3

```<code>let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942
</code>```

I would like to know if there are other ways to solve this problem. Thank you.

答:
For fold3, you could just do zip3 and then fold:

```<code>let polynomial (x:double) (a, b, c) = a*x + b*x*x + c*x*x*x
List.zip3 A B C |> List.fold polynomial 0.7
</code>```

But if you want this for the general case, then you need what we call "applicative functors".

First, imagine you have a list of functions and a list of values. Let's assume for now they're of the same size:

```<code>let fs = [ (fun x -> x+1); (fun x -> x+2); (fun x -> x+3) ]
let xs = [3;5;7]
</code>```

And what you'd like to do (only natural) is to apply each function to each value. This is easily done with List.map2:

```<code>let apply fs xs = List.map2 (fun f x -> f x) fs xs

apply fs xs  // Result = [4;7;10]
</code>```

This operation "apply" is why these are called "applicative functors". Not just any ol' functors, but applicative ones. (the reason for why they're "functors" is a tad more complicated)

So far so good. But wait! What if each function in my list of functions returned another function?

```<code>let f1s = [ (fun x -> fun y -> x+y); (fun x -> fun y -> x-y); (fun x -> fun y -> x*y) ]
</code>```

Or, if I remember that fun x -> fun y -> ... can be written in the short form of fun x y -> ...

```<code>let f1s = [ (fun x y -> x+y); (fun x y -> x-y); (fun x y -> x*y) ]
</code>```

What if I apply such list of functions to my values? Well, naturally, I'll get another list of functions:

```<code>let f2s = apply f1s xs
// f2s = [ (fun y -> 3+y); (fun y -> 5+y); (fun y -> 7+y) ]
</code>```

Hey, here's an idea! Since f2s is also a list of functions, can I apply it again? Well of course I can!

```<code>let ys = [1;2;3]
apply f2s ys  // Result: [4;7;10]
</code>```

Wait, what? What just happened?

I first applied the first list of functions to xs, and got another list of functions as a result. And then I applied that result to ys, and got a list of numbers.

We could rewrite that without intermediate variable f2s:

```<code>let f1s = [ (fun x y -> x+y); (fun x y -> x-y); (fun x y -> x*y) ]
let xs = [3;5;7]
let ys = [1;2;3]
apply (apply f1s xs) ys  // Result: [4;7;10]
</code>```

For extra convenience, this operation apply is usually expressed as an operator:

```<code>let (<*>) = apply
f1s <*> xs <*> ys
</code>```

See what I did there? With this operator, it now looks very similar to just calling the function with two arguments. Neat.

But wait. What about our original task? In the original requirements we don't have a list of functions, we only have one single function.

Well, that can be easily fixed with another operation, let's call it "apply first". This operation will take a single function (not a list) plus a list of values, and apply this function to each value in the list:

```<code>let applyFirst f xs = List.map f xs
</code>```

Oh, wait. That's just map. Silly me :-)

For extra convenience, this operation is usually also given an operator name:

```<code>let (<|>) = List.map
</code>```

And now, I can do things like this:

```<code>let f x y = x + y
let xs = [3;5;7]
let ys = [1;2;3]
f <|> xs <*> ys  // Result: [4;7;10]
</code>```

Or this:

```<code>let f x y z = (x + y)*z
let xs = [3;5;7]
let ys = [1;2;3]
let zs = [1;-1;100]
f <|> xs <*> ys <*> zs  // Result: [4;-7;1000]
</code>```

Neat! I made it so I can apply arbitrary functions to lists of arguments at once!

Now, finally, you can apply this to your original problem:

```<code>let polynomial a b c (x:double) = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let ps = polynomial <|> A <*> B <*> C
let result = ps |> List.fold (fun x f -> f x) 0.7
</code>```

The list ps consists of polynomial instances that are partially applied to corresponding elements of A, B, and C, and still expecting the final argument x. And on the next line, I simply fold over this list of functions, applying each of them to the result of the previous.

Title: F#, implement fold3, fold4, fold_n

Body:
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]

My second method is to declare a mutable data, and use List.map3

let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942

I would like to know if there are other ways to solve this problem. Thank you.

Body:
For fold3, you could just do zip3 and then fold:

let polynomial (x:double) (a, b, c) = a*x + b*x*x + c*x*x*x
List.zip3 A B C |> List.fold polynomial 0.7

But if you want this for the general case, then you need what we call "applicative functors".

First, imagine you have a list of functions and a list of values. Let's assume for now they're of the same size:

let fs = [ (fun x -> x+1); (fun x -> x+2); (fun x -> x+3) ]
let xs = [3;5;7]

And what you'd like to do (only natural) is to apply each function to each value. This is easily done with List.map2:

let apply fs xs = List.map2 (fun f x -> f x) fs xs

apply fs xs  // Result = [4;7;10]

This operation "apply" is why these are called "applicative functors". Not just any ol' functors, but applicative ones. (the reason for why they're "functors" is a tad more complicated)

So far so good. But wait! What if each function in my list of functions returned another function?

let f1s = [ (fun x -> fun y -> x+y); (fun x -> fun y -> x-y); (fun x -> fun y -> x*y) ]

Or, if I remember that fun x -> fun y -> ... can be written in the short form of fun x y -> ...

let f1s = [ (fun x y -> x+y); (fun x y -> x-y); (fun x y -> x*y) ]

What if I apply such list of functions to my values? Well, naturally, I'll get another list of functions:

let f2s = apply f1s xs
// f2s = [ (fun y -> 3+y); (fun y -> 5+y); (fun y -> 7+y) ]

Hey, here's an idea! Since f2s is also a list of functions, can I apply it again? Well of course I can!

let ys = [1;2;3]
apply f2s ys  // Result: [4;7;10]

Wait, what? What just happened?

I first applied the first list of functions to xs, and got another list of functions as a result. And then I applied that result to ys, and got a list of numbers.

We could rewrite that without intermediate variable f2s:

let f1s = [ (fun x y -> x+y); (fun x y -> x-y); (fun x y -> x*y) ]
let xs = [3;5;7]
let ys = [1;2;3]
apply (apply f1s xs) ys  // Result: [4;7;10]

For extra convenience, this operation apply is usually expressed as an operator:

let (<*>) = apply
f1s <*> xs <*> ys

See what I did there? With this operator, it now looks very similar to just calling the function with two arguments. Neat.

But wait. What about our original task? In the original requirements we don't have a list of functions, we only have one single function.

Well, that can be easily fixed with another operation, let's call it "apply first". This operation will take a single function (not a list) plus a list of values, and apply this function to each value in the list:

let applyFirst f xs = List.map f xs

Oh, wait. That's just map. Silly me :-)

For extra convenience, this operation is usually also given an operator name:

let (<|>) = List.map

And now, I can do things like this:

let f x y = x + y
let xs = [3;5;7]
let ys = [1;2;3]
f <|> xs <*> ys  // Result: [4;7;10]

Or this:

let f x y z = (x + y)*z
let xs = [3;5;7]
let ys = [1;2;3]
let zs = [1;-1;100]
f <|> xs <*> ys <*> zs  // Result: [4;-7;1000]

Neat! I made it so I can apply arbitrary functions to lists of arguments at once!

Now, finally, you can apply this to your original problem:

let polynomial a b c (x:double) = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let ps = polynomial <|> A <*> B <*> C
let result = ps |> List.fold (fun x f -> f x) 0.7

The list ps consists of polynomial instances that are partially applied to corresponding elements of A, B, and C, and still expecting the final argument x. And on the next line, I simply fold over this list of functions, applying each of them to the result of the previous.


问:
How to convert a dict inside a list to a DataFrame in python?
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

```<code>a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}
</code>```

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

```<code>b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)
</code>```

This displays my dataframe as:

```<code>                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None
</code>```

Instead, I am looking for:

```<code>Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89
</code>```

I would appreciate any help I can get.

答:
You can just extract all the scores with a comprehension/generator:</p>

```<code>>>> pd.DataFrame(s for k, v in a['Scores'].items() for s in v)
  English  Math Science
0    60.5    95    74.5
1    78.3  87.9    97.3
2      89  67.2    74.2
</code>```

Body:
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)

This displays my dataframe as:

                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None

Instead, I am looking for:

Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89

I would appreciate any help I can get.

Body:
You can just extract all the scores with a comprehension/generator:

>>> pd.DataFrame(s for k, v in a['Scores'].items() for s in v)
  English  Math Science
0    60.5    95    74.5
1    78.3  87.9    97.3
2      89  67.2    74.2


问:
Google Cloud Storage files access policy based on IP Address
Is there any way to limit access of all files in a bucket in Google Cloud Storage based on the client IP address?
I have a file stored there, which should be access only by specific IP address. How to do this?</p>

答: No, there is not currently a way to do this.</p>


问:
How to store text as paragraphs in SQLite database in a iPhone app?
In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.

What should I do to store the text as paragraphs in SQLite database?

For example, I want to store paragraphs like the ones below in:

(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.

The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'

Basically I want to save the paragraphs in database in the same format with carriage returns.

答:
My suggestion would be if you want to display your text in a webview then add HTML tags to your text.So in that way you can add paragraphs,New lines and many other effects to your text.

Thanks

ContentLicense: CC BY-SA 4.0


问:
Is it possible to show the restart policy of a running Docker container?
When I create containers I'm specifying a restart policy, but this is not shown in docker ps, and it doesn't appear any format string shows this either.

Does anyone know how to see the restart policy of a running container(s)?

答:
Yes, it is possible using docker inspect which is json format and just need to query it.

Here is relevant output of docker inspect for a running container zen_easley. Note to change container name as suitable for your environment.

docker inspect zen_easley

"HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": true,
```

<p>You can just run the following command to get the same and its output.</p>

```$ docker inspect -f "{{ .HostConfig.RestartPolicy }}"  zen_easley
{no 0}
```

<p>If you see <code>RestartPolicy</code> has two properties <code>Name, MaximumRetryCount</code> and <strong>no, 0</strong> are the values respectively in the above output</p>

<p>You may also get the individual property value, say <code>Name</code> by using below command, appending <code>.Name</code> to the above command:</p>

```docker inspect -f "{{ .HostConfig.RestartPolicy.Name }}"  zen_easley
no
```

Body:
Yes, it is possible using docker inspect which is json format and just need to query it.

Here is relevant output of docker inspect for a running container zen_easley. Note to change container name as suitable for your environment.

docker inspect zen_easley

"HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": true,

You can just run the following command to get the same and its output.

$ docker inspect -f "{{ .HostConfig.RestartPolicy }}"  zen_easley
{no 0}

If you see RestartPolicy has two properties Name, MaximumRetryCount and no, 0 are the values respectively in the above output

You may also get the individual property value, say Name by using below command, appending .Name to the above command:

docker inspect -f "{{ .HostConfig.RestartPolicy.Name }}"  zen_easley
no


问:
Apply query total for variable
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

```<code>$sumQuery = 'sum(Condition) total';
</code>```

And select sum:

```<code> $query->select(['*', $sumQuery]);
</code>```

So how can i get it's in Data Provinder.

答:
Or try   </p>

```<code> $query->select('*, sum(Condition) as total');
</code>```

Title: Apply query total for variable

Body:
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

$sumQuery = 'sum(Condition) total';

And select sum:

 $query->select(['*', $sumQuery]);

So how can i get it's in Data Provinder.

Body:
Or try

 $query->select('*, sum(Condition) as total');


问:
Getting current week of current month
I found a javascript and a php script to get current week of the month base on the entire year. That's great but im a little confused. I would like to know whether if it's week 1,2,3,4 of current month not entire year. How should I got about that?

javascript

```<code>/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() -
    (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4) {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52) {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
              the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};
</code>```

Usage

```<code>var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());
</code>```

答:
The ISO week in month number is based on Mondays, so Thursday, 2 March 2017 is in week 4 of February 2017 and Monday 6 March 2017 is in week 1 of March.

So the algorithm is to move to the previous Monday and see which Monday of the month it is. I would have thought this was a duplicate but I can't find one, so here's a function.

/* Get ISO week in month, based on first Monday in month
** @param {Date} date - date to get week in month of
** @returns {Object} month: month that week is in
**                   week: week in month
*/
function getISOWeekInMonth(date) {
  // Copy date so don't affect original
  var d = new Date(+date);
  if (isNaN(d)) return;
  // Move to previous Monday
  d.setDate(d.getDate() - d.getDay() + 1);
  // Week number is ceil date/7
  return {month: +d.getMonth()+1,
          week: Math.ceil(d.getDate()/7)};
}
//*
[new Date(2017,2,2),   // Thu 2 Mar 2017
 new Date(2017,2,6),   // Mon 6 Mar 2017
 new Date(2017,4,31),  // Wed 31 May 2017
 new Date()].forEach(  // Current date
  function(date) {
    console.log(date.toString() + '\nis in week ' +
    getISOWeekInMonth(date).week + ' of month ' +
    getISOWeekInMonth(date).month);
  }
);
//*/```

If you want to get the ISO week in the year, then Get week of year in JavaScript like in PHP has your answer.

Title: Getting current week of current month

Body:
I found a javascript and a php script to get current week of the month base on the entire year. That's great but im a little confused. I would like to know whether if it's week 1,2,3,4 of current month not entire year. How should I got about that?

javascript

/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() -
    (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4) {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52) {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
              the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};

Usage

var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());

Body:
The ISO week in month number is based on Mondays, so Thursday, 2 March 2017 is in week 4 of February 2017 and Monday 6 March 2017 is in week 1 of March.

So the algorithm is to move to the previous Monday and see which Monday of the month it is. I would have thought this was a duplicate but I can't find one, so here's a function.

/* Get ISO week in month, based on first Monday in month
** @param {Date} date - date to get week in month of
** @returns {Object} month: month that week is in
**                   week: week in month
*/
function getISOWeekInMonth(date) {
  // Copy date so don't affect original
  var d = new Date(+date);
  if (isNaN(d)) return;
  // Move to previous Monday
  d.setDate(d.getDate() - d.getDay() + 1);
  // Week number is ceil date/7
  return {month: +d.getMonth()+1,
          week: Math.ceil(d.getDate()/7)};
}
//*
[new Date(2017,2,2),   // Thu 2 Mar 2017
 new Date(2017,2,6),   // Mon 6 Mar 2017
 new Date(2017,4,31),  // Wed 31 May 2017
 new Date()].forEach(  // Current date
  function(date) {
    console.log(date.toString() + '\nis in week ' +
    getISOWeekInMonth(date).week + ' of month ' +
    getISOWeekInMonth(date).month);
  }
);
//*/

If you want to get the ISO week in the year, then Get week of year in JavaScript like in PHP has your answer.


问:
after save not direct to original page
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.  </p>

```<code>$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "<script type='text/javascript'>window.location.href='administration.php?id='.$id;</script>";
        }
    }
$conn->close();
</code>```

答:
You can use below code for your question hope this will help you<br>

```<code>$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
           echo "<script type='text/javascript'>window.location.href='administration.php?id=".$id."';</script>";
        }
    }
$conn->close();
</code>```

Title: after save not direct to original page

Body:
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.

$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "";
        }
    }
$conn->close();

Body:
You can use below code for your question hope this will help you

$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
           echo "<script type='text/javascript'>window.location.href='administration.php?id=".$id."';</script>";
        }
    }
$conn->close();


问:
How to seterror of textview
IN Edittext seterror working perfecty but  Textview  how to seterror

I tried coding so for

```<code>Textview  spinner = (TextView) view.findViewById(R.id.spinner_txt);
spinner_txt.setText(name);///from the coding i am setting settext
String spinnertxt=spinner.getText.toString;

if(spinnertxt.length()==0){
    spinner_txt.setError("select the representative");
    }
spinner_txt.requestFocus();
</code>```

答:
```<code>Textview  spinner = (TextView) view.findViewById(R.id.spinner_txt);
</code>```

spinner_txt.setText(name);///from the coding i am setting settext

Over here you are setting settext to spinner_txt instead of spinner. I wonder how is your setText is getting called.

```<code>String spinnertxt=spinner.getText.toString;
</code>```

You are getting NullPointerException because your spinner textview does not contain any text and so, snippertxt is null and you are trying to get length of a null object.

Try this:-

```<code>spinner.setText(name);
String spinnertxt=spinner.getText.toString;
</code>```

Title: How to seterror of textview

Body:
IN Edittext seterror working perfecty but  Textview  how to seterror

I tried coding so for

Textview  spinner = (TextView) view.findViewById(R.id.spinner_txt);
spinner_txt.setText(name);///from the coding i am setting settext
String spinnertxt=spinner.getText.toString;

if(spinnertxt.length()==0){
    spinner_txt.setError("select the representative");
    }
spinner_txt.requestFocus();

Body:
Textview  spinner = (TextView) view.findViewById(R.id.spinner_txt);

spinner_txt.setText(name);///from the coding i am setting settext

Over here you are setting settext to spinner_txt instead of spinner. I wonder how is your setText is getting called.

String spinnertxt=spinner.getText.toString;

You are getting NullPointerException because your spinner textview does not contain any text and so, snippertxt is null and you are trying to get length of a null object.

Try this:-

spinner.setText(name);
String spinnertxt=spinner.getText.toString;


问:
URL Beautification using .htaccess or php?
In search of a more userfriendly & search engine friendly urls, i want have beautied my urls:
The htacces apache rule that achieves this (Thanks to Laurence Gonsalves)

```<code>RewriteRule ^([a-z][a-z])/(.*) /$2?ln=$1 [L]
</code>```

which makes this possible:

/uk/somepage  instead of   /somepage?ln=uk

/de/somepage  instead of   /somepage?ln=de

/ja/somepage  instead of   /somepage?ln=ja

Now the difficult part: previously, the url was replaced with a normal link like href="?ln=de" or href="?ln=it" for changing language of the current page. But now how can i achieve that? Sothat the current page stays the same, but only the preceding two lowercase letters that say to the browser what language it is in change?

So how to tell the link to only change the /uk/contact to /de/contact once the german (de) language flag is clicked? php solution to rewrite the url or htaccess solutions are accepted.

I found out that $_SERVER['REQUEST_URI'] will output /uk/somepage but i cant write the php code that can split up the components, add a new language code like "de" into it, which i can put manually into a normal href that goes on a German flag. etc. Thanks for any and all clues/answers!

答:
Well, you can split the request_uri using, well, split() or explode().

```<code>$uri_bits=explode('/', $_SERVER['REQUEST_URI']);
</code>```

In theory the language identifier will be in $uri_bits[ 1] (as [0] would contain a zero length string, but you should test it by print_r()-ing the array). Of course, you should test if the $uri_bits[ 1] exists, and it's the language identifier, the simplest way to do it would be:

```<code>if($uri_bits[1]==$_GET['lang'])
</code>```

Then you can change that and concatenate the bits again using implode()

```<code>$uri_bits[1]="it";
$url_german=implode('/', $uri_bits);
</code>```

At least that's how I'd do it.

Body:
In search of a more userfriendly & search engine friendly urls, i want have beautied my urls:
The htacces apache rule that achieves this (Thanks to Laurence Gonsalves)

RewriteRule ^([a-z][a-z])/(.*) /$2?ln=$1 [L]

which makes this possible:

/uk/somepage  instead of   /somepage?ln=uk

/de/somepage  instead of   /somepage?ln=de

/ja/somepage  instead of   /somepage?ln=ja

Now the difficult part: previously, the url was replaced with a normal link like href="?ln=de" or href="?ln=it" for changing language of the current page. But now how can i achieve that? Sothat the current page stays the same, but only the preceding two lowercase letters that say to the browser what language it is in change?

So how to tell the link to only change the /uk/contact to /de/contact once the german (de) language flag is clicked? php solution to rewrite the url or htaccess solutions are accepted.

I found out that $_SERVER['REQUEST_URI'] will output /uk/somepage but i cant write the php code that can split up the components, add a new language code like "de" into it, which i can put manually into a normal href that goes on a German flag. etc. Thanks for any and all clues/answers!

Body:
Well, you can split the request_uri using, well, split() or explode().

$uri_bits=explode('/', $_SERVER['REQUEST_URI']);

In theory the language identifier will be in $uri_bits[ 1] (as [0] would contain a zero length string, but you should test it by print_r()-ing the array). Of course, you should test if the $uri_bits[ 1] exists, and it's the language identifier, the simplest way to do it would be:

if($uri_bits[1]==$_GET['lang'])

Then you can change that and concatenate the bits again using implode()

$uri_bits[1]="it";
$url_german=implode('/', $uri_bits);

At least that's how I'd do it.


问:
Calling tracking JavaScript from AMP pages
We are using in house tracking mechanism for our website. We use our tracking.js file on our all pages.

Every page sent some info in an js object to this script file which later send this information to our tracking application using spring controller.

Now as to move page faster we use some pages in AMP templates.

But this does not allow us to use tracking.js

We tried iframe tag but it does not allow to use http call (it only allow https calls)

Could you please suggest a way to do it as it very critical and we can not move to https right now for other limitation.

Thanks

Virendra Agarwal

答:
As we worked with Google. We got it sorted.
You can add your API to AMP pages after validation by Google.
This API must be behind https and all calls should be validated by Google.
Google then will white list on AMP page and you can use that code in production.</p>


问:
Error in SQL Syntax use near '06:09:43 WHERE Book_id = 19 AND Date_issued = 2017-03-29 17:28:34' at line 1

ERROR: Could not able to execute You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near '06:09:43 WHERE Book_id = 19 AND
  Date_issued = 2017-03-29 17:28:34' at line 1

I've been getting the above error upon executing the following code -

```<code>if(isset($_GET['rt']))//rt is a variable I'm passing in an anchor tag
{
$dateis=$_GET['rt'];
}
if(isset($_GET['id']))//id is also sent along with rt
{
$bk_id=$_GET['id'];
}
$ret = 'returned successfully';
$date = date('Y-m-d H:i:s');
if(mysqli_query($conn, "UPDATE issued_books SET Date_returned = $date WHERE Book_id = $bk_id AND Date_issued = $dateis"))
{
    $fine = mysqli_query($conn, "SELECT DATEDIFF('$dateis', '$date') AS days");
    $fine = $fine*10;
    mysqli_query($conn, "UPDATE issued_books SET Fine_amt = (Fine_amt + $fine) WHERE Date_issued = $dateis");
    mysqli_query($conn, "UPDATE library_books SET Available = (Available + 1) WHERE Book_id = $bk_id");
    header("Location: return-books.php?book=".urlencode($ret));
} else{
    echo "ERROR: Could not able to execute " .mysqli_error($conn);
}
</code>```

答:
Try these, just add single quotes to variables

```<code>"UPDATE issued_books SET Date_returned = '$date' WHERE Book_id = '$bk_id' AND Date_issued = '$dateis'"

"UPDATE issued_books SET Fine_amt = (Fine_amt + '$fine') WHERE Date_issued = '$dateis'"

"UPDATE library_books SET Available = (Available + 1) WHERE Book_id = '$bk_id'"
</code>```

Although it would be better if you use prepared statements.

Body:
ERROR: Could not able to execute You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near '06:09:43 WHERE Book_id = 19 AND
  Date_issued = 2017-03-29 17:28:34' at line 1

I've been getting the above error upon executing the following code -

if(isset($_GET['rt']))//rt is a variable I'm passing in an anchor tag
{
$dateis=$_GET['rt'];
}
if(isset($_GET['id']))//id is also sent along with rt
{
$bk_id=$_GET['id'];
}
$ret = 'returned successfully';
$date = date('Y-m-d H:i:s');
if(mysqli_query($conn, "UPDATE issued_books SET Date_returned = $date WHERE Book_id = $bk_id AND Date_issued = $dateis"))
{
    $fine = mysqli_query($conn, "SELECT DATEDIFF('$dateis', '$date') AS days");
    $fine = $fine*10;
    mysqli_query($conn, "UPDATE issued_books SET Fine_amt = (Fine_amt + $fine) WHERE Date_issued = $dateis");
    mysqli_query($conn, "UPDATE library_books SET Available = (Available + 1) WHERE Book_id = $bk_id");
    header("Location: return-books.php?book=".urlencode($ret));
} else{
    echo "ERROR: Could not able to execute " .mysqli_error($conn);
}

Body:
Try these, just add single quotes to variables

"UPDATE issued_books SET Date_returned = '$date' WHERE Book_id = '$bk_id' AND Date_issued = '$dateis'"

"UPDATE issued_books SET Fine_amt = (Fine_amt + '$fine') WHERE Date_issued = '$dateis'"

"UPDATE library_books SET Available = (Available + 1) WHERE Book_id = '$bk_id'"

Although it would be better if you use prepared statements.


问:
Not able to understand FAKE Code : - FAKE F#MAKE
I have a  sample script , and I am not able to understand a piece of code from that file , here is the code:

```<code>Target "Package1" (fun _ ->
  NuGet (fun p ->
    { p with
      OutputPath = DeployDir
      ReleaseNotes = ReleaseNote
      WorkingDir = BuildDir
      Publish = false
      Version = PackageVersion
      Files = [
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })
    "src/Client/Project.Client.nuspec"
)
</code>```

and this target's order is last . So what is the purpose of using this target. and what is last line doing src/Project.Client/Project.Client.nuspec .If anyone can explain this in details , that would be really helpful.

答:
Look at the indentation. The "src/Client/Project.Client.nuspec" string is indented further than NuGet, because it's one of the parameters to the NuGet function (which wants two parameters). Here's another way this target could have been written, with the same effect but different indentation:

```<code>Target "Package1" (fun _ ->
  NuGet
    (fun p -> { p with OutputPath = DeployDir
                       ReleaseNotes = ReleaseNote
                       WorkingDir = BuildDir
                       Publish = false
                       Version = PackageVersion
                       Files = [
                         (@"*.dll", Some "lib", None)
                         (@"*.pdb", Some "lib",  None)
                       ]
              }
    )
    "src/Client/Project.Client.nuspec"
)
</code>```

Or to make it even clearer:

```<code>let nuGetParameterFunction =
    (fun p -> { p with OutputPath = DeployDir
                       ReleaseNotes = ReleaseNote
                       WorkingDir = BuildDir
                       Publish = false
                       Version = PackageVersion
                       Files = [
                         (@"*.dll", Some "lib", None)
                         (@"*.pdb", Some "lib",  None)
                       ]
              }
    )

Target "Package1" (fun _ ->
  NuGet nuGetParameterFunction "src/Client/Project.Client.nuspec"
)
</code>```

Both of these snippets do exactly the same thing as the snippet you asked about. It's just that in these, it's a little more obvious that the NuGet function takes two parameters.

Body:
I have a  sample script , and I am not able to understand a piece of code from that file , here is the code:

Target "Package1" (fun _ ->
  NuGet (fun p ->
    { p with
      OutputPath = DeployDir
      ReleaseNotes = ReleaseNote
      WorkingDir = BuildDir
      Publish = false
      Version = PackageVersion
      Files = [
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })
    "src/Client/Project.Client.nuspec"
)

and this target's order is last . So what is the purpose of using this target. and what is last line doing src/Project.Client/Project.Client.nuspec .If anyone can explain this in details , that would be really helpful.

Body:
Look at the indentation. The "src/Client/Project.Client.nuspec" string is indented further than NuGet, because it's one of the parameters to the NuGet function (which wants two parameters). Here's another way this target could have been written, with the same effect but different indentation:

Target "Package1" (fun _ ->
  NuGet
    (fun p -> { p with OutputPath = DeployDir
                       ReleaseNotes = ReleaseNote
                       WorkingDir = BuildDir
                       Publish = false
                       Version = PackageVersion
                       Files = [
                         (@"*.dll", Some "lib", None)
                         (@"*.pdb", Some "lib",  None)
                       ]
              }
    )
    "src/Client/Project.Client.nuspec"
)

Or to make it even clearer:

let nuGetParameterFunction =
    (fun p -> { p with OutputPath = DeployDir
                       ReleaseNotes = ReleaseNote
                       WorkingDir = BuildDir
                       Publish = false
                       Version = PackageVersion
                       Files = [
                         (@"*.dll", Some "lib", None)
                         (@"*.pdb", Some "lib",  None)
                       ]
              }
    )

Target "Package1" (fun _ ->
  NuGet nuGetParameterFunction "src/Client/Project.Client.nuspec"
)

Both of these snippets do exactly the same thing as the snippet you asked about. It's just that in these, it's a little more obvious that the NuGet function takes two parameters.


问:
Silverstripe 3.3: how to translate date month variable in a template?
On my page I have a date variable. I wish to translate it's shortened month name by locale (in my case Lithuanian).

I've set up the translations in langed/lang/lt_LT.yml:

```<code>Month:
    Jan: 'Sau'
    Feb: 'Vas'
    Mar: 'Kov'
    Apr: 'Bal'
    ...
</code>```

And in my template when I put

```<code>$Date.Format(M d)
</code>```

It gives the month and day always in English, no matter the locale (ex. "Apr 18", I need "Bal 18" in this case).

I have attempted to try to put the variable of Month into translation quotes of .ss template:

```<code><%t Month.$Date.Format('M') %>
</code>```

But it doesn't work. It throws an error:

"[User Error] Uncaught SSTemplateParseException: Parse error in template on line 16. Error was: Malformed opening block tag t. Perhaps you have tried to use operators?"

Can anyone please explain to me how am I doing this wrong?

答:
The way I've implemented this is put a function on the controller:

```<code>public function MonthForVar($var) {
    return _t("Month.$var");
}
</code>```

and then you can call $MonthForVar($Date) in your template. Don't forget if you're doing it in a loop to go $Up.MonthForVar($Date)

** Should add that wmk's answer is better for date format however I was lead here from Google when I'm trying to translate something non-date related, in which case this should work.

Body:
On my page I have a date variable. I wish to translate it's shortened month name by locale (in my case Lithuanian).

I've set up the translations in langed/lang/lt_LT.yml:

Month:
    Jan: 'Sau'
    Feb: 'Vas'
    Mar: 'Kov'
    Apr: 'Bal'
    ...

And in my template when I put

$Date.Format(M d)

It gives the month and day always in English, no matter the locale (ex. "Apr 18", I need "Bal 18" in this case).

I have attempted to try to put the variable of Month into translation quotes of .ss template:

<%t Month.$Date.Format('M') %>

But it doesn't work. It throws an error:

"[User Error] Uncaught SSTemplateParseException: Parse error in template on line 16. Error was: Malformed opening block tag t. Perhaps you have tried to use operators?"

Can anyone please explain to me how am I doing this wrong?

Body:
The way I've implemented this is put a function on the controller:

public function MonthForVar($var) {
    return _t("Month.$var");
}

and then you can call $MonthForVar($Date) in your template. Don't forget if you're doing it in a loop to go $Up.MonthForVar($Date)

** Should add that wmk's answer is better for date format however I was lead here from Google when I'm trying to translate something non-date related, in which case this should work.