问:
ER_ACCESS_DENIED_ERROR: When i try to connect to the database on remote server - Node.js
I have issue when i try to connect to the database on remote server.

My code:

```<code>const mysql = require('mysql');
const database = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'db'
});

database.getConnection(function (err, connection) {
    if (!err) {
        console.log('Database is connected ...');
    } else {
        console.log('Error connecting database ...');
    }
});
</code>```

The credentials for connection in code is faked. With the right credentials  I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.

When I run script, return this error:
view error

Also, when I input credentials for connection with my local database, everything work perfect.

答:
phpmyadmin runs on the same machine as your MySQL server, so it can connect to the server using the generic host name localhost.

I guess, from your question, that your nodejs program runs on some other machine (your personal machine, maybe?). That takes some special-purpose setup to do.

You must use the server's actual hostname in your host: property, not localhost.

MySQL login credentials aren't just username/password. They are host/username/password. You may need to create a new set of credentials for remote access so your nodejs program can get in. Read this: https://webmasters.stackexchange.com/questions/2242/how-to-create-separate-users-in-phpmyadmin-each-one-cant-see-others-databases

If your MySQL server runs on a rented server at some cloud or hosting service, you may need to open up a firewall to allow your machine to connect. If you're on a hosting service, ask their customer support krewe about that. On a cloud service, you want to open port 3306. Look up how to do that in their documentation. (It may be a gnarly configuration task).

Your easiest way of troubleshooting this is to use some MyQSL client program (like MySQL Workbench or HeidiSQL) on your own machine. when you get that to connect, you can use the same credentials in your createPool() call.

Body:
I have issue when i try to connect to the database on remote server.

My code:

const mysql = require('mysql');
const database = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'db'
});

database.getConnection(function (err, connection) {
    if (!err) {
        console.log('Database is connected ...');
    } else {
        console.log('Error connecting database ...');
    }
});

The credentials for connection in code is faked. With the right credentials  I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.

When I run script, return this error:
view error

Also, when I input credentials for connection with my local database, everything work perfect.


来源: stackexchange

问:
Valgrind massif - measure total memory allocations per callstack
I record memory allocations using valgrind massif and use ms_print to create a document of snapshots that shows me which callstack holds how much memory currently, right?

I want to measure which callstacks have allocated most over the whole program run, that means deallocated memory should be taken into account when calculating the weight of a callstack.

Is this possible?

Regards

答:
When a tool (such as memcheck, massif, ...) replaces the memory allocation functions (malloc, free, ...), then valgrind provides the option:

```<code>--xtree-memory=none|allocs|full   profile heap memory in an xtree [none]
                          and produces a report at the end of the execution
                          none: no profiling, allocs: current allocated
                          size/blocks, full: profile current and cumulative
                          allocated size/blocks and freed size/blocks.
--xtree-memory-file=<file>   xtree memory report file [xtmemory.kcg.%p]
</code>```

So, if you use --xtree-memory=full, you will get a file that you can visualise with kcachegrind.  The resulting file details a.o. what is currently allocated, and what was allocated and then freed.

See http://www.valgrind.org/docs/manual/manual-core.html#manual-core.xtree
for more details.

ContentLicense: CC BY-SA 4.0

Body:
When a tool (such as memcheck, massif, ...) replaces the memory allocation functions (malloc, free, ...), then valgrind provides the option:

--xtree-memory=none|allocs|full   profile heap memory in an xtree [none]
                          and produces a report at the end of the execution
                          none: no profiling, allocs: current allocated
                          size/blocks, full: profile current and cumulative
                          allocated size/blocks and freed size/blocks.
--xtree-memory-file=<file>   xtree memory report file [xtmemory.kcg.%p]

So, if you use --xtree-memory=full, you will get a file that you can visualise with kcachegrind.  The resulting file details a.o. what is currently allocated, and what was allocated and then freed.

See http://www.valgrind.org/docs/manual/manual-core.html#manual-core.xtree
for more details.


问:
Cascading Parsers in Haskell
My parser type is

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
</code>```

I have two parsers :

1) a = (satisfy isAlpha)  that knows how to match the first alpha  numeric character in a string.

Running parse a "k345" gives Just ('k',"345")

2) b = many (satisfy isDigit) that  knows how to match any number of digits. Running parse b "1234 abc" gives Just ("1234"," abc")

Now I want to combine those two parsers and match a singe alphanumeric character followed by any number of digits.

I tried:

parse (a *> b) "k1234 7"   and got Just ("1234"," 7 "). Looks like the 'k' matched by the first parser a is gone from the output. How do I fix this problem ?

Thanks!

答:
For a toy parser, look the following code:

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
module Parse where

import Data.Char
import Data.List

newtype Parser a = Parser
  { parse :: String -> Maybe (a, String) }

satisfy :: (Char -> Bool) -> Parser Char
satisfy cond = Parser $ \s ->
   case s of
     "" -> Nothing
     (c:cs) -> if cond c then Just (c, cs) else Nothing

many :: Parser a -> Parser [a]
many p = Parser $ \s ->
  case parse p s of
    Nothing -> Just ([], s)
    Just (c, cs) -> let Just (cc, cs') = parse (many p) cs
                     in Just (c:cc, cs')

string :: String -> Parser String
string str = Parser $ \s -> if isPrefixOf str s
                               then Just (str, drop (length str) s)
                               else Nothing

instance Functor Parser where
  fmap f (Parser g) = Parser $ \s ->
    case g s of
      Nothing -> Nothing
      Just (r, remain) -> Just (f r, remain)

instance Applicative Parser where
  pure a = Parser $ \s -> Just (a, s)
  -- (<*>) :: f (a -> b) -> f a -> f b
  (Parser f) <*> (Parser g) = Parser $ \s ->
    case f s of
      Nothing -> Nothing
      Just (ab, remain) -> case g remain of
                            Nothing -> Nothing
                            Just (r, remain1) -> Just (ab r, remain1)

instance Semigroup a => Semigroup (Parser a) where
  (Parser p1) <> (Parser p2) = Parser $ \s ->
    case p1 s of
      Nothing -> Nothing
      Just (r1, s1) -> case p2 s1 of
                         Nothing -> Nothing
                         Just (r2, s2) -> Just (r1 <> r2, s2)

instance (Monoid a, Semigroup (Parser a))=> Monoid (Parser a) where
  mempty = Parser $ \s -> Just (mempty, s)
  mappend = (<>)

a = satisfy isAlpha
b = many (satisfy isDigit)
```

```λ> parse a "k345"
Just ('k',"345")
λ> parse b "12345 abc"
Just ("12345"," abc")
λ> parse (a *> b) "k1234 7"
Just ("1234"," 7")
λ> parse (string "k" <> b) "k1234 7"
Just ("k1234"," 7")
```

So maybe you should find some tutorials and try to be familiar with Functor, Applicative, and Monad. See, you can implement the instance of a Monoid for your Parser type, and then you can use (<>) to combine your parsed results together.

Title: Cascading Parsers in Haskell

Body:
My parser type is

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

I have two parsers :

1) a = (satisfy isAlpha)  that knows how to match the first alpha  numeric character in a string.

Running parse a "k345" gives Just ('k',"345")

2) b = many (satisfy isDigit) that  knows how to match any number of digits. Running parse b "1234 abc" gives Just ("1234"," abc")

Now I want to combine those two parsers and match a singe alphanumeric character followed by any number of digits.

I tried:

parse (a *> b) "k1234 7"   and got Just ("1234"," 7 "). Looks like the 'k' matched by the first parser a is gone from the output. How do I fix this problem ?

Thanks!

Body:
For a toy parser, look the following code:

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
module Parse where

import Data.Char
import Data.List

newtype Parser a = Parser
  { parse :: String -> Maybe (a, String) }

satisfy :: (Char -> Bool) -> Parser Char
satisfy cond = Parser $ \s ->
   case s of
     "" -> Nothing
     (c:cs) -> if cond c then Just (c, cs) else Nothing

many :: Parser a -> Parser [a]
many p = Parser $ \s ->
  case parse p s of
    Nothing -> Just ([], s)
    Just (c, cs) -> let Just (cc, cs') = parse (many p) cs
                     in Just (c:cc, cs')

string :: String -> Parser String
string str = Parser $ \s -> if isPrefixOf str s
                               then Just (str, drop (length str) s)
                               else Nothing

instance Functor Parser where
  fmap f (Parser g) = Parser $ \s ->
    case g s of
      Nothing -> Nothing
      Just (r, remain) -> Just (f r, remain)

instance Applicative Parser where
  pure a = Parser $ \s -> Just (a, s)
  -- (<*>) :: f (a -> b) -> f a -> f b
  (Parser f) <*> (Parser g) = Parser $ \s ->
    case f s of
      Nothing -> Nothing
      Just (ab, remain) -> case g remain of
                            Nothing -> Nothing
                            Just (r, remain1) -> Just (ab r, remain1)

instance Semigroup a => Semigroup (Parser a) where
  (Parser p1) <> (Parser p2) = Parser $ \s ->
    case p1 s of
      Nothing -> Nothing
      Just (r1, s1) -> case p2 s1 of
                         Nothing -> Nothing
                         Just (r2, s2) -> Just (r1 <> r2, s2)

instance (Monoid a, Semigroup (Parser a))=> Monoid (Parser a) where
  mempty = Parser $ \s -> Just (mempty, s)
  mappend = (<>)

a = satisfy isAlpha
b = many (satisfy isDigit)

λ> parse a "k345"
Just ('k',"345")
λ> parse b "12345 abc"
Just ("12345"," abc")
λ> parse (a *> b) "k1234 7"
Just ("1234"," 7")
λ> parse (string "k" <> b) "k1234 7"
Just ("k1234"," 7")

So maybe you should find some tutorials and try to be familiar with Functor, Applicative, and Monad. See, you can implement the instance of a Monoid for your Parser type, and then you can use (<>) to combine your parsed results together.


问:
How to merge two different url for parsing using jquery
i want to try make parse with two different url but I my code not works:
I have tried two different examples:</p>

```<code>   var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1.address.village);
    alert(data2.address.city);

    //do stuff with 'data' and 'data2'
});

$.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data) {
    $.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data2) {
        var concatenatedJson = $.extend({}, data, data2);

        alert(concatenatedJson.address.road);

    });
});
</code>```

答:
```<code>var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

var data = {};

$.getJSON(url, function(result){
  data.data1 = result;
});

$.getJSON(url2, function(result){
  data.data2 = result;
});

console.log(data); // will return the two urls json code
</code>```

You can try the code on jsfiddle (https://jsfiddle.net/qtcvux31/)

Body:
i want to try make parse with two different url but I my code not works:
I have tried two different examples:

   var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1.address.village);
    alert(data2.address.city);

    //do stuff with 'data' and 'data2'
});

$.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data) {
    $.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data2) {
        var concatenatedJson = $.extend({}, data, data2);

        alert(concatenatedJson.address.road);

    });
});

Body:
var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

var data = {};

$.getJSON(url, function(result){
  data.data1 = result;
});

$.getJSON(url2, function(result){
  data.data2 = result;
});

console.log(data); // will return the two urls json code

You can try the code on jsfiddle (https://jsfiddle.net/qtcvux31/)


问:
Generic interface problem
So here is my problem:

I have the interface:

```<code>public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}
</code>```

And wanted to implement ISubstratum interface in this way:

```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

答:
Basically you've got to have an extra constraint on T:

```<code>where T : struct, IComparable<ICell<T>>
</code>```

then it should work fine. That's required to satisfy the same constraint on Feature in ICell<Feature>.

I would also suggest you rename the type parameter Feature to TFeature to make it more obviously a type parameter.

ContentLicense: CC BY-SA 3.0

Title: Generic interface problem

Body:
So here is my problem:

I have the interface:

public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}

And wanted to implement ISubstratum interface in this way:

public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

Body:
Basically you've got to have an extra constraint on T:

where T : struct, IComparable<ICell<T>>

then it should work fine. That's required to satisfy the same constraint on Feature in ICell<Feature>.

I would also suggest you rename the type parameter Feature to TFeature to make it more obviously a type parameter.


问:
Java useDelimiter and nextLine
I am trying to create a program that separate a string input (windows pathway) by using the delimiter. However my programme seems so ignore the delimiter.

The result I am expecting:

Skriv in sökvägen: C://Windows/System/

C

Windows

System
```

<p>The result I am getting:</p>

<pre class="lang-none prettyprint-override"><code>Skriv in sökvägen: C://Windows/System/

C://Windows/System/
</code>```

What am I missing in the below code?

```<code>import java.util.Scanner;

public class Sokvagen
{

   public static void main(String[] args)

   {

      //String representing pathway
      String sokvag;

      //Creating scanner object for reading from input stream
      Scanner userInput = new Scanner(System.in);

      // Set delimiter to ':' or '/' or whitespace
      userInput.useDelimiter("[:/\\s]+");

      // Instructions to the user to type a windows patway ex: C://Windows/System/
      System.out.print("Skriv in sökvägen: ");

      //Input
      sokvag = userInput.nextLine();

      //Print the result
      System.out.println(sokvag);

      userInput.close();
   }
}
</code>```

答:
userInput.nextLine() always returns the whole line in one piece, while userInput.next() returns a token using your delimiter. But then you need to read the input in a loop token by token until ...

```<code>import java.util.Arrays;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args) throws Exception
    {
        String sokvag;

        //Creating scanner object for reading from input stream
        Scanner userInput = new Scanner(System.in);

        // Set delimiter to ':' or '/' or whitespace
        userInput.useDelimiter("[:/\\s]+");

        // Instructions to the user to type a windows patway ex: C://Windows/System/
        System.out.print("Skriv in sökvägen: ");

        do
        {
            //Input
            sokvag = userInput.next();

            //Print the result
            System.out.println(sokvag);
        }
        while (????);

        userInput.close();
    }
}
</code>```

The problem is, you do not know when the user entered the last token (the last part of pathway).

So better keep reading the whole input as one line and then split it into parts. For example:

```<code>import java.util.Arrays;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args) throws Exception
    {
        String sokvag;

        //Creating scanner object for reading from input stream
        Scanner userInput = new Scanner(System.in);

        // Instructions to the user to type a windows patway ex: C://Windows/System/
        System.out.print("Skriv in sökvägen: ");

        //Input
        sokvag = userInput.nextLine();
        String[] parts = sokvag.split("[:/\\s]+");

        //Print the result
        System.out.println(Arrays.toString(parts));

        userInput.close();
    }
}
</code>```

Of course you can also iterate over the parts-array to output the content line by line.

Title: Java useDelimiter and nextLine

Body:
I am trying to create a program that separate a string input (windows pathway) by using the delimiter. However my programme seems so ignore the delimiter.

The result I am expecting:

Skriv in sökvägen: C://Windows/System/

C

Windows

System

The result I am getting:

Skriv in sökvägen: C://Windows/System/

C://Windows/System/

What am I missing in the below code?

import java.util.Scanner;

public class Sokvagen
{

   public static void main(String[] args)

   {

      //String representing pathway
      String sokvag;

      //Creating scanner object for reading from input stream
      Scanner userInput = new Scanner(System.in);

      // Set delimiter to ':' or '/' or whitespace
      userInput.useDelimiter("[:/\\s]+");

      // Instructions to the user to type a windows patway ex: C://Windows/System/
      System.out.print("Skriv in sökvägen: ");

      //Input
      sokvag = userInput.nextLine();

      //Print the result
      System.out.println(sokvag);

      userInput.close();
   }
}

Body:
userInput.nextLine() always returns the whole line in one piece, while userInput.next() returns a token using your delimiter. But then you need to read the input in a loop token by token until ...

import java.util.Arrays;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args) throws Exception
    {
        String sokvag;

        //Creating scanner object for reading from input stream
        Scanner userInput = new Scanner(System.in);

        // Set delimiter to ':' or '/' or whitespace
        userInput.useDelimiter("[:/\\s]+");

        // Instructions to the user to type a windows patway ex: C://Windows/System/
        System.out.print("Skriv in sökvägen: ");

        do
        {
            //Input
            sokvag = userInput.next();

            //Print the result
            System.out.println(sokvag);
        }
        while (????);

        userInput.close();
    }
}

The problem is, you do not know when the user entered the last token (the last part of pathway).

So better keep reading the whole input as one line and then split it into parts. For example:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args) throws Exception
    {
        String sokvag;

        //Creating scanner object for reading from input stream
        Scanner userInput = new Scanner(System.in);

        // Instructions to the user to type a windows patway ex: C://Windows/System/
        System.out.print("Skriv in sökvägen: ");

        //Input
        sokvag = userInput.nextLine();
        String[] parts = sokvag.split("[:/\\s]+");

        //Print the result
        System.out.println(Arrays.toString(parts));

        userInput.close();
    }
}

Of course you can also iterate over the parts-array to output the content line by line.


问:
EF Core FromSql with IN Clause
How to pass a dynamic list of int to FromSql method?
i tried the following code but it not works.

Conversion failed when converting the nvarchar value '1,2,3' to data type int.

```<code>var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({string.Join(",", listOfInt)})")
</code>```

答:
You can try this way</p>

```<code>var Ids = string.Join(',', listOfInt.Select(n => n.ToString()).ToArray());

var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({Ids})")
</code>```

Title: EF Core FromSql with IN Clause

Body:
How to pass a dynamic list of int to FromSql method?
i tried the following code but it not works.

Conversion failed when converting the nvarchar value '1,2,3' to data type int.

var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({string.Join(",", listOfInt)})")

Body:
You can try this way

var Ids = string.Join(',', listOfInt.Select(n => n.ToString()).ToArray());

var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({Ids})")


问:
Capturing stdout to zip and interrupting using CTRL-C gives a corrupted zip file
I am developing a C++ program that can run all day. It outputs to stdout and I want to compress this output. The uncompressed output can be many GB. A startup Bourne shell script compiles the C++ code and starts up the program like so:

./prog | gzip > output.gz

When I interrupt the script using CTRL-C, the .gz file is always corrupted.
When I start the program from a terminal and interrupt it using CTRL-C, the .gz file is also always corrupted.
When I start the program a terminal and terminate it using Linux killall, the .gz file is fine.

On the other hand, on a terminal cat <large_file> | gzip > cat.gz can be interrupted using CTRL-C and cat.gz is always fine. So I suspect cat has a signal handler of some sort that I have to implement as well in my program in C++... but looking at a cat implementation online, I found nothing like it. Never the less, I implemented this:

```<code>void SignalHandler(int aSignum)
{
  exit(0);
}

void Signals()
{
  signal(SIGINT,  SignalHandler);
  signal(SIGKILL, SignalHandler);
  signal(SIGTERM, SignalHandler);
}
</code>```

...and even something in the bsh script, but nothing helps. After CTRL-C, the gz file is corrupted.

Questions:

What does cat have what my program does not?

How can I terminate my script/program using CTRL-C with the zip file in order?

Edit 1

Opening the resulting file using zcat gives some output, but then:
gzip: file.gz: unexpected end of file. Opening it in Ubuntu's Archive Manager just gives a popup saying An error occurred while extracting files.

Edit 2

Tried flushing; no change in the problem was observed.

Edit 3

More info about the issue: Missing end (EOCDR) signature

```<code>Fix archive (-F) - assume mostly intact archive
    zip warning: bad archive - missing end signature
    zip warning: (If downloaded, was binary mode used?  If not, the
    zip warning:  archive may be scrambled and not recoverable)
    zip warning: Can't use -F to fix (try -FF)

zip error: Zip file structure invalid (file.gz)
maot@HP-Pavilion-dv7:~/temp$ zip -FF file.gz --out file2.gz
Fix archive (-FF) - salvage what can
    zip warning: Missing end (EOCDR) signature - either this archive
                     is not readable or the end is damaged
Is this a single-disk archive?  (y/n): y
  Assuming single-disk archive
Scanning for entries...
    zip warning: zip file empty
maot@HP-Pavilion-dv7:~/temp$ ls -lh file2.gz
-rw------- 1 maot maot 22 feb 15 15:18 file2.gz
maot@HP-Pavilion-dv7:~/temp$
</code>```

Edit 4

Thanks @Maxim Egorushkin, but it does not work. The interruption of the script by CTRL-C kills prog before the signal handler of the script is executed. Hence, I can not send it a signal, it's already gone... and without output of SignalHandler. When prog is started from the command line, the output of SignalHandler is observed. Prog:

```<code>#include <iostream>
#include <unistd.h>
#include <csignal>

void SignalHandler(int aSignum)
{
  std::cout << "prog: Interrupt signal " << aSignum << " received.\n";
  fflush(nullptr);
  exit(0);
}

int main()
{
  for (int sig = 1; sig <=31; sig++)
  {
    std::cout << " sig " << sig;
    signal(sig,  SignalHandler);
  }

  while (true)
  {
    std::cout << "prog: Sleep ";
    fflush(nullptr);
    usleep(1e4);
  }
}
</code>```

Script:

```<code>#!/bin/sh

onerror()
{
  echo "onerror(): Started."
  ps -jef | grep prog
  killall -s SIGINT prog
  exit
}

g++ -Wall prog.cpp -o prog

trap onerror 2

prog | gzip > file.gz
</code>```

Result:

```<code>maot@HP-Pavilion-dv7:~/temp$ test.sh
^Conerror(): Started.
maot     16733 16721 16721  5781  0 16:17 pts/1    00:00:00 grep prog
prog: no process found
maot@HP-Pavilion-dv7:~/temp$
</code>```

Edit 5 minimal working solution

Implementation of the answer of Maxim Egorushkin. Script:

```<code>#!/bin/sh
g++ -Wall prog.cpp -o prog
prog | setsid gzip > file.gz & wait
</code>```

Prog:

```<code>#include <iostream>
#include <unistd.h>
#include <csignal>

void SignalHandler(int aSignum)
{
  std::cout << "prog: Interrupt signal " << aSignum << " received.\n";
  exit(0);
}

int main()
{
  signal(SIGINT,  SignalHandler);

  while (true)
  {
    std::cout << "prog: Sleep ";
    usleep(1e4);
  }
}
</code>```

答:
When you press Ctrl+C the shell sends SIGINT to the last process in the pipeline, which is gzip here. gzip terminates and the next time prog writes into stdout it receives SIGPIPE.

You need to send SIGINT to prog for it to flush its stdout and exit (provided you installed the signal handler as you did), so that gzip receives all of its output and then terminates.

You can run your pipeline as follows:

```<code>prog | setsid gzip > file.gz & wait
</code>```

It uses shell job control feature to start the pipeline in the background (that & symbol). Then it waits for the job to terminate. On Ctrl+C SIGINT is sent to the foreground process which is the shell in wait and all processes in the same terminal process group (unlike when the pipeline is in the foreground and SIGINT is sent only to the last process in the pipeline). prog is in that group. But gzip is started with setsid to place it into another group, so that it doesn't receive SIGINT but rather terminates when its stdin is closed when prog terminated.

Body:
I am developing a C++ program that can run all day. It outputs to stdout and I want to compress this output. The uncompressed output can be many GB. A startup Bourne shell script compiles the C++ code and starts up the program like so:

./prog | gzip > output.gz

When I interrupt the script using CTRL-C, the .gz file is always corrupted.
When I start the program from a terminal and interrupt it using CTRL-C, the .gz file is also always corrupted.
When I start the program a terminal and terminate it using Linux killall, the .gz file is fine.

On the other hand, on a terminal cat <large_file> | gzip > cat.gz can be interrupted using CTRL-C and cat.gz is always fine. So I suspect cat has a signal handler of some sort that I have to implement as well in my program in C++... but looking at a cat implementation online, I found nothing like it. Never the less, I implemented this:

void SignalHandler(int aSignum)
{
  exit(0);
}

void Signals()
{
  signal(SIGINT,  SignalHandler);
  signal(SIGKILL, SignalHandler);
  signal(SIGTERM, SignalHandler);
}

...and even something in the bsh script, but nothing helps. After CTRL-C, the gz file is corrupted.

Questions:

What does cat have what my program does not?

How can I terminate my script/program using CTRL-C with the zip file in order?

Edit 1

Opening the resulting file using zcat gives some output, but then:
gzip: file.gz: unexpected end of file. Opening it in Ubuntu's Archive Manager just gives a popup saying An error occurred while extracting files.

Edit 2

Tried flushing; no change in the problem was observed.

Edit 3

More info about the issue: Missing end (EOCDR) signature

Fix archive (-F) - assume mostly intact archive
    zip warning: bad archive - missing end signature
    zip warning: (If downloaded, was binary mode used?  If not, the
    zip warning:  archive may be scrambled and not recoverable)
    zip warning: Can't use -F to fix (try -FF)

zip error: Zip file structure invalid (file.gz)
maot@HP-Pavilion-dv7:~/temp$ zip -FF file.gz --out file2.gz
Fix archive (-FF) - salvage what can
    zip warning: Missing end (EOCDR) signature - either this archive
                     is not readable or the end is damaged
Is this a single-disk archive?  (y/n): y
  Assuming single-disk archive
Scanning for entries...
    zip warning: zip file empty
maot@HP-Pavilion-dv7:~/temp$ ls -lh file2.gz
-rw------- 1 maot maot 22 feb 15 15:18 file2.gz
maot@HP-Pavilion-dv7:~/temp$

Edit 4

Thanks @Maxim Egorushkin, but it does not work. The interruption of the script by CTRL-C kills prog before the signal handler of the script is executed. Hence, I can not send it a signal, it's already gone... and without output of SignalHandler. When prog is started from the command line, the output of SignalHandler is observed. Prog:

#include <iostream>
#include <unistd.h>
#include <csignal>

void SignalHandler(int aSignum)
{
  std::cout << "prog: Interrupt signal " << aSignum << " received.\n";
  fflush(nullptr);
  exit(0);
}

int main()
{
  for (int sig = 1; sig <=31; sig++)
  {
    std::cout << " sig " << sig;
    signal(sig,  SignalHandler);
  }

  while (true)
  {
    std::cout << "prog: Sleep ";
    fflush(nullptr);
    usleep(1e4);
  }
}

Script:

#!/bin/sh

onerror()
{
  echo "onerror(): Started."
  ps -jef | grep prog
  killall -s SIGINT prog
  exit
}

g++ -Wall prog.cpp -o prog

trap onerror 2

prog | gzip > file.gz

Result:

maot@HP-Pavilion-dv7:~/temp$ test.sh
^Conerror(): Started.
maot     16733 16721 16721  5781  0 16:17 pts/1    00:00:00 grep prog
prog: no process found
maot@HP-Pavilion-dv7:~/temp$

Edit 5 minimal working solution

Implementation of the answer of Maxim Egorushkin. Script:

#!/bin/sh
g++ -Wall prog.cpp -o prog
prog | setsid gzip > file.gz & wait

Prog:

#include <iostream>
#include <unistd.h>
#include <csignal>

void SignalHandler(int aSignum)
{
  std::cout << "prog: Interrupt signal " << aSignum << " received.\n";
  exit(0);
}

int main()
{
  signal(SIGINT,  SignalHandler);

  while (true)
  {
    std::cout << "prog: Sleep ";
    usleep(1e4);
  }
}

Body:
When you press Ctrl+C the shell sends SIGINT to the last process in the pipeline, which is gzip here. gzip terminates and the next time prog writes into stdout it receives SIGPIPE.

You need to send SIGINT to prog for it to flush its stdout and exit (provided you installed the signal handler as you did), so that gzip receives all of its output and then terminates.

You can run your pipeline as follows:

prog | setsid gzip > file.gz & wait

It uses shell job control feature to start the pipeline in the background (that & symbol). Then it waits for the job to terminate. On Ctrl+C SIGINT is sent to the foreground process which is the shell in wait and all processes in the same terminal process group (unlike when the pipeline is in the foreground and SIGINT is sent only to the last process in the pipeline). prog is in that group. But gzip is started with setsid to place it into another group, so that it doesn't receive SIGINT but rather terminates when its stdin is closed when prog terminated.


问:
Valgrind massif - inverse ignore?
Is there a parameter in valgrind massif that allows me to only track allocations made by certain functions and classes? I would like to make a run that only traces (de)allocations made by std::vector.

Regards

答:
Using the option --xtree-memory=full, you might be able to visualise the stacktraces that are interesting you.

See http://www.valgrind.org/docs/manual/manual-core.html#manual-core.xtree for more details.

Title: Valgrind massif - inverse ignore?


问:
The move sum operator with unique_ptr
It's a little complex for me to understand the mechanic of pointers management.

I try to reduce copy operations with a class members by this approuch:

```<code>#include <iostream>
#include <vector>

class Shape {

public:

    std::unique_ptr<int> x;

    Shape(const Shape& val) = delete; // will be delete by default by compiler?

    Shape& operator=(const Shape& val) = delete; // will be delete by default by compiler?

    Shape(Shape&& val) noexcept {
        this->x = std::move(val.x);
    }

    Shape& operator=(Shape&& val) noexcept {
        std::cout << "Move operator=" << std::endl;
        this->x = std::move(val.x);
        return *this;
    }

    Shape() : x(std::unique_ptr<int>(new int)) {
        std::cout << "Constructor Shape" << std::endl;
    }

    Shape(int v) : x(std::unique_ptr<int>(new int(v))) {
        std::cout << "Constructor Shape (by value)" << std::endl;
    }

    virtual ~Shape() {
        std::cout << "Destructor Shape" << std::endl;
    };

    Shape operator+(const Shape& val) {

        std::cout << "Move sum" << std::endl;
        Shape res(*x + *val.x);
        return res;
    }
};

int main()
{

    Shape a(1);
    Shape b(3);

    Shape res = a + b;

    std::cout << "Value a is (" << *(a.x) << ")" << std::endl;
    std::cout << "Value b is (" << *(b.x) << ")" << std::endl;
    std::cout << "Value res is (" << *(res.x) << ")" << std::endl;

};
</code>```

The result is:

Constructor Shape (by value)
Constructor Shape (by value)
Move sum
Constructor Shape (by value)
Destructor Shape
Value a is (1)
Value b is (3)
Value res is (4)
Destructor Shape
Destructor Shape
Destructor Shape

Is it the good idea to mark copy constructor and copy operator= as "deleted" or I can remove those lines?
How expensive std::move operator is by himself?

答:
Is it the good idea to mark copy constructor and copy operator= as "deleted" or I can remove those lines?

You can remove your deletes of the copy constructor and copy operator lines:

https://en.cppreference.com/w/cpp/language/copy_constructor in Deleted implicitly-declared copy constructor

The implicitly-declared or defaulted copy constructor for class T is defined as deleted if any of the following conditions are true:

...

T has a user-defined move constructor or move assignment operator (this condition only causes the implicitly-declared, not the defaulted, copy constructor to be deleted).

How expensive std::move operator is by himself?

std::move is used to cast a value to an xvalue (eXpiring value). It has no cost (it is cast at compile time) and the implications are that once you've called std::move on an object, you shouldn't use it after. For example, in your code, a+b gets implicitly cast to an xvalue

You can find more info on xvalues here: https://en.cppreference.com/w/cpp/language/value_category

Title: The move sum operator with unique_ptr

Body:
It's a little complex for me to understand the mechanic of pointers management.

I try to reduce copy operations with a class members by this approuch:

#include <iostream>
#include <vector>

class Shape {

public:

    std::unique_ptr<int> x;

    Shape(const Shape& val) = delete; // will be delete by default by compiler?

    Shape& operator=(const Shape& val) = delete; // will be delete by default by compiler?

    Shape(Shape&& val) noexcept {
        this->x = std::move(val.x);
    }

    Shape& operator=(Shape&& val) noexcept {
        std::cout << "Move operator=" << std::endl;
        this->x = std::move(val.x);
        return *this;
    }

    Shape() : x(std::unique_ptr<int>(new int)) {
        std::cout << "Constructor Shape" << std::endl;
    }

    Shape(int v) : x(std::unique_ptr<int>(new int(v))) {
        std::cout << "Constructor Shape (by value)" << std::endl;
    }

    virtual ~Shape() {
        std::cout << "Destructor Shape" << std::endl;
    };

    Shape operator+(const Shape& val) {

        std::cout << "Move sum" << std::endl;
        Shape res(*x + *val.x);
        return res;
    }
};

int main()
{

    Shape a(1);
    Shape b(3);

    Shape res = a + b;

    std::cout << "Value a is (" << *(a.x) << ")" << std::endl;
    std::cout << "Value b is (" << *(b.x) << ")" << std::endl;
    std::cout << "Value res is (" << *(res.x) << ")" << std::endl;

};

The result is:

Constructor Shape (by value)
Constructor Shape (by value)
Move sum
Constructor Shape (by value)
Destructor Shape
Value a is (1)
Value b is (3)
Value res is (4)
Destructor Shape
Destructor Shape
Destructor Shape

Is it the good idea to mark copy constructor and copy operator= as "deleted" or I can remove those lines?
How expensive std::move operator is by himself?


问:
Pass string class variable by reference in C++
Look at the following code:

```<code>#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}
</code>```

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

答:
You have to pass by reference because that's how the language is designed.

Your theory that "strings are arrays" is incorrect. Strings are strings.

It is true that, for historical reasons, passing C arrays by value actually appears to pass them by reference (in reality the array's name is decaying to a pointer). But that's not what you have here, and it's not how the rest of the language works.

If you pass by value, usually, you get a copy. So your function operates on a copy. Passing a reference means you operate on the original object, instead.

Body:
Look at the following code:

#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?


答:
Is it because your T in ISubstratum<K,T> is only limited to struct, whereas the T in ICell<T> is required to also be IComparable<ICell<T>> ? If you add that additiion where, does it work?

```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct, IComparable<ICell<T>>
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

?

Title: Generic interface problem

Body:
Is it because your T in ISubstratum<K,T> is only limited to struct, whereas the T in ICell<T> is required to also be IComparable<ICell<T>> ? If you add that additiion where, does it work?

public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct, IComparable<ICell<T>>
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

?


问:
Adding space/padding to a UILabel
I have a UILabel where I want to add space in the top and in the bottom. With the minimum height in constraints, I've modified it to:

To do this I've used:

```<code>override func drawTextInRect(rect: CGRect) {
    var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
</code>```

But I've to find a different method because if I write more than two lines, the problem is the same:

答:
If you're looking for just left and right padding, you can simply add empty spaces before and after the text:

```<code>titleLabel.text = " \(categoryName) "
</code>```

Title: Adding space/padding to a UILabel

Body:
I have a UILabel where I want to add space in the top and in the bottom. With the minimum height in constraints, I've modified it to:

To do this I've used:

override func drawTextInRect(rect: CGRect) {
    var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}

But I've to find a different method because if I write more than two lines, the problem is the same:

Body:
If you're looking for just left and right padding, you can simply add empty spaces before and after the text:

titleLabel.text = " \(categoryName) "


问:
How to download 300k log lines from my application?
I am running a job on my Heroku app that generates about 300k lines of log within 5 minutes. I need to extract all of them into a file. How can I do this?

The Heroku UI only shows logs in real time, since the moment it was opened, and only keeps 10k lines.

I attached a LogDNA Add-on as a drain, but their export also only allows 10k lines export. To even have the option of export, I need to apply a search filter (I typed 2020 because all the lines start with a date, but still...). I can scroll through all the logs to see them, but as I scroll up the bottom gets truncated, so I can't even copy-paste them myself.

I then attached Sumo Logic as a drain, which is better, because the export limit is 100k. However I still need to filter the logs in 30s to 60s intervals and download separately. Also it exports to CSV file and in reverse order (newest first, not what I want) so I have to still work on the file after its downloaded.

Is there no option to get actual raw log files in full?

答:
Is there no option to get actual raw log files in full?

There are no actual raw log files.

Heroku's architecture requires that logging be distributed. By default, its Logplex service aggregates log output from all services into a single stream and makes it available via heroku logs. However,

Logplex is designed for collating and routing log messages, not for storage. It retains the most recent 1,500 lines of your consolidated logs, which expire after 1 week.

For longer persistence you need something else. In addition to commercial logging services like those you mentioned, you have several options:

Log to a database instead of files. Something like Apache Cassandra might be a good fit.

Send your logs to a logging server via Syslog (my preference):

Syslog drains allow you to forward your Heroku logs to an external Syslog server for long-term archiving.

Send your logs to a custom logging process via HTTPS.

Log drains also support messaging via HTTPS. This makes it easy to write your own log-processing logic and run it on a web service (such as another Heroku app).


问:
Forever Crashes and Doesn't Restart after 4 times
I have a node server running on AWS and I am using forever to keep it running in the background.

I have been very happy with forever so far; it's super easy to set up and use. However, even though my app is very simple, sometimes it crashes with this error:

Express server listening on port 3001

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)
error: Forever detected script exited with code: 8
error: Forever restarting script for 4 time
```

<p>When I look back at the logs, I can see that this has happened 4 more times, and each time forever manages to restart the server. However, when it happens for the 5th time, for some reason forever fails to restart the server and my app becomes unresponsive.</p>

<pre class="lang-none prettyprint-override"><code>Express server listening on port 3001

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)
error: Forever detected script exited with code: 8

/usr/lib/node_modules/forever/node_modules/forever-monitor/node_modules/broadway/node_modules/eventemitter2/lib/ev$
          throw arguments[1]; // Unhandled 'error' event
                         ^
Error: Cannot stop process that is not running.
    at /usr/lib/node_modules/forever/node_modules/forever-monitor/lib/forever-monitor/monitor.js:332:26
    at process._tickCallback (node.js:415:13)
</code>```

Has anyone else experienced similar problems?

答:
You have to use the option -MAX like this:

```<code>forever -MAX 10000000000 Mypath/ToMyFile.js
</code>```

Also put a -minUptime for the minimum time the server can stay up, if it crash before that laps of time then it won't go up again so set it to 1.

```<code>forever --minUptime (number-in-milisecond-here) -MAX (number-of-restart-here) path/file.js
</code>```

Just try this:

```<code>forever --minUptime 1 -MAX 1000000000 YourPath/ToYourFile.js
</code>```

More documentation there
https://www.npmjs.com/package/forever

Body:
I have a node server running on AWS and I am using forever to keep it running in the background.

I have been very happy with forever so far; it's super easy to set up and use. However, even though my app is very simple, sometimes it crashes with this error:

Express server listening on port 3001

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)
error: Forever detected script exited with code: 8
error: Forever restarting script for 4 time

When I look back at the logs, I can see that this has happened 4 more times, and each time forever manages to restart the server. However, when it happens for the 5th time, for some reason forever fails to restart the server and my app becomes unresponsive.

Express server listening on port 3001

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)
error: Forever detected script exited with code: 8

/usr/lib/node_modules/forever/node_modules/forever-monitor/node_modules/broadway/node_modules/eventemitter2/lib/ev$
          throw arguments[1]; // Unhandled 'error' event
                         ^
Error: Cannot stop process that is not running.
    at /usr/lib/node_modules/forever/node_modules/forever-monitor/lib/forever-monitor/monitor.js:332:26
    at process._tickCallback (node.js:415:13)

Has anyone else experienced similar problems?

Body:
You have to use the option -MAX like this:

forever -MAX 10000000000 Mypath/ToMyFile.js

Also put a -minUptime for the minimum time the server can stay up, if it crash before that laps of time then it won't go up again so set it to 1.

forever --minUptime (number-in-milisecond-here) -MAX (number-of-restart-here) path/file.js

Just try this:

forever --minUptime 1 -MAX 1000000000 YourPath/ToYourFile.js

More documentation there
https://www.npmjs.com/package/forever


问:
Cannot build cocos2d-x 4.0 cpp-test
Im just starting with cocos2d-x. I start by following the guide here. https://docs.cocos2d-x.org/cocos2d-x/v4/en/installation/Windows.html

Regarding prerequisites:

Windows 7+ - have windows 10

VS 2017+ - have visual studio 2019

CMake 3.1+ - installed latest

Python 2.7.5+, Python 2.7.10 reccomended , NOT Python 3+ - installed Python 2.7.10

Downloaded Cocos2dx v4 from github repo.

I run this command

```<code>python setup.py
</code>```

https://i.imgur.com/td7Yo8c.png

Then i run this command

```<code>cd COCOS2DX/tests/cpp-tests
mkdir win32-build
cd win32-build
cmake ..
</code>```

Then I rebuild the generated solution and get this error.
https://i.imgur.com/bZ8QUZF.png

Please advise.

Thanks.

答: use cmake .. -G"Visual Studio 16 2019" -Tv142 -A Win32 </p>

Title: Cannot build cocos2d-x 4.0 cpp-test

Body:
Im just starting with cocos2d-x. I start by following the guide here. https://docs.cocos2d-x.org/cocos2d-x/v4/en/installation/Windows.html

Regarding prerequisites:

Windows 7+ - have windows 10

VS 2017+ - have visual studio 2019

CMake 3.1+ - installed latest

Python 2.7.5+, Python 2.7.10 reccomended , NOT Python 3+ - installed Python 2.7.10

Downloaded Cocos2dx v4 from github repo.

I run this command

python setup.py

https://i.imgur.com/td7Yo8c.png

Then i run this command

cd COCOS2DX/tests/cpp-tests
mkdir win32-build
cd win32-build
cmake ..

Then I rebuild the generated solution and get this error.
https://i.imgur.com/bZ8QUZF.png

Please advise.

Thanks.


问:
Which design pattern to use for a 2D iPhone game?
To give a little background about the game: falling items float from the top, and the objective is to flick/slide another object to hit them. If an item hits the ground, you lose a life, and gain points for hitting falling items.

Here is where I'm a little confused. In O'Reilly's iPhone game development. They state have the AppDelegate inherit a game state machine object, and have the main game loop in the App Delegate. Nothing about MVC.

I was going to use MVC. I have all the objects identified for the models, and was going to use one controller to update each model and their corresponding view. Then have a navigation controller in the App Delegate, and push certain controllers (Play, instructions, stats) from the home screen. Then have the game loop run in my gameViewController. I am using Chipmunk as a physics engine by the way.

This is my first game so I'm little confused. I would greatly appreciate any advice on how to proceed. I would like to get the object orientated design right from the start before jumping into code.

答:
My MVC goes something as follows.  Each Game Object that is create is just a single Model.  Empty data with no logic attached.  When the object is created it also gets a Brain or controller attached to it.  Each created Brain is added to the Brain list.  The Brain List updates each brain and the brains change the Model.

To show something on screen the Brain adds the Model to the Scene.  The scene keeps a list of all the models it is rendering.  The Scene is also Updated from the Game Loop.  Each update the Scene looks at each Model, any model without a View, is given a view (a new view is created based on data in the model).  The Scene then tracks the view until the Model's data says it no longer needs it.

When I have been working on the iPhone I like to break the game loop out onto its own thread.  Those folks over at O'Reilly are pretty smart though so take what I've got to say with a grain of salt.

```<code>[NSThread detachNewThreadSelector:@selector(GameLoop:) toTarget:self withObject:nil];
</code>```

Then the game loop itself is updating first the Brains (or "Controller List"), then the Scene (or "view list").

The final piece that ties it all together is the input.  For iPhone I use a full screen View.  In the touchesBegan and touchesEnd of the view I generate Events which I pass off to the InputManager.  The InputManager will send events to different models as needed.

Body:
My MVC goes something as follows.  Each Game Object that is create is just a single Model.  Empty data with no logic attached.  When the object is created it also gets a Brain or controller attached to it.  Each created Brain is added to the Brain list.  The Brain List updates each brain and the brains change the Model.

To show something on screen the Brain adds the Model to the Scene.  The scene keeps a list of all the models it is rendering.  The Scene is also Updated from the Game Loop.  Each update the Scene looks at each Model, any model without a View, is given a view (a new view is created based on data in the model).  The Scene then tracks the view until the Model's data says it no longer needs it.

When I have been working on the iPhone I like to break the game loop out onto its own thread.  Those folks over at O'Reilly are pretty smart though so take what I've got to say with a grain of salt.

[NSThread detachNewThreadSelector:@selector(GameLoop:) toTarget:self withObject:nil];

Then the game loop itself is updating first the Brains (or "Controller List"), then the Scene (or "view list").

The final piece that ties it all together is the input.  For iPhone I use a full screen View.  In the touchesBegan and touchesEnd of the view I generate Events which I pass off to the InputManager.  The InputManager will send events to different models as needed.


问:
Finding all unique values including NAs in a dataframe column in R
Importing a .csv file into R using read.csv (with stringsAsFactors = FALSE)

One field is numeric (integers between 0 and 10) but has quite a lot of blanks in it.

read.csv gives me a data frame with this field as an int column, but with blanks tagged as NA. That's ok. But...I wanted a quick line of code to show me the unique values appearing in this field (including NA) so I used:

```<code>levels(as.factor(dataframe$fieldname))
</code>```

but it doesn't include the NA entries in there, just the 1-10.

Is there another way to do this, so that I don't miss the NA entries?

答:
You can use</p>

```<code>unique(dataframe$fieldname)
</code>```

Body:
Importing a .csv file into R using read.csv (with stringsAsFactors = FALSE)

One field is numeric (integers between 0 and 10) but has quite a lot of blanks in it.

read.csv gives me a data frame with this field as an int column, but with blanks tagged as NA. That's ok. But...I wanted a quick line of code to show me the unique values appearing in this field (including NA) so I used:

levels(as.factor(dataframe$fieldname))

but it doesn't include the NA entries in there, just the 1-10.

Is there another way to do this, so that I don't miss the NA entries?

Body:
You can use

unique(dataframe$fieldname)


问:
access var outside function scope
I havethe following code and I'm trying to access selectedBrand var outside so to use it elsewhere in may code

```<code>var selectedBrand;
var brand_sel = d3.select('select')
    .on("change",function(b) {
        selectedBrand = d3.select("#brand").node().value;
    });

  console.log(selectedBrand)
</code>```

when I try to consollog selectedBrand I get undefined results.

I try almost everything I understand without success

many thanks for any help

答:
You are trying to log it's value immediately but it will remain undefined until after your change handler has been executed:

Does below help illustrate?

```<code>var selectedBrand;
var brand_sel = d3.select('select')
   .on("change",function(b){
      selectedBrand = d3.select("#brand").node().value;
      run();
   })

var run = function() { console.log(selectedBranch); } // <- this runs after you've defined the value because you've called `run()` in your change handler
console.log(selectedBrand); // <- this runs first, while the value is undefined
</code>```

This feels like the age old How do I return the response from an asynchronous call?

Title: access var outside function scope

Body:
I havethe following code and I'm trying to access selectedBrand var outside so to use it elsewhere in may code

var selectedBrand;
var brand_sel = d3.select('select')
    .on("change",function(b) {
        selectedBrand = d3.select("#brand").node().value;
    });

  console.log(selectedBrand)

when I try to consollog selectedBrand I get undefined results.

I try almost everything I understand without success

many thanks for any help

Body:
You are trying to log it's value immediately but it will remain undefined until after your change handler has been executed:

Does below help illustrate?

var selectedBrand;
var brand_sel = d3.select('select')
   .on("change",function(b){
      selectedBrand = d3.select("#brand").node().value;
      run();
   })

var run = function() { console.log(selectedBranch); } // <- this runs after you've defined the value because you've called `run()` in your change handler
console.log(selectedBrand); // <- this runs first, while the value is undefined

This feels like the age old How do I return the response from an asynchronous call?


问:
How to search for specific text from a website, retrieve and use it with google app engine (python)?
I'm trying to retrieve basically this block of text from www.crossfit.com.

Monday 110516

Complete as many rounds as possible in five minutes of:

275 pound Deadlift, 3 reps

115 pound Push press, 7 reps

It's basically just the date (Monday yymmdd), and a short description of a workout. The site updates daily with a new workout. I want to write a google app using the python version that will pull the daily workout automatically. Where should I start? I followed along google's helloworld example and that's about as much as I know about html, python, and google apps.

答:
Instead of parsing the HTML yourself, use the already provided XML feed: http://www.crossfit.com/index.xml.

You can parse the XML feed in python 2.5 with xml.etree.ElementTree.


问:
How to find sum of node's value for given depth in binary tree?
I've been scratching my head for several hours for this...

problem:

```<code>Binary Tree

   (0)      depth 0
   / \
  10   20   depth 1
 / \   / \
30 40  50 60  depth 2
</code>```

I am trying to write a function that takes depth as argument and return the sum of values of nodes of the given depth.

For instance, if I pass 2, it should return 180 (i.e. 30+40+50+60)

I decided to use breadth first search and when I find the node with desired depth,
sum up the value, but I just can't figure out how to find out the way which node is in what depth.
But with this approach I feel like going to totally wrong direction.

```<code>function level_order($root, $targetDepth) {
$q = new Queue();
$q->enqueue($root);

while(!$q->isEmpty) {
    //how to determin the depth of the node???
    $node = $q->dequeue();

    if($currentDepth == $targetDepth) {
        $sum = $node->value;
    }

    if($node->left != null) {
        $q->enqueue($node->left);
    }
    if($node->right != null) {
        $q->enqueue($node->right);
    }
    //need to reset this somehow
    $currentDepth ++;
}
</code>```

}

答:
```<code>int sumOnSelectedLevel(BNode node, int k){
            if(k==0) return node.data;
            int left = node.left == null? 0: sumOnSelectedLevel(node.left, k-1);
            int right = node.right == null? 0: sumOnSelectedLevel(node.right, k-1);
            return left+right;
        }
</code>```

also handles NullPionterException.

Body:
I've been scratching my head for several hours for this...

problem:

Binary Tree

   (0)      depth 0
   / \
  10   20   depth 1
 / \   / \
30 40  50 60  depth 2

I am trying to write a function that takes depth as argument and return the sum of values of nodes of the given depth.

For instance, if I pass 2, it should return 180 (i.e. 30+40+50+60)

I decided to use breadth first search and when I find the node with desired depth,
sum up the value, but I just can't figure out how to find out the way which node is in what depth.
But with this approach I feel like going to totally wrong direction.

function level_order($root, $targetDepth) {
$q = new Queue();
$q->enqueue($root);

while(!$q->isEmpty) {
    //how to determin the depth of the node???
    $node = $q->dequeue();

    if($currentDepth == $targetDepth) {
        $sum = $node->value;
    }

    if($node->left != null) {
        $q->enqueue($node->left);
    }
    if($node->right != null) {
        $q->enqueue($node->right);
    }
    //need to reset this somehow
    $currentDepth ++;
}

}

Body:
int sumOnSelectedLevel(BNode node, int k){
            if(k==0) return node.data;
            int left = node.left == null? 0: sumOnSelectedLevel(node.left, k-1);
            int right = node.right == null? 0: sumOnSelectedLevel(node.right, k-1);
            return left+right;
        }

also handles NullPionterException.


问:
How to merge two different url for parsing using jquery
i want to try make parse with two different url but I my code not works:
I have tried two different examples:</p>

```<code>   var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1.address.village);
    alert(data2.address.city);

    //do stuff with 'data' and 'data2'
});

$.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data) {
    $.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data2) {
        var concatenatedJson = $.extend({}, data, data2);

        alert(concatenatedJson.address.road);

    });
});
</code>```

答:
the only wrong you're doing is assuming the data you are receiving

a simple console.log(data1) would be suffice to tell you that the data received in data1 is not the data from the URL, but an array with a bit more information

all you need is to point to the correct Array and all will be working as you wanted:

var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1[0].address.village);
    alert(data2[0].address.city);

    //do stuff with 'data' and 'data2'
});
```

Body:
i want to try make parse with two different url but I my code not works:
I have tried two different examples:

   var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1.address.village);
    alert(data2.address.city);

    //do stuff with 'data' and 'data2'
});

$.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data) {
    $.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data2) {
        var concatenatedJson = $.extend({}, data, data2);

        alert(concatenatedJson.address.road);

    });
});


问:
How to get the corresponding time of a byte from WAV file?
I'm sorry that it's kind of hard to put this concept into the question title, maybe somebody could help, thanks!

I was able to get the "byte-wised" waveform watching this video.

Turned the whole WAV file into a byte array, now my question is:

How could I get the corresponding time from the certain index of the byte array!?

For example, b[3520] corresponding to 0.013s!?

I had thought about maybe I could divide the total timespan of the WAV file by the total length of the bit array, then I would know how much time each byte occupy.

But I was sketchy about the accuracy, is there any more accurate way to do such a thing!?

Much appreciated.

答:
I would try using WaveFormat.BitsPerSample and WaveFormat.SampleRate.

eg. BitsPerSample = 32 => 4bytes WaveFormat.SampleRate = 44100 => 4*44100bytes/sec
I don't know if this way will be more accurate.


问:
Mysql Query structure for searching two tables
I have two tables sturctured like so:

```<code>Posts Table
id
content

Meta Table
id
post_id
content
name
</code>```

The posts table is the main parent that can have data from the meta table joined with it

```<code>Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading
</code>```

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
</code>```

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')
</code>```

Any help would be greatly appreciated, Thanks!

答:
You need to join to the meta table twice (once for each search) - like this:</p>

```<code>Select *
from posts p
 join meta m_date on m_date.post_id = p.id AND m_date.name='date'
 join meta m_heading on m_heading.post_id = p.id AND m_heading.name='heading'
where
 m_date.content = '2011-5-5' and
 m_heading.content = 'My Heading'
</code>```

Body:
I have two tables sturctured like so:

Posts Table
id
content

Meta Table
id
post_id
content
name

The posts table is the main parent that can have data from the meta table joined with it

Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')

Any help would be greatly appreciated, Thanks!

Body:
You need to join to the meta table twice (once for each search) - like this:

Select *
from posts p
 join meta m_date on m_date.post_id = p.id AND m_date.name='date'
 join meta m_heading on m_heading.post_id = p.id AND m_heading.name='heading'
where
 m_date.content = '2011-5-5' and
 m_heading.content = 'My Heading'


问:
Info.plist: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 0.)
I am getting this error during debugging the build.

unable to read property list from file:

/Users/..TestApp/FastApp/ios/FastApp/Info.plist: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 0.)

答: You can navigate in the Terminal to the file and execute plutil ./Info.plist which should show you where the issue is. Then fix in a text editor


问:
Force hibernate to leave id empty
So I am using Postgres and Hibernate 4.2.2 and with entity like this

```<code>@Entity(name = "Users")
@Check(constraints = "email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$'")
@DynamicInsert
public class Users {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id_user",unique = true)
  @Index(name = "user_pk")
  private Integer idUser;
</code>```

Hibernate still inserts some id that is already in the table, instead of leaving it emtpy for the database to fill it in. Also hibernate forces ids based on its cache not even checking the database whether it has the lates id.

How can I force it so I can leave id blank and let the database insert it?

First I thought it was because I was using int and that int is by default 0 but even when using object it just forces the id there from its cache.

So my goal is to let the database fill the ids instead of hibernate or at least Hibernate before filling it in to check the database for id first.

答:
Seeding the data is the problem. However you can still seed with pure sequal and have the sequence "keep up".

1) Assure your primary key is of type SERIAL.

```<code>CREATE TABLE table_name(
    id SERIAL
);
</code>```

2) Add this 'setval' line to assure the sequence is updated.

```<code>select setval('table_name_id_seq',COALESCE((select max(id) + 1 from table_name), 1));
</code>```

Reference:

https://www.postgresqltutorial.com/postgresql-serial/

Title: Force hibernate to leave id empty

Body:
So I am using Postgres and Hibernate 4.2.2 and with entity like this

@Entity(name = "Users")
@Check(constraints = "email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$'")
@DynamicInsert
public class Users {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id_user",unique = true)
  @Index(name = "user_pk")
  private Integer idUser;

Hibernate still inserts some id that is already in the table, instead of leaving it emtpy for the database to fill it in. Also hibernate forces ids based on its cache not even checking the database whether it has the lates id.

How can I force it so I can leave id blank and let the database insert it?

First I thought it was because I was using int and that int is by default 0 but even when using object it just forces the id there from its cache.

So my goal is to let the database fill the ids instead of hibernate or at least Hibernate before filling it in to check the database for id first.

Body:
Seeding the data is the problem. However you can still seed with pure sequal and have the sequence "keep up".

1) Assure your primary key is of type SERIAL.

CREATE TABLE table_name(
    id SERIAL
);

2) Add this 'setval' line to assure the sequence is updated.

select setval('table_name_id_seq',COALESCE((select max(id) + 1 from table_name), 1));

Reference:

https://www.postgresqltutorial.com/postgresql-serial/


问:
Should EndReceive ever return zero if the socket is still connected?
I'm making the following BeginReceive call on a socket:

```<code>m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);
</code>```

in my classes ReceiveCallback function I call

```<code>try {
    int bytesReadFromSocket = m_socket.EndReceive(ar);
    if(bytesReadFromSocket > 0) {
         // Do some processing
    }
}
finally {
   if(m_socket.Connected) m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);
}
</code>```

The issue I'm having is that EndReceive is returning zero, but m_socket.Connected is returning true, so I call BeginReceive again. This occurs in a tight loop which doesn't ever stop. It's not clear from the documentation when EndReceive returns a zero. I assumed it only happens when the socket is closed, but this does no appear to be true.

So the question remains, under what conditions can EndReceive return zero?

答: Sometimes we are testing the TCP connection, forgot to initialize the buffer array. When it is null or empty, EndReceive() will return 0 always. I have a stupid experience on this.</p>

Body:
I'm making the following BeginReceive call on a socket:

m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);

in my classes ReceiveCallback function I call

try {
    int bytesReadFromSocket = m_socket.EndReceive(ar);
    if(bytesReadFromSocket > 0) {
         // Do some processing
    }
}
finally {
   if(m_socket.Connected) m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);
}

The issue I'm having is that EndReceive is returning zero, but m_socket.Connected is returning true, so I call BeginReceive again. This occurs in a tight loop which doesn't ever stop. It's not clear from the documentation when EndReceive returns a zero. I assumed it only happens when the socket is closed, but this does no appear to be true.

So the question remains, under what conditions can EndReceive return zero?


问:
Rich Text Box padding between text and border
Is it possible to add padding into a Rich Text Box control between the text and the border?

I tried docking a rich text box inside of a panel, with its padding for all four side set to 10 and that accomplished what I wanted. Except once the vertical scroll bar for the rich text box is needed that gets padded as well.

答:
In the controltemplate the contentpart is this:

```<code><ScrollViewer x:Name="PART_ContentHost"
              Style="{StaticResource ScrollViewerTextBox}"
              VerticalAlignment="Top"/>`
</code>```

Create a style (and controltemplate) for the scrollviewer; Set the MinWidth on the Grid column similar to the width of your scrollbar and adjust the margin to your preference on the ScrollContentPresenter.

```<code><Style x:Key="ScrollViewerTextBox" TargetType="{x:Type ScrollViewer}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ScrollViewer}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="Auto" MinWidth="18"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <ScrollContentPresenter Grid.Column="0" Margin="3 3 3 0" CanVerticallyScroll="True" CanContentScroll="True"/>
                    <ScrollBar x:Name="PART_VerticalScrollBar"
                               Grid.Row="0"
                               Grid.Column="1"
                               Value="{TemplateBinding VerticalOffset}"
                               Maximum="{TemplateBinding ScrollableHeight}"
                               ViewportSize="{TemplateBinding ViewportHeight}"
                               Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}">
                        <ScrollBar.ContextMenu>
                            <ContextMenu Visibility="Hidden" />
                        </ScrollBar.ContextMenu>
                    </ScrollBar>
                    <ScrollBar x:Name="PART_HorizontalScrollBar"
                               Orientation="Horizontal"
                               Grid.Row="1"
                               Grid.Column="0"
                               Value="{TemplateBinding HorizontalOffset}"
                               Maximum="{TemplateBinding ScrollableWidth}"
                               ViewportSize="{TemplateBinding ViewportWidth}"
                               Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}">
                        <ScrollBar.ContextMenu>
                            <ContextMenu Visibility="Hidden" />
                        </ScrollBar.ContextMenu>
                    </ScrollBar>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
In the controltemplate the contentpart is this:

<ScrollViewer x:Name="PART_ContentHost"
              Style="{StaticResource ScrollViewerTextBox}"
              VerticalAlignment="Top"/>`

Create a style (and controltemplate) for the scrollviewer; Set the MinWidth on the Grid column similar to the width of your scrollbar and adjust the margin to your preference on the ScrollContentPresenter.

<Style x:Key="ScrollViewerTextBox" TargetType="{x:Type ScrollViewer}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ScrollViewer}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="Auto" MinWidth="18"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <ScrollContentPresenter Grid.Column="0" Margin="3 3 3 0" CanVerticallyScroll="True" CanContentScroll="True"/>
                    <ScrollBar x:Name="PART_VerticalScrollBar"
                               Grid.Row="0"
                               Grid.Column="1"
                               Value="{TemplateBinding VerticalOffset}"
                               Maximum="{TemplateBinding ScrollableHeight}"
                               ViewportSize="{TemplateBinding ViewportHeight}"
                               Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}">
                        <ScrollBar.ContextMenu>
                            <ContextMenu Visibility="Hidden" />
                        </ScrollBar.ContextMenu>
                    </ScrollBar>
                    <ScrollBar x:Name="PART_HorizontalScrollBar"
                               Orientation="Horizontal"
                               Grid.Row="1"
                               Grid.Column="0"
                               Value="{TemplateBinding HorizontalOffset}"
                               Maximum="{TemplateBinding ScrollableWidth}"
                               ViewportSize="{TemplateBinding ViewportWidth}"
                               Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}">
                        <ScrollBar.ContextMenu>
                            <ContextMenu Visibility="Hidden" />
                        </ScrollBar.ContextMenu>
                    </ScrollBar>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
Grails Rendering plugin save to file
I'm trying to use the rendering plugin to save a generated pdf to a file when a controller action to generate a PDF is shown. I'm following the instructions per: http://gpc.github.com/grails-rendering/docs/manual/index.html

```<code>def pdf = {
        def project = Project.get(params.id)
        def numGoodMilestones = queryService.getGoodShapeMilestonesCount(project)
        def totalMilestones = project.milestones.size()
        def updateHistory = queryService.getReadableHistory(project)
        def summaryName = "${project.name.replace(" ","_")}_summary_${String.format('%tF', new Date()).replace(" ","_")}"
        if(!project)
        {
            flash.message = g.message(code:'default.not.found.message',
                args:[message(code:'project.label',default:'Project'),params.id])
            redirect(uri:'/')
        }
        // see if a summary has been generated with this data and attached to the
        // project. If not, do it.
        def existingAttachedSummary = ProjectDocument.findByName(summaryName)
        if(!existingAttachedSummary)
        {
            //make the file
            def savedSummary = new File(summaryName).withOutputStream { outputStream ->
                pdfRenderingService.render( controller:this,
                template: "projectDetail",
                model:[project:project,
                      numGoodMilestones:numGoodMilestones,
                      totalMilestones:totalMilestones,
                      updateHistory: updateHistory])
            }
            def projectDocument = new ProjectDocument(name:summaryName,
                                  description:"Project summary automatically generated on ${new Date()}}",
                                  fileData:savedSummary,
                                  owner: springSecurityService.currentUser,
                                  project:project
                              )
            if(projectDocument.validate())
            {
                projectDocument.save(flush:true)
                flash.message="I saved a document, yo. ${projectDocument}."
            }
            else
            {
                flash.message="Errors, yo. ${projectDocument.errors.allErrors.each{ it }}."
            }
        }
        else
        {
            flash.message = "project summary already attached to project"
        }

        renderPdf(template: "projectDetail",
        model:[project:project, numGoodMilestones:numGoodMilestones, totalMilestones:totalMilestones, updateHistory: updateHistory],
        filename: "${summaryName}.pdf")
    }
</code>```

The renderPdf() method works fine, as the output in my browser is what is expected.  But when I go look at the created ProjectDocument, I see a blank PDF file. I'm trying to save to a file in the exact same way described by the rendering documentation. What am I doing wrong?

答:
I think this is an error in the docs.  Pass your outputStream as the last argument to pdfRenderingService.render.

```<code>def savedSummary = new File(summaryName).withOutputStream { outputStream ->
    pdfRenderingService.render( controller:this,
        template: "projectDetail",
        model:[project:project,
              numGoodMilestones:numGoodMilestones,
              totalMilestones:totalMilestones,
              updateHistory: updateHistory],
        outputStream)  // <- added this parameter
}
</code>```

Title: Grails Rendering plugin save to file

Body:
I'm trying to use the rendering plugin to save a generated pdf to a file when a controller action to generate a PDF is shown. I'm following the instructions per: http://gpc.github.com/grails-rendering/docs/manual/index.html

def pdf = {
        def project = Project.get(params.id)
        def numGoodMilestones = queryService.getGoodShapeMilestonesCount(project)
        def totalMilestones = project.milestones.size()
        def updateHistory = queryService.getReadableHistory(project)
        def summaryName = "${project.name.replace(" ","_")}_summary_${String.format('%tF', new Date()).replace(" ","_")}"
        if(!project)
        {
            flash.message = g.message(code:'default.not.found.message',
                args:[message(code:'project.label',default:'Project'),params.id])
            redirect(uri:'/')
        }
        // see if a summary has been generated with this data and attached to the
        // project. If not, do it.
        def existingAttachedSummary = ProjectDocument.findByName(summaryName)
        if(!existingAttachedSummary)
        {
            //make the file
            def savedSummary = new File(summaryName).withOutputStream { outputStream ->
                pdfRenderingService.render( controller:this,
                template: "projectDetail",
                model:[project:project,
                      numGoodMilestones:numGoodMilestones,
                      totalMilestones:totalMilestones,
                      updateHistory: updateHistory])
            }
            def projectDocument = new ProjectDocument(name:summaryName,
                                  description:"Project summary automatically generated on ${new Date()}}",
                                  fileData:savedSummary,
                                  owner: springSecurityService.currentUser,
                                  project:project
                              )
            if(projectDocument.validate())
            {
                projectDocument.save(flush:true)
                flash.message="I saved a document, yo. ${projectDocument}."
            }
            else
            {
                flash.message="Errors, yo. ${projectDocument.errors.allErrors.each{ it }}."
            }
        }
        else
        {
            flash.message = "project summary already attached to project"
        }

        renderPdf(template: "projectDetail",
        model:[project:project, numGoodMilestones:numGoodMilestones, totalMilestones:totalMilestones, updateHistory: updateHistory],
        filename: "${summaryName}.pdf")
    }

The renderPdf() method works fine, as the output in my browser is what is expected.  But when I go look at the created ProjectDocument, I see a blank PDF file. I'm trying to save to a file in the exact same way described by the rendering documentation. What am I doing wrong?

Body:
I think this is an error in the docs.  Pass your outputStream as the last argument to pdfRenderingService.render.

def savedSummary = new File(summaryName).withOutputStream { outputStream ->
    pdfRenderingService.render( controller:this,
        template: "projectDetail",
        model:[project:project,
              numGoodMilestones:numGoodMilestones,
              totalMilestones:totalMilestones,
              updateHistory: updateHistory],
        outputStream)  // <- added this parameter
}


问:
My website hosted Amazon S3 downloads index.html though my content-type is type/html
Similar Question: Amazon S3 downloads index.html instead of serving

I am trying to upload a directory to my S3, when I upload manually I can see as static web page. But when I upload using curl, the index.html is getting downloaded.

When I curl my request curl -I https://s3-eu-west-1.amazonaws.com/bucket_name/index.html, I can see

```<code>HTTP/1.1 200 OK
x-amz-id-2: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
x-amz-request-id: XXXXXXXXXXXXXXXX
Date: Fri, 15 Mar 2019 21:03:50 GMT
Last-Modified: Fri, 15 Mar 2019 20:53:05 GMT
ETag: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Accept-Ranges: bytes
Content-Type: text/html
Content-Length: 48210
Server: AmazonS3
</code>```

But still the index.html is downloading.

答:
If you click on the file on AWS S3 console and go to Properties tab details of the file, you will see Metadata section

Remove the existing "Content-Type" metadata entry and retype it as "text/html"

If you have configured your S3 as a static web site hosting, now the file will be displayed with its HTML content instead of forcing the browser to download it

Body:
Similar Question: Amazon S3 downloads index.html instead of serving

I am trying to upload a directory to my S3, when I upload manually I can see as static web page. But when I upload using curl, the index.html is getting downloaded.

When I curl my request curl -I https://s3-eu-west-1.amazonaws.com/bucket_name/index.html, I can see

HTTP/1.1 200 OK
x-amz-id-2: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
x-amz-request-id: XXXXXXXXXXXXXXXX
Date: Fri, 15 Mar 2019 21:03:50 GMT
Last-Modified: Fri, 15 Mar 2019 20:53:05 GMT
ETag: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Accept-Ranges: bytes
Content-Type: text/html
Content-Length: 48210
Server: AmazonS3

But still the index.html is downloading.


问:
string variables in C++
OK, I know that string is a class in C++. Now if I declare an instance somewhat like string str. Is it an array of characters terminated by \0 character only or something is different from regular array of characters?

答:
On the contract level, it's a class that can give you a null terminated array of characters if you want (methods c_str(), data()).

As of C++11, the array returned by the c_str() and also by data() is guaranteed to correspond to the internal storage of the string. Before, that wasn't required by the standard but happened in practice.

Title: string variables in C++


问:
Static assertion failed error when trying to use std::vector<std::thread>
I have the below class and it's header file. When I include the line std::vector<std::thread> threads; in ProducerManager.h, I get the error shown at the bottom of this question. I have gone through multiple SO questions where the issue was not using std::move() to move the thread into the vector, however, apparently since I am doing it by rvalue it should work. But I get this weird error I don't understand. Could anyone be so kind as to help me out?

```<code>// ProducerManager.h

#include <thread>
#include <queue>

#include "Producer.h"

class ProducerManager {
  public:
    ProducerManager(std::queue<std::string> *buffer, Semaphore *items);
    int run();
  private:
    std::queue<std::string> *buffer;
    Semaphore *items;
    bool empty_page_reached = false;
    unsigned int max_threads = 50;
    unsigned int num_pages = 0;
    std::vector<std::thread> threads;   // If I remove this line, I no longer get the error
    std::vector<Producer*> producers;
    std::queue<int> pids;
};
</code>```

```<code>// ProducerManager.cc

#include "ProducerManager.h"

ProducerManager::ProducerManager(std::queue<std::string> *buffer, Semaphore *items) {
  this->buffer = buffer;
  this->items = items;
}

int ProducerManager::run(void) {
  ...
}
</code>```

```<code>// main.cc

#include <string>
#include <thread>

#include "ProducerManager.h"
#include "Consumer.h"
#include "Semaphore.h"

int main(int argc, char *argv[]) {
  std::queue<std::string> *buffer = new std::queue<std::string>();
  Semaphore *items = new Semaphore(0);

  // Testing with just one consumer
  Consumer *c1 = new Consumer(buffer, items);
  std::thread cth1(&Consumer::perform, c1);

  ProducerManager pm(buffer, items);
  std::thread pm_thread(&ProducerManager::run, pm);

  pm_thread.join();
  cth1.join();

  delete c1;

  return 0;
}
</code>```

Error:

```<code>/usr/include/c++/9.2.1/bits/stl_uninitialized.h: In instantiation of ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::thread*, std::vector<std::thread> >; _ForwardIterator = std::thread*]’:
/usr/include/c++/9.2.1/bits/stl_uninitialized.h:307:37:   required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::thread*, std::vector<std::thread> >; _ForwardIterator = std::thread*; _Tp = std::thread]’
/usr/include/c++/9.2.1/bits/stl_vector.h:555:31:   required from ‘std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::thread; _Alloc = std::allocator<std::thread>]’ProducerManager.h:6:7:   required from ‘constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(_UHead&&) [with _UHead = ProducerManager&; long unsigned int _Idx = 1; _Head = ProducerManager]’/usr/include/c++/9.2.1/tuple:349:38:   required from ‘static std::thread::_Invoker<std::tuple<typename std::decay<_Tp>::type, typename std::decay<_Args>::type ...> > std::thread::__make_invoker(_Callable&&, _Args&& ...) [with _Callable = int (ProducerManager::*)(); _Args = {ProducerManager&}; typename std::decay<_Tp>::type = int (ProducerManager::*)()]’/usr/include/c++/9.2.1/thread:131:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int (ProducerManager::*)(); _Args = {ProducerManager&}; <template-parameter-1-3> = void]’main.cc:17:50:   required from here
/usr/include/c++/9.2.1/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range  127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
</code>```

答:
Make it

```<code>std::thread pm_thread(&ProducerManager::run, std::ref(pm));
// or
std::thread pm_thread(&ProducerManager::run, &pm);
</code>```

std::thread's constructor takes arguments by value. As originally written, it attempts to copy pm, but ProducerManager is not copyable (because its member std::vector<std::thread> threads is not copyable, because std::thread is not copyable).

Body:
I have the below class and it's header file. When I include the line std::vector<std::thread> threads; in ProducerManager.h, I get the error shown at the bottom of this question. I have gone through multiple SO questions where the issue was not using std::move() to move the thread into the vector, however, apparently since I am doing it by rvalue it should work. But I get this weird error I don't understand. Could anyone be so kind as to help me out?

// ProducerManager.h

#include <thread>
#include <queue>

#include "Producer.h"

class ProducerManager {
  public:
    ProducerManager(std::queue<std::string> *buffer, Semaphore *items);
    int run();
  private:
    std::queue<std::string> *buffer;
    Semaphore *items;
    bool empty_page_reached = false;
    unsigned int max_threads = 50;
    unsigned int num_pages = 0;
    std::vector<std::thread> threads;   // If I remove this line, I no longer get the error
    std::vector<Producer*> producers;
    std::queue<int> pids;
};

// ProducerManager.cc

#include "ProducerManager.h"

ProducerManager::ProducerManager(std::queue<std::string> *buffer, Semaphore *items) {
  this->buffer = buffer;
  this->items = items;
}

int ProducerManager::run(void) {
  ...
}

// main.cc

#include <string>
#include <thread>

#include "ProducerManager.h"
#include "Consumer.h"
#include "Semaphore.h"

int main(int argc, char *argv[]) {
  std::queue<std::string> *buffer = new std::queue<std::string>();
  Semaphore *items = new Semaphore(0);

  // Testing with just one consumer
  Consumer *c1 = new Consumer(buffer, items);
  std::thread cth1(&Consumer::perform, c1);

  ProducerManager pm(buffer, items);
  std::thread pm_thread(&ProducerManager::run, pm);

  pm_thread.join();
  cth1.join();

  delete c1;

  return 0;
}

Error:

/usr/include/c++/9.2.1/bits/stl_uninitialized.h: In instantiation of ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::thread*, std::vector<std::thread> >; _ForwardIterator = std::thread*]’:
/usr/include/c++/9.2.1/bits/stl_uninitialized.h:307:37:   required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::thread*, std::vector<std::thread> >; _ForwardIterator = std::thread*; _Tp = std::thread]’
/usr/include/c++/9.2.1/bits/stl_vector.h:555:31:   required from ‘std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::thread; _Alloc = std::allocator<std::thread>]’ProducerManager.h:6:7:   required from ‘constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(_UHead&&) [with _UHead = ProducerManager&; long unsigned int _Idx = 1; _Head = ProducerManager]’/usr/include/c++/9.2.1/tuple:349:38:   required from ‘static std::thread::_Invoker<std::tuple<typename std::decay<_Tp>::type, typename std::decay<_Args>::type ...> > std::thread::__make_invoker(_Callable&&, _Args&& ...) [with _Callable = int (ProducerManager::*)(); _Args = {ProducerManager&}; typename std::decay<_Tp>::type = int (ProducerManager::*)()]’/usr/include/c++/9.2.1/thread:131:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int (ProducerManager::*)(); _Args = {ProducerManager&}; <template-parameter-1-3> = void]’main.cc:17:50:   required from here
/usr/include/c++/9.2.1/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range  127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,

Body:
Make it

std::thread pm_thread(&ProducerManager::run, std::ref(pm));
// or
std::thread pm_thread(&ProducerManager::run, &pm);

std::thread's constructor takes arguments by value. As originally written, it attempts to copy pm, but ProducerManager is not copyable (because its member std::vector<std::thread> threads is not copyable, because std::thread is not copyable).