问:
Inflate data from PNG only succeed with specific image?
I had some trouble with trying to inflate data from IDAT block of an PNG image file. So far, I was able to read the IHDR block and return correct data. However, when i tried to decompress to get the raw RGB value of the file, I was able to only succeed on 1 image while getting 0's from the others. This was the code I used for inflate from zlib.

```<code>unsigned char temp[4];
fread(&temp,1,4,pf);
unsigned int ihdr_size = convert_endian(temp);

unsigned char blk[ihdr_size + 8];
fread(blk,1,ihdr_size + 8,pf);

if (check_ihdr(blk) == -1){
    fclose(pf);
    return -1;
}
this->width  = convert_endian(blk+4);
this->height = convert_endian(blk+8);
long area = this->width*this->height*3 +this->height+1;
printf("%ld x %ld\n",this->width, this->height);
printf("Bit depth: %1x\n", (unsigned char)blk[12]);
printf("Color type: %1x\n", (unsigned char)blk[13]);

while(fread(&temp,1,4,pf) > 0){
    unsigned int bsize = convert_endian(temp);
    unsigned char chunk[bsize+8] = {0};
    fread(chunk,1, bsize+8,pf);   //8 extra for block name and CRC
    if (chunk_type(chunk)== 1){ //IDAT
        this->picture = new unsigned char[area];

        z_stream infstream;
        infstream.zalloc = Z_NULL;
        infstream.zfree = Z_NULL;
        infstream.opaque = Z_NULL;
        infstream.avail_in = bsize; // size of input
        infstream.next_in = chunk+4; // input char array (without chunk name)
        infstream.avail_out = area; // size of output
        infstream.next_out = this->picture; // output char array

        inflateInit(&infstream);
        if (int er = inflate(&infstream, Z_NO_FLUSH) != Z_STREAM_END){
            printf("Error!\n");
        }
        inflateEnd(&infstream);
        printf("OUT:%d %ld\n", infstream.avail_out, area);
        for (long i = 0; i < 1000; i+=4){
            printf("%x %x %x\n",this->picture[i], this->picture[i+1], this->picture[i+2]);
        }

    }
    printf("B:%x\n",bsize);
    printf("%c%c%c%c\n",chunk[0], chunk[1], chunk[2], chunk[3]);
}
</code>```

From the above, I had succeed in getting RGB value with this image
image#1
However, when I tried with this imageimage2
(the same image but cropped), the program was only able to return the first 3 bytes of the RGB data (while the rest are zeroes). Was there some thing I implemented incorrectly with this code?

答:
You are not interpreting the result correctly. The reason you have a +this->height is that each line of the image is preceded by a filter byte. For the image that "succeeded", the filter bytes are all zero, indicating no filtering. That means that the pixel values appear directly in the decompressed data. Even in that case, you are displaying the incorrect bytes for the pixel values, since you are not looking at and moving past the filter byte.

For the image that did not "succeed", the first line uses filter 1, and the subsequent lines use filter 2. Filter 1 is the Sub filter, indicating that preceding pixel values after the first have subtracted from them the previous pixel value. 2 indicates the Up filter, where each pixel value after the first row has the previous row's pixel value in that position subtracted from it. That's why nearly all (but not all) of the values after the first are zero. Look at the result more carefully.

Body:
I had some trouble with trying to inflate data from IDAT block of an PNG image file. So far, I was able to read the IHDR block and return correct data. However, when i tried to decompress to get the raw RGB value of the file, I was able to only succeed on 1 image while getting 0's from the others. This was the code I used for inflate from zlib.

unsigned char temp[4];
fread(&temp,1,4,pf);
unsigned int ihdr_size = convert_endian(temp);

unsigned char blk[ihdr_size + 8];
fread(blk,1,ihdr_size + 8,pf);

if (check_ihdr(blk) == -1){
    fclose(pf);
    return -1;
}
this->width  = convert_endian(blk+4);
this->height = convert_endian(blk+8);
long area = this->width*this->height*3 +this->height+1;
printf("%ld x %ld\n",this->width, this->height);
printf("Bit depth: %1x\n", (unsigned char)blk[12]);
printf("Color type: %1x\n", (unsigned char)blk[13]);

while(fread(&temp,1,4,pf) > 0){
    unsigned int bsize = convert_endian(temp);
    unsigned char chunk[bsize+8] = {0};
    fread(chunk,1, bsize+8,pf);   //8 extra for block name and CRC
    if (chunk_type(chunk)== 1){ //IDAT
        this->picture = new unsigned char[area];

        z_stream infstream;
        infstream.zalloc = Z_NULL;
        infstream.zfree = Z_NULL;
        infstream.opaque = Z_NULL;
        infstream.avail_in = bsize; // size of input
        infstream.next_in = chunk+4; // input char array (without chunk name)
        infstream.avail_out = area; // size of output
        infstream.next_out = this->picture; // output char array

        inflateInit(&infstream);
        if (int er = inflate(&infstream, Z_NO_FLUSH) != Z_STREAM_END){
            printf("Error!\n");
        }
        inflateEnd(&infstream);
        printf("OUT:%d %ld\n", infstream.avail_out, area);
        for (long i = 0; i < 1000; i+=4){
            printf("%x %x %x\n",this->picture[i], this->picture[i+1], this->picture[i+2]);
        }

    }
    printf("B:%x\n",bsize);
    printf("%c%c%c%c\n",chunk[0], chunk[1], chunk[2], chunk[3]);
}

From the above, I had succeed in getting RGB value with this image
image#1
However, when I tried with this imageimage2
(the same image but cropped), the program was only able to return the first 3 bytes of the RGB data (while the rest are zeroes). Was there some thing I implemented incorrectly with this code?


来源: stackexchange

问:
Save resolution created with xrandr
I am having troubles with my screen resolution on my fedora 24.

The screen keep getting 1024x768 and the 1280x1024 is unavailable.

digging a little i found, on arch linux forum, this commands:

https://bbs.archlinux.org/viewtopic.php?id=73738

```<code>gtf 1280 1024 60
xrandr --newmode "1280x1024_60.00"  108.88  1280 1360 1496 1712  1024 1025 1028 1060  -HSync +Vsync
xrandr --addmode DVI-1 1280x1024_60.00
xrandr --output DVI-1 --mode 1280x1024_60.00
</code>```

This solves my problem, but the new mode wont persists in a system reboot. Anyone knows how to force this config to me applied even after a system reboot?

答:
you can put the prefered resolution to a file like below:

Create a file in /etc/X11/xorg.conf.d/

40-monitor.conf

```<code>Section "Monitor"
  Identifier  "VGA1"
  Option      "PreferredMode" "1280x1024"
EndSection
</code>```

Restart your X system.

If it doesn't work try creating the next two files in the same path, and restarting again:

30-graphic.conf

```<code>Section "Device"
    Identifier      "Intel Integrated"
    Driver          "intel"
EndSection
</code>```

50-screen.conf

```<code>Section "Screen"
    Identifier      "Default Screen"
    DefaultDepth  24
    SubSection "Display"
            Depth          24
            Modes         "1280x1024"  "1024x768"   "640x480"
    EndSubSection
EndSection
</code>```

Please read here for more details:

https://ask.fedoraproject.org/en/question/8301/how-do-i-change-my-monitors-resolution/

ContentLicense: CC BY-SA 3.0

Title: Save resolution created with xrandr

Body:
I am having troubles with my screen resolution on my fedora 24.

The screen keep getting 1024x768 and the 1280x1024 is unavailable.

digging a little i found, on arch linux forum, this commands:

https://bbs.archlinux.org/viewtopic.php?id=73738

gtf 1280 1024 60
xrandr --newmode "1280x1024_60.00"  108.88  1280 1360 1496 1712  1024 1025 1028 1060  -HSync +Vsync
xrandr --addmode DVI-1 1280x1024_60.00
xrandr --output DVI-1 --mode 1280x1024_60.00

This solves my problem, but the new mode wont persists in a system reboot. Anyone knows how to force this config to me applied even after a system reboot?

Body:
you can put the prefered resolution to a file like below:

Create a file in /etc/X11/xorg.conf.d/

40-monitor.conf

Section "Monitor"
  Identifier  "VGA1"
  Option      "PreferredMode" "1280x1024"
EndSection

Restart your X system.

If it doesn't work try creating the next two files in the same path, and restarting again:

30-graphic.conf

Section "Device"
    Identifier      "Intel Integrated"
    Driver          "intel"
EndSection

50-screen.conf

Section "Screen"
    Identifier      "Default Screen"
    DefaultDepth  24
    SubSection "Display"
            Depth          24
            Modes         "1280x1024"  "1024x768"   "640x480"
    EndSubSection
EndSection

Please read here for more details:

https://ask.fedoraproject.org/en/question/8301/how-do-i-change-my-monitors-resolution/


问:
Coding in Python: Combining List Data
I need to write a tabular file that has the lists written so that it would come up as "Bob, 50, 45, 39", "Haley, 28, 27, 45", etc for the rest of the names, showing a report of their grades. So far, I know how to separate the names or numbers from one list, but I do not know how to combine the data. </p>

```<code>students = ["Bob", "Haley", "Chris", "Nolan", "Asuka", "Cameron", "Tommy"]

midterm = [50, 28, 49, 90, 74, 0, 47]

essay = [45, 27, 76, 94, 0, 73, 67]

final = [39, 45, 65, 74, 36, 29, 90]

f = open ("student_data.txt", "w")

for i in students:
    f.write(str(i) + "\n")
f.close ()
</code>```

答:
If you must write a tabular file you may as well leverage the csv module:

```<code>f = csv.writer(open("student_data.txt", "w", newlines=""))
f.writerows(zip(students, midterm, essay, final))
</code>```

Title: Coding in Python: Combining List Data

Body:
I need to write a tabular file that has the lists written so that it would come up as "Bob, 50, 45, 39", "Haley, 28, 27, 45", etc for the rest of the names, showing a report of their grades. So far, I know how to separate the names or numbers from one list, but I do not know how to combine the data.

students = ["Bob", "Haley", "Chris", "Nolan", "Asuka", "Cameron", "Tommy"]

midterm = [50, 28, 49, 90, 74, 0, 47]

essay = [45, 27, 76, 94, 0, 73, 67]

final = [39, 45, 65, 74, 36, 29, 90]

f = open ("student_data.txt", "w")

for i in students:
    f.write(str(i) + "\n")
f.close ()

Body:
If you must write a tabular file you may as well leverage the csv module:

f = csv.writer(open("student_data.txt", "w", newlines=""))
f.writerows(zip(students, midterm, essay, final))


问:
Visual studio code suppress pep8 warnings
How can I suppress pep8 warnings, in Visual studio code? What I want to do is to suppress E501 warning I don't want to get warnings where my code length is more than 80 chars. I'm using Don Jayamanne's Python extension and here is my config file for vscode

```<code>{
    "python.linting.pylintEnabled": false,
    "python.linting.pep8Enabled": true,
    "python.pythonPath": "/workspace/virtualenvs/abr/bin/python3",
    "python.linting.enabled": true
}
</code>```

I know that there is one another option "python.linting.pep8Args": [] but I couldn't to get it work. I've installed pep8 on virtualenv

What I've already tried.

"python.linting.pep8Args": ['--ignore=E501']

"Searched all visual studio code settings"

答:
Please try double quote " instead of single '

['--ignore=E501'] --> ["--ignore=E501"]

It worked for me. Don't forget to restart the program.

Body:
How can I suppress pep8 warnings, in Visual studio code? What I want to do is to suppress E501 warning I don't want to get warnings where my code length is more than 80 chars. I'm using Don Jayamanne's Python extension and here is my config file for vscode

{
    "python.linting.pylintEnabled": false,
    "python.linting.pep8Enabled": true,
    "python.pythonPath": "/workspace/virtualenvs/abr/bin/python3",
    "python.linting.enabled": true
}

I know that there is one another option "python.linting.pep8Args": [] but I couldn't to get it work. I've installed pep8 on virtualenv

What I've already tried.

"python.linting.pep8Args": ['--ignore=E501']

"Searched all visual studio code settings"

ContentLicense: CC BY-SA 4.0


问:
You tube channels as Json
I am trying to create an android app ..for that i want to know how to retrieve the particular youtube channels videos as a json Data ..?I mean I dont want to search the videos i want to display only for particular channel videos..</p>

答:
HI,

Try this JSON Link

http://gdata.youtube.com/feeds/api/users/UserName/uploads?&v=2&max-results=50&alt=jsonc

here that content Object returns to my channel videos

Reference by

http://code.google.com/apis/youtube/2.0/reference.html#Response_codes_uploading_videos

ContentLicense: CC BY-SA 2.5

Title: You tube channels as Json


问:
Initializer list of RValues
Right now I have a class with only one constructor

```<code>ShaderProgram(std::initializer_list<std::reference_wrapper<const Shader>> shaders);
</code>```

I'm using a reference wrapper because I can't have an initializer_list of references and I can't copy

This code works

```<code>    Shader v{ Shader::Type::Vertex, readFile("res/simple.vert") };
    Shader f{ Shader::Type::Fragment, readFile("res/simple.frag") };
    ShaderProgram shader{ v, f };
</code>```

But this does not

```<code>    ShaderProgram shader{
        Shader { Shader::Type::Vertex, readFile("res/simple.vert") },
        Shader { Shader::Type::Fragment, readFile("res/simple.frag") }
    };
</code>```

What should I be covering here? I suppose I'm missing some kind of constructor to handle rvalues but I can't seem to make it work

The current error is:

E1776 function "std::reference_wrapper<_Ty>::reference_wrapper(_Ty &&) [with
  _Ty=const core::graphics::Shader]" (declared at line 1830 of "c:\Program Files (x86)\Microsoft Visual
  Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\type_traits")
  cannot be referenced -- it is a deleted
  function  RenderEngine    Main.cpp    (77)

答:
reference_wrapper cannot be created from a prvalue. So what you're doing isn't possible.

It seems to me that your interface seems somewhat confused. On the one hand, Shader is a non-copyable type. But on the other hand, you seem to want to call ShaderProgram with Shader prvalues, which will be destroyed immediately after the ShaderProgram object is constructed.

I say, have two interfaces for ShaderProgram: one that takes an initializer_list<Shader>: such users would be uninterested in keeping their Shader objects around past the function's initialization. The other would take an array/vector/etc of non-null pointers to Shader objects. This would be for those users who want to keep their Shader objects around after creating the program.

It's also possible to create a variadic template, where you require that all of the elements are of the Shader type. The last part (verifying that all of the types passed are Shader of some form) is rather difficult without C++17 features.

Title: Initializer list of RValues

Body:
Right now I have a class with only one constructor

ShaderProgram(std::initializer_list<std::reference_wrapper<const Shader>> shaders);

I'm using a reference wrapper because I can't have an initializer_list of references and I can't copy

This code works

    Shader v{ Shader::Type::Vertex, readFile("res/simple.vert") };
    Shader f{ Shader::Type::Fragment, readFile("res/simple.frag") };
    ShaderProgram shader{ v, f };

But this does not

    ShaderProgram shader{
        Shader { Shader::Type::Vertex, readFile("res/simple.vert") },
        Shader { Shader::Type::Fragment, readFile("res/simple.frag") }
    };

What should I be covering here? I suppose I'm missing some kind of constructor to handle rvalues but I can't seem to make it work

The current error is:

E1776 function "std::reference_wrapper<_Ty>::reference_wrapper(_Ty &&) [with
  _Ty=const core::graphics::Shader]" (declared at line 1830 of "c:\Program Files (x86)\Microsoft Visual
  Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\type_traits")
  cannot be referenced -- it is a deleted
  function  RenderEngine    Main.cpp    (77)


问:
Substitute formal arguments in a function factory r
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?</p>

```<code>MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>
</code>```

答:
There may be a more succinct way to get there, but here's one idea:

```<code>fn <- function(x) {
    f <- eval(bquote(function(a, b) 1 / (a + b * .(as.name(x)))))
    formals(f) <- c(formals(f), setNames(alist(dummy = ), x))
    f
}
</code>```

In the first line of fn(), we use bquote() to substitute x into the math expression.  We need to evaluate that (with eval()) to turn it from a call into a function.  Then in the second line, we add the third argument to the formal argument list.  The final line returns the function.

```<code>fn("mpg")
# function (a, b, mpg)
# 1/(a + b * mpg)
# <environment: 0x4f05c78>

fn("cyl")
# function (a, b, cyl)
# 1/(a + b * cyl)
# <environment: 0x4f9ba28>
</code>```

Quick check:

```<code>fn("mpg")(1, 2, 3)
# [1] 0.1428571
1 / (1 + 2 * 3)
# [1] 0.1428571
</code>```

And THANK YOU for asking for a better alternative to eval(parse(text = ...)), it definitely is bad practice.

Body:
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?

MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>

Body:
There may be a more succinct way to get there, but here's one idea:

fn <- function(x) {
    f <- eval(bquote(function(a, b) 1 / (a + b * .(as.name(x)))))
    formals(f) <- c(formals(f), setNames(alist(dummy = ), x))
    f
}

In the first line of fn(), we use bquote() to substitute x into the math expression.  We need to evaluate that (with eval()) to turn it from a call into a function.  Then in the second line, we add the third argument to the formal argument list.  The final line returns the function.

fn("mpg")
# function (a, b, mpg)
# 1/(a + b * mpg)
# <environment: 0x4f05c78>

fn("cyl")
# function (a, b, cyl)
# 1/(a + b * cyl)
# <environment: 0x4f9ba28>

Quick check:

fn("mpg")(1, 2, 3)
# [1] 0.1428571
1 / (1 + 2 * 3)
# [1] 0.1428571

And THANK YOU for asking for a better alternative to eval(parse(text = ...)), it definitely is bad practice.


问:
PIVOT from JOIN tables
I have a large database and in this database, there are two tables I need to pull information from.  I have pulled all the data I need out of the two tables by using both a JOIN and a CASE WHEN. Here is a screen shot from the output

SQL Server output

This is the code that I used to pull the data:

```<code>SELECT [PORTMultiMax].[dbo].cardholdertable.cardid as CardID,CardHolderTable.FirstName as FirstName,CardHolderTable.LastName as LastName, CardHolderTable.InitLet as MI, CardHolderPersonalDataXrTable.PersonalDataItem as Data,
  CASE WHEN PersonalDataID = '4' THEN 'SSN'
         WHEN PersonalDataID = '22' THEN 'Employer'
         WHEN PersonalDataID = '30' THEN 'Training Type'
         WHEN PersonalDataID = '32' THEN 'Primary Sponsor'
         WHEN PersonalDataID = '37' THEN 'Training Date'
         ELSE NULL END AS Description
  FROM [PORTMultiMax].[dbo].[CardHolderTable]
  join [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable]
  on cardholdertable.CardID=CardHolderPersonalDataXrTable.CardID
    where PersonalDataID IN (4,22,30,32,33,37)
    order by LastName
</code>```

The tables involved are named: CardHolderTable and CardHolderPersonalDataXrTable
What I need to do next is get rid of the duplicate name entries in the data. So for example, "JAMES AARON" has multiple rows due to him having multiple descriptors ("Training Date, TrainingType, Employer, and SSN").

I wanted to try and use a PIVOT to pull the row data out and put them in columns named "SSN, Employer, etc...". My problem is I have never used PIVOT before and I am confused on how to apply a PIVOT code to my current SQL query.

PLEASE HELP. Thank you so much

答:
Given your query, I think conditional aggregation is simpler:</p>

```<code>SELECT ch.FirstName, ch.LastName
       MAX(CASE WHEN PersonalDataID = '4' THEN 1 ELSE 0 END) as is_SSN
       MAX(CASE WHEN PersonalDataID = '22' THEN ELSE 0 END) as is_Employer,
       MAX(CASE WHEN PersonalDataID = '30' THEN ELSE 0 END) as is_TrainingType,
       MAX(CASE WHEN PersonalDataID = '32' THEN ELSE 0 END) as is_PrimarySponsor,
       MAX(CASE WHEN PersonalDataID = '37' THEN ELSE 0 END) as is_TrainingDate
from [PORTMultiMax].[dbo].[CardHolderTable] ch join
     [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable] cp
     on ch.CardID = cp.CardID
where PersonalDataID IN (4, 22, 30, 32, 33, 37)
group by ch.FirstName, ch.LastName;
</code>```

Title: PIVOT from JOIN tables

Body:
I have a large database and in this database, there are two tables I need to pull information from.  I have pulled all the data I need out of the two tables by using both a JOIN and a CASE WHEN. Here is a screen shot from the output

SQL Server output

This is the code that I used to pull the data:

SELECT [PORTMultiMax].[dbo].cardholdertable.cardid as CardID,CardHolderTable.FirstName as FirstName,CardHolderTable.LastName as LastName, CardHolderTable.InitLet as MI, CardHolderPersonalDataXrTable.PersonalDataItem as Data,
  CASE WHEN PersonalDataID = '4' THEN 'SSN'
         WHEN PersonalDataID = '22' THEN 'Employer'
         WHEN PersonalDataID = '30' THEN 'Training Type'
         WHEN PersonalDataID = '32' THEN 'Primary Sponsor'
         WHEN PersonalDataID = '37' THEN 'Training Date'
         ELSE NULL END AS Description
  FROM [PORTMultiMax].[dbo].[CardHolderTable]
  join [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable]
  on cardholdertable.CardID=CardHolderPersonalDataXrTable.CardID
    where PersonalDataID IN (4,22,30,32,33,37)
    order by LastName

The tables involved are named: CardHolderTable and CardHolderPersonalDataXrTable
What I need to do next is get rid of the duplicate name entries in the data. So for example, "JAMES AARON" has multiple rows due to him having multiple descriptors ("Training Date, TrainingType, Employer, and SSN").

I wanted to try and use a PIVOT to pull the row data out and put them in columns named "SSN, Employer, etc...". My problem is I have never used PIVOT before and I am confused on how to apply a PIVOT code to my current SQL query.

PLEASE HELP. Thank you so much

Body:
Given your query, I think conditional aggregation is simpler:

SELECT ch.FirstName, ch.LastName
       MAX(CASE WHEN PersonalDataID = '4' THEN 1 ELSE 0 END) as is_SSN
       MAX(CASE WHEN PersonalDataID = '22' THEN ELSE 0 END) as is_Employer,
       MAX(CASE WHEN PersonalDataID = '30' THEN ELSE 0 END) as is_TrainingType,
       MAX(CASE WHEN PersonalDataID = '32' THEN ELSE 0 END) as is_PrimarySponsor,
       MAX(CASE WHEN PersonalDataID = '37' THEN ELSE 0 END) as is_TrainingDate
from [PORTMultiMax].[dbo].[CardHolderTable] ch join
     [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable] cp
     on ch.CardID = cp.CardID
where PersonalDataID IN (4, 22, 30, 32, 33, 37)
group by ch.FirstName, ch.LastName;


问:
What is the best way to check if a variable is a list?
I found this 3 ways to check it, but I don't know which of them is the best:

```<code>x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')
</code>```

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?

答:
Usually we prefer, isinstance(a, list) because it allows a to be either a list or list subclass.

For better speed, an exact check can to an identity test, type(a) is list.  This is a bit faster than using ==.

That said, the norm in Python is to avoid type checks altogether and instead do "duck typing".  You call list methods on a and if they succeed, then we deem a to be sufficiently list like.

Body:
I found this 3 ways to check it, but I don't know which of them is the best:

x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?


问:
Syntax "Number.isFinite" don't work with Chutzpah
It doesn't work to use syntax code "Number.isFinite" in relation to Chutzpah.

Is it supposed to be?

Thank you!

答: Chutzpah uses PhantomJs for running the JS and the current version of Phantom does not support this. A new version (2.5) should be coming out soon and when it does I will update Chutzpah to this to resolve this issue. </p>


问:
How to include data files with the app's APK?
I want to create some pre-created files when my Android application is installed.

I would like to create the file in both the internal memory (data/data//files/) and in a newly created sdcard directories (/sdcard//data1/).

How can I do this?

答:
You can save you files in \res\raw and write the code to store this files to the desired locations if it does not exist when the app start.

Check this to access the internal memory and sdcard

and access the raw file using the following

```<code>InputStream databaseInputStream = getResources().openRawResource(R.raw.yourfile);
</code>```

Body:
You can save you files in \res\raw and write the code to store this files to the desired locations if it does not exist when the app start.

Check this to access the internal memory and sdcard

and access the raw file using the following

InputStream databaseInputStream = getResources().openRawResource(R.raw.yourfile);


问:
Create line breaks in output based on array index
I want to display output like this:

```<code>1 2 3 4
5 6 7 8
9 1 2
</code>```

I've tried this code:

```<code>$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
  echo $value;
  if($key >= round($size){
    echo "<br>"
  }
}
</code>```

But the output is like this:

```<code>1 2 3 4
5
6
7
8
...
</code>```

Can anyone suggest how to write the loop?

Body:
I want to display output like this:

1 2 3 4
5 6 7 8
9 1 2

I've tried this code:

$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
  echo $value;
  if($key >= round($size){
    echo "
"
  }
}

But the output is like this:

1 2 3 4
5
6
7
8
...

Can anyone suggest how to write the loop?

Body:
You can try this:

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 8, 19, 20];

$len = 1;

foreach ($numbers as $number) {
  echo $number . ' ';
  $len++;
  if ($len > 4) {
    echo '<br>';
    $len = 1;
  }
}


问:
Sending text onto network using OSC/UDP
I am trying to send out packets with text that corresponds with a button press, then capture it on wireshark. I am using OSC/UDP and, while the code seems correct, I am failing to see any packets sent from my phone.

For now, I am only using OSCPortOut:

```<code>    OSCPortOut reciever ;
    OSCListener listener ;
    OSCPortOut sender ;
    String sendIPaddr;
    int sendPort;
</code>```

Then, OnCreate, I am connecting to the designated IP (my PC).

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     //   setContentView(R.layout.playerlogin);
        setContentView(R.layout.activity_main);

        Size = (SeekBar)findViewById(R.id.size);
        Speed =(SeekBar)findViewById(R.id.speed);
        Agility=(SeekBar)findViewById(R.id.agility);
        Vision =(SeekBar)findViewById(R.id.vision);

        text = (TextView) findViewById(R.id.text);
        Size.setOnSeekBarChangeListener(this);
        Speed.setOnSeekBarChangeListener(this);
        Agility.setOnSeekBarChangeListener(this);
        Vision.setOnSeekBarChangeListener(this);

        try {
       InetAddress otherIP = InetAddress.getByName("192.168.1.2");

       sender = new OSCPortOut(otherIP,5000);
   }catch (Exception e){
       text.setText("IO Exc: "
               + e.getClass().getName() + ", "
               + e.getMessage());
   }
    }
</code>```

On radio button click, I am trying to send the text corresponding with the click out on to the network.

```<code> public void onRadioClick(View v) {

        n = (RadioButton) findViewById(R.id.north);
        s = (RadioButton) findViewById(R.id.south);
        e = (RadioButton) findViewById(R.id.east);
        w = (RadioButton) findViewById(R.id.west);
        c = (RadioButton) findViewById(R.id.center);
        //String direction = text.setText();
        // or, you can check each radiobutton and find which one is checked.
        if (n.isChecked()) {
            text.setText("North");
        } else if (s.isChecked()) {
            text.setText("South");
        } else if (e.isChecked()) {
            text.setText("East");
        } else if (w.isChecked()) {
            text.setText("West");
        } else if (c.isChecked()) {
            text.setText("Center");
        }
        String direction = String.valueOf(text);
        try{
            sender.send(new OSCMessage(direction));
        }catch(Exception E){
}
</code>```

Initially, there was an issue accessing the port, but this was resolved by adding a permission to the manifest. Does anyone have any ide why I am not seeing North, South, East West or Center in any of the UDP packets that I am capturing?

答:
In the MainCativity, this  must be added for any network communication:</p>

```<code> if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
</code>```

Title: Sending text onto network using OSC/UDP

Body:
I am trying to send out packets with text that corresponds with a button press, then capture it on wireshark. I am using OSC/UDP and, while the code seems correct, I am failing to see any packets sent from my phone.

For now, I am only using OSCPortOut:

    OSCPortOut reciever ;
    OSCListener listener ;
    OSCPortOut sender ;
    String sendIPaddr;
    int sendPort;

Then, OnCreate, I am connecting to the designated IP (my PC).

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     //   setContentView(R.layout.playerlogin);
        setContentView(R.layout.activity_main);

        Size = (SeekBar)findViewById(R.id.size);
        Speed =(SeekBar)findViewById(R.id.speed);
        Agility=(SeekBar)findViewById(R.id.agility);
        Vision =(SeekBar)findViewById(R.id.vision);

        text = (TextView) findViewById(R.id.text);
        Size.setOnSeekBarChangeListener(this);
        Speed.setOnSeekBarChangeListener(this);
        Agility.setOnSeekBarChangeListener(this);
        Vision.setOnSeekBarChangeListener(this);

        try {
       InetAddress otherIP = InetAddress.getByName("192.168.1.2");

       sender = new OSCPortOut(otherIP,5000);
   }catch (Exception e){
       text.setText("IO Exc: "
               + e.getClass().getName() + ", "
               + e.getMessage());
   }
    }

On radio button click, I am trying to send the text corresponding with the click out on to the network.

 public void onRadioClick(View v) {

        n = (RadioButton) findViewById(R.id.north);
        s = (RadioButton) findViewById(R.id.south);
        e = (RadioButton) findViewById(R.id.east);
        w = (RadioButton) findViewById(R.id.west);
        c = (RadioButton) findViewById(R.id.center);
        //String direction = text.setText();
        // or, you can check each radiobutton and find which one is checked.
        if (n.isChecked()) {
            text.setText("North");
        } else if (s.isChecked()) {
            text.setText("South");
        } else if (e.isChecked()) {
            text.setText("East");
        } else if (w.isChecked()) {
            text.setText("West");
        } else if (c.isChecked()) {
            text.setText("Center");
        }
        String direction = String.valueOf(text);
        try{
            sender.send(new OSCMessage(direction));
        }catch(Exception E){
}

Initially, there was an issue accessing the port, but this was resolved by adding a permission to the manifest. Does anyone have any ide why I am not seeing North, South, East West or Center in any of the UDP packets that I am capturing?

Body:
In the MainCativity, this  must be added for any network communication:

 if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


问:
Object not found - XAMPP
I've not changed anything in my xampp recently, and it was working correctly until yesterday.

But now I got this error:

```<code>Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
</code>```

I don't know what happened, because it was working until yesterday.

And also I have to say this address localhost/phpmyadmin work correctly, just my projects address like localhost/project22 not working.

this page and this page  couldn't help me.

答:
Well, Im not sure if it will work for you but you can try this method:

-Create a new .htaccess (if you have one) and put it on your project folder.

Then add the following code on it:

```<code>    <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

  # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
  #  slashes.
  # If your page resides at
  #  http://www.example.com/mypage/test1
  # then use
  # RewriteBase /mypage/test1/
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: ElliotHaughin

  ErrorDocument 404 /index.php
</IfModule>
</code>```

Then refresh your page.

Title: Object not found - XAMPP

Body:
I've not changed anything in my xampp recently, and it was working correctly until yesterday.

But now I got this error:

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3

I don't know what happened, because it was working until yesterday.

And also I have to say this address localhost/phpmyadmin work correctly, just my projects address like localhost/project22 not working.

this page and this page  couldn't help me.

Body:
Well, Im not sure if it will work for you but you can try this method:

-Create a new .htaccess (if you have one) and put it on your project folder.

Then add the following code on it:

    <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

  # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
  #  slashes.
  # If your page resides at
  #  http://www.example.com/mypage/test1
  # then use
  # RewriteBase /mypage/test1/
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: ElliotHaughin

  ErrorDocument 404 /index.php
</IfModule>

Then refresh your page.


问:
Counting Line Numbers in Eclipse
I have a Java project in Eclipse with ~10 packages and ~10 class files per package.  Is there a way to determine total lines of code for the whole project from within Eclipse?  I am familiar with other tools (e.g., Code Analyzer, wc, etc.) but I want to know if there is a way to do this within Eclipse (or get confirmation that there is no way to do it).</p>

答:
A very simple plugin for counting actual lines of source code is step counter eclipse plugin. Please download and try.

github link

Place the downloaded jar file under eclipse\plugin folder and restart eclipse.

Rightclick and select step counter

Step Result

Title: Counting Line Numbers in Eclipse


问:
What's the latest version of Tomcat plugin for Eclipse?
I can only find version 3.2.1 which was released in 2007. Is there a new one?</p>

答:
If you're using Eclipse IDE for Java EE developers, you already get the tools to create Dynamic Web Projects and integrated servletcontainers (which are part of Web Tools Platform, WTP).

The latest WTP release is 3.2.2 from Sept 2010 and this supports up to Tomcat 7, but it's better to go for the integrated IDE rather than just the WTP.

Additional Reading:

Migrating from Sysdeo to WTP - a bit old though


问:
differences between MVCarray and array
I have been looking up the differences between MVCArray and Array for Google map API, but I haven't found any concrete.

I kind of get that MVCArray is a better option since it keeps track of changes (somehow) and have some kind of special events. And some of the same methods have slightly different names, e.g. array.length and MVCarray.getLength().

But can someone please explain in layman's term the explicit differences between the two? and it would be great if you could give some simple examples to make it easier to understand.

Thank you!

答:
Thank you for your input. From what I have read and tried out changing polylines using both arrayand MVCarray to store different coordinates, I found that:

Since MVCarray has events attached to it (insert, remove,
set) so when I change any value, the line is updated immediately and
the old line is gone.

When value in arrayis changed, the new line also appears but the

old line is retained.

Thus, it's better to use MVCarray

Title: differences between MVCarray and array


问:
Merge Overlapping Intervals
Question : Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let the intervals be represented as pairs of integers for simplicity.
For example, let the given set of intervals be {{1,3}, {2,4}, {5,7}, {6,8} }. The intervals {1,3} and {2,4} overlap with each other, so they should be merged and become {1, 4}. Similarly {5, 7} and {6, 8} should be merged and become {5, 8}

Write a function which produces the set of merged intervals for the given set of intervals.

My code:

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class Interval
{
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e)
    {
        start = s;
        end = e;
    }
}

class Ideone
{
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {

        if(intervals.size() == 0)
            return intervals;
        if(intervals.size() == 1)
            return intervals;

        Collections.sort(intervals, new IntervalComparator());

        Interval first = intervals.get(0);
        int start = first.start;
        int end = first.end;

        ArrayList<Interval> result = new ArrayList<Interval>();

        for(int i = 1; i < intervals.size(); i++){
            Interval current = intervals.get(i);
            if(current.start <= end){
                end = Math.max(current.end, end);
            }else{
                result.add(new Interval(start, end));
                start = current.start;
                end = current.end;
            }

        }

        result.add(new Interval(start, end));

        return result;

    }
}

class IntervalComparator implements Comparator
{
    public int compare(Object o1, Object o2)
    {
        Interval i1 = (Interval)o1;
        Interval i2 = (Interval)o2;
        return i1.start - i2.start;
    }
}
public static void main (String[] args) throws java.lang.Exception
{
    ArrayList<Interval> x = new ArrayList<Interval>();
    Interval i1 = new Interval(1,3);
    Interval i2 = new Interval(2,6);
    Interval i3 = new Interval(8,10);
    Interval i4 = new Interval(15,18);

    x.add(i1);x.add(i2);x.add(i3);x.add(i4);

    ArrayList<Interval> r = merge(x);

    for(Interval i : r)
    {
        System.out.println(i.start+" "+i.end);
    }

}
}
</code>```

These are the errors which i got after compiling, can anyone please explain me how to rectify it?

```<code>Main.java:69: error: class, interface, or enum expected
public static void main (String[] args) throws java.lang.Exception
              ^
Main.java:72: error: class, interface, or enum expected
    Interval i1 = new Interval(1,3);
    ^
Main.java:73: error: class, interface, or enum expected
    Interval i2 = new Interval(2,6);
    ^
Main.java:74: error: class, interface, or enum expected
    Interval i3 = new Interval(8,10);
    ^
Main.java:75: error: class, interface, or enum expected
    Interval i4 = new Interval(15,18);
    ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
    ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
              ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
                        ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
                                  ^
Main.java:79: error: class, interface, or enum expected
        ArrayList<Interval> r = merge(x);
        ^
Main.java:81: error: class, interface, or enum expected
        for(Interval i : r)
        ^
Main.java:84: error: class, interface, or enum expected
        }
        ^
12 errors
</code>```

答:
My implementation using BST. O(logn) to merge: Inorder traversal gives you updated intervals.</p>

```<code>private static Interval add(Interval root, Interval x){
    if(root == null)
        return x;
    if(root.start >= x.start){
        root.left = add(root.left,x);
        if(mergeLeft(root,root.left)){
            root.left = null;
        }
    }
    else{
        root.right = add(root.right,x);
        if(mergeRight(root,root.right)){
            root.right = null;
        }
    }

    return root;
}

private static boolean mergeLeft(Interval root,Interval left){
    if(left.end < root.start)
        return false;

    else{
        root.start = Math.min(root.start, left.start);
        root.end = Math.max(root.end, left.end);
        return true;
    }
}

private static boolean mergeRight(Interval root,Interval right){
    if(right.start > root.end)
        return false;
    else{
        root.start = Math.min(root.start, right.start);
        root.end = Math.max(root.end, right.end);
        return true;
    }
}
</code>```

Title: Merge Overlapping Intervals

Body:
Question : Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let the intervals be represented as pairs of integers for simplicity.
For example, let the given set of intervals be {{1,3}, {2,4}, {5,7}, {6,8} }. The intervals {1,3} and {2,4} overlap with each other, so they should be merged and become {1, 4}. Similarly {5, 7} and {6, 8} should be merged and become {5, 8}

Write a function which produces the set of merged intervals for the given set of intervals.

My code:

import java.util.*;
import java.lang.*;
import java.io.*;

class Interval
{
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e)
    {
        start = s;
        end = e;
    }
}

class Ideone
{
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {

        if(intervals.size() == 0)
            return intervals;
        if(intervals.size() == 1)
            return intervals;

        Collections.sort(intervals, new IntervalComparator());

        Interval first = intervals.get(0);
        int start = first.start;
        int end = first.end;

        ArrayList<Interval> result = new ArrayList<Interval>();

        for(int i = 1; i < intervals.size(); i++){
            Interval current = intervals.get(i);
            if(current.start <= end){
                end = Math.max(current.end, end);
            }else{
                result.add(new Interval(start, end));
                start = current.start;
                end = current.end;
            }

        }

        result.add(new Interval(start, end));

        return result;

    }
}

class IntervalComparator implements Comparator
{
    public int compare(Object o1, Object o2)
    {
        Interval i1 = (Interval)o1;
        Interval i2 = (Interval)o2;
        return i1.start - i2.start;
    }
}
public static void main (String[] args) throws java.lang.Exception
{
    ArrayList<Interval> x = new ArrayList<Interval>();
    Interval i1 = new Interval(1,3);
    Interval i2 = new Interval(2,6);
    Interval i3 = new Interval(8,10);
    Interval i4 = new Interval(15,18);

    x.add(i1);x.add(i2);x.add(i3);x.add(i4);

    ArrayList<Interval> r = merge(x);

    for(Interval i : r)
    {
        System.out.println(i.start+" "+i.end);
    }

}
}

These are the errors which i got after compiling, can anyone please explain me how to rectify it?

Main.java:69: error: class, interface, or enum expected
public static void main (String[] args) throws java.lang.Exception
              ^
Main.java:72: error: class, interface, or enum expected
    Interval i1 = new Interval(1,3);
    ^
Main.java:73: error: class, interface, or enum expected
    Interval i2 = new Interval(2,6);
    ^
Main.java:74: error: class, interface, or enum expected
    Interval i3 = new Interval(8,10);
    ^
Main.java:75: error: class, interface, or enum expected
    Interval i4 = new Interval(15,18);
    ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
    ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
              ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
                        ^
Main.java:77: error: class, interface, or enum expected
    x.add(i1);x.add(i2);x.add(i3);x.add(i4);
                                  ^
Main.java:79: error: class, interface, or enum expected
        ArrayList<Interval> r = merge(x);
        ^
Main.java:81: error: class, interface, or enum expected
        for(Interval i : r)
        ^
Main.java:84: error: class, interface, or enum expected
        }
        ^
12 errors

Body:
My implementation using BST. O(logn) to merge: Inorder traversal gives you updated intervals.

private static Interval add(Interval root, Interval x){
    if(root == null)
        return x;
    if(root.start >= x.start){
        root.left = add(root.left,x);
        if(mergeLeft(root,root.left)){
            root.left = null;
        }
    }
    else{
        root.right = add(root.right,x);
        if(mergeRight(root,root.right)){
            root.right = null;
        }
    }

    return root;
}

private static boolean mergeLeft(Interval root,Interval left){
    if(left.end < root.start)
        return false;

    else{
        root.start = Math.min(root.start, left.start);
        root.end = Math.max(root.end, left.end);
        return true;
    }
}

private static boolean mergeRight(Interval root,Interval right){
    if(right.start > root.end)
        return false;
    else{
        root.start = Math.min(root.start, right.start);
        root.end = Math.max(root.end, right.end);
        return true;
    }
}


问:
what is difference between chutzpah reference path and typescript reference path
In my work I have seen there is a test project for typescript project(with ts file app1.ts).It is using Chutzpah as test runner.In its config file it has reference path to the  the js file generated by ts compiler(app1.js).In test project there is a file appTests.ts in which there is a import statement to import app1.ts.As per my knowledge both are doing same referencing to the same file,But what chutzpah runner is doing with this reference.</p>

答: The chutzpah_reference is an old way to let Chutzpah know that your file is referencing another one just for testing. You would use this if you knew when building for real deployment you handled this differently. That said, you should not use this anymore and just make use of a Chutzpah.json file.


问:
Using Excel formulas to find a substring in cells when condition is met
I want to search for a given sub-string in column D when conditions are met in columns A and B.

A simple countifs as suggested in the question Count if two criteria match - EXCEL formula does not match because I would like the ingredient (Chocolate in my example) to be part of the values and not an exact match like in that question. It is therefore NOT a duplicate question.

Let's say I own a restaurant (I wish :) and I have this:

Column A: the category of a dish

Column B: the price range of the dish

Column C: the name of a dish

Column D: a list of ingredients in that dish

I want to search if any of the main course that is expensive contains chocolate (i.e. putting in a cell the value FALSE, "No" or 0). It could look like something like that

I don't want to do this by using VBA but rather using Excel Formulas.

Really appreciate your help.

Thanks

[NOTE]:
The difference with the suggested related question is to add * in the matched strings. Although a small difference, it is what made me ask the question in the first place.

答:
CountIfS is your friend here

```<code>=COUNTIFS(A:A,"Main",B:B,"Expensive",D:D,"*chocolate*")>0
</code>```

Body:
CountIfS is your friend here

=COUNTIFS(A:A,"Main",B:B,"Expensive",D:D,"*chocolate*")>0


问:
Why Calendar.getActualMaximum does not work
I want to get the max date of one month, that it's does't work in some day like the code, it's appear by condition as below
February has problem 2017 Feb Max is 28，If your computer's date is larger than 28, like 2017-03-29 or 2017-04-30</p>

```<code>Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,date.getYear());
c.set(Calendar.MONTH,date.getMonth());
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(c.getTime());
</code>```

答:
I solve the problem by myself,I flow the resource code find that If put February, and use c.set(Calendar.MONTH, date.getMonth()) that the GregorianCalendar have return a wrong time, it's maybe a bug of Calendar, I change my code like below, it will work well

```<code>Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(c.DAY_OF_MONTH));
System.out.println(c.getTime());
</code>```

the console will print:

```<code>Wed Feb 01 00:00:00 CST 2017
Tue Feb 28 00:00:00 CST 2017
</code>```

It's looks like cause by the mythod c.set(Calendar.MONTH, date.getMonth());

Body:
I want to get the max date of one month, that it's does't work in some day like the code, it's appear by condition as below
February has problem 2017 Feb Max is 28，If your computer's date is larger than 28, like 2017-03-29 or 2017-04-30

Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,date.getYear());
c.set(Calendar.MONTH,date.getMonth());
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(c.getTime());

Body:
I solve the problem by myself,I flow the resource code find that If put February, and use c.set(Calendar.MONTH, date.getMonth()) that the GregorianCalendar have return a wrong time, it's maybe a bug of Calendar, I change my code like below, it will work well

Date date = PrimeUtil.formatStringToTime("2017-02","yyyy-MM");
System.out.println(date);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(c.DAY_OF_MONTH));
System.out.println(c.getTime());

the console will print:

Wed Feb 01 00:00:00 CST 2017
Tue Feb 28 00:00:00 CST 2017

It's looks like cause by the mythod c.set(Calendar.MONTH, date.getMonth());


问:
Onclick event for a button
I am creating a simple onclick event for a button. It's just not working. Below is what I wrote.

```<code><script type='text/javascript'>
    rec(){
<?php
   $myfilename = "info.txt";
    if(file_exists($myfilename)){
      echo file_get_contents($myfilename);
    }
?>
    };
</script>
<button onclick="rec()">Click me</button>
</code>```

Not sure, what wrong. I also commented entire php and just tried to echo hi, that also didn't work.
Kindly request your advice. Thanks.

答:
Try printing out your javascript rather than putting PHP inside your javascript. For example you can try.

```<code><?php
   $myfilename = "info.txt";
    if(file_exists($myfilename)){
       $file = file_get_contents($myfilename);
      echo "<script type='text/javascript'> function rec(){ console.log($file); console.log('This is JS being printed by PHP'); }</script>";
    }
?>
</code>```

Please keep in mind you should declare your function with the function keyword and there is no way for us to tell what $myfilename returns without more information, but if you're just trying to print html inside of PHP this should work for you.

Title: Onclick event for a button

Body:
I am creating a simple onclick event for a button. It's just not working. Below is what I wrote.

<button onclick="rec()">Click me</button>

Not sure, what wrong. I also commented entire php and just tried to echo hi, that also didn't work.
Kindly request your advice. Thanks.

Body:
Try printing out your javascript rather than putting PHP inside your javascript. For example you can try.

<?php
   $myfilename = "info.txt";
    if(file_exists($myfilename)){
       $file = file_get_contents($myfilename);
      echo "<script type='text/javascript'> function rec(){ console.log($file); console.log('This is JS being printed by PHP'); }</script>";
    }
?>

Please keep in mind you should declare your function with the function keyword and there is no way for us to tell what $myfilename returns without more information, but if you're just trying to print html inside of PHP this should work for you.


问:
Reversing key value pairs in a HashMap
I have a data structure as follows:

```<code>Map<String,ArrayList<String>> graph = new HashMap<String,ArrayList<String>>();
</code>```

This is essentially a hash map which puts string values as keys and stores array list of strings in the value for the keys.
Now I am trying to reverse the key value pattern to make value the key and key the value. The way I am doing it is as follows:

```<code>private Map<String,ArrayList<String>> reverseAdjList(Map<String,ArrayList<String>> adjList){
    Map<String,ArrayList<String>> tGraph = new HashMap<String,ArrayList<String>>();
    for (Map.Entry<String, ArrayList<String>> entry : adjList.entrySet()) {
        String key = entry.getKey();
        ArrayList<String> values = new ArrayList<>();
        values.add(key);
        ArrayList<String> value = entry.getValue();
        for(String v:value){
            if(tGraph.containsKey(v)){
                values.addAll(tGraph.get(v));
            }
            tGraph.put(v, values);
        }
    }
    return tGraph;
}
</code>```

So this works for me in reversing the hash map keys values pattern for small data set however when I try it on a larger dataset I run into

```<code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.addAll(ArrayList.java:579)
at GraphProcessor.reverseAdjList(GraphProcessor.java:67)
at GraphProcessor.SCC(GraphProcessor.java:135)
at GraphProcessor.<init>(GraphProcessor.java:50)
at GraphProcessor.main(GraphProcessor.java:250)
</code>```

I know this is a very naïve and wrong approach to do it, what is a better and correct way to do it?

答:
There's a bug in your code:

```<code>for (Map.Entry<String, ArrayList<String>> entry : adjList.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> values = new ArrayList<>(); // Wrong place for this variable.
    values.add(key);
    ArrayList<String> value = entry.getValue();
    for(String v:value){
        if(tGraph.containsKey(v)){
            values.addAll(tGraph.get(v));
        }
        tGraph.put(v, values);
    }
}
</code>```

The local variable values should be in the nested for loop, otherwise values are accumulated for all later new key v and will cost a lot of memory if your dataset is large, it should be:

```<code>private Map<String, ArrayList<String>> reverseAdjList(Map<String, List<String>> adjList) {
    Map<String, ArrayList<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet())  {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        for (String v : value) {
            ArrayList<String> values = new ArrayList<>();
            values.add(key);
            if (tGraph.containsKey(v)) {
                values.addAll(tGraph.get(v));
            }
            tGraph.put(v, values);
        }
    }
    return tGraph;
}
</code>```

But actually you don't need to create a new List instance for each inner for step, try the following code with JDK 1.8:

```<code>private  Map<String, List<String>> reverseMap(Map<String, List<String>> adjList) {
    Map<String, List<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet()) {
        for (String value : entry.getValue()) {
            tGraph.computeIfAbsent(value, v -> new ArrayList<>()).add(entry.getKey()); // Updated according comment from @shmosel
        }
    }
    return tGraph;
}
</code>```

If you're using older version of jdk, you can try:

```<code>    private Map<String, List<String>> reverseMap(Map<String, List<String>> adjList) {
    Map<String, List<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet()) {
        for (String value : entry.getValue()) {
            List<String> newValues = tGraph.get(value);
            if (newValues == null) {
                newValues = new ArrayList<>();
                tGraph.put(value, newValues);
            }
            newValues.add(entry.getKey());
        }
    }
    return tGraph;
}
</code>```

Hope this could be helpful :-)

Title: Reversing key value pairs in a HashMap

Body:
I have a data structure as follows:

Map<String,ArrayList<String>> graph = new HashMap<String,ArrayList<String>>();

This is essentially a hash map which puts string values as keys and stores array list of strings in the value for the keys.
Now I am trying to reverse the key value pattern to make value the key and key the value. The way I am doing it is as follows:

private Map<String,ArrayList<String>> reverseAdjList(Map<String,ArrayList<String>> adjList){
    Map<String,ArrayList<String>> tGraph = new HashMap<String,ArrayList<String>>();
    for (Map.Entry<String, ArrayList<String>> entry : adjList.entrySet()) {
        String key = entry.getKey();
        ArrayList<String> values = new ArrayList<>();
        values.add(key);
        ArrayList<String> value = entry.getValue();
        for(String v:value){
            if(tGraph.containsKey(v)){
                values.addAll(tGraph.get(v));
            }
            tGraph.put(v, values);
        }
    }
    return tGraph;
}

So this works for me in reversing the hash map keys values pattern for small data set however when I try it on a larger dataset I run into

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.addAll(ArrayList.java:579)
at GraphProcessor.reverseAdjList(GraphProcessor.java:67)
at GraphProcessor.SCC(GraphProcessor.java:135)
at GraphProcessor.<init>(GraphProcessor.java:50)
at GraphProcessor.main(GraphProcessor.java:250)

I know this is a very naïve and wrong approach to do it, what is a better and correct way to do it?

Body:
There's a bug in your code:

for (Map.Entry<String, ArrayList<String>> entry : adjList.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> values = new ArrayList<>(); // Wrong place for this variable.
    values.add(key);
    ArrayList<String> value = entry.getValue();
    for(String v:value){
        if(tGraph.containsKey(v)){
            values.addAll(tGraph.get(v));
        }
        tGraph.put(v, values);
    }
}

The local variable values should be in the nested for loop, otherwise values are accumulated for all later new key v and will cost a lot of memory if your dataset is large, it should be:

private Map<String, ArrayList<String>> reverseAdjList(Map<String, List<String>> adjList) {
    Map<String, ArrayList<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet())  {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        for (String v : value) {
            ArrayList<String> values = new ArrayList<>();
            values.add(key);
            if (tGraph.containsKey(v)) {
                values.addAll(tGraph.get(v));
            }
            tGraph.put(v, values);
        }
    }
    return tGraph;
}

But actually you don't need to create a new List instance for each inner for step, try the following code with JDK 1.8:

private  Map<String, List<String>> reverseMap(Map<String, List<String>> adjList) {
    Map<String, List<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet()) {
        for (String value : entry.getValue()) {
            tGraph.computeIfAbsent(value, v -> new ArrayList<>()).add(entry.getKey()); // Updated according comment from @shmosel
        }
    }
    return tGraph;
}

If you're using older version of jdk, you can try:

    private Map<String, List<String>> reverseMap(Map<String, List<String>> adjList) {
    Map<String, List<String>> tGraph = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : adjList.entrySet()) {
        for (String value : entry.getValue()) {
            List<String> newValues = tGraph.get(value);
            if (newValues == null) {
                newValues = new ArrayList<>();
                tGraph.put(value, newValues);
            }
            newValues.add(entry.getKey());
        }
    }
    return tGraph;
}

Hope this could be helpful :-)


答:
Enter into E2:

```<code>=AND(A2="Main",B2="Expensive",IFERROR(SEARCH("Chocolate",D2)>=0,FALSE))
</code>```

And drag down.

Title: Using Excel formulas to find a substring in cells when condition is met

Body:
I want to search for a given sub-string in column D when conditions are met in columns A and B.

A simple countifs as suggested in the question Count if two criteria match - EXCEL formula does not match because I would like the ingredient (Chocolate in my example) to be part of the values and not an exact match like in that question. It is therefore NOT a duplicate question.

Let's say I own a restaurant (I wish :) and I have this:

Column A: the category of a dish

Column B: the price range of the dish

Column C: the name of a dish

Column D: a list of ingredients in that dish

I want to search if any of the main course that is expensive contains chocolate (i.e. putting in a cell the value FALSE, "No" or 0). It could look like something like that

I don't want to do this by using VBA but rather using Excel Formulas.

Really appreciate your help.

Thanks

[NOTE]:
The difference with the suggested related question is to add * in the matched strings. Although a small difference, it is what made me ask the question in the first place.

Body:
Enter into E2:

=AND(A2="Main",B2="Expensive",IFERROR(SEARCH("Chocolate",D2)>=0,FALSE))

And drag down.


问:
Apple Mach -O Linker command failed

After updating my POD install, Xcode sprouted a new issue:

答:
First thing you have to do is to delete the files in
/Users/Yourname/Library/Developer/Xcode/DerivedData/YourAppName-xxxx
and then restart your Xcode. That is no joke!

If you got an error like "duplicate symbol_OBJC_CLASS_$_Pod in:",
you should go to TARGETS->Build Phases->Compile Sources and delete extra file.

Title: Apple Mach -O Linker command failed


问:
can I create Buttons on status bar of internet explorer?
I want to create 3 buttons on the status bar of IE.
Any idead how can i do that using C++?</p>

答: I'd be looking in the MSDN library for documentation on creating IE add-ins.</p>


问:
Is it possible to pull all messages contained in an Azure Servicebus Topic into an app?
The only method I see to pull messages from a topic is SubscriptionClient.OnMessage(), which seems to only trigger if the topic receives a new message.

Queues have the QueueClient.Receive() method for this purpose, but topics don't seem to have this capability.

Am I missing something?

答:
Firstly, as Sean Feldman said, messages are not received from the topic directly. Besides, if you’d like to receive and process all messages, you could create a subscription with the default (MatchAll) filter, which will place all messages that published to the topic in the subscription's virtual queue, and then you could  receive and process messages from that subscription in your application. This article describes how to use Service Bus topics and subscriptions with examples, please refer to it.

Additionally, if necessary, please remember to check and process the dead-letter messages.


问:
What is a "cache-friendly" code?
What is the difference between "cache unfriendly code" and the "cache friendly" code?

How can I make sure I write cache-efficient code?

答:
As @Marc Claesen mentioned that one of the ways to write cache friendly code is to exploit the structure in which our data is stored. In addition to that another way to write cache friendly code is: change the way our data is stored; then write new code to access the data stored in this new structure.

This makes sense in the case of how database systems linearize the tuples of a table and store them. There are two basic ways to store the tuples of a table i.e. row store and column store. In row store as the name suggests the tuples are stored row wise. Lets suppose a table named Product being stored has 3 attributes i.e. int32_t key, char name[56] and int32_t price, so the total size of a tuple is 64 bytes.

We can simulate a very basic row store query execution in main memory by creating an array of Product structs with size N, where N is the number of rows in table. Such memory layout is also called array of structs. So the struct for Product can be like:

```<code>struct Product
{
   int32_t key;
   char name[56];
   int32_t price'
}

/* create an array of structs */
Product* table = new Product[N];
/* now load this array of structs, from a file etc. */
</code>```

Similarly we can simulate a very basic column store query execution in main memory by creating an 3 arrays of size N, one array for each attribute of the Product table. Such memory layout is also called struct of arrays. So the 3 arrays for each attribute of Product can be like:

```<code>/* create separate arrays for each attribute */
int32_t* key = new int32_t[N];
char* name = new char[56*N];
int32_t* price = new int32_t[N];
/* now load these arrays, from a file etc. */
</code>```

Now after loading both the array of structs (Row Layout) and the 3 separate arrays (Column Layout), we have row store and column store on our table Product present in our memory.

Now we move on to the cache friendly code part. Suppose that the workload on our table is such that we have an aggregation query on the price attribute. Such as

```<code>SELECT SUM(price)
FROM PRODUCT
</code>```

For the row store we can convert the above SQL query into

```<code>int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + table[i].price;
</code>```

For the column store we can convert the above SQL query into

```<code>int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + price[i];
</code>```

The code for the column store would be faster than the code for the row layout in this query as it requires only a subset of attributes and in column  layout we are doing just that i.e. only accessing the price column.

Suppose that the cache line size is 64 bytes.

In the case of row layout when a cache line is read, the price value of only 1(cacheline_size/product_struct_size = 64/64 = 1) tuple is read, because our struct size of 64 bytes and it fills our whole cache line, so for every tuple a cache miss occurs in case of a row layout.

In the case of column layout when a cache line is read, the price value of 16(cacheline_size/price_int_size = 64/4 = 16) tuples is read, because 16 contiguous price values stored in memory are brought into the cache, so for every sixteenth tuple a cache miss ocurs in case of column layout.

So the column layout will be faster in the case of given query, and is faster in such aggregation queries on a subset of columns of the table. You can try out such experiment for yourself using the data from TPC-H benchmark, and compare the run times for both the layouts. The wikipedia article on column oriented database systems is also good.

So in database systems, if the query workload is known beforehand, we can store our data in layouts which will suit the queries in workload and access data from these layouts. In the case of above example we created a column layout and changed our code to compute sum so that it became cache friendly.

Title: What is a "cache-friendly" code?

Body:
As @Marc Claesen mentioned that one of the ways to write cache friendly code is to exploit the structure in which our data is stored. In addition to that another way to write cache friendly code is: change the way our data is stored; then write new code to access the data stored in this new structure.

This makes sense in the case of how database systems linearize the tuples of a table and store them. There are two basic ways to store the tuples of a table i.e. row store and column store. In row store as the name suggests the tuples are stored row wise. Lets suppose a table named Product being stored has 3 attributes i.e. int32_t key, char name[56] and int32_t price, so the total size of a tuple is 64 bytes.

We can simulate a very basic row store query execution in main memory by creating an array of Product structs with size N, where N is the number of rows in table. Such memory layout is also called array of structs. So the struct for Product can be like:

struct Product
{
   int32_t key;
   char name[56];
   int32_t price'
}

/* create an array of structs */
Product* table = new Product[N];
/* now load this array of structs, from a file etc. */

Similarly we can simulate a very basic column store query execution in main memory by creating an 3 arrays of size N, one array for each attribute of the Product table. Such memory layout is also called struct of arrays. So the 3 arrays for each attribute of Product can be like:

/* create separate arrays for each attribute */
int32_t* key = new int32_t[N];
char* name = new char[56*N];
int32_t* price = new int32_t[N];
/* now load these arrays, from a file etc. */

Now after loading both the array of structs (Row Layout) and the 3 separate arrays (Column Layout), we have row store and column store on our table Product present in our memory.

Now we move on to the cache friendly code part. Suppose that the workload on our table is such that we have an aggregation query on the price attribute. Such as

SELECT SUM(price)
FROM PRODUCT

For the row store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + table[i].price;

For the column store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + price[i];

The code for the column store would be faster than the code for the row layout in this query as it requires only a subset of attributes and in column  layout we are doing just that i.e. only accessing the price column.

Suppose that the cache line size is 64 bytes.

In the case of row layout when a cache line is read, the price value of only 1(cacheline_size/product_struct_size = 64/64 = 1) tuple is read, because our struct size of 64 bytes and it fills our whole cache line, so for every tuple a cache miss occurs in case of a row layout.

In the case of column layout when a cache line is read, the price value of 16(cacheline_size/price_int_size = 64/4 = 16) tuples is read, because 16 contiguous price values stored in memory are brought into the cache, so for every sixteenth tuple a cache miss ocurs in case of column layout.

So the column layout will be faster in the case of given query, and is faster in such aggregation queries on a subset of columns of the table. You can try out such experiment for yourself using the data from TPC-H benchmark, and compare the run times for both the layouts. The wikipedia article on column oriented database systems is also good.

So in database systems, if the query workload is known beforehand, we can store our data in layouts which will suit the queries in workload and access data from these layouts. In the case of above example we created a column layout and changed our code to compute sum so that it became cache friendly.


问:
how does the google map api validate the key
If one want to use the google map api and its map data,he should register for a key for his website.

Now we want to open our own map api for other,so we require user who use our map api and map data register first.

However we have no idea how to validate.

FOr example, I have obtain a key of google map api,when I call the api,the js will downloaded to local,but I think there must be another validation when request map data from google.

how does they do?

Validte the site and key for each map tile?

答: They deprecated the key in v3. In v2 I'm assuming they matched your HTTP REFERER to the key that was assigned to your domain, and allowed the request if there was a match. </p>


问:
how to display two home pages for two different users using php
i'm new for web developing and i have a question regarding user login. I have two types of users and I need to link them for two different home pages when they log in. for an example the user whose user id is M00001 should get the home page MemberHome.php and the user whose user id is G00001 should get the home page called GuestHome.php.
Please tell me how should i create my web pages according to above requirement using PHP and MySql.</p>

答:
In database fields probably you can store a field call 'user_type' <br>
'user_type' field contains 'member', 'guest', etc. </p>

Body:
In database fields probably you can store a field call 'user_type'

'user_type' field contains 'member', 'guest', etc.


问:
How do I share Firebase auth data across an iOS app?
I have an app that has 2 view controllers. One is the login/register page, and the other is the page that SHOULD change a UILabel to say the user's email, but it doesn't. I guess it's because I don't have the data from the first view controller. So how can I get the data from the first view controller?

Here's part of the code from SecondViewController.swift

```<code>if let user = FIRAuth.auth()?.currentUser {
    self.usernameLabel.text = user.email
    print(user.email)
}
</code>```

答:
You want to grab a single event "snapshot" of the user's email from Firebase DB.  The email is stored as a dictionary entry in Firebase. So this is what's worked for me: </p>

```<code>let uid = FIRAuth.auth()?.currentUser?.uid
FirDatabase.database().reference()child("YOUR_FIREBASE_CHILD_NODE").child(uid!).
observeSingleEvent(of: .value, with: { (snapshot) in

   if let dictionary = snapshot.value as? [String:Any] {
   self.usernameLabel.text = dictionary["email"] as? String
}
</code>```

Body:
I have an app that has 2 view controllers. One is the login/register page, and the other is the page that SHOULD change a UILabel to say the user's email, but it doesn't. I guess it's because I don't have the data from the first view controller. So how can I get the data from the first view controller?

Here's part of the code from SecondViewController.swift

if let user = FIRAuth.auth()?.currentUser {
    self.usernameLabel.text = user.email
    print(user.email)
}

Body:
You want to grab a single event "snapshot" of the user's email from Firebase DB.  The email is stored as a dictionary entry in Firebase. So this is what's worked for me:

let uid = FIRAuth.auth()?.currentUser?.uid
FirDatabase.database().reference()child("YOUR_FIREBASE_CHILD_NODE").child(uid!).
observeSingleEvent(of: .value, with: { (snapshot) in

   if let dictionary = snapshot.value as? [String:Any] {
   self.usernameLabel.text = dictionary["email"] as? String
}


问:
Hflex in Grid. Doesn't show correclty after resize the Browser

I have this grid with this data. The columns are set with hflex="min". Here is my .zul

```<code><?page title="" contentType="text/html;charset=UTF-8"?>
<div sclass="container-resume-procedure">
    <grid sclass="grid-resume-procedure" height="130px">
        <auxhead>
            <auxheader  colspan="1">
                <label value=""/>
            </auxheader>
            <auxheader  colspan="2" style="align:center">
                <label value="Resumen del Tramite"/>
            </auxheader>
            <auxheader  colspan="1">
                <label value=""/>
            </auxheader>
        </auxhead>
        <columns>
            <column label="Numero de Tramite" hflex="min" width="15%"  align="center"/>
            <column label="Cliente" hflex="min" width="15%" align="center"/>
            <column label="Orden" hflex="min" width="15%" align="center"/>
            <column label="Estado" hflex="min" width="15%" align="center"/>
        </columns>
        <rows>
            <row>
                <label id="proced"/>
                <label id="resume_client"/>
                <label id="resumenumOrder"/>
                <label id="resume_status"/>
            </row>
        </rows>
    </grid>
</div>
</code>```

It's working okay, when the browser is resized with a small width I can see the grid with a scrrolbar and the info is legible. but when the browser is resized the problem in the image occurs. I find one solution, which is set hflex in the grid, but when the browser is resized very small, the horizontall scrollbar doesn't appear.

答:
You need to give ID and use invalidate() to refresh that grid
just like this:

```<code>grid id="grdProcedure" sclass="grid-resume-procedure" height="130px"
</code>```

Than in Java class just add grdProcedure.invalidate();.

Body:
I have this grid with this data. The columns are set with hflex="min". Here is my .zul

<?page title="" contentType="text/html;charset=UTF-8"?>

    <grid sclass="grid-resume-procedure" height="130px">
        <auxhead>
            <auxheader  colspan="1">

            </auxheader>
            <auxheader  colspan="2" style="align:center">

            </auxheader>
            <auxheader  colspan="1">

            </auxheader>
        </auxhead>
        <columns>
            <column label="Numero de Tramite" hflex="min" width="15%"  align="center"/>
            <column label="Cliente" hflex="min" width="15%" align="center"/>
            <column label="Orden" hflex="min" width="15%" align="center"/>
            <column label="Estado" hflex="min" width="15%" align="center"/>
        </columns>
        <rows>
            <row>

            </row>
        </rows>
    </grid>

It's working okay, when the browser is resized with a small width I can see the grid with a scrrolbar and the info is legible. but when the browser is resized the problem in the image occurs. I find one solution, which is set hflex in the grid, but when the browser is resized very small, the horizontall scrollbar doesn't appear.

Body:
You need to give ID and use invalidate() to refresh that grid
just like this:

grid id="grdProcedure" sclass="grid-resume-procedure" height="130px"

Than in Java class just add grdProcedure.invalidate();.


问:
For-loop going down a tree
I have a k-ary tree stored in a std::vector called tree:

```<code>0,                          1,                          2
3,       4,       5         6,       7,       8         9,       10,      11
12,13,14 15,16,17 18,19,20  21,22,23 24,25,26 27,28,29  30,31,32 33,34,35 36,37,38
</code>```

tree.size() == 39 as sketched above

I'm searching for a loop similar to following:

```<code>for (size_t i=0,j=tree.size(); i!=j; i=some_magic()) // <<---here
{
  std::cout << i << std::endl;
}
</code>```

Which should output:

```<code>0
3
12
13
14
4
15
...
</code>```

答:
For depth-first search you'll need a stack of some kind.</p>

```<code>int child(int i, int c) { return (i+1)*3+c; }

int main()
{
    std::vector<int> parents = { 2, 1, 0 };
    while(!parents.empty())
    {
        int i = parents.back();
        parents.pop_back();
        std::cout << tree[i] << std::endl;
        for(int c = 0; c != 3; ++c)
        {
            if(child(i, 2-c) < tree.size())
                parents.push_back(child(i, 2-c));
        }
    }
}
</code>```

Title: For-loop going down a tree

Body:
I have a k-ary tree stored in a std::vector called tree:

0,                          1,                          2
3,       4,       5         6,       7,       8         9,       10,      11
12,13,14 15,16,17 18,19,20  21,22,23 24,25,26 27,28,29  30,31,32 33,34,35 36,37,38

tree.size() == 39 as sketched above

I'm searching for a loop similar to following:

for (size_t i=0,j=tree.size(); i!=j; i=some_magic()) // <<---here
{
  std::cout << i << std::endl;
}

Which should output:

0
3
12
13
14
4
15
...

Body:
For depth-first search you'll need a stack of some kind.

int child(int i, int c) { return (i+1)*3+c; }

int main()
{
    std::vector<int> parents = { 2, 1, 0 };
    while(!parents.empty())
    {
        int i = parents.back();
        parents.pop_back();
        std::cout << tree[i] << std::endl;
        for(int c = 0; c != 3; ++c)
        {
            if(child(i, 2-c) < tree.size())
                parents.push_back(child(i, 2-c));
        }
    }
}


问:
How to remove white gap between navbar and header?
I would like to remove the white gap between my navbar and header , i dont know why i got the gap . i hope someone can help me

@import url(http://fonts.googleapis.com/css?family=Lato);

.container
{
    width:800px;
    overflow:hidden;
    display:inline-block;
    margin-top: 0px;
}
.side-bar
{
    background:#74AFAD;
    position:absolute;
    height:100%;
    width:200px;
    color:#fff;
    transition: margin-left 0.5s;
}

.side-bar ul
{
    list-style:none;
    padding:0px;

}

.side-bar ul li.menu-head
{
    font-family: 'Lato', sans-serif;
    padding:20px;
}

.side-bar ul li.menu-head a
{
    color:#fff;
    text-decoration:none;
    height:50px;
}

.side-bar ul .menu-head  a
{
    color:#fff;
    text-decoration:none;
    height:50px;
    margin: 0;
}

.side-bar ul .menu li  a
{
    color:#fff;
    text-decoration:none;
    display:inline-table;
    width:100%;
    padding-left:20px;
    padding-right:20px;
    padding-top:10px;
    padding-bottom:10px;
}

.side-bar ul .menu li  a:hover
{
    border-left:3px solid #ECECEA;
    padding-left:17px;
}

.side-bar ul .menu li  a.active
{
    padding-left:17px;
    background:#D9853B;
    border-left:3px solid #ECECEA;
}

.side-bar ul .menu li  a.active:before {
   content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;

    border-left: 7px solid #D9853B;
    margin-top: -10px;
    margin-left: 180px;
}

.content
{
    padding-left: 200px;
    transition: padding-left 0.5s;
}

.active > .side-bar
{
    margin-left:-150px;
    transition: margin-left 0.5s;
}

.active > .content
{
    padding-left:50px;
    transition: padding-left 0.5s;
}
#logout_sidebar {
    position: absolute;
    display: inline-block;
    bottom: 0;
    width: 100%;
}

@media screen and (max-width: 768px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
    width:calc(100% + 220px);
  }

  .row-offcanvas-left
  {
    left: -220px;
  }

  .row-offcanvas-left.active {
    left: 0;
  }

  .sidebar-offcanvas {
    position: absolute;
    top: 0;
  }
}

#sidebar {
  width: inherit;
  min-width: 220px;
  max-width: 220px;
  background-color:#f5f5f5;
  float: left;
  height:100%;
  position:relative;
  overflow-y:auto;
  overflow-x:hidden;
}
#main {
  height:100%;
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" type="text/css" href="css/navbar.css">

  <title> Bagus Gamestore Admin Dashboard</title>
</head>
<body>
<div class="container">
  <div class="row">
    <div class="wrapper">
          <div class="side-bar">
                <ul>
                    <li class="menu-head">
                        ADMIN PANEL <span class="glyphicon glyphicon-align-justify pull-right"></span>
                    </li>
                    <div class="menu">
                        <li>
                            Dashboard <span class="glyphicon glyphicon-dashboard pull-right"></span>
                        </li>
                        <li>
                            User List<span class="glyphicon glyphicon-user pull-right"></span>
                        </li>
                        <li>
                            Add New Product<span class="glyphicon glyphicon-plus pull-right"></span>
                        </li>
                        <li>
                            Go to Website <span class="glyphicon glyphicon-globe pull-right"></span>
                        </li>
                    </div>

                    <div class="menu ">
                    <li id="logout_sidebar">
                      Logout<span class="glyphicon glyphicon-log-out pull-right"></span>
                    </li>
                    </div>
                </ul>
          </div>
            <div class="content">
            <!-- show user list -->
            <!-- end of show user list-->

            </div>
    </div>
  </div>
</div>
</body>
</html></code>```

as you can see , theres a litle gap over the ADMIN PANEL , how do i remove those gap ? thank you before

答:
Applying

```<code>margin: 0px;
</code>```

to your body and removing

```<code>display:inline-block;
</code>```

from your container appears to
work, but that might not be what you want depending on what other elements you want on your page.

Body:
I would like to remove the white gap between my navbar and header , i dont know why i got the gap . i hope someone can help me

@import url(http://fonts.googleapis.com/css?family=Lato);

.container
{
    width:800px;
    overflow:hidden;
    display:inline-block;
    margin-top: 0px;
}
.side-bar
{
    background:#74AFAD;
    position:absolute;
    height:100%;
    width:200px;
    color:#fff;
    transition: margin-left 0.5s;
}

.side-bar ul
{
    list-style:none;
    padding:0px;

}

.side-bar ul li.menu-head
{
    font-family: 'Lato', sans-serif;
    padding:20px;
}

.side-bar ul li.menu-head a
{
    color:#fff;
    text-decoration:none;
    height:50px;
}

.side-bar ul .menu-head  a
{
    color:#fff;
    text-decoration:none;
    height:50px;
    margin: 0;
}

.side-bar ul .menu li  a
{
    color:#fff;
    text-decoration:none;
    display:inline-table;
    width:100%;
    padding-left:20px;
    padding-right:20px;
    padding-top:10px;
    padding-bottom:10px;
}

.side-bar ul .menu li  a:hover
{
    border-left:3px solid #ECECEA;
    padding-left:17px;
}

.side-bar ul .menu li  a.active
{
    padding-left:17px;
    background:#D9853B;
    border-left:3px solid #ECECEA;
}

.side-bar ul .menu li  a.active:before {
   content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;

    border-left: 7px solid #D9853B;
    margin-top: -10px;
    margin-left: 180px;
}

.content
{
    padding-left: 200px;
    transition: padding-left 0.5s;
}

.active > .side-bar
{
    margin-left:-150px;
    transition: margin-left 0.5s;
}

.active > .content
{
    padding-left:50px;
    transition: padding-left 0.5s;
}
#logout_sidebar {
    position: absolute;
    display: inline-block;
    bottom: 0;
    width: 100%;
}

@media screen and (max-width: 768px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
    width:calc(100% + 220px);
  }

  .row-offcanvas-left
  {
    left: -220px;
  }

  .row-offcanvas-left.active {
    left: 0;
  }

  .sidebar-offcanvas {
    position: absolute;
    top: 0;
  }
}

#sidebar {
  width: inherit;
  min-width: 220px;
  max-width: 220px;
  background-color:#f5f5f5;
  float: left;
  height:100%;
  position:relative;
  overflow-y:auto;
  overflow-x:hidden;
}
#main {
  height:100%;
  overflow:auto;
}

    <!DOCTYPE html>

<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="css/navbar.css">

  <title> Bagus Gamestore Admin Dashboard</title>

                        ADMIN PANEL

                            Dashboard

                            User List

                            Add New Product

                            Go to Website

                      Logout

as you can see , theres a litle gap over the ADMIN PANEL , how do i remove those gap ? thank you before

Body:
Applying

margin: 0px;

to your body and removing

display:inline-block;

from your container appears to
work, but that might not be what you want depending on what other elements you want on your page.


问:
Video not Autoplaying in Html
I have a video which is not autoplaying:

```<code>  <video preload="auto" autoplay="autoplay" loop="loop" muted="muted" className="myVideo" id="vidAd">
        <source src={video} type="video/mp4"/>
        <source src={video} type="video/ogg"/>
        <source src={video} type="video/webm"/>
      Your browser does not support the video tag.
    </video>
</code>```

Currently the video shows up but does not autoplay.

I tried to tackle this with javascript but I'm not sure what the correct syntax is

```<code><script type="text/javascript">
$(document).ready(function() {
   var vid = document.getElementById("vidAd");
   vid.autoplay = true;
   vid.load();
});
</script>
</code>```

答:
Try:

HTML

```<code><video preload="auto" loop="loop" muted="muted" className="myVideo" id="vidAd">
    <source src={video} type="video/mp4"/>
    <source src={video} type="video/ogg"/>
    <source src={video} type="video/webm"/>
  Your browser does not support the video tag.
</video>
</code>```

JS

```<code>var vid = document.getElementById("vidAd");
vid.autoplay = true;
vid.load();
</code>```

Title: Video not Autoplaying in Html

Body:
I have a video which is not autoplaying:

  <video preload="auto" autoplay="autoplay" loop="loop" muted="muted" className="myVideo" id="vidAd">
        <source src={video} type="video/mp4"/>
        <source src={video} type="video/ogg"/>
        <source src={video} type="video/webm"/>
      Your browser does not support the video tag.
    </video>

Currently the video shows up but does not autoplay.

I tried to tackle this with javascript but I'm not sure what the correct syntax is

Body:
Try:

HTML

<video preload="auto" loop="loop" muted="muted" className="myVideo" id="vidAd">
    <source src={video} type="video/mp4"/>
    <source src={video} type="video/ogg"/>
    <source src={video} type="video/webm"/>
  Your browser does not support the video tag.
</video>

JS

var vid = document.getElementById("vidAd");
vid.autoplay = true;
vid.load();


问:
Retrieving data from array of array objects
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

```<code>   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}
</code>```

];

I need to search for employeeid 1 and return both projects. How do i search it.

答:
I hope this is the code you're looking for:</p>

```<code>for(i=0;i<data.length;i++)
 {
    emp=data[i].employees;
    for(j=0;j<emp.length;j++)
    {
        if(emp[j].employeeId==1)
          console.log('Project of' + emp[j].fullName + 'is = ' + data[i].projectName)
    }
}
</code>```

Body:
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}

];

I need to search for employeeid 1 and return both projects. How do i search it.

Body:
I hope this is the code you're looking for:

for(i=0;i<data.length;i++)
 {
    emp=data[i].employees;
    for(j=0;j<emp.length;j++)
    {
        if(emp[j].employeeId==1)
          console.log('Project of' + emp[j].fullName + 'is = ' + data[i].projectName)
    }
}