问:
(PHP) writing a form inside a php file
I have written a form inside a php file and used post method to send the value to next page. however the variable is not sent to next page. What am I doing wrong?

In the code below I can't get the post value. It says  $dbid undefined!

```<code>echo '<table width = "30%" cellpadding = "2" cellspacing ="2" border = "2px">
echo '<table width = "30%" cellpadding = "2" cellspacing ="2" border = "2px">
  <tr>
    <form action="sample.php" method="POST">
      <td> <input  type="text" name="dbid" value='.$row['ID'].' size="4" readonly ></td>
           <button  type="submit" name="submit" >view form</button>
    </form>
  <td>'.$row['username'].'</td>
  <td>'.$row['ecno'].'</td>
  <td>'.$row['division'].'</td>
  <td>'.$row['code'].'</td>
  <td>'.$row['doj'].'</td>
  <td>'.$row['dor'].'</td>
  <td>'.$row['fc'].'</td>
  <td>'.$row['tc'].'</td>
</tr>
</code>```

Sample.php:

```<code><?php
$dbid= $_POST['dbid'];

$db = mysqli_connect("localhost", "root", "", "logindb1");
if (mysqli_connect_errno())
{
  echo "something went wrong with the connection" . mysqli_connect_error();
 }
echo ' <input type="hidden" name="dbid" value="'.$_POST['dbid'].'"> ';
$query = mysqli_query($db,"SELECT * FROM users2  WHERE ID ='$dbid'");
</code>```

答:
Use  tag instead of  to create submit button

Code

```<code><input type="submit" name="submit" >view form</button>
</code>```

Instead of

```<code><button  type="submit" name="submit" >view form</button>
</code>```

Reference : stackoverflow.com/questions/3543615/difference-between-input-type-submit-and-button-type-submittext-butto

Title: (PHP) writing a form inside a php file

Body:
I have written a form inside a php file and used post method to send the value to next page. however the variable is not sent to next page. What am I doing wrong?

In the code below I can't get the post value. It says  $dbid undefined!

echo '

echo '

    <form action="sample.php" method="POST">
       <input  type="text" name="dbid" value='.$row['ID'].' size="4" readonly >
           <button  type="submit" name="submit" >view form</button>
    </form>
  '.$row['username'].'
  '.$row['ecno'].'
  '.$row['division'].'
  '.$row['code'].'
  '.$row['doj'].'
  '.$row['dor'].'
  '.$row['fc'].'
  '.$row['tc'].'

Sample.php:

<?php
$dbid= $_POST['dbid'];

$db = mysqli_connect("localhost", "root", "", "logindb1");
if (mysqli_connect_errno())
{
  echo "something went wrong with the connection" . mysqli_connect_error();
 }
echo ' <input type="hidden" name="dbid" value="'.$_POST['dbid'].'"> ';
$query = mysqli_query($db,"SELECT * FROM users2  WHERE ID ='$dbid'");

Body:
Use  tag instead of  to create submit button

Code

<input type="submit" name="submit" >view form</button>

Instead of

<button  type="submit" name="submit" >view form</button>

Reference : stackoverflow.com/questions/3543615/difference-between-input-type-submit-and-button-type-submittext-butto


来源: stackexchange

问:
Monitoring Apache Tomcat applications in production environment
How do you ensure that your applications in production are up and running?
How do you alert your team of developers if something goes wrong?

I'm asking this because I'm writing a bash script to check for this issue, I'd like to know if there is a smarter or more complete way to achieve this.
The idea behind is this command: wget -q -O - APPLICATION_URL_HERE | grep 'ERROR 404, I still have to check all kinds of HTTP errors, but you can get the point of what I mean.
If an application is recognized to not be running a mail is sent to the list of the team it belongs to.

All my applications are running on Apache Tomcat.

答:
You may try a community fork of Lambda Probe, the Psi Probe

Here's a short summary taken from their home page:

"... Ultimate tool for monitoring and management of Apache Tomcat instance in real time. Lambda Probe will help you to visualise real time information about Apache Tomcat instance via easy to use and friendly web interface. For more information please visit the overview section."

OwnerDisplayName: Montecristo

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Patrick Cuff

OwnerDisplayName: Boris Pavlović


问:
improve locality and decrease Cache pollution in a medical image reconstruction implementation
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

```<code>for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}
</code>```

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.

答:
A simple optimization to reduce the random access on vector b would be to never write into vector b within the inner for loop.

Instead load all values needed from vector B into temporary variables, do the entire inner for loop while updating these temporary variables, then write the temporary variables back into vector B.

The temporary variables will at worst be located on the same cache lines, depending on your compiler and environment you may also hint for the compiler to use registers for these variables.

ContentLicense: CC BY-SA 2.5

Body:
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.


问:
angular4 css / js differs when I refresh the page
When I load a page with this kind of script : </p>

```<code>this.router.navigateByUrl('/report-result/'+report.id);
</code>```

<p>It seems that all the css is not loaded, and the js too.
For example, my bootstrap popover are not loaded, some fields are misplaced.
While I load the page directly with the url or if I refresh the page, all is allright.
Do you have an idea? </p>

答:
You should change the way of navigate to something like this:

this.router.navigate(['report-result', report.id]);

Remember the routes are absolute, so if your are trying to access to localhost/parentRoute/report-result/report. The you have to do it like this:

this.router.navigate(['parentRoute', 'report-result', report.id]);

Or make it to be relative to the parentRoute like this:

this.router.navigate(['report-result', report.id], {relativeTo:'/parentReport'});

Body:
When I load a page with this kind of script :

this.router.navigateByUrl('/report-result/'+report.id);

It seems that all the css is not loaded, and the js too.
For example, my bootstrap popover are not loaded, some fields are misplaced.
While I load the page directly with the url or if I refresh the page, all is allright.
Do you have an idea?


问:
get rid of blank space around widgets in tkinter
I put widgets on a window with .grid and noticed that the widgets have space around them. I fixed that on canvas widget with highlightthickness but this doesn't work with button widgets. It doesn't look cool when you have grey window background and there's white space around buttons.
P.S. I use python3 on macos Sierra

```<code>root = Tk()
root.configure(bg='grey')

w = Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()
</code>```

P.S. TKinter leaving borders around widgets that's what it looks like. The guy was advised to use highlightbackground, but when I screenshot widgets, I still have that blank space around the widget.

答:
To get the button to fill the entire space of the grid box it occupies, try setting the sticky argument of the grid() function to "NSEW":

```<code>from tkinter import *

root = Tk()
root.configure(bg = "grey")

w = Canvas(root, width = 150, height = 150, highlightthickness = 0)
w.grid(row = 1, column = 1, sticky = "NSEW")

clear_btn = Button(text = "Clear", width = 15, command = lambda: w.delete("all"))
clear_btn.grid(row = 2, column = 1, sticky  =  "NSEW")

root.mainloop()
</code>```

Before:

After:

Note: The appearance of these windows may vary slightly between operating systems and even between different visual themes on the same operating system.

Body:
I put widgets on a window with .grid and noticed that the widgets have space around them. I fixed that on canvas widget with highlightthickness but this doesn't work with button widgets. It doesn't look cool when you have grey window background and there's white space around buttons.
P.S. I use python3 on macos Sierra

root = Tk()
root.configure(bg='grey')

w = Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()

P.S. TKinter leaving borders around widgets that's what it looks like. The guy was advised to use highlightbackground, but when I screenshot widgets, I still have that blank space around the widget.

Body:
To get the button to fill the entire space of the grid box it occupies, try setting the sticky argument of the grid() function to "NSEW":

from tkinter import *

root = Tk()
root.configure(bg = "grey")

w = Canvas(root, width = 150, height = 150, highlightthickness = 0)
w.grid(row = 1, column = 1, sticky = "NSEW")

clear_btn = Button(text = "Clear", width = 15, command = lambda: w.delete("all"))
clear_btn.grid(row = 2, column = 1, sticky  =  "NSEW")

root.mainloop()

Before:

After:

Note: The appearance of these windows may vary slightly between operating systems and even between different visual themes on the same operating system.


问:
Get data from pandas into a SQL server with PYODBC
I am trying to understand how python could pull data from an FTP server into pandas then move this into SQL server.  My code here is very rudimentary to say the least and I am looking for any advice or help at all.  I have tried to load the data from the FTP server first which works fine.... If I then remove this code and change it to a select from ms sql server it is fine so the connection string works, but the insertion into the SQL server seems to be causing problems.

```<code>import pyodbc
import pandas
from ftplib import FTP
from StringIO import StringIO
import csv

ftp = FTP ('ftp.xyz.com','user','pass' )
ftp.set_pasv(True)
r = StringIO()
ftp.retrbinary('filname.csv', r.write)

pandas.read_table (r.getvalue(), delimiter=',')

connStr = ('DRIVER={SQL Server Native Client 10.0};SERVER=localhost;DATABASE=TESTFEED;UID=sa;PWD=pass')
conn = pyodbc.connect(connStr)

cursor = conn.cursor()
cursor.execute("INSERT INTO dbo.tblImport(Startdt, Enddt, x,y,z,)" "VALUES                  (x,x,x,x,x,x,x,x,x,x.x,x)")
cursor.close()
conn.commit()
conn.close()
print"Script has successfully run!"
</code>```

When I remove the ftp code this runs perfectly, but I do not understand how to make the next jump to get this into Microsoft SQL server, or even if it is possible without saving into a file first.

答: I found that using bcp utility (https://learn.microsoft.com/en-us/sql/tools/bcp-utility) works best when you have a large dataset.  I have 2.7 million rows that inserts at 80K rows/sec.  You can store your data frame as csv file (use tabs for separator if your data doesn't have tabs and utf8 encoding).  With bcp, I've used format "-c" and it works without issues so far.</p>

Body:
I am trying to understand how python could pull data from an FTP server into pandas then move this into SQL server.  My code here is very rudimentary to say the least and I am looking for any advice or help at all.  I have tried to load the data from the FTP server first which works fine.... If I then remove this code and change it to a select from ms sql server it is fine so the connection string works, but the insertion into the SQL server seems to be causing problems.

import pyodbc
import pandas
from ftplib import FTP
from StringIO import StringIO
import csv

ftp = FTP ('ftp.xyz.com','user','pass' )
ftp.set_pasv(True)
r = StringIO()
ftp.retrbinary('filname.csv', r.write)

pandas.read_table (r.getvalue(), delimiter=',')

connStr = ('DRIVER={SQL Server Native Client 10.0};SERVER=localhost;DATABASE=TESTFEED;UID=sa;PWD=pass')
conn = pyodbc.connect(connStr)

cursor = conn.cursor()
cursor.execute("INSERT INTO dbo.tblImport(Startdt, Enddt, x,y,z,)" "VALUES                  (x,x,x,x,x,x,x,x,x,x.x,x)")
cursor.close()
conn.commit()
conn.close()
print"Script has successfully run!"

When I remove the ftp code this runs perfectly, but I do not understand how to make the next jump to get this into Microsoft SQL server, or even if it is possible without saving into a file first.


问:
Microseconds in PHP
I'm accessing an API that requires a timestamp to be in microseconds, I can print the value and it works it prints this:

```<code>1295308800
</code>```

So I figured I can multiply this by 1000 and then print this but when I print the query before I send it (using CURL) it prints this:

```<code>1.2953088E+12
</code>```

Can I use a different variable type or something?

Thanks!

答:
PHP has a built-in microtime() function...

http://php.net/manual/en/function.microtime.php

Depending on exactly what you're trying to do, this may be of use to you.

Here is a StackOverflow post regarding microtime

php microseconds

If you're looking for microseconds of a specific timestamp, then check out the u Format Character here: http://no.php.net/manual/en/function.date.php

Title: Microseconds in PHP

Body:
I'm accessing an API that requires a timestamp to be in microseconds, I can print the value and it works it prints this:

1295308800

So I figured I can multiply this by 1000 and then print this but when I print the query before I send it (using CURL) it prints this:

1.2953088E+12

Can I use a different variable type or something?

Thanks!


问:
Python matching strings in list and incrementing values
I have two lists one as a global, and one as a local in a function

```<code>List1 = [[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]]

function():
    List2 = [['MP18', 100], ['MP28', 50], ['MP20', 30], ['MP07', 30], ['MP12', 10], ['MP03', 10], ['MP30', 10], ['MP14', 10], ['MP15', 5], ['MP16', 5], ['MP13', 5], ['MP02', 5], ['MP26', 5], ['MP23', 5], ['MP22 ', 5], ['MP01', 5]]

    final_list = [[[a], b+dict(List2).get(a, 0)] for [a], b in List1]
</code>```

Basically, "List2" represents scores that players have achieved in a round of a game (MP18 got 100, MP28 got 50 etc) and "List1" will be used to accumulated the scores for a number of rounds of the game for each player.

What I'm wanting to do is essentially add each players score to "List1" and the problem that I am having is that since "final_list" is within the function, everytime the function is called and produces new values for "List2", insead of adding the new values to "List1" it simply overwrites them. For example, after the first round "List1" will have the updated values for players from "List2":

```<code>['MP18', 100], ['MP28', 50] etc
</code>```

So MP18 will have 100 points and MP28 will have 50 etc. However, on the second run through of the program (second round) "List2" will have different values for each player for example:

```<code>[['MP18, 50], [MP28, 100] etc
</code>```

But because the "final_list" is being created from within the function, the first set of scores are being overwritten  by the second instead of the second being added to the first if that makes sense? so on the second run through "List1" will look like:

```<code>[[MP28, 100], [MP18, 50]
</code>```

As oppose to the desired outcome of:

```<code>[[MP28, 150], [MP18, 150]]
</code>```

Hopefully this is a bit more of a helpful explanation :D

Body:
I have two lists one as a global, and one as a local in a function

List1 = [[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]]

function():
    List2 = [['MP18', 100], ['MP28', 50], ['MP20', 30], ['MP07', 30], ['MP12', 10], ['MP03', 10], ['MP30', 10], ['MP14', 10], ['MP15', 5], ['MP16', 5], ['MP13', 5], ['MP02', 5], ['MP26', 5], ['MP23', 5], ['MP22 ', 5], ['MP01', 5]]

    final_list = [[[a], b+dict(List2).get(a, 0)] for [a], b in List1]

Basically, "List2" represents scores that players have achieved in a round of a game (MP18 got 100, MP28 got 50 etc) and "List1" will be used to accumulated the scores for a number of rounds of the game for each player.

What I'm wanting to do is essentially add each players score to "List1" and the problem that I am having is that since "final_list" is within the function, everytime the function is called and produces new values for "List2", insead of adding the new values to "List1" it simply overwrites them. For example, after the first round "List1" will have the updated values for players from "List2":

['MP18', 100], ['MP28', 50] etc

So MP18 will have 100 points and MP28 will have 50 etc. However, on the second run through of the program (second round) "List2" will have different values for each player for example:

[['MP18, 50], [MP28, 100] etc

But because the "final_list" is being created from within the function, the first set of scores are being overwritten  by the second instead of the second being added to the first if that makes sense? so on the second run through "List1" will look like:

[[MP28, 100], [MP18, 50]

As oppose to the desired outcome of:

[[MP28, 150], [MP18, 150]]

Hopefully this is a bit more of a helpful explanation :D

Body:
You can try this:

List1 = [[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]]

List2 = [['MP18', 100], ['MP28', 50], ['MP20', 30], ['MP07', 30], ['MP12', 10], ['MP03', 10], ['MP30', 10], ['MP14', 10], ['MP15', 5], ['MP16', 5], ['MP13', 5], ['MP02', 5], ['MP26', 5], ['MP23', 5], ['MP22 ', 5], ['MP01', 5]]
final_list = [[[a], b+dict(List2).get(a, 0)] for [a], b in List1]

Then, later on, multiplying the values in the list:

new_final_list = [[[a], 2*b] for [a], b in List1]

Output:

[[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]]

Edit:

Regarding your recent comment, you can try this to create a final_list outside of the function:

List1 = [[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]]

def some_function():
    List2 = [['MP18', 100], ['MP28', 50], ['MP20', 30], ['MP07', 30], ['MP12', 10], ['MP03', 10], ['MP30', 10], ['MP14', 10], ['MP15', 5], ['MP16', 5], ['MP13', 5], ['MP02', 5], ['MP26', 5], ['MP23', 5], ['MP22 ', 5], ['MP01', 5]]
    global List1
    List1 = [[[a], b+dict(List2).get(a, 0)] for [a], b in List1]


问:
Is there anyway to have a linked list of dimension? like (x, y)?
I'm trying to see if I could have a java linked list of dimensions x, y ( not using hash map and not having x and y as two separate integers)
I'm trying to store each square of a grid in a linked list for example
(0, 1) (0, 2) ..</p>

答:
You have to add some class for a dimension:

```<code>public class Dimension {
    private Integer x, y;

    public Dimension(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    // getters/setters/equals/hashCode
}
</code>```

Thus you can save dimensions into LinkedList using objects of this class:

```<code>List<Dimension> list = new LinkedList<>();
list.add(new Dimension(0, 1));
list.add(new Dimension(1, 2));
</code>```

Body:
You have to add some class for a dimension:

public class Dimension {
    private Integer x, y;

    public Dimension(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    // getters/setters/equals/hashCode
}

Thus you can save dimensions into LinkedList using objects of this class:

List<Dimension> list = new LinkedList<>();
list.add(new Dimension(0, 1));
list.add(new Dimension(1, 2));


问:
how to align 2 rows in an info box
so i have these 2 rows of text displaying in an info box....but one row has an icon and the next one doesnt. i'm not exactly sure how to align the words so that the second row without the icon is indented correctly.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed

```

it comes out like this

EDIT: also using bootstrap...if that helps

答:
If you are able to make a custom stylesheet, you should try display: flex;.

Creating container span for your text and then setting them to stand on the same line with flexbox is pretty easy then.

.alert {
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="alert alert-info">
  <i class="alert-icon-info alert-icon"><!--WARNING : remove the image, it's only there to demonstrate that it's working--><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Info_icon-72a7cf.svg/1024px-Info_icon-72a7cf.svg.png" width="20"/><!--END OF WARNING--></i>
  <span class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed <br> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed </span>
</div></code>```

See here for a complete guide : A Complete Guide to Flexbox

Title: how to align 2 rows in an info box

Body:
so i have these 2 rows of text displaying in an info box....but one row has an icon and the next one doesnt. i'm not exactly sure how to align the words so that the second row without the icon is indented correctly.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed

it comes out like this

EDIT: also using bootstrap...if that helps

Body:
If you are able to make a custom stylesheet, you should try display: flex;.

Creating container span for your text and then setting them to stand on the same line with flexbox is pretty easy then.

.alert {
  display: flex;
  align-items: center;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="alert alert-info">
  <i class="alert-icon-info alert-icon"><!--WARNING : remove the image, it's only there to demonstrate that it's working--><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Info_icon-72a7cf.svg/1024px-Info_icon-72a7cf.svg.png" width="20"/><!--END OF WARNING--></i>
  <span class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed <br> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed </span>
</div>

See here for a complete guide : A Complete Guide to Flexbox


问:
Change email on git commits?
I used to have email A as my primary, but now have email B as my primary and do not use A at all. I changed my github primary email to B, but forgot to update my .gitconfig locally, so all the patch for all of my commits still say they were created by a user with email A.

Because of this, none of my commits are logged under my "Contributions" on github.

Official github response to this is to add email A to my github account, and my Contributions will automatically be rebuilt.

However, I would like to erase email A from every platform that I can - is there a way to instead change the "commiter" of every commit I have made to email B?

答:
git filter-branch should be able to do this for you; essentially it rewrites the entire commit history of the branch with the same SHA1's.

There's an example script on Github that demonstrates how to do this; it's short, so I'm reproducing it here.

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

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
</code>```

It will be necessary to force push the filtered branch, as you've changed history on it. If anyone is sharing your branch, that will make their history and yours mismatch -- you'll need to have all your collaborators re-pull the edited branch. If they've been working on the old branch and have made commits on it, they can cherry-pick those onto the new branch.

You may want to make this easier by creating a whole new branch and updating history there, then letting everyone pull it. At that point you can all agree that this is the new master branch and work on that basis, or simply have everyone delete their copy of the old master and rename the new branch to master.

Title: Change email on git commits?

Body:
git filter-branch should be able to do this for you; essentially it rewrites the entire commit history of the branch with the same SHA1's.

There's an example script on Github that demonstrates how to do this; it's short, so I'm reproducing it here.

#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

It will be necessary to force push the filtered branch, as you've changed history on it. If anyone is sharing your branch, that will make their history and yours mismatch -- you'll need to have all your collaborators re-pull the edited branch. If they've been working on the old branch and have made commits on it, they can cherry-pick those onto the new branch.

You may want to make this easier by creating a whole new branch and updating history there, then letting everyone pull it. At that point you can all agree that this is the new master branch and work on that basis, or simply have everyone delete their copy of the old master and rename the new branch to master.


问:
Change Text Colour in Cell Based on Text in Same Cell - Word VBA
I am new to VBA so I am struggling with what seems to be quite a simple task.

I have a few lines of text in each cell in a word document. Each cell contains a category such "Science" or "Health" or one of several others. At the minute I'm actually just using a special character such as "*" or "@" for testing purposes.

I need the text colour of all text in the cell to change depending on which category is in the cell. So the txt would be e.g. green for "Science" and red for "Health".

It seems that running a macro is quickest way of making these changes (there will be over 200 such cells in my final document and colouring manually is such a waste of time). Basically, I'm struggling with first changing the colour of all the text in the cell, and secondly how to make the macro search again if the first criteria is not met. I would like 1 macro that could complete colouring for the entire document, rather than having multiple macros for each colour I need.

If you could give me some examples of VBA I could work with that would be most helpful. I'm really struggling and any help you could give will save me and my team so much time.

答:
This should perform reasonably well unless your document is huge or your keyword list is huge or both.

```<code>Sub ColorCells()

    Dim tbl As Table
    Dim rw As Row
    Dim cll As Cell
    Dim i As Long
    Dim Keywords As Variant, Colors As Variant

    'if you have more than one table, you have to look through them
    Set tbl = ThisDocument.Tables(1)

    'Make two arrays - one with keywords and the second with colors
    'where the colors are in the same position in their array as the
    'keywords are in theirs
    Keywords = Array("Science", "Health")
    Colors = Array(wdBlue, wdDarkRed)

    'Loop through every row in the table
    For Each rw In tbl.Rows
        'Loop through every cell in the row
        For Each cll In rw.Cells
            'Loop through every keyword in your array
            For i = LBound(Keywords) To UBound(Keywords)
                'if the keyword exist, change the color and stop checking
                'further keywords
                If InStr(1, cll.Range.Text, Keywords(i)) > 0 Then
                    cll.Range.Font.ColorIndex = Colors(i)
                    Exit For
                End If
            Next i
        Next cll
    Next rw

End Sub
</code>```

If you want to use custom colors instead of built in ones, change the Colors array assignment line to

```<code>Colors = Array(RGB(192, 192, 192), RGB(188, 25, 67))
</code>```

and the line where you set the color to

```<code>cll.Range.Font.TextColor.RGB = Colors(i)
</code>```

Body:
This should perform reasonably well unless your document is huge or your keyword list is huge or both.

Sub ColorCells()

    Dim tbl As Table
    Dim rw As Row
    Dim cll As Cell
    Dim i As Long
    Dim Keywords As Variant, Colors As Variant

    'if you have more than one table, you have to look through them
    Set tbl = ThisDocument.Tables(1)

    'Make two arrays - one with keywords and the second with colors
    'where the colors are in the same position in their array as the
    'keywords are in theirs
    Keywords = Array("Science", "Health")
    Colors = Array(wdBlue, wdDarkRed)

    'Loop through every row in the table
    For Each rw In tbl.Rows
        'Loop through every cell in the row
        For Each cll In rw.Cells
            'Loop through every keyword in your array
            For i = LBound(Keywords) To UBound(Keywords)
                'if the keyword exist, change the color and stop checking
                'further keywords
                If InStr(1, cll.Range.Text, Keywords(i)) > 0 Then
                    cll.Range.Font.ColorIndex = Colors(i)
                    Exit For
                End If
            Next i
        Next cll
    Next rw

End Sub

If you want to use custom colors instead of built in ones, change the Colors array assignment line to

Colors = Array(RGB(192, 192, 192), RGB(188, 25, 67))

and the line where you set the color to

cll.Range.Font.TextColor.RGB = Colors(i)


问:
Method 'Android.Support.CustomTabs.CustomTabsIntent.LaunchUrl' not found
Trying to use  Microsoft.Identity.Client v1.1.0-preview to authenticate users via Microsoft.  When I execute App.IdentityClientApp.AcquireTokenAsync, even with a try/catch around it, it terminates the app.

The android device log shows

```<code>Info 6756 MonoDroid System.MissingMethodException:
  Method 'Android.Support.CustomTabs.CustomTabsIntent.LaunchUrl' not found.
  at Android.App.Activity.n_OnResume (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <e975227ac8644a30bb0866117325de0d>:0
  at (wrapper dynamic-method) System.Object:40d0e467-e2e5-447f-a0b5-87cb60ce49a7 (intptr,intptr)
</code>```

If you try to just build in Release mode, it won't.  It has a similar error in the output window.

```<code>Mono.Linker.MarkException:
Error processing method: 'System.Void Microsoft.Identity.Client.AuthenticationActivity::OnResume()' in assembly:
 'Microsoft.Identity.Client.dll' ---> Mono.Cecil.ResolutionException:
  Failed to resolve System.Void
  Android.Support.CustomTabs.CustomTabsIntent::LaunchUrl(Android.App.Activity,Android.Net.Uri)
</code>```

Does anyone know if they have just abandoned this code, or better yet, any idea how to make it work?  It use to work for iOS, but now even that has some issues after the login process is complete.

答:
I recently had a bad experience with Microsoft.Identity.Client on Android, please pay attention to the next things:

Use the latest nightly build instead of preview version

Ensure you meet all the requirements: Android Lollipop+ & Google Chrome is installed

Follow the official guide carefully

Follow the github project page, I found most of the solutions there

It seems like there is a problem with a custom URL scheme in the manifest, so I would recheck it first.

Body:
Trying to use  Microsoft.Identity.Client v1.1.0-preview to authenticate users via Microsoft.  When I execute App.IdentityClientApp.AcquireTokenAsync, even with a try/catch around it, it terminates the app.

The android device log shows

Info 6756 MonoDroid System.MissingMethodException:
  Method 'Android.Support.CustomTabs.CustomTabsIntent.LaunchUrl' not found.
  at Android.App.Activity.n_OnResume (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <e975227ac8644a30bb0866117325de0d>:0
  at (wrapper dynamic-method) System.Object:40d0e467-e2e5-447f-a0b5-87cb60ce49a7 (intptr,intptr)

If you try to just build in Release mode, it won't.  It has a similar error in the output window.

Mono.Linker.MarkException:
Error processing method: 'System.Void Microsoft.Identity.Client.AuthenticationActivity::OnResume()' in assembly:
 'Microsoft.Identity.Client.dll' ---> Mono.Cecil.ResolutionException:
  Failed to resolve System.Void
  Android.Support.CustomTabs.CustomTabsIntent::LaunchUrl(Android.App.Activity,Android.Net.Uri)

Does anyone know if they have just abandoned this code, or better yet, any idea how to make it work?  It use to work for iOS, but now even that has some issues after the login process is complete.


问:
fatal: Could not read from remote repository.; because of static machine login
I cannot push to my git repo on bitbucket. My url is set correctly, I have the ssh key in the account, and the permissions are fine.

I have the following output when I run ssh -vvv git@bitbucket.com:

```<code>debug2: channel 0: input open -> closed
debug3: channel 0: will not send data after close
logged in as servandoavila1.

You can use git or hg to connect to Bitbucket. Shell access is disabled.
debug3: channel 0: will not send data after close
debug2: channel 0: obuf empty
debug2: channel 0: close_write
debug2: channel 0: output drain -> closed
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug3: send packet: type 97
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1)

debug3: send packet: type 1
Connection to bitbucket.com closed.
Transferred: sent 3508, received 1836 bytes, in 0.2 seconds
Bytes per second: sent 22807.7, received 11937.0
debug1: Exit status 0
</code>```

Then

```<code>cchilders@cchilders-Latitude-E7240:~/projects/foodtruck-remake$ git push
repository access denied.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

It seems I'm still logged in as my friend on the machine, servandoavila1. But I recently fixed the global user.email/user.name of git. How can I push to this repo?

答:
The output you've posted here from ssh -vvv git@bitbucket.com (nit: use .org) suggests you're authenticating as your friend. The git committer name and email are for git's internal tracking mechanisms, not for authenticating to remote systems, so you're still trying to push as your friend - and it looks like s/he doesn't have access to that repo.

You have a couple options here:

Give your friend write access to that repo

Set up a separate SSH keypair on that system; associate it with your Bitbucket user; and update your git remotes to use your username instead of your friend's or "git" (e.g. git remote set-url origin username@bitbucket.org:owner/repo.git)

Use HTTPS (e.g. git remote set-url origin https://username@bitbucket.org/owner/repo.git)

ContentLicense: CC BY-SA 4.0

Body:
I cannot push to my git repo on bitbucket. My url is set correctly, I have the ssh key in the account, and the permissions are fine.

I have the following output when I run ssh -vvv git@bitbucket.com:

debug2: channel 0: input open -> closed
debug3: channel 0: will not send data after close
logged in as servandoavila1.

You can use git or hg to connect to Bitbucket. Shell access is disabled.
debug3: channel 0: will not send data after close
debug2: channel 0: obuf empty
debug2: channel 0: close_write
debug2: channel 0: output drain -> closed
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug3: send packet: type 97
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1)

debug3: send packet: type 1
Connection to bitbucket.com closed.
Transferred: sent 3508, received 1836 bytes, in 0.2 seconds
Bytes per second: sent 22807.7, received 11937.0
debug1: Exit status 0

Then

cchilders@cchilders-Latitude-E7240:~/projects/foodtruck-remake$ git push
repository access denied.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

It seems I'm still logged in as my friend on the machine, servandoavila1. But I recently fixed the global user.email/user.name of git. How can I push to this repo?


问:
Drive.comments.list(fileId).items.length doesn't seem to count correctly
Just found something peculiar in the Drive Comments API. Not sure if its user error or an issue in the API.

In my main() Logger is putting the length of comments as 20. I go back into my document and create another comment. Logger still puts length of comments items as 20.

Thanks in advance.

```<code>function main() {
  var fileId = getFileId();
  var fileComments = getComments(fileId);
  Logger.log(fileComments.items.length); // this always says 20
}
function getFileId() {
  return DocumentApp.getActiveDocument().getId();
}
function getComments(fileId) {
  return Drive.Comments.list(fileId);
  //Logger.log(cmnts.items.length);
}
</code>```

答: Just read further on the drive comments list reference and the default page size is 20 per page. https://developers.google.com/drive/v3/reference/comments/list</p>

Body:
Just found something peculiar in the Drive Comments API. Not sure if its user error or an issue in the API.

In my main() Logger is putting the length of comments as 20. I go back into my document and create another comment. Logger still puts length of comments items as 20.

Thanks in advance.

function main() {
  var fileId = getFileId();
  var fileComments = getComments(fileId);
  Logger.log(fileComments.items.length); // this always says 20
}
function getFileId() {
  return DocumentApp.getActiveDocument().getId();
}
function getComments(fileId) {
  return Drive.Comments.list(fileId);
  //Logger.log(cmnts.items.length);
}


问:
Binding a Combobox control to a separate source within a DataGrid
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

```<code><my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>
</code>```

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

答:
This is what I ended up with in my little test project, Ill be adapting this for use in the proper code.</p>

```<code><Grid>
    <Controls:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
        <Controls:DataGrid.Columns>
            <Controls:DataGridTemplateColumn Header="SomeHeader">
                <Controls:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding TTYPE_NAME}" />
                    </DataTemplate>
                </Controls:DataGridTemplateColumn.CellTemplate>
                <Controls:DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox DisplayMemberPath="TTYPE_NAME"
                            SelectedValuePath="TERMINAL_TYPE_ID"
                            SelectedValue="{Binding TERMINAL_TYPE_ID}"
                            ItemsSource="{Binding DataContext.TerminalTypes,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Controls:DataGrid}}" />
                    </DataTemplate>
                </Controls:DataGridTemplateColumn.CellEditingTemplate>
            </Controls:DataGridTemplateColumn>
        </Controls:DataGrid.Columns>
    </Controls:DataGrid>
</Grid>
</code>```

Body:
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

<my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

Body:
This is what I ended up with in my little test project, Ill be adapting this for use in the proper code.

<Grid>
    <Controls:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
        <Controls:DataGrid.Columns>
            <Controls:DataGridTemplateColumn Header="SomeHeader">
                <Controls:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding TTYPE_NAME}" />
                    </DataTemplate>
                </Controls:DataGridTemplateColumn.CellTemplate>
                <Controls:DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox DisplayMemberPath="TTYPE_NAME"
                            SelectedValuePath="TERMINAL_TYPE_ID"
                            SelectedValue="{Binding TERMINAL_TYPE_ID}"
                            ItemsSource="{Binding DataContext.TerminalTypes,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Controls:DataGrid}}" />
                    </DataTemplate>
                </Controls:DataGridTemplateColumn.CellEditingTemplate>
            </Controls:DataGridTemplateColumn>
        </Controls:DataGrid.Columns>
    </Controls:DataGrid>
</Grid>


问:
Google Sheets Scripts Number Decimal Place Fomatting
Using Google Sheets Script Editor, I am trying to create a custom function that can help me format a number string with a certain amount of decimal places. I need the string to be a number type so that the data can be charted.

The reason I need this function is because I have a in-cell dropdown that triggers the displays different sets of numbers with different decimal places within a cell. Therefore, I cannot rely on the static number formatting settings within Sheets.

While this returns the number of decimal places I want...

```<code>function format(amt) { return amt.toFixed(2); }
</code>```

toFixed() creates a text string, therefore the value cannot be used for charting (the chart will say "No Data").

I have tried the following alternatives...

```<code>return parseFloat(amt); // var = number; can chart but cannot control decimal places
return parseFloat(amt).toFixed(2); //var = string; cannot chart
return parseInt(amt).toFixed(2); //var = string; cannot chart
</code>```

Can anyone let me know if there is a way to create a custom function that lets me control the number of decimal places I want while keepign it as a number string?

答:
```<code>function format(x, n){
    x = parseFloat(x);
    n = n || 2;
    return parseFloat(x.toFixed(n))
}
</code>```

Basically you need to parse the value after the toFixed() method is called, but you're parsing it before the toFixed() method is called.

With the above function you can say format(amt) to get 2 decimal places, or format(2, n) to get n decimal places

Body:
Using Google Sheets Script Editor, I am trying to create a custom function that can help me format a number string with a certain amount of decimal places. I need the string to be a number type so that the data can be charted.

The reason I need this function is because I have a in-cell dropdown that triggers the displays different sets of numbers with different decimal places within a cell. Therefore, I cannot rely on the static number formatting settings within Sheets.

While this returns the number of decimal places I want...

function format(amt) { return amt.toFixed(2); }

toFixed() creates a text string, therefore the value cannot be used for charting (the chart will say "No Data").

I have tried the following alternatives...

return parseFloat(amt); // var = number; can chart but cannot control decimal places
return parseFloat(amt).toFixed(2); //var = string; cannot chart
return parseInt(amt).toFixed(2); //var = string; cannot chart

Can anyone let me know if there is a way to create a custom function that lets me control the number of decimal places I want while keepign it as a number string?

Body:
function format(x, n){
    x = parseFloat(x);
    n = n || 2;
    return parseFloat(x.toFixed(n))
}

Basically you need to parse the value after the toFixed() method is called, but you're parsing it before the toFixed() method is called.

With the above function you can say format(amt) to get 2 decimal places, or format(2, n) to get n decimal places


问:
Ruby on rails - unable to create comments. NoMethodError
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

```<code>class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
</code>```

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

```<code>class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end
</code>```

Below is the form for section from the show.html.erb for the forum page

```<code><h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>
</code>```

And this is the error from rails:

```<code>undefined method `comment' for #<Forum:0x444d518>
</code>```

with the following extract:

```<code>end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end
</code>```

答:
Looks like you may be missing a has_many :comments association in your Forum model.  Check it out.

Alternatively if the has_many association exits then it allows you to call 'comments' on any Forum object, not 'comment'.

if you want to create a comment for a particular forum you can do so like this:

```<code>@comment = Comment.create(comment_params) #create a comment associated with this forum.
</code>```

Body:
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end

Below is the form for section from the show.html.erb for the forum page

Comments

<% @forum.comments.each do |comment| %>

    <%= comment.body %>

<% end %>

Add a comment

<%= form_for([@forum, @forum.comments.build]) do |f| %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

And this is the error from rails:

undefined method `comment' for #<Forum:0x444d518>

with the following extract:

end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end

Body:
Looks like you may be missing a has_many :comments association in your Forum model.  Check it out.

Alternatively if the has_many association exits then it allows you to call 'comments' on any Forum object, not 'comment'.

if you want to create a comment for a particular forum you can do so like this:

@comment = Comment.create(comment_params) #create a comment associated with this forum.


问:
How to use long file names on Teensy/Arduino SD Card Reader
Does anyone know if there is a way to get Arduino SD card readers to work with long files names (bigger than the 8.3 filename format)? I am currently trying read files from a Teensy 3.5 using the standard Arduino SD card library, and the file fails to open whenever I use longer file names. Is this an inherent hardware limitation, or is it simply a software limitation? If I could implement this, it would greatly simplify my code and would improve the user experience significantly.</p>

答: I figured it out...I looked into the "SD.h" Arduino library noticed that the library is only designed for small file names since many of the array declarations specifically limit the name of the file size(e.g. char _name[13]). I found that using the "SdFat.h" library works with large filenames and completely solved my problem.</p>


问:
cmake replace string in custom target
I want to have a cmake target that updates a specific file.
I tried following but it seems that I cannot put all what I want into a custom target.

```<code>ADD_CUSTOM_TARGET(update
            file(READ "file.h" myFile)
            string(REPLACE "originalString" "newString" myFile"${myFile}"))
            )
</code>```

I'm quite new to cmake so I may be missing something basic. How could I update the file on request ?

答:
What I personally use for this type of problem is use configure_file. Essentially, you can make what you consider a template file and wrap variable names in the files.

```<code>Example.h.template
Here is my @VAR@
</code>```

Then if you have VAR defined in your CMake project, it will replace VAR in your destination.

```<code>configure_file(<input> <output> NEWLINE_STYLE WIN32)
</code>```

If input (your template) is modified, CMake will be re-run to keep your file up to date. So in your cmake you can

```<code>set(VAR "program")
configure_file("Path/To/Example.h.template" "Path/To/File.h" NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF])
</code>```

The result should be:

```<code>File.h
Here is my program
</code>```

Title: cmake replace string in custom target

Body:
I want to have a cmake target that updates a specific file.
I tried following but it seems that I cannot put all what I want into a custom target.

ADD_CUSTOM_TARGET(update
            file(READ "file.h" myFile)
            string(REPLACE "originalString" "newString" myFile"${myFile}"))
            )

I'm quite new to cmake so I may be missing something basic. How could I update the file on request ?

Body:
What I personally use for this type of problem is use configure_file. Essentially, you can make what you consider a template file and wrap variable names in the files.

Example.h.template
Here is my @VAR@

Then if you have VAR defined in your CMake project, it will replace VAR in your destination.

configure_file(<input> <output> NEWLINE_STYLE WIN32)

If input (your template) is modified, CMake will be re-run to keep your file up to date. So in your cmake you can

set(VAR "program")
configure_file("Path/To/Example.h.template" "Path/To/File.h" NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF])

The result should be:

File.h
Here is my program


问:
How to display Table in README.md file in Github?
I want to display a table in readme.md file. I read GitHub Flavored Markdown and followed what it said. So this is my table:

```<code>| Attempt | #1 | #2 | #3 | #4 | #5 | #6 | #7 | #8 | #9 | #10 | #11 | #12 |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| Seconds | 301 | 283 | 290 | 286 | 289 | 285 | 287 | 287 | 272 | 276 | 269 | 254 |
</code>```

However, I don't see any table and result looks like:

答:
I use the Markdown Table tool (https://www.tablesgenerator.com/markdown_tables) that helps me to import data from csv or convert my html tables into Markdown which I can simply copy it into my README.md file and it's a real timesaver for me.

I generally write things that I'm going to publish on my README file on excel file and save it as csv and import into this tool and copy paste the Generated Markdown and it creates a table that its decent for others to read your instructions.

Hope that helps.

Body:
I want to display a table in readme.md file. I read GitHub Flavored Markdown and followed what it said. So this is my table:

| Attempt | #1 | #2 | #3 | #4 | #5 | #6 | #7 | #8 | #9 | #10 | #11 | #12 |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| Seconds | 301 | 283 | 290 | 286 | 289 | 285 | 287 | 287 | 272 | 276 | 269 | 254 |

However, I don't see any table and result looks like:


问:
SQL INTERSECT by one field and get another field
I'm trying to do this SQL query:

```<code> SELECT field FROM table
 INTERSECT
 SELECT field FROM table
</code>```

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

答:
```<code>SELECT anotherField
FROM table b
JOIN table1 a ON a.field=b.field
</code>```

Body:
I'm trying to do this SQL query:

 SELECT field FROM table
 INTERSECT
 SELECT field FROM table

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?


问:
What approach should I use in mysql database designing that includes more than billion of rows to find particular value using minimum of time?
I have a Django project where I have to solve the following task: client paste the phone number to the search field and application returns full address. If there is no requested address in database, it should be added to another database table of unknown numbers. So, when admin uploads the list of number-address pairs, application should check if everey number exists in database table of unknown numbers. And if exists - it should be removed. This database after some time will contain more than billion rows. My approach is to create two database tables: first - the main table with two columns: "number" and "address". For the column "number" I provide indexation for the faster searching for address. And second one - table with unknown numbers where will be single column "number" which also should be indexed. So, asking for help of experts: do I think right? Or what approach should be the best to solve this task?

I can not ask you for deep answer, I just need to which direction I should move on.

Thank you very much. I will be happy for any kind of help (comments, links etc).

答:
number should be the PRIMARY KEY in each of your tables.  This will make "billion rows" not-a-problem.

Two somewhat simple SQL statements can perform the maintenance you describe very rapidly.


问:
Can i post a task to a specific location in a project through asana API?
I'm trying to post a task within a project under a certain section, does anyone have any suggestions as to go about doing it/ is it even possible?

Thanks

答:
To POST a new task to a project in a specific section (column) hit the workspace URL

https://app.asana.com/api/1.0/workspaces/[workspace-id]/tasks

You need to declare the memberships property in your POST request, the API documentation makes this very confusing.

Here is how it should be:

"memberships": [{
  "project": 12345,
  "section": 12345
}]

The API documentation makes it seem like you need to also include the name that goes along with the project and section.

Here is their example from the docs which is NOT how it should be done:

[{ project: { id: 1331, name: 'Bugs' }, section: { id: 1123, name: 'P1:' } }]

I found this answer here: https://community.asana.com/t/how-create-task-with-membership-via-api/10481/2


问:
Install Angular Material 2 with Angular 4 Unmet Dependency
How do I get Angular Material 2 to work with Angular 4?

I re-installed Angular CLI and now it is at 1.0.0 using: npm install -g @angular/cli

I created a new Angular 4 project using:  ng new MyProject

I tried to install Material 2 but it failed using: npm install --save @angular/material

+-- UNMET PEER DEPENDENCY @angular/common@4.0.0

+-- UNMET PEER DEPENDENCY @angular/core@4.0.0

+-- UNMET PEER DEPENDENCY @angular/http@4.0.0

-- @angular/material@2.0.0-beta.2

Here is what I get when I do a ng -v for the project:
@angular/cli: 1.0.0

node: 6.10.0

os: win32 x64

@angular/common: 4.0.0

@angular/compiler: 4.0.0

@angular/core: 4.0.0

@angular/forms: 4.0.0

@angular/http: 4.0.0

@angular/material: 2.0.0-beta.2

@angular/platform-browser: 4.0.0

@angular/platform-browser-dynamic: 4.0.0

@angular/router: 4.0.0

@angular/cli: 1.0.0

@angular/compiler-cli: 4.0.0

答:
This question is kind of old but I stumbled upon it as I was just getting to work Angular with Material.

Installing the latest version of material2 will make it depend on Angular 5. If you want to get it to work with Angular 4 you can install the latest version before the breaking change:

```<code>npm install --save @angular/material@2.0.0-beta.12 @angular/cdk@2.0.0-beta.12
</code>```

Body:
This question is kind of old but I stumbled upon it as I was just getting to work Angular with Material.

Installing the latest version of material2 will make it depend on Angular 5. If you want to get it to work with Angular 4 you can install the latest version before the breaking change:

npm install --save @angular/material@2.0.0-beta.12 @angular/cdk@2.0.0-beta.12


问:
Is there built-in support for enabling SSL on Azure Container Instances?
Is there built-in support for enabling SSL on Azure Container Instances? If not, can we hook up to SSL providers like Lets Encrypt?</p>

答: There is nothing built-in today. You need to load the certs into the container and terminate SSL there. Soon, we will enable support for ACI containers to join an Azure virtual network, at which point you could front your containers with Azure Application Gateway and terminate SSL there.</p>


问:
How to find very bad result considering standards?
I have a data about air quality. Each attributes related to cocentration of it.
So, question is:

How to find very bad row with consedering Air Quality Standarts?

Is it Correlation coefficient? Or Could you give me any advice about formula?

答:
There is no mathematical answer to this.

It's a matter of what you define as bad.

High O2 levels are good (well, at least as high as we realistically can get. 100% O2 would cause a lot of damage), high O3 however is bad (Ozone) in the lower air layers (but you do want the protective Ozone layer). Don't expect any algorithm to figure out that O2 is good, and O2 is bad, in that particular task...


问:
Searchkick: import scope with group clause
I'm trying to group page fragments by kind and aggregate html content.
Here is how my search import scope looks like:

```<code>scope :search_import, -> {
  select("kind, string_agg(html_content, '\r\n') AS html_content")
  .group(:kind)
}
</code>```

When I attempt to reindex records searchkick uses find_in_batches which automatically sets the order to ascending on the primary key to make the batch ordering work. This leads me to the following error: column "page_fragments.id" must appear in the GROUP BY clause or be used in an aggregate function.

Clearly, I can't add id to the group clause and I've tried to workaround this by adding id aggregation to the select: COUNT (*) AS id. However, a clear indication of a primary key "page_fragments"."id" in the order clause misses the alias.

The question is what possibly can be done? Looks like a dead end.

答:
What is it you're trying to do with your search_import scope? The searchkick docs state that it is intended to scope the records which you want to index, and thus should return an ActiveRecord::Relation, not a group hash.

Searchkick uses find_in_batches to import documents. To eager load
  associations, use the search_import scope.

...

By default, all records are indexed. To control which records are
  indexed, use the should_index? method together with the search_import
  scope.

Body:
I'm trying to group page fragments by kind and aggregate html content.
Here is how my search import scope looks like:

scope :search_import, -> {
  select("kind, string_agg(html_content, '\r\n') AS html_content")
  .group(:kind)
}

When I attempt to reindex records searchkick uses find_in_batches which automatically sets the order to ascending on the primary key to make the batch ordering work. This leads me to the following error: column "page_fragments.id" must appear in the GROUP BY clause or be used in an aggregate function.

Clearly, I can't add id to the group clause and I've tried to workaround this by adding id aggregation to the select: COUNT (*) AS id. However, a clear indication of a primary key "page_fragments"."id" in the order clause misses the alias.

The question is what possibly can be done? Looks like a dead end.


问:
npm (5.4.*) module - How to disable node_modules removal if not defined in package.json
I am using npm versioned 5.4.2, I have some node_modules, now from 3.x npm module behavior is if the modules inside node_modules directory are not defined in package.json, then npm deletes the modules in node_modules.

how to override this behavior, like I do not want to remove the npm modules already installed even if they are not defined in package.json

If new module is added using "npm install", I do not want to overwrite package.json file.

How to achieve this? Is there any flag in .npmrc?

With regards,

-M-

答:
Not the answer, but still... :  https://github.com/npm/npm/issues/16853

npm install package --no-save


问:
How to set different color of text for the legends using core plot
I am using core plot to for drawing the graph. My problem is i want to set the legends text color according to line color. I have four scatter plot in one graph, each scatter plot is having different line color.

In the legends it will show line color correctly but i want to change the text color according to line color for each scatter graph title. I have written the following code for the legend.

```<code>newGraph.legend = CPTLegend(graph: newGraph)
        newGraph.legend?.numberOfRows = UInt(2.0)
        let dataSourceLabelStyle = CPTMutableTextStyle()
        dataSourceLabelStyle.color = CPTColor.white()
        newGraph.legend?.textStyle       = dataSourceLabelStyle
        newGraph.legend?.fill = CPTFill(color: CPTColor.init(componentRed: 50/244, green: 43/244, blue: 87/244, alpha: 1.0))
        newGraph.legend?.cornerRadius = 5.0
        newGraph.legendDisplacement = CGPoint.init(x: -50, y: 210)
        let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
        fadeInAnimation.duration            = 1.0
        fadeInAnimation.isRemovedOnCompletion = false
        fadeInAnimation.fillMode            = kCAFillModeForwards
        fadeInAnimation.toValue             = 1.0
        dataSourceLinePlot.add(fadeInAnimation, forKey: "animateOpacity")
        self.scatterGraph = newGraph
</code>```

as form the above code it is seen that legends can take only one style i.e newGraph.legend?.textStyle       = dataSourceLabelStyle so all the text in the legends is of white color.

I want to change the legends text color also according to line color.

Can any body help me with this.

答:
Do not think it is possible cause you set the legend for the graph and graph contains all your plots. Here is how I am using it in ObjC though:</p>

```<code>CPTScatterPlot *aPlot = [[CPTScatterPlot alloc] init];
    aPlot.dataSource = self;
    aPlot.identifier = stringPlotId;
    [graph addPlot:aPlot toPlotSpace:plotSpace];
 aPlot.title=stringPlotTitle;//will show in legends

 //add more plots if needed then format labels text once for all plots

graph.legend= [CPTLegend legendWithGraph:graph];
CPTMutableTextStyle *mySmallerTextStyle = [[CPTMutableTextStyle alloc] init];
[mySmallerTextStyle setFontSize:8];
mySmallerTextStyle.color=[CPTColor whiteColor];
[graph.legend setTextStyle:(CPTTextStyle *)mySmallerTextStyle];
</code>```

Body:
I am using core plot to for drawing the graph. My problem is i want to set the legends text color according to line color. I have four scatter plot in one graph, each scatter plot is having different line color.

In the legends it will show line color correctly but i want to change the text color according to line color for each scatter graph title. I have written the following code for the legend.

newGraph.legend = CPTLegend(graph: newGraph)
        newGraph.legend?.numberOfRows = UInt(2.0)
        let dataSourceLabelStyle = CPTMutableTextStyle()
        dataSourceLabelStyle.color = CPTColor.white()
        newGraph.legend?.textStyle       = dataSourceLabelStyle
        newGraph.legend?.fill = CPTFill(color: CPTColor.init(componentRed: 50/244, green: 43/244, blue: 87/244, alpha: 1.0))
        newGraph.legend?.cornerRadius = 5.0
        newGraph.legendDisplacement = CGPoint.init(x: -50, y: 210)
        let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
        fadeInAnimation.duration            = 1.0
        fadeInAnimation.isRemovedOnCompletion = false
        fadeInAnimation.fillMode            = kCAFillModeForwards
        fadeInAnimation.toValue             = 1.0
        dataSourceLinePlot.add(fadeInAnimation, forKey: "animateOpacity")
        self.scatterGraph = newGraph

as form the above code it is seen that legends can take only one style i.e newGraph.legend?.textStyle       = dataSourceLabelStyle so all the text in the legends is of white color.

I want to change the legends text color also according to line color.

Can any body help me with this.

Body:
Do not think it is possible cause you set the legend for the graph and graph contains all your plots. Here is how I am using it in ObjC though:

CPTScatterPlot *aPlot = [[CPTScatterPlot alloc] init];
    aPlot.dataSource = self;
    aPlot.identifier = stringPlotId;
    [graph addPlot:aPlot toPlotSpace:plotSpace];
 aPlot.title=stringPlotTitle;//will show in legends

 //add more plots if needed then format labels text once for all plots

graph.legend= [CPTLegend legendWithGraph:graph];
CPTMutableTextStyle *mySmallerTextStyle = [[CPTMutableTextStyle alloc] init];
[mySmallerTextStyle setFontSize:8];
mySmallerTextStyle.color=[CPTColor whiteColor];
[graph.legend setTextStyle:(CPTTextStyle *)mySmallerTextStyle];


问:
static variables in c
Static variables when declared in a file cannot be accessed from outside the file.
But if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?

答: Think of variable names of static and external linkage as addresses like "maddy's house" and "123 foo street", respectively. The former is only meaningful to people who know you, while the latter is meaningful to others as well due to an established convention. But even if "maddy's house" doesn't have a street address, it still has a latitude and longitude you could give to somebody who wants to fire a missile at it. :-)

OwnerDisplayName: maddy

Title: static variables in c


问:
can I post data to my server directly instead of firebase
I am considering firebase for an app - mainly for the real-time but other features like the analytics and authentication (and price) are other bonuses.

I have my own database and I want everything saved in there. Firebase will have a small portion of the dataset I push as it's needed.

So I'm basically thinking that the firebase data will be read only to the users.  If a user comments, that will actually go to my server, I'll authenticate, clean, whatever.. and push to the that feed.

Are there problems with this approach?  Are there other (better) ways to solve the problem?

答: This is a completely valid approach. Firebase is designed so you can use specific features that suit your needs. </p>


问:
jQuery: Replace every char on page with an image
Need your help, maybe just tunnel-vision right now.

I just want to replace every occurrence of a special character with an image using jQuery. Can't be that hard, can it?

I found several questions and I've been through them, but maybe I'm just missing something.

In that case, I'll try to replace every dot . with an image from an external resource (which is accessible) regardless of it's container. It doesn't make a difference if it is in a
 or
 or even just standing alone.

```<code>$("body").html().replace('/\./g', "<img src='my external image link'>");
</code>```

Shouldn't that just do it?

答:
You need to re-assign the string you are building from the body's HTML.

Something like

```<code>let newHtml = $("body").html().replace(/\./g, "<img src='my external image link'>");
$('body').html(newHtml);
</code>```

However, I'd be careful with replacing the '.'-character in the entire HTML, as it can be valid content of e.g. URLs in anchors. But I'm sure you thought about that already :)

Edit: Fixed RegEx-syntax. You should leave away the single-quotes around the RegEx.

Body:
Need your help, maybe just tunnel-vision right now.

I just want to replace every occurrence of a special character with an image using jQuery. Can't be that hard, can it?

I found several questions and I've been through them, but maybe I'm just missing something.

In that case, I'll try to replace every dot . with an image from an external resource (which is accessible) regardless of it's container. It doesn't make a difference if it is in a
 or
 or even just standing alone.

$("body").html().replace('/\./g', "");

Shouldn't that just do it?

Body:
You need to re-assign the string you are building from the body's HTML.

Something like

let newHtml = $("body").html().replace(/\./g, "<img src='my external image link'>");
$('body').html(newHtml);

However, I'd be careful with replacing the '.'-character in the entire HTML, as it can be valid content of e.g. URLs in anchors. But I'm sure you thought about that already :)

Edit: Fixed RegEx-syntax. You should leave away the single-quotes around the RegEx.


问:
Disabled caching for a WordPress shortcode?
Preface: I have developed a plugin, so editing theme files is out of the question.

My shortcode function:

```<code>/*** [leaderboard] shortcode with tournament_id input value ***/
function leaderboard_shortcode( $tournamentid ) {
    ob_start();
    include_once dirname( __FILE__ ) . '/leaderboard.php';
    $output = ob_get_clean();
    return $output;
}
add_shortcode( 'golf-deputy-leaderboard', 'leaderboard_shortcode' );
</code>```

I tried adding in  to relevant pages, however, if the shortcode is added to a page not controlled by the plugin - e.g. the home page - , the shortcode caches.

I guess my question is this: what options do I have to NOT cache the content of the shortcode, even if the page it is placed on, has caching enabled.

I have been racking my brain, the internetz, the WordPress Codex... all to no avail. I am open to any and all suggestions. Help me Stackoverflow, you're my only hope.

答:
Cache functions start working before all possible filers&actions, and as shortcodes run inside the_content filter, it is impossible not to cache a shortcode only. I mean, when WP returns cached data, it returns static HTML data, no any theme&plugin's PHP runs in that case.

You need add that page (which has a shortcode in its content) to exclude list of your plugin. All popular cache plugins have such exclude field inside their settings.

Or another way is building custom cache solution which simply ignores caching then the_content contains any shortcode.

Body:
Preface: I have developed a plugin, so editing theme files is out of the question.

My shortcode function:

/*** [leaderboard] shortcode with tournament_id input value ***/
function leaderboard_shortcode( $tournamentid ) {
    ob_start();
    include_once dirname( __FILE__ ) . '/leaderboard.php';
    $output = ob_get_clean();
    return $output;
}
add_shortcode( 'golf-deputy-leaderboard', 'leaderboard_shortcode' );

I tried adding in  to relevant pages, however, if the shortcode is added to a page not controlled by the plugin - e.g. the home page - , the shortcode caches.

I guess my question is this: what options do I have to NOT cache the content of the shortcode, even if the page it is placed on, has caching enabled.

I have been racking my brain, the internetz, the WordPress Codex... all to no avail. I am open to any and all suggestions. Help me Stackoverflow, you're my only hope.


问:
Prevent developers from unintentionally killing daemon / worker processes on local machine
A lot of newbs will kill all their node.js processes on their local machines with

```<code>pkill -f node
</code>```

Or

```<code>killall node
</code>```

Etc.

I have a library that uses some daemon processes/workers running on the developer's machine and I will need to restart them if the development "accidentally" kills (all) node.js processes.

The problem is that using NPM libs like forever  or supervisor will not solve this problem because they are node.js processes as well TMK.

Can anyone recommend a daemon watcher / relauncher system that will work on MacOS or *nix?

Perhaps supervisord can do what I want to do on both MacOS and *nix? Or perhaps there is another solution to this problem?

答: I wrote node-windows, node-mac, and node-linux for this purpose. They are essentially wrappers around node processes, but all three libraries share a common API for managing things like restarts/stop/start/etc.</p>

Body:
A lot of newbs will kill all their node.js processes on their local machines with

pkill -f node

Or

killall node

Etc.

I have a library that uses some daemon processes/workers running on the developer's machine and I will need to restart them if the development "accidentally" kills (all) node.js processes.

The problem is that using NPM libs like forever  or supervisor will not solve this problem because they are node.js processes as well TMK.

Can anyone recommend a daemon watcher / relauncher system that will work on MacOS or *nix?

Perhaps supervisord can do what I want to do on both MacOS and *nix? Or perhaps there is another solution to this problem?


问:
How to get DropDownList selected Text in MVC controller
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

```<code> @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })
</code>```

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

```<code>detailsConfig.Project = Convert.ToString(form["Project"]);
</code>```

For example:
If the dropdownlist values are

```<code>Project     ID
test        1
testagain   2
</code>```

In controller I should get test, not 1. Please help

答:
First, you should definitely strongly-type your dropdownlist to your model.

What I mean is this...

In the controller is where I would create the selectlist to be used in the view.

Controller

```<code>ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");
</code>```

Disclaimer:

Submitting the Text value is not preferred because typically the Text value of the select element is not unique.  Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want.  This is the best way to get the most accurate and reliable data.

Then in your view, strongly-type your ProjectSelection selectlist to the Project property in your model.

View

```<code>@Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, @class = "form-control" })
</code>```

Why are you declaring required in the dropdownlist?  That should be declared in your model.

Explanation

In MVC, when it comes to HTML elements where the user can select options to be submitted to the server (dropdownlist, listbox, etc).. only the Value will be submitted (which in your case was the ID).  The Text portion of the element is just for the user to see to make their selection's easier.

Let me know if this helps!

Body:
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

 @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

detailsConfig.Project = Convert.ToString(form["Project"]);

For example:
If the dropdownlist values are

Project     ID
test        1
testagain   2

In controller I should get test, not 1. Please help

Body:
First, you should definitely strongly-type your dropdownlist to your model.

What I mean is this...

In the controller is where I would create the selectlist to be used in the view.

Controller

ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");

Disclaimer:

Submitting the Text value is not preferred because typically the Text value of the select element is not unique.  Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want.  This is the best way to get the most accurate and reliable data.

Then in your view, strongly-type your ProjectSelection selectlist to the Project property in your model.

View

@Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, @class = "form-control" })

Why are you declaring required in the dropdownlist?  That should be declared in your model.

Explanation

In MVC, when it comes to HTML elements where the user can select options to be submitted to the server (dropdownlist, listbox, etc).. only the Value will be submitted (which in your case was the ID).  The Text portion of the element is just for the user to see to make their selection's easier.

Let me know if this helps!


问:
TempData not displaying success message Asp.net MVC
I'm using tempdata to give user a "success message" before redirection however at the moment it just redirect without giving the message. Maybe I have it at wrong place, I tried moving it to different parts of the code but it still didn't work.

Index View

```<code>    @{
    ViewBag.Title = "Home Page";
}
@if (TempData["notice"] != null)
{
    <p>@TempData["notice"]</p>
}

<div>
    <img src="~/Content/Images/TWO_Logo.jpg" alt="Logo" />
</div>
<div class="jumbotron">
    <h1></h1>
    <p class="lead">
</div>
</code>```

Home Controller

```<code>namespace com.twcl.it.isms.Controllers
{
    [Authorize(Roles = "Administrator, Issue, Transaction_Edit, Print")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
TempData["notice"] = "Your item(s) successfully requested";
            ViewBag.SuccessMessage = TempData["SuccesMeassge"];

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Logoff()
        {
            HttpContext.Session.Abandon();
            Response.Redirect("http://192.168.5.127");
            //Response.StatusCode = 401;
            //Response.End();
            //////throw new HttpException(401, "Please close your browser to complete Log Off");
            return View("Index");
        }
</code>```

答:
If you are returning a RedirectResponse from your action method, it will send a 302 response back to the browser with the location header set to the url you want to redirect to and the browser makes a new GET request to that url. You will not be able to show an alert before the new GET request.

What you can do is, show the alert message in page rendered by the redirect.

```<code>[HttpPost]
public ActionResult Save(SomeViewmodel model)
{
   TempData["Msg"] = "Some message";
   return RedirectToAction("Index");
}
</code>```

Now in the view returned by Index action, you can directly access TempData. No need to read and pass it via ViewBag again in Index action.

```<code><script>
    var msg = '@TempData["Msg"]';
    if (msg.length) {
        alert(msg);
    }
</script>
</code>```

Body:
I'm using tempdata to give user a "success message" before redirection however at the moment it just redirect without giving the message. Maybe I have it at wrong place, I tried moving it to different parts of the code but it still didn't work.

Index View

    @{
    ViewBag.Title = "Home Page";
}
@if (TempData["notice"] != null)
{

@TempData["notice"]

}

Home Controller

namespace com.twcl.it.isms.Controllers
{
    [Authorize(Roles = "Administrator, Issue, Transaction_Edit, Print")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
TempData["notice"] = "Your item(s) successfully requested";
            ViewBag.SuccessMessage = TempData["SuccesMeassge"];

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Logoff()
        {
            HttpContext.Session.Abandon();
            Response.Redirect("http://192.168.5.127");
            //Response.StatusCode = 401;
            //Response.End();
            //////throw new HttpException(401, "Please close your browser to complete Log Off");
            return View("Index");
        }

Body:
If you are returning a RedirectResponse from your action method, it will send a 302 response back to the browser with the location header set to the url you want to redirect to and the browser makes a new GET request to that url. You will not be able to show an alert before the new GET request.

What you can do is, show the alert message in page rendered by the redirect.

[HttpPost]
public ActionResult Save(SomeViewmodel model)
{
   TempData["Msg"] = "Some message";
   return RedirectToAction("Index");
}

Now in the view returned by Index action, you can directly access TempData. No need to read and pass it via ViewBag again in Index action.

<script>
    var msg = '@TempData["Msg"]';
    if (msg.length) {
        alert(msg);
    }
</script>


问:
Python requests gives me "bad handshake" error
Using Python requests like this

```<code>import requests;
requests.get('https://internal.site.no')
</code>```

gives me an error many have had;

```<code>SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",)
</code>```

however, none of the missing package they suggest works. Even setting verify=False gives me the same error.
Curl gives me no error trying to access the same site.

Versions:

Alpine 3.4

requests 2.12.1 (it works in 2.11.1)

OpenSSL 1.0.2j 26 sep 2016

答:
I also had the same issue. Check which version of requests you are using.

```<code>import requests
print requests.__version__
</code>```

You should try downgrading to version 2.11.1. I did this, and it fixed my problem. To do this, issue the following commands in the terminal

```<code>pip uninstall requests
pip install requests==2.11.1
</code>```

Hope this helps.

Body:
Using Python requests like this

import requests;
requests.get('https://internal.site.no')

gives me an error many have had;

SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",)

however, none of the missing package they suggest works. Even setting verify=False gives me the same error.
Curl gives me no error trying to access the same site.

Versions:

Alpine 3.4

requests 2.12.1 (it works in 2.11.1)

OpenSSL 1.0.2j 26 sep 2016

Body:
I also had the same issue. Check which version of requests you are using.

import requests
print requests.__version__

You should try downgrading to version 2.11.1. I did this, and it fixed my problem. To do this, issue the following commands in the terminal

pip uninstall requests
pip install requests==2.11.1

Hope this helps.


问:
error during installation of EMBOSS on MacOSX "dyld: Library not loaded: /usr/local/opt/jpeg/lib/libjpeg.8.dylib"
I'm trying to install EMBOSS v6.6.0 on a MacOSX 10.12 laptop. I did the following:

```<code>./configure --prefix=/Users/pc/local/opt/emboss/v6.6.0
sudo mkdir /usr/local/emboss
sudo chown pc /usr/local/emboss
make -j 4
</code>```

Then I did make install and got the following error:

```<code>dyld: Library not loaded: /usr/local/opt/jpeg/lib/libjpeg.8.dylib
  Referenced from: /usr/local/opt/gd/lib/libgd.3.dylib
  Reason: image not found
make[3]: *** [install-exec-hook] Abort trap: 6
make[2]: *** [install-exec-am] Error 2
make[1]: *** [install-am] Error 2
make: *** [install-recursive] Error 1
</code>```

Not sure how to fix this. What should I try?

答:
If you don't need the UI elements then

```<code>./configure  --without-x
make
</code>```

generally makes life a lot easier on OSX.

Otherwise it looks like your installed library gd in /usr/local/opt/gd is out of sync with the jpeg library. If you ls /usr/local/opt/jpeg/lib/  I am guessing you see libjpeg.9.dylib. From this it is difficult to know exactly the next steps without knowing how you originally installed /usr/local/opt/gd. It might be as simple as (if you have homebrew) brew install gd to overwrite the 'broken' gd library. Or removing it entirely as I think it is getting in the way of the emboss included gd during compilation.

Body:
I'm trying to install EMBOSS v6.6.0 on a MacOSX 10.12 laptop. I did the following:

./configure --prefix=/Users/pc/local/opt/emboss/v6.6.0
sudo mkdir /usr/local/emboss
sudo chown pc /usr/local/emboss
make -j 4

Then I did make install and got the following error:

dyld: Library not loaded: /usr/local/opt/jpeg/lib/libjpeg.8.dylib
  Referenced from: /usr/local/opt/gd/lib/libgd.3.dylib
  Reason: image not found
make[3]: *** [install-exec-hook] Abort trap: 6
make[2]: *** [install-exec-am] Error 2
make[1]: *** [install-am] Error 2
make: *** [install-recursive] Error 1

Not sure how to fix this. What should I try?

Body:
If you don't need the UI elements then

./configure  --without-x
make

generally makes life a lot easier on OSX.

Otherwise it looks like your installed library gd in /usr/local/opt/gd is out of sync with the jpeg library. If you ls /usr/local/opt/jpeg/lib/  I am guessing you see libjpeg.9.dylib. From this it is difficult to know exactly the next steps without knowing how you originally installed /usr/local/opt/gd. It might be as simple as (if you have homebrew) brew install gd to overwrite the 'broken' gd library. Or removing it entirely as I think it is getting in the way of the emboss included gd during compilation.