问:
CloudBerry PowerShell Multipart
I've written a powershell script to upload from a windows system to an  Amazon S3 Bucket.  The script successfully uploads all files, except those over 5Gb.  I have the Cloud Berry Explorer Pro license which allows for multipart upload on files up to 5TB.  However there is no flag for multipart on the powershell snapin documentation.  Cloudberry support directed me here as they only support the GUI not the powershell snapin.  When running my script I get the error

"WARNING: Your proposed upload exceeds the maximum allowed object size (5 Gb)".

So question is, does anyone know if there is a command line option, or another way to enable multipart upload to Amazon S3 using Cloudberry Explorer Pro's Powershell Snapin?

答:
We did purchase the cloudberry explorer pro license for the native multipart upload capability, but we wanted to automate it.  I believe based on their documentation that the old chunk method is deprecated in favor of their new multi-part functionality.  We wound up testing the options listed in the powershell documentation.  Those options are as follows:

Set-CloudOption -UseChunks  -ChunkSizeKB

"Defines a size of chunk in KB; files larger than a chunk will be divided into chunks."

We verified that this was successfully uploading files beyond the 5GB restriction to our S3 bucket.  I attempted to get a response from Cloudberry as to whether this was the old Chunking method or the new Multi-Part method, but I was unable to get a straight answer.  They confirmed that because we were using pro, this powershell option was supported, but they failed to confirm which option the powershell command was using.

From what I can tell it appears that Cloudberry's legacy chunking mechanism would actually just break the file into individual files and thus would appear in S3 as multiple files.  The Chunk Transparency mechanism in Cloudberry Explorer would allow the multiple chunks to appear as a single file in the Cloudberry Explorer GUI only.  Since I can see the file as a single file on the S3 side, I'm assuming that the powershell option uses the new Multi-Part functionality and not the legacy Chunking functionality.  Again I was not able to confirm this through Cloudberry so it's speculation on my part.

However, I can confirm that using the powershell options above will get you around the 5GB upload limit when using powershell.

Title: CloudBerry PowerShell Multipart


来源: stackexchange

问:
Why is $0 different between `sh myscript` and `source myscript`?
I have a very simple shell scripts name test.sh:

```<code>[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"
</code>```

However, when I source it and sh it, the results are quite different:

```<code>[mylinux ~]$ sh test.sh
a
test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x
</code>```

I can't understand the results of source test.sh, and, after I changed the name of test.sh, the results changed also:

```<code>[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh
a
-bash
</code>```

How can I understand this phenomenon?

BTW, the second strange results only exits in one of my remote linux session, in my local linux system, everything works fine. So for sure it's related to the environment, and what I can do to find the fundamental reason?

I found the real problem, that is, even if their is no such a file test.sh, I can even perform source test.sh to get the results:

```<code>[mylinux ~]$ rm test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x
</code>```

This is quite strange for me...

答: When you run source test.sh, a new shell is not created, so the program, ${0}, is bash.  When you run sh test.sh, bash creates a new shell, and sets ${0} to the name of the script.

ContentLicense: CC BY-SA 3.0

Body:
I have a very simple shell scripts name test.sh:

[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"

However, when I source it and sh it, the results are quite different:

[mylinux ~]$ sh test.sh
a
test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x

I can't understand the results of source test.sh, and, after I changed the name of test.sh, the results changed also:

[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh
a
-bash

How can I understand this phenomenon?

BTW, the second strange results only exits in one of my remote linux session, in my local linux system, everything works fine. So for sure it's related to the environment, and what I can do to find the fundamental reason?

I found the real problem, that is, even if their is no such a file test.sh, I can even perform source test.sh to get the results:

[mylinux ~]$ rm test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x

This is quite strange for me...


问:
c++ How could I properly predefined array of char*?
I am doing it that way:

```<code>int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";
</code>```

but I get notice, that it is deprecated. What is better way?

答:
+1 for Vlad.

Some more explanation from me on what happens here:

You get the "deprecated" warning, because such code:

```<code>"asdf"
</code>```

now has type const char*, not char*. And string literals can be converted to char*, to retain some compatibility with the older conventions when const wasn't that strict. But conversion of a string literal to char* from const char* is deprecated and you should not rely on it.

Why? String literal is a pointer to constant memory, that's why it needs to be const char*.

Body:
I am doing it that way:

int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";

but I get notice, that it is deprecated. What is better way?

Body:
+1 for Vlad.

Some more explanation from me on what happens here:

You get the "deprecated" warning, because such code:

"asdf"

now has type const char*, not char*. And string literals can be converted to char*, to retain some compatibility with the older conventions when const wasn't that strict. But conversion of a string literal to char* from const char* is deprecated and you should not rely on it.

Why? String literal is a pointer to constant memory, that's why it needs to be const char*.

ContentLicense: CC BY-SA 2.5


问:
How to avoid "trap" with linear interpolation?
I have a range a (starting range) and a range b (target range), and I need to scale a value aX from range a to range b. Code is a basic linear interpolation:

```<code>double LinearInterpolation(double a0, double a1, double b0, double b1, double aX) {
    return b0 + (b1 - b0) * (aX - a0) / (a1 - a0);
}
</code>```

The fact is: range b can be 0-length from 1.0 to 1.0. But when I reach that range, I got a value that is "trap", and can't go back. Here's an example:

```<code>int main ()
{
    double a0 = 0.4;
    double a1 = 1.0;
    double b0 = 0.6;
    double b1 = 1.0;

    double aX = 0.58;

    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;

    b0 = 1.0;
    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;

    b0 = 0.6;
    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;
}
</code>```

Until b0 is 0, it scales correctly the aX value. When I reach b0 = b1 = 1.0, I can't go back (aX is always 1.0, because aX = a1, thus is always  b0 + (b1 - b0) => b1).

How can I avoid this?

答:
How can I avoid this?

Don't store the actual value, but rather the relative position within a range:

```<code>struct value_in_range {
  double normalized_offset;
  double in_range (double from, double to) const {
    return from + (to - from) * normalized_offset;
  }
};

value_in_range make_value_in_range (double from, double value, double to) {
  // Add assertions to avoid misuse
  return {(value - from) / (to - from)};
}
</code>```

With your example:

```<code>int main ()
{
    double a0 = 0.4;
    double a1 = 1.0;
    double b0 = 0.6;
    double b1 = 1.0;

    double aX = 0.58;

    value_in_range X = make_value_in_range (a0, aX, a1);

    std::cout << X.in_range(b0, b1) << std::endl;

    b0 = 1.0;
    std::cout << X.in_range(b0, b1) << std::endl;

    b0 = 0.6;
    std::cout << X.in_range(b0, b1) << std::endl;
}
</code>```

You could also set aX as in your original code.

Body:
I have a range a (starting range) and a range b (target range), and I need to scale a value aX from range a to range b. Code is a basic linear interpolation:

double LinearInterpolation(double a0, double a1, double b0, double b1, double aX) {
    return b0 + (b1 - b0) * (aX - a0) / (a1 - a0);
}

The fact is: range b can be 0-length from 1.0 to 1.0. But when I reach that range, I got a value that is "trap", and can't go back. Here's an example:

int main ()
{
    double a0 = 0.4;
    double a1 = 1.0;
    double b0 = 0.6;
    double b1 = 1.0;

    double aX = 0.58;

    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;

    b0 = 1.0;
    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;

    b0 = 0.6;
    aX = LinearInterpolation(a0, a1, b0, b1, aX);
    std::cout << aX << std::endl;
}

Until b0 is 0, it scales correctly the aX value. When I reach b0 = b1 = 1.0, I can't go back (aX is always 1.0, because aX = a1, thus is always  b0 + (b1 - b0) => b1).

How can I avoid this?

Body:
How can I avoid this?

Don't store the actual value, but rather the relative position within a range:

struct value_in_range {
  double normalized_offset;
  double in_range (double from, double to) const {
    return from + (to - from) * normalized_offset;
  }
};

value_in_range make_value_in_range (double from, double value, double to) {
  // Add assertions to avoid misuse
  return {(value - from) / (to - from)};
}

With your example:

int main ()
{
    double a0 = 0.4;
    double a1 = 1.0;
    double b0 = 0.6;
    double b1 = 1.0;

    double aX = 0.58;

    value_in_range X = make_value_in_range (a0, aX, a1);

    std::cout << X.in_range(b0, b1) << std::endl;

    b0 = 1.0;
    std::cout << X.in_range(b0, b1) << std::endl;

    b0 = 0.6;
    std::cout << X.in_range(b0, b1) << std::endl;
}

You could also set aX as in your original code.


问:
Creating canonical basis vectors in R?
Is there an efficient way of creating the canonical basis vectors:

```<code>e_1=c(1,0,0,...),

e_2=c(0,1,0,...),

e_3=c(0,0,1,...),

...
</code>```

for arbitrary lengths in R and probably large p?

I know that I could do

```<code>e_1 = rep(0,p)
e_1[1] = 1
</code>```

and so on or diag(p)[1] ... But I wonder if there is a more efficient way since I only need one at a time in a loop.

答:
It can be somewhat shorter with replace:

```<code>make_basis <- function(k, p = 10) replace(numeric(p), k, 1)

# usage
e_4 = make_basis(4)
e_4
# [1] 0 0 0 1 0 0 0 0 0 0
</code>```

Title: Creating canonical basis vectors in R?

Body:
Is there an efficient way of creating the canonical basis vectors:

e_1=c(1,0,0,...),

e_2=c(0,1,0,...),

e_3=c(0,0,1,...),

...

for arbitrary lengths in R and probably large p?

I know that I could do

e_1 = rep(0,p)
e_1[1] = 1

and so on or diag(p)[1] ... But I wonder if there is a more efficient way since I only need one at a time in a loop.

Body:
It can be somewhat shorter with replace:

make_basis <- function(k, p = 10) replace(numeric(p), k, 1)

# usage
e_4 = make_basis(4)
e_4
# [1] 0 0 0 1 0 0 0 0 0 0


问:
Table Aliases in FastReport (DataField Attribute)
i have a SQL query in the form of:

```<code>Select * from table a
inner join table b
on a.id = b.id;
</code>```

The Result of this SQL goes to FastReport.
Within FastReport, I have some TfrxMemoView with the Attribute "DataField".

I can now write the name of the column in "DataField" and get the Value back as long, the column name is unique.

How can I make aliases work for the "DataField" Attribute?
Something like: a.example

答: You may set fields aliases for TfrxDBDataset (right click on the TfrxDBDataset in the IDE -> menu item "Edit Fields Aliases..." or set TfrxDBDataset.FieldAliases)</p>

Body:
i have a SQL query in the form of:

Select * from table a
inner join table b
on a.id = b.id;

The Result of this SQL goes to FastReport.
Within FastReport, I have some TfrxMemoView with the Attribute "DataField".

I can now write the name of the column in "DataField" and get the Value back as long, the column name is unique.

How can I make aliases work for the "DataField" Attribute?
Something like: a.example


问:
How to extract a line and a line before that based on certain strings
I am trying to extract lines containing a certain string also 4 lines before it (just the fourth line not the ones in between). Right now I can get the line itself;

```<code>grep -n "my string" myfile.out > output.txt
</code>```

I can also get the lines before it, but not that specific one, all the four preceding lines;

```<code>grep "my string" -B 4 myfile.out > output.txt
</code>```

Let's take this example:

```<code> ! CREEK
 FLUX 6739, 6670, 6640, 6672, 6582, 6583, 6548, 6576, 6570 &
 656565
 ***
 ***  THE SUM OF SPECIFIED:   -1.192451
 ***  THE AVERAGE:  -6.2760599E-02
 ***  THE MAXIMUM:    0.000000
 ***  THE MINIMUM:  -0.4294980
 ***  THE SUM OF POSITIVE:    0.000000
 ***  THE SUM OF NEGATIVE:   -1.192451
</code>```

I want this output:

```<code> ! CREEK
 ***  THE SUM OF SPECIFIED:   -1.192451
</code>```

I would appreciate windows-batch-file solution or PowerShell as well.

答:
If your file is named myfile.out this should do what you want to:

```<code>grep "THE SUM OF SPECIFIED" -B 4  myfile.out | sed -n "1p;5p"
</code>```

Body:
I am trying to extract lines containing a certain string also 4 lines before it (just the fourth line not the ones in between). Right now I can get the line itself;

grep -n "my string" myfile.out > output.txt

I can also get the lines before it, but not that specific one, all the four preceding lines;

grep "my string" -B 4 myfile.out > output.txt

Let's take this example:

 ! CREEK
 FLUX 6739, 6670, 6640, 6672, 6582, 6583, 6548, 6576, 6570 &
 656565
 ***
 ***  THE SUM OF SPECIFIED:   -1.192451
 ***  THE AVERAGE:  -6.2760599E-02
 ***  THE MAXIMUM:    0.000000
 ***  THE MINIMUM:  -0.4294980
 ***  THE SUM OF POSITIVE:    0.000000
 ***  THE SUM OF NEGATIVE:   -1.192451

I want this output:

 ! CREEK
 ***  THE SUM OF SPECIFIED:   -1.192451

I would appreciate windows-batch-file solution or PowerShell as well.

Body:
If your file is named myfile.out this should do what you want to:

grep "THE SUM OF SPECIFIED" -B 4  myfile.out | sed -n "1p;5p"


问:
Is it possible to use regex with cucumber.options tags?
I want run multiple cucumber feature tags. I don't want to mention all the tags in the command line because it can be tedious if there are lots of tags. Instead I want to provide a pattern of tags that will run all the tags which matches the pattern like -Dcucumber.options=" --tags @my-test*". This will run all the tags that matches @my-test patter.

So is there any way to do this?

答: If you are using Cucumber ruby, then you can use profiles to do this using cucumber.yml. I don't know if there is an equivalent in java. If there isn't I would just create some shell scripts (maybe even aliases) to deal with this.


问:
Espresso, scrolling not working when NestedScrollView or RecyclerView is in CoordinatorLayout
It looks like CoordinatorLayout breaks the behaviour of Espresso actions such as scrollTo() or RecyclerViewActions.scrollToPosition().

Issue with NestedScrollView

For a layout like this one:

```<code><android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        ...

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        ...

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

If I try to scroll to any view inside the NestedScrollView using ViewActions.scrollTo() the first problem I find is that I get a PerformException. This is because this action only supports ScrollView and NestedScrollView doesn't extend it. A workaround for this problem is explained here, basically we can copy the code in scrollTo() and change the constrains to support NestedScrollView. This seems to work if the NestedScrollView is not in a CoordinatorLayout but as soon as you put it inside a the CoordinatorLayout the scrolling action fails.

Issue with RecyclerView

For the same layout, if I replace the NestedScrollView with a RecyclerView there is also problems with the the scrolling.

In this case I'm using RecyclerViewAction.scrollToPosition(position). Unlike the NestedScrollView, here I can see some scrolling happening. However, it looks like it scrolls to the wrong position. For example, if I scroll to the last position, it makes visible the second to last but not the last one. When I move the RecyclerView out of the CoordinatorLayout the scrolling works as it should.

At the moment we can't write any Espresso test for the screens that use CoordinatorLayout due to this issues. Anyone experiencing the same problems or knows a workaround?

答:
Barista's scrollTo(R.id.button) works on all kinds of scrollable views, also on NestedScrollView.

It's useful to fix this kind of issues with Espresso. We develop and use it just to write Espresso tests in a fast and reliable way. And here's a link: https://github.com/SchibstedSpain/Barista

Body:
It looks like CoordinatorLayout breaks the behaviour of Espresso actions such as scrollTo() or RecyclerViewActions.scrollToPosition().

Issue with NestedScrollView

For a layout like this one:

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        ...

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        ...

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

If I try to scroll to any view inside the NestedScrollView using ViewActions.scrollTo() the first problem I find is that I get a PerformException. This is because this action only supports ScrollView and NestedScrollView doesn't extend it. A workaround for this problem is explained here, basically we can copy the code in scrollTo() and change the constrains to support NestedScrollView. This seems to work if the NestedScrollView is not in a CoordinatorLayout but as soon as you put it inside a the CoordinatorLayout the scrolling action fails.

Issue with RecyclerView

For the same layout, if I replace the NestedScrollView with a RecyclerView there is also problems with the the scrolling.

In this case I'm using RecyclerViewAction.scrollToPosition(position). Unlike the NestedScrollView, here I can see some scrolling happening. However, it looks like it scrolls to the wrong position. For example, if I scroll to the last position, it makes visible the second to last but not the last one. When I move the RecyclerView out of the CoordinatorLayout the scrolling works as it should.

At the moment we can't write any Espresso test for the screens that use CoordinatorLayout due to this issues. Anyone experiencing the same problems or knows a workaround?


问:
How does the browser render Images with different sizes ( tag in HTML)?
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

```<code><img src="5_mb_img.jpg" /> <!-- a 5MB image file -->
<img src="50_kb_img.jpg" /> <!-- a 50KB image file -->
<img src="10_mb_img.jpg" /> <!-- a 10MB image file -->
</code>```

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow

答: The 50KB one will render first as it is the smallest file size there and will load first and therefore get more time to render. </p>

Title: How does the browser render Images with different sizes (<img> tag in HTML)?

Body:
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow


问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
You've confused the single and double quotes

You have:

```<code>$query = 'select * From user where email="$email" and password="$password" ' ;
</code>```

You want:

```<code>$query = "select * From user where email='$email' and password='$password' " ;
</code>```

Single quotes evaluate to whats literally inside.  Double quotes will parse for variables inside.  Theres also a curly brace {$variable} syntax you can use.

Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well.  At the very least use mysql_real_escape on parameters that come from user input.

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>

Body:
You've confused the single and double quotes

You have:

$query = 'select * From user where email="$email" and password="$password" ' ;

You want:

$query = "select * From user where email='$email' and password='$password' " ;

Single quotes evaluate to whats literally inside.  Double quotes will parse for variables inside.  Theres also a curly brace {$variable} syntax you can use.

Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well.  At the very least use mysql_real_escape on parameters that come from user input.


问:
How can I use the same file created in the code?
I have created a file as:

```<code>fd = open("output.txt",'w')
fd.write("*TITLE")
fd.write('\n')
fd.write("*Look below")
fd.write('\n')
</code>```

And, I want to write more into this file with the following command:

```<code>temp = [(1,2),(3,4),(a,b)]
np.savetxt("output.txt", temp , fmt="%d", comments='')
fd.close()
</code>```

However, when I open the output.txt file, it only has "b" and nothing more.

How can I fix it or do you know where I am making a mistake?

答:
You can pass the open file to the NumPy output function:

```<code>np.savetxt(fd, temp , fmt="%d", comments='')
</code>```

As per the documentation, the first argument is a filename or file handle.

Body:
I have created a file as:

fd = open("output.txt",'w')
fd.write("*TITLE")
fd.write('\n')
fd.write("*Look below")
fd.write('\n')

And, I want to write more into this file with the following command:

temp = [(1,2),(3,4),(a,b)]
np.savetxt("output.txt", temp , fmt="%d", comments='')
fd.close()

However, when I open the output.txt file, it only has "b" and nothing more.

How can I fix it or do you know where I am making a mistake?

Body:
You can pass the open file to the NumPy output function:

np.savetxt(fd, temp , fmt="%d", comments='')

As per the documentation, the first argument is a filename or file handle.


问:
Completely disable Firebase/Analytics to stop console spam on app startup
I've installed Google/SignIn cocoapod into my application (which I need to support GoogleDrive), but it depends on Google/Core which depends on FirebaseAnalytics. I don't want or need FirebaseAnalytics.

FirebaseAnalytics spams the developer console with 8 lines of output when our app starts:

```<code>2017-06-07 18:07:19.612994+0100 son[2909:877661] [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at http://gooX.gl/9vSsPb
2017-06-07 18:07:19.613 son[2909] <Warning> [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at http://gooX.gl/9vSsPb
2017-06-07 18:07:19.613896+0100 son[2909:877661] [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3900000 started
2017-06-07 18:07:19.614 son[2909] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3900000 started
2017-06-07 18:07:19.614525+0100 son[2909:877661] [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://gooX.gl/RfcP7r)
2017-06-07 18:07:19.614 son[2909] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://gooX.gl/RfcP7r)
2017-06-07 18:07:19.622560+0100 son[2909:877662] [Firebase/Analytics][I-ACS023013] Firebase Analytics disabled
2017-06-07 18:07:19.623 son[2909] <Notice> [Firebase/Analytics][I-ACS023013] Firebase Analytics disabled
</code>```

(I had to add X to the URLs in the above output to get past stackoverflow's URL shortener blocker.)

I tried setting FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED to YES in my Info.plist, that removed 2 lines, but added another 2 lines to tell me that Analytics is disabled (FFS!).

This spammed output makes it difficult for our developers to see any console output that is actually important. How can I disable it?

(Failing that, a suggestion on how to get it outputting each line only once would be really welcome.)

答:
You can find this buried in the output:

```<code><Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging
 set the following application argument: -FIRAnalyticsDebugEnabled
</code>```

Disabling is the opposite - set the argument: -noFIRAnalyticsDebugEnabled:

Additionally, you can control the default Firebase logging level with the setLoggerLevel method in FIRConfiguration. For example to disable all Firebase logging:

```<code>  [[FIRConfiguration sharedInstance] setLoggerLevel:FIRLoggerLevelMin];
  [FIRApp configure];
</code>```

or in Swift:

```<code>FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.min)
FirebaseApp.configure()
</code>```

More details in the FIRLogger implementation here

Body:
I've installed Google/SignIn cocoapod into my application (which I need to support GoogleDrive), but it depends on Google/Core which depends on FirebaseAnalytics. I don't want or need FirebaseAnalytics.

FirebaseAnalytics spams the developer console with 8 lines of output when our app starts:

2017-06-07 18:07:19.612994+0100 son[2909:877661] [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at http://gooX.gl/9vSsPb
2017-06-07 18:07:19.613 son[2909] <Warning> [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at http://gooX.gl/9vSsPb
2017-06-07 18:07:19.613896+0100 son[2909:877661] [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3900000 started
2017-06-07 18:07:19.614 son[2909] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3900000 started
2017-06-07 18:07:19.614525+0100 son[2909:877661] [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://gooX.gl/RfcP7r)
2017-06-07 18:07:19.614 son[2909] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://gooX.gl/RfcP7r)
2017-06-07 18:07:19.622560+0100 son[2909:877662] [Firebase/Analytics][I-ACS023013] Firebase Analytics disabled
2017-06-07 18:07:19.623 son[2909] <Notice> [Firebase/Analytics][I-ACS023013] Firebase Analytics disabled

(I had to add X to the URLs in the above output to get past stackoverflow's URL shortener blocker.)

I tried setting FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED to YES in my Info.plist, that removed 2 lines, but added another 2 lines to tell me that Analytics is disabled (FFS!).

This spammed output makes it difficult for our developers to see any console output that is actually important. How can I disable it?

(Failing that, a suggestion on how to get it outputting each line only once would be really welcome.)

Body:
You can find this buried in the output:

<Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging
 set the following application argument: -FIRAnalyticsDebugEnabled

Disabling is the opposite - set the argument: -noFIRAnalyticsDebugEnabled:

Additionally, you can control the default Firebase logging level with the setLoggerLevel method in FIRConfiguration. For example to disable all Firebase logging:

  [[FIRConfiguration sharedInstance] setLoggerLevel:FIRLoggerLevelMin];
  [FIRApp configure];

or in Swift:

FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.min)
FirebaseApp.configure()

More details in the FIRLogger implementation here

ContentLicense: CC BY-SA 4.0


问:
What is the OR operator in emacs regexps?
The manual says to use '\|', as in a\|b matches a or b. But when I use it with regexp builder or align-regexp e.g. with, "True\|False", it doesn't recognize "True" or "False". I get the following message:

```<code>Wrong argument type: integer-or-marker-p, nil
</code>```

What am I doing wrong?

答:
Use double escape: \\|

A Few Additional Notes:

Emacs has 2 escaping styles, one in EmacsLisp the other when used in commands,

ie. from the M-x prompt (rgrep, occur, …)

In EmacsLisp, use the double backslash  \\|

…

From M-x … use a single backslash \|

… As a side note, when writing embedded EmacsLisp, for example in yasnippet dynamic expansions, you have to use a quadruple backslash: \\\\| (to escape the double backslashes.)

Always avoid this (if possible), for example in yasnippet you can provide mode related emacslisp, without the additional escaping, via a .yas-setup.el

Body:
The manual says to use '\|', as in a\|b matches a or b. But when I use it with regexp builder or align-regexp e.g. with, "True\|False", it doesn't recognize "True" or "False". I get the following message:

Wrong argument type: integer-or-marker-p, nil

What am I doing wrong?


问:
how does nginx picks a resolver when there are multiple defined?
How does nginx picks a resolver if you define several like:

```<code>...
resolver 108.x.x.x 120.x.x.x 19.x.x.x valid=30s;
...
</code>```

Is it in a round-robin fashion? or there is some failover logic in there?

答:
According to the nginx document
http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver

Name servers are queried in a round-robin fashion.

They are using RR.

Body:
How does nginx picks a resolver if you define several like:

...
resolver 108.x.x.x 120.x.x.x 19.x.x.x valid=30s;
...

Is it in a round-robin fashion? or there is some failover logic in there?


问:
How do I subset a list in R by selecting all elements in a list except for one value?
So basically I have a list called "parameters" with values (x1, x2, ... , xj). I want to, through a for loop, subset this list, but each time leave out one element. So for example I want the first subset (through the first iteration of the for loop) to be (x2, x3, ..., xj), and the next to be (x1, x3, ..., xj) and so on, until the last subset which would be (x1, x2, ... , xj-1). How do I do this?</p>

答:
You can subset the element from the list by indicating they order in the list.

To select the items 1 and 3 from a list

```<code>my.list[c(1,3))]
</code>```

Try this:

```<code># create a dummy list of data frames
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
d3 <- data.frame(y1=c(3,2,1),y2=c(9,8,7))
my.list <- list(d1, d2, d3)

# get the items 1 and 3
my.list[c(1,3)]

# get the all element except of the first one
my.list[c(-1)]
</code>```

Body:
You can subset the element from the list by indicating they order in the list.

To select the items 1 and 3 from a list

my.list[c(1,3))]

Try this:

# create a dummy list of data frames
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
d3 <- data.frame(y1=c(3,2,1),y2=c(9,8,7))
my.list <- list(d1, d2, d3)

# get the items 1 and 3
my.list[c(1,3)]

# get the all element except of the first one
my.list[c(-1)]


问:
Best way to combine 2 lists
I have the below 2 list:

```<code>List<string> a = new List<string>()
{
    "a",
    "b"
};

List<string> b = new List<string>()
{
    "c",
    "d"
};
</code>```

What is the best way to combine a and b to get the following:

```<code>{
    "ac",
    "ad",
    "bc",
    "bd"
};
</code>```

Is there a LINQ function that enables us to do the above?

答:
Can try:</p>

```<code>    List<string> c = new List<string>();

    for(int i=0; i<a.Count; i++){
        for(int j=0; j< b.Count; j++){
            c.Add(a[i]+b[j]);
        }
    }
</code>```

Title: Best way to combine 2 lists

Body:
I have the below 2 list:

List<string> a = new List<string>()
{
    "a",
    "b"
};

List<string> b = new List<string>()
{
    "c",
    "d"
};

What is the best way to combine a and b to get the following:

{
    "ac",
    "ad",
    "bc",
    "bd"
};

Is there a LINQ function that enables us to do the above?

Body:
Can try:

    List<string> c = new List<string>();

    for(int i=0; i<a.Count; i++){
        for(int j=0; j< b.Count; j++){
            c.Add(a[i]+b[j]);
        }
    }


问:
Bootstrap CSS not working in chrome or firefox
I wrote a basic "Hello World" web page and added bootstrap CSS from CDN but it is working only in Microsoft Edge. Google Chrome and Mozilla Firefox are not displaying the correct output.

Please help me resolve this issue.

Correct Microsoft Edge Output

Incorrect Google Chrome Output

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <title>Shadow Shop</title>
  </head>
  <body class="container-fluid">
    <div class="jumbotron">
      <h1>Hello World</h1>
    </div>

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

答:
I found the solution to the problem finally!!

This problem was caused due to the character encoding being implemented while saving the file. In Atom editor, the default saving was in UTF-16LE. But, UTF-8 was required.

Once I changed the encoding, the problem was solved.

Body:
I wrote a basic "Hello World" web page and added bootstrap CSS from CDN but it is working only in Microsoft Edge. Google Chrome and Mozilla Firefox are not displaying the correct output.

Please help me resolve this issue.

Correct Microsoft Edge Output

Incorrect Google Chrome Output

<!DOCTYPE html>

    <meta charset="utf-8">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <title>Shadow Shop</title>

Hello World


问:
ASP.NET MVC background image
i'm a newbie in ASP.NET MVC. I'm trying to make a decent site, and i've encountered a stupid problem:
I can't set the background to be a local image.

-in Site.css, this works :

```<code>body {
padding-top: 50px;
padding-bottom: 20px;
background-image: url(http://wallpapercave.com/wp/zJj7EIt.jpg);
}
</code>```

,but i don't want the image be an URL.

I've tried the following things:

Number one :

```<code>body {
padding-top: 50px;
padding-bottom: 20px;
background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)
}
</code>```

Number two :

```<code><body style="background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)">
</code>```

Number three(wich is obsolete):

```<code><body background="C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg">
</code>```

I must miss something related to resources, and not with properties. Do you have any solution or ideea ? Or an explication about what vs does.

答:
Don't use an absolute path. Use a relative path.

if your css file is located here for instance (from the root of your site):
/Styles/Site.css

then your CSS should be:

```<code>body {
  padding-top: 50px;
  padding-bottom: 20px;
  background-image:url(Images/background.jpg)
}
</code>```

so, you're saying from where your css file is (/Styles) your image file is a sub-directory of this (/Styles/Images/[the-filename-for-your-image]).

Also, not the use of / rather than \ in your image path

Title: ASP.NET MVC background image

Body:
i'm a newbie in ASP.NET MVC. I'm trying to make a decent site, and i've encountered a stupid problem:
I can't set the background to be a local image.

-in Site.css, this works :

body {
padding-top: 50px;
padding-bottom: 20px;
background-image: url(http://wallpapercave.com/wp/zJj7EIt.jpg);
}

,but i don't want the image be an URL.

I've tried the following things:

Number one :

body {
padding-top: 50px;
padding-bottom: 20px;
background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)
}

Number two :

Number three(wich is obsolete):

I must miss something related to resources, and not with properties. Do you have any solution or ideea ? Or an explication about what vs does.

Body:
Don't use an absolute path. Use a relative path.

if your css file is located here for instance (from the root of your site):
/Styles/Site.css

then your CSS should be:

body {
  padding-top: 50px;
  padding-bottom: 20px;
  background-image:url(Images/background.jpg)
}

so, you're saying from where your css file is (/Styles) your image file is a sub-directory of this (/Styles/Images/[the-filename-for-your-image]).

Also, not the use of / rather than \ in your image path


问:
Cubic Root of Pandas DataFrame
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

```<code>sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))
</code>```

答:
It looks like you are passing a list or array of column names.  I assume this because your variable name is plural with an s at the end.  If this is the case, then sample[columns] is a dataframe.  This is an issue because apply iterates through each column, passing that column the lambda you passed to apply.  So you get

```<code>(-1) * np.power(-series_object, -1./3) if series_object < 0 else...
</code>```

And it's the series_object < 0 that is messing things up because you are asking for the truthiness of a whole series being less than zero.

applymap

```<code>f = lambda x: -np.power(-x, 1./3) if x < 0 else np.power(x, 1./3)
sample[columns] = sample[columns].applymap(f)
</code>```

That said, I'd use a lambda defined as follows

```<code>f = lambda x: np.sign(x) * np.power(abs(x), 1./3)
</code>```

Then you could perform this on the entire dataframe

```<code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.randint(-10, 10, (5, 5)))

df

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

```<code>f = lambda x: np.sign(x) * np.power(abs(x), 1./3)
f(df)

          0         1         2         3         4
0  1.817121  1.000000 -2.000000  0.000000  1.709976
1  1.442250  1.000000  1.442250  2.080084 -1.259921
2 -2.154435  1.259921 -2.154435 -2.000000 -2.154435
3 -1.442250  2.080084  1.442250  2.000000  1.259921
4 -1.817121 -1.912931  2.080084  1.442250 -1.442250
</code>```

Same as

```<code>df.applymap(f)

          0         1         2         3         4
0  1.817121  1.000000 -2.000000  0.000000  1.709976
1  1.442250  1.000000  1.442250  2.080084 -1.259921
2 -2.154435  1.259921 -2.154435 -2.000000 -2.154435
3 -1.442250  2.080084  1.442250  2.000000  1.259921
4 -1.817121 -1.912931  2.080084  1.442250 -1.442250
</code>```

Check for equality

```<code>df.applymap(f).equals(f(df))

True
</code>```

And its faster

```<code>%timeit df.applymap(f)
%timeit f(df)

1000 loops, best of 3: 1.11 ms per loop
1000 loops, best of 3: 473 µs per loop
</code>```

Title: Cubic Root of Pandas DataFrame

Body:
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))

Body:
It looks like you are passing a list or array of column names.  I assume this because your variable name is plural with an s at the end.  If this is the case, then sample[columns] is a dataframe.  This is an issue because apply iterates through each column, passing that column the lambda you passed to apply.  So you get

(-1) * np.power(-series_object, -1./3) if series_object < 0 else...

And it's the series_object < 0 that is messing things up because you are asking for the truthiness of a whole series being less than zero.

applymap

f = lambda x: -np.power(-x, 1./3) if x < 0 else np.power(x, 1./3)
sample[columns] = sample[columns].applymap(f)

That said, I'd use a lambda defined as follows

f = lambda x: np.sign(x) * np.power(abs(x), 1./3)

Then you could perform this on the entire dataframe

np.random.seed([3,1415])
df = pd.DataFrame(np.random.randint(-10, 10, (5, 5)))

df

    0  1   2  3   4
0   6  1  -8  0   5
1   3  1   3  9  -2
2 -10  2 -10 -8 -10
3  -3  9   3  8   2
4  -6 -7   9  3  -3

f = lambda x: np.sign(x) * np.power(abs(x), 1./3)
f(df)

          0         1         2         3         4
0  1.817121  1.000000 -2.000000  0.000000  1.709976
1  1.442250  1.000000  1.442250  2.080084 -1.259921
2 -2.154435  1.259921 -2.154435 -2.000000 -2.154435
3 -1.442250  2.080084  1.442250  2.000000  1.259921
4 -1.817121 -1.912931  2.080084  1.442250 -1.442250

Same as

df.applymap(f)

          0         1         2         3         4
0  1.817121  1.000000 -2.000000  0.000000  1.709976
1  1.442250  1.000000  1.442250  2.080084 -1.259921
2 -2.154435  1.259921 -2.154435 -2.000000 -2.154435
3 -1.442250  2.080084  1.442250  2.000000  1.259921
4 -1.817121 -1.912931  2.080084  1.442250 -1.442250

Check for equality

df.applymap(f).equals(f(df))

True

And its faster

%timeit df.applymap(f)
%timeit f(df)

1000 loops, best of 3: 1.11 ms per loop
1000 loops, best of 3: 473 µs per loop


问:
Qualifier concept in ddd
According to Eric Evans, associations should

Impose a traversal direction

Add qualifiers and reduce multiplicity

Not be present if it is non-essential

I am not able to understand qualifier concept, how do we add to reduce multiplicity. Can any body explain with example.

答: this is general oop. read more here and here </p>

Title: Qualifier concept in ddd


问:
Lisp - Splitting Input into Separate Strings
I'm trying to take user input and storing it in a list, only instead of a list consisting of a single string, I want each word scanned in to be its own string.
Example:

```<code>> (input)
This is my input. Hopefully this works
</code>```

would return:

```<code>("this" "is" "my" "input" "hopefully" "this" "works")
</code>```

Taking note that I don't want any spaces or punctuation in my final list.

Any input would be greatly appreciated.

答:
```<code>(defun splitStr (src pat /)
    (setq wordlist (list))
    (setq len (strlen pat))
    (setq cnt 0)
    (setq letter cnt)
    (while (setq cnt (vl-string-search pat src letter))
        (setq word (substr src (1+ letter) (- cnt letter)))
        (setq letter (+ cnt len))
        (setq wordlist (append wordlist (list word)))
    )
    (setq wordlist (append wordlist (list (substr src (1+ letter)))))
)
</code>```

Body:
I'm trying to take user input and storing it in a list, only instead of a list consisting of a single string, I want each word scanned in to be its own string.
Example:

> (input)
This is my input. Hopefully this works

would return:

("this" "is" "my" "input" "hopefully" "this" "works")

Taking note that I don't want any spaces or punctuation in my final list.

Any input would be greatly appreciated.


问:
Export queries from SSMS to files - not the results but the query
I want to export all my queries as individual files for purposes of putting them into mercurial source control, but I don't know how to export the individual queries as individual files without having to open each one, then save to the folder, then add into the project, or some equally convoluted process.

I wouldn't mind having to add each one individually, but how do I get them out of the database as individual files without opening them all and doing each one save as? Ostensibly I would like them named with the name they have in the database right now.

I could easily dump the whole lot into one long file using database tasks, but that's not really super helpful is it?

I have SSMS 2k5 and 2k8 (and VS 2k5, 2k8, 2010 to boot) to work with, any thoughts?

答: I would write a small C# program which extracts your database object via SMO and stores them in your filesystem the way you want.</p>


问:
How to pass, from <input>, a different value that the chosen one
I use <input> to choose a value in a Vue.js context. The context does not matter (I believe) - this is just to say the value of the <input> field is always synchronized with a variable called searchedName and that there is no actual "submission" of the input (as it is already available at all times):

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</datalist>```
</div>
</div>
</p>

<p>When choosing from the dropdown a value, it is this exact string which is chosen (<code>One</code> for instance). </p>

<p>I would like, however, this string to just be a display name, and that the actual choice is an Object. As an example, when choosing <code>One</code> from the dropdown, I would like to pass further <code>{"choice": "one", "value": 1, "weather": ["cloudy", "rainy"]}</code> - and not the string <code>"One"</code>.</p>

<p><strong>Is this possible?</strong></p>

<hr>

<p><strong>EDIT</strong>: Just in case, I am posting the actual Vue.js code which handle this bit. <code>foundNames</code> is updated somewhere else (in an AJAX call) and is an Array of Objects. The <code>addID</code> method is supposed to use <code>{{name._source}}</code>, which is currently displayed as it. I would like to hide it and display some of its elements instead.</p>

```
            Input "Something":
            <input v-model="searchedName" list="foundNames">
            <datalist id="foundNames">
                <option v-for="name in foundNames" value="name">{{name._source}}</option>
            </datalist>

        <button v-on:click="addID">add name</button>
```

<p>Looking at the first answers, the way to go would be something along the lines of </p>

```<option v-for="name in foundNames" value="name">{{name._source.interesingelementtodisplay}}</option>
```

but value="name" sets the value to "name" (verbatim) and not the current value of the variable name in the v-for iteration.

答:
Simply just value should do the first thing you were looking for.

```<code><input id="searchedName" list="foundNames">
<datalist id="foundNames">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</datalist>
</code>```

Body:
I use <input> to choose a value in a Vue.js context. The context does not matter (I believe) - this is just to say the value of the <input> field is always synchronized with a variable called searchedName and that there is no actual "submission" of the input (as it is already available at all times):

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</datalist>

When choosing from the dropdown a value, it is this exact string which is chosen (One for instance).

I would like, however, this string to just be a display name, and that the actual choice is an Object. As an example, when choosing One from the dropdown, I would like to pass further {"choice": "one", "value": 1, "weather": ["cloudy", "rainy"]} - and not the string "One".

Is this possible?

EDIT: Just in case, I am posting the actual Vue.js code which handle this bit. foundNames is updated somewhere else (in an AJAX call) and is an Array of Objects. The addID method is supposed to use {{name._source}}, which is currently displayed as it. I would like to hide it and display some of its elements instead.

            Input "Something":
            <input v-model="searchedName" list="foundNames">
            <datalist id="foundNames">
                <option v-for="name in foundNames" value="name">{{name._source}}</option>
            </datalist>

        <button v-on:click="addID">add name</button>

Looking at the first answers, the way to go would be something along the lines of

<option v-for="name in foundNames" value="name">{{name._source.interesingelementtodisplay}}</option>

but value="name" sets the value to "name" (verbatim) and not the current value of the variable name in the v-for iteration.

Body:
Simply just value should do the first thing you were looking for.

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</datalist>


问:
String startswith a particular text
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

```<code>inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)
</code>```

答:
You can first initialize your Engagement column to zeros.  Then create a mask to find the tweets that don't start with 'RT @' (note the ~ negation).  Finally, use the mask to add the Favorite_Count and Retweet_Count columns.

Note that you rarely want to use loops with a dataframe.

```<code>inf = pd.read_csv('string.csv')

inf['Engagement'] = 0
mask = ~inf.Tweet.str.startswith('RT @')
inf.loc[mask, 'Engagement'] = (
    inf.loc[mask, 'Favorite_Count']
    + inf.loc[mask, 'Retweet_Count']
)
</code>```

Example:

```<code># Sample data.
inf = pd.DataFrame(
    {'Tweet': ["RT @ something", "something that doesn't start with RT @", "something else"],
     'Favorite_Count': [1, 2, 3],
     'Retweet_Count': [3, 2, 1]})

# Apply code
inf['Engagement'] = 0
mask = ~inf.Tweet.str.startswith('RT @')
inf.loc[mask, 'Engagement'] = (
    inf.loc[mask, 'Favorite_Count']
    + inf.loc[mask, 'Retweet_Count']
)

>>> inf[['Favorite_Count', 'Retweet_Count', 'Engagement', 'Tweet']]
    Favorite_Count  Retweet_Count   Engagement  Tweet
0   1   3   0   RT @ something
1   2   2   4   something that doesn't start with RT @
2   3   1   4   something else
</code>```

Title: String startswith a particular text

Body:
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)

Body:
You can first initialize your Engagement column to zeros.  Then create a mask to find the tweets that don't start with 'RT @' (note the ~ negation).  Finally, use the mask to add the Favorite_Count and Retweet_Count columns.

Note that you rarely want to use loops with a dataframe.

inf = pd.read_csv('string.csv')

inf['Engagement'] = 0
mask = ~inf.Tweet.str.startswith('RT @')
inf.loc[mask, 'Engagement'] = (
    inf.loc[mask, 'Favorite_Count']
    + inf.loc[mask, 'Retweet_Count']
)

Example:

# Sample data.
inf = pd.DataFrame(
    {'Tweet': ["RT @ something", "something that doesn't start with RT @", "something else"],
     'Favorite_Count': [1, 2, 3],
     'Retweet_Count': [3, 2, 1]})

# Apply code
inf['Engagement'] = 0
mask = ~inf.Tweet.str.startswith('RT @')
inf.loc[mask, 'Engagement'] = (
    inf.loc[mask, 'Favorite_Count']
    + inf.loc[mask, 'Retweet_Count']
)

>>> inf[['Favorite_Count', 'Retweet_Count', 'Engagement', 'Tweet']]
    Favorite_Count  Retweet_Count   Engagement  Tweet
0   1   3   0   RT @ something
1   2   2   4   something that doesn't start with RT @
2   3   1   4   something else


问:
Selenium Webdriver with Python: Element is not clickable & Cannot read property 'click' of null
when running this command, I'm getting an error:

```<code>driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="javascript:void(0);" class="c-button u-fontSize13 c-button--blue transparent-button js-connect-button js-request-connection" data-href="https://angel.co/user_graph_requests" data-invited-id="5911955">...</a> is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`
</code>```

After searching answers on this issue, I've changed the above code to:

```<code>element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)
</code>```

For the first click it worked and then printed this error:

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null
</code>```

The HTML code is:

```<code><a href="javascript:void(0);" class="c-button js-close s-vgLeft0_5 c-button--blue" data-modal="true" data-url="https://angel.co/user_graph_requests/102006082/verify">Confirm</a>
</code>```

答:
So this worked for me:

```<code>driver.find_element_by_link_text("Confirm").send_keys('\n')
</code>```

Thanks to everybody :)

Body:
when running this command, I'm getting an error:

driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`

After searching answers on this issue, I've changed the above code to:

element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)

For the first click it worked and then printed this error:

selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null

The HTML code is:

Confirm

Body:
So this worked for me:

driver.find_element_by_link_text("Confirm").send_keys('\n')

Thanks to everybody :)


问:
Set row/column/block to 0 in Eigen sparse matrix?
I see with new Eigen 3.2, you can get row, column or even block from a sparse matrix, is there a way to set any of these to 0?

```<code>Eigen::SparseMatrix<float, Eigen::RowMajor> A( 5, 5 );
    A.block(1, 1, 2, 2) = 0; // won't work
    A.row(1) = 0; // won't work
    A.col(1) = 0; // won't work
</code>```

Thanks!

答:
Eigen's Tutorial for sparse matrices (Tutorial Sparse: block operations) explain that for ColumnMajor (resp. RowMajor) sparse matrices, the column (resp. row) sub-matrix operators have write-access.

So, for example, to set to zero the 2nd, 3rd and 4th rows of a rowmajor sparse matrix you could do:
Eigen::SparseMatrix<float, Eigen::RowMajor> A;
A = MatrixXf::Random(5,5).sparseView();
A.middleRows(1,3) = Eigen::SparseMatrix<float,Eigen::RowMajor>(3,A.cols());

And leave prune() for setting to zero columns of row major matrices and vicevesa.

Body:
I see with new Eigen 3.2, you can get row, column or even block from a sparse matrix, is there a way to set any of these to 0?

Eigen::SparseMatrix<float, Eigen::RowMajor> A( 5, 5 );
    A.block(1, 1, 2, 2) = 0; // won't work
    A.row(1) = 0; // won't work
    A.col(1) = 0; // won't work

Thanks!


问:
Pop to root view when tab is selected
I've been having some trouble with something I thought might be easy. I have a table in my root view controller, when a row is selected I push a new view and from there I go to another tab. </p>

<p>My question is how do I make sure that as soon as the user taps the first tab the navigation controller will pop to root? </p>

答:
In Swift 3.1

Add UITabBarControllerDelegate to your TabBar Class:

class YourClass: UITabBarController, UITabBarControllerDelegate {

After:

override func tabBar(tabBar: UITabBar, didSelectItem item:
  UITabBarItem) {

```<code>let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView .popToRootViewControllerAnimated(false)
</code>```

}

Title: Pop to root view when tab is selected

Body:
I've been having some trouble with something I thought might be easy. I have a table in my root view controller, when a row is selected I push a new view and from there I go to another tab.

My question is how do I make sure that as soon as the user taps the first tab the navigation controller will pop to root?

Body:
In Swift 3.1

Add UITabBarControllerDelegate to your TabBar Class:

class YourClass: UITabBarController, UITabBarControllerDelegate {

After:

override func tabBar(tabBar: UITabBar, didSelectItem item:
  UITabBarItem) {

let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView .popToRootViewControllerAnimated(false)

}


问:
Couchbase LiveQuery doesn't work with other keyPath than "rows"
I have a problem: I use Xcode and Swift in addition to the latest Couchbase Mobile Solution. LiveQuery also works perfectly, if I use the String "rows" in order to register the Observer and then listen to it. But I have a view in my app, where I need two livequerys. So I intended to make two livequeries with two different key paths, for example the first one "getTopicComments", and the second one "getTopicDetails", so I could differenciate between them like below. But as I said, it only works for the key path "rows". Am I misunderstanding sth? Because I totally don't understand why it doesn't work with another String. In my opinion and as I read in the documentation of couchbase it shouldn't be relevant which String I use when registering the live query.

```<code>liveQueryOne.addObserver(self, forKeyPath: "getTopicComments", options: .new, context: nil)
liveQueryTwo.addObserver(self, forKeyPath: "getTopicDetails", options: .new, context: nil)
</code>```

and

```<code>override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "getTopicComments") {
} else if (keyPath == "getTopicDetails") {
}
}
</code>```

答: "rows" is a KVO observable property on CBLLiveQuery. That is why you can add an observer and look for KVO notifications. The idea behind live queries is that the app can be automatically notified of changes to database that affect the results of the query. The "rows" property will be updated when database updates and that's why you observe this property to be informed of changes. The keyPaths that you added above do not exist in CBLLiveQuery, so you will not see any notifications.</p>

Body:
I have a problem: I use Xcode and Swift in addition to the latest Couchbase Mobile Solution. LiveQuery also works perfectly, if I use the String "rows" in order to register the Observer and then listen to it. But I have a view in my app, where I need two livequerys. So I intended to make two livequeries with two different key paths, for example the first one "getTopicComments", and the second one "getTopicDetails", so I could differenciate between them like below. But as I said, it only works for the key path "rows". Am I misunderstanding sth? Because I totally don't understand why it doesn't work with another String. In my opinion and as I read in the documentation of couchbase it shouldn't be relevant which String I use when registering the live query.

liveQueryOne.addObserver(self, forKeyPath: "getTopicComments", options: .new, context: nil)
liveQueryTwo.addObserver(self, forKeyPath: "getTopicDetails", options: .new, context: nil)

and

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "getTopicComments") {
} else if (keyPath == "getTopicDetails") {
}
}


问:
Section with background image expanding to overall sidebar
I am currently building a web page and encountered the following problem and would appreciate if someone helped me solve it:

I want to have a full-width background image for every "section" (div) of the page. Within this background, there is a smaller div for content (text). On the right, there is a scrolling sidebar which scrolls with the user. I could not find how to have a full-width div and the sidebar(which is a div element with descendants) going over it?

The current structure looks like:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      here go all the "sections"...

      and that is the sidebar...

```

So in short, what is needed is background images with some html content on top of them and a sidebar on the right (but being covered by the image). Thank you in advance!

答:
So I guess that means you plan to make a fixed sidebar? You need to put the columns in a row. Make the row have the background-image. Position the sidebar fixed, this makes the bootstrap class ineffective but you can make the width 25% so it stays responsive. You may need to add some padding/margin, but I made something up quick with random colors so you can get the idea.

#sidebar{
  position:fixed;
  right:0;
  top:0;
  background-color:rgba(0,0,0, .5);
  width:25%;
  color:white;
}
.blue{
  background-color:blue;
}
.white{
  background-color:white;
}
.red{
  background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
  <div class="container">
    <div class="row red">
      <div class="col-md-9">
        Section 1
      </div>
      <div class="col-md-3" id="sidebar">
        and that is the sidebar...<br/>
        ber<br/>
        baer
        badsr
      </div>
    </div>
    <div class="row white">
      <div class="col-md-9">
        Section 2
      </div>
    </div>
    <div class="row blue">
      <div class="col-md-9">
        Section 3
      </div>
    </div>
  </div>
</body></code>```

Body:
I am currently building a web page and encountered the following problem and would appreciate if someone helped me solve it:

I want to have a full-width background image for every "section" (div) of the page. Within this background, there is a smaller div for content (text). On the right, there is a scrolling sidebar which scrolls with the user. I could not find how to have a full-width div and the sidebar(which is a div element with descendants) going over it?

The current structure looks like:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      here go all the "sections"...

      and that is the sidebar...

So in short, what is needed is background images with some html content on top of them and a sidebar on the right (but being covered by the image). Thank you in advance!

Body:
So I guess that means you plan to make a fixed sidebar? You need to put the columns in a row. Make the row have the background-image. Position the sidebar fixed, this makes the bootstrap class ineffective but you can make the width 25% so it stays responsive. You may need to add some padding/margin, but I made something up quick with random colors so you can get the idea.

#sidebar{
  position:fixed;
  right:0;
  top:0;
  background-color:rgba(0,0,0, .5);
  width:25%;
  color:white;
}
.blue{
  background-color:blue;
}
.white{
  background-color:white;
}
.red{
  background-color:red;
}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
  <div class="container">
    <div class="row red">
      <div class="col-md-9">
        Section 1
      </div>
      <div class="col-md-3" id="sidebar">
        and that is the sidebar...<br/>
        ber<br/>
        baer
        badsr
      </div>
    </div>
    <div class="row white">
      <div class="col-md-9">
        Section 2
      </div>
    </div>
    <div class="row blue">
      <div class="col-md-9">
        Section 3
      </div>
    </div>
  </div>
</body>


问:
how to display the maximum value in the array?
```<code>int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }
</code>```

How do I then tell the program to display the max value of the array??
Thank you

答:
If you are not doing this for home work I would suggest using std::max_element (available in <algorithm>).

```<code>std::cout << "Max Value: " << *(std::max_element(number, numbers+30)) << std::endl;
</code>```

Otherwise, in your program all thats left to do is to print the value. You could use std::cout (available in <iostream>). After you've computed the great in the for loop.

```<code>// Dump the value greatest to standard output
std::cout << "Max value: " << greatest << std::endl;
</code>```

Body:
int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }

How do I then tell the program to display the max value of the array??
Thank you

Body:
If you are not doing this for home work I would suggest using std::max_element (available in <algorithm>).

std::cout << "Max Value: " << *(std::max_element(number, numbers+30)) << std::endl;

Otherwise, in your program all thats left to do is to print the value. You could use std::cout (available in <iostream>). After you've computed the great in the for loop.

// Dump the value greatest to standard output
std::cout << "Max value: " << greatest << std::endl;


问:
More appropriate way to loop over hex values
I'm populating a container with different symbols using an icon font. I want to know if there is a better way to iterate through hexadecimal values than to create a custom array and do it like this:

```<code>var hexPlaceValue1=0, hexPlaceValue2=0;
var hexArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];

for(var i=0;i through something;i++){
    if(hexPlaceValue1 == 15) {
        var $glyph = $('<div class="glyph" data-glyph-index="' + i + '">&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';</div>');
        hexPlaceValue1 = 0;
        hexPlaceValue2++;
    } else {
        var $glyph = $('<div class="glyph" data-glyph-index="' + i + '">&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';</div>');
        hexPlaceValue1++;
    }
}
</code>```

Obviously, this can lead to problems if more icons are introduced (granted, it would have to be a lot.) I just want to know if there is an more efficient way of doing this.

答:
Javascript, like most (all?) programing languages, knows how to handle Hexadecimal.

```<code>for (i=0x0; i < 0x30; i++) { print("0x0" + i.toString(16) +" = " + i) }
</code>```

Output:

```<code>0x00 = 0
0x01 = 1
0x02 = 2
0x03 = 3
0x04 = 4
0x05 = 5
0x06 = 6
0x07 = 7
0x08 = 8
0x09 = 9
0x0a = 10
0x0b = 11
0x0c = 12
0x0d = 13
0x0e = 14
0x0f = 15
0x010 = 16
[...]
0x026 = 38
0x027 = 39
0x028 = 40
0x029 = 41
0x02a = 42
0x02b = 43
0x02c = 44
0x02d = 45
0x02e = 46
0x02f = 47
</code>```

And then one can play with padding, see google or this question: Pad a number with leading zeros in JavaScript

Body:
I'm populating a container with different symbols using an icon font. I want to know if there is a better way to iterate through hexadecimal values than to create a custom array and do it like this:

var hexPlaceValue1=0, hexPlaceValue2=0;
var hexArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];

for(var i=0;i through something;i++){
    if(hexPlaceValue1 == 15) {
        var $glyph = $('
&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';
');
        hexPlaceValue1 = 0;
        hexPlaceValue2++;
    } else {
        var $glyph = $('
&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';
');
        hexPlaceValue1++;
    }
}

Obviously, this can lead to problems if more icons are introduced (granted, it would have to be a lot.) I just want to know if there is an more efficient way of doing this.

Body:
Javascript, like most (all?) programing languages, knows how to handle Hexadecimal.

for (i=0x0; i < 0x30; i++) { print("0x0" + i.toString(16) +" = " + i) }

Output:

0x00 = 0
0x01 = 1
0x02 = 2
0x03 = 3
0x04 = 4
0x05 = 5
0x06 = 6
0x07 = 7
0x08 = 8
0x09 = 9
0x0a = 10
0x0b = 11
0x0c = 12
0x0d = 13
0x0e = 14
0x0f = 15
0x010 = 16
[...]
0x026 = 38
0x027 = 39
0x028 = 40
0x029 = 41
0x02a = 42
0x02b = 43
0x02c = 44
0x02d = 45
0x02e = 46
0x02f = 47

And then one can play with padding, see google or this question: Pad a number with leading zeros in JavaScript


问:
Standard deviation of a list
I want to find mean and standard deviation of 1st, 2nd,... digits of several (Z) lists. For example, I have

```<code>A_rank=[0.8,0.4,1.2,3.7,2.6,5.8]
B_rank=[0.1,2.8,3.7,2.6,5,3.4]
C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1]
# etc (up to Z_rank )...
</code>```

Now I want to take the mean and std of *_Rank[0], the mean and std of *_Rank[1], etc.

(ie: mean and std of the 1st digit from all the (A..Z)_rank lists;

the mean and std of the 2nd digit from all the (A..Z)_rank lists;

the mean and std of the 3rd digit...; etc).

答:
pure python code:</p>

```<code>from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))
</code>```

Title: Standard deviation of a list

Body:
I want to find mean and standard deviation of 1st, 2nd,... digits of several (Z) lists. For example, I have

A_rank=[0.8,0.4,1.2,3.7,2.6,5.8]
B_rank=[0.1,2.8,3.7,2.6,5,3.4]
C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1]
# etc (up to Z_rank )...

Now I want to take the mean and std of *_Rank[0], the mean and std of *_Rank[1], etc.

(ie: mean and std of the 1st digit from all the (A..Z)_rank lists;

the mean and std of the 2nd digit from all the (A..Z)_rank lists;

the mean and std of the 3rd digit...; etc).

Body:
pure python code:

from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))


问:
How to debug using Docker on Mac
I have kafka running in a docker container on my Maac. Here is how i start it

```<code>#Start Zookeeper
docker run -d -p 2181:2181 --net myNet --name myZookeeper myRegistry/kafka:0.10.1.0 zookeeper-server-start

#Start Kafka
export KAFKA_ADVERTISE_HOSTNAME="my.ip.add"

docker run -d --net br-advisor-nw  --name whi-kafka -p 9092:9092 --link myZookeeper:myZookeeper myRegistry/kafka:0.10.1.0 kafka-server-start --override zookeeper.connect=${KAFKA_ADVERTISE_HOSTNAME}:2181  --override broker.id=0 --override advertised.host.name=${KAFKA_ADVERTISE_HOSTNAME} --override group.max.session.timeout.ms=3600000 --override auto.create.topics.enable=false --override replica.fetch.max.bytes=10485760 --override message.max.bytes=10485760 --override port=9092 --override  listeners=PLAINTEXT://:9092
</code>```

I can see the containers running in Docker, and i can ssh into the containers just fine.

Now, I am trying to connect to the container from my host machine as

```<code>kafka-topics.sh --list --zookeeper my.ip.add:2181
</code>```

but this fails to connect. I have also tried

```<code>kafka-topics.sh --list --zookeeper 0.0.0.0:2181

kafka-topics.sh --list --zookeeper 127.0.0.0:2181

kafka-topics.sh --list --zookeeper localhost:2181
</code>```

but they all fail. I also tried to get the IP of the container from

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' myZookeeper
</code>```

gives

```<code>ip.of.container
</code>```

but

```<code>kafka-topics.sh --list --zookeeper ip.of.container:2181
</code>```

fails as well.

Is there any way for me to connect to kafka/zookeeper running inside the docker container?

Also, it appears that although i am using the -p flag, neither of the ports are exposed. Why is that?

答:
It looks like you're using docker-toolbox/docker-machine on your Mac to run docker. This creates a Linux VM under the covers but doesn't have some of the features of the xhyve release that hides the VM. You'll see it running in virutalbox, and you'll see it in the IP address you need to use to connect to your containers.

You should be able to run:

```<code>kafka-topics.sh --list --zookeeper 192.168.99.100:2181
</code>```

To lookup your IP in the future, you can use docker-machine ip. If your install of Mac is new enough, you may want to upgrade to a newer version that uses xhyve.

Title: How to debug using Docker on Mac

Body:
I have kafka running in a docker container on my Maac. Here is how i start it

#Start Zookeeper
docker run -d -p 2181:2181 --net myNet --name myZookeeper myRegistry/kafka:0.10.1.0 zookeeper-server-start

#Start Kafka
export KAFKA_ADVERTISE_HOSTNAME="my.ip.add"

docker run -d --net br-advisor-nw  --name whi-kafka -p 9092:9092 --link myZookeeper:myZookeeper myRegistry/kafka:0.10.1.0 kafka-server-start --override zookeeper.connect=${KAFKA_ADVERTISE_HOSTNAME}:2181  --override broker.id=0 --override advertised.host.name=${KAFKA_ADVERTISE_HOSTNAME} --override group.max.session.timeout.ms=3600000 --override auto.create.topics.enable=false --override replica.fetch.max.bytes=10485760 --override message.max.bytes=10485760 --override port=9092 --override  listeners=PLAINTEXT://:9092

I can see the containers running in Docker, and i can ssh into the containers just fine.

Now, I am trying to connect to the container from my host machine as

kafka-topics.sh --list --zookeeper my.ip.add:2181

but this fails to connect. I have also tried

kafka-topics.sh --list --zookeeper 0.0.0.0:2181

kafka-topics.sh --list --zookeeper 127.0.0.0:2181

kafka-topics.sh --list --zookeeper localhost:2181

but they all fail. I also tried to get the IP of the container from

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' myZookeeper

gives

ip.of.container

but

kafka-topics.sh --list --zookeeper ip.of.container:2181

fails as well.

Is there any way for me to connect to kafka/zookeeper running inside the docker container?

Also, it appears that although i am using the -p flag, neither of the ports are exposed. Why is that?

Body:
It looks like you're using docker-toolbox/docker-machine on your Mac to run docker. This creates a Linux VM under the covers but doesn't have some of the features of the xhyve release that hides the VM. You'll see it running in virutalbox, and you'll see it in the IP address you need to use to connect to your containers.

You should be able to run:

kafka-topics.sh --list --zookeeper 192.168.99.100:2181

To lookup your IP in the future, you can use docker-machine ip. If your install of Mac is new enough, you may want to upgrade to a newer version that uses xhyve.


答:
I had a similar problem once, what I did was something like this

```<code><datalist id="foundNames">
  <option value="{'choice': 'one', 'value': 1, 'weather': ['cloudy', 'rainy']}">One</option>
  <option value="{'choice': 'two', 'value': 2, 'weather': ['cloudy', 'rainy']}">Two</option>
  <option value="{'choice': 'three', 'value': 3, 'weather': ['cloudy', 'rainy']}">Three</option>
</datalist>
</code>```

Notice I had to change a little that JSON to use just a single quote, and then to parse it back to JSON I had return to double quote. Nowadays it may be some lib to do that, like this https://github.com/jcoc611/cassandraMAP

Title: How to pass, from <input>, a different value that the chosen one

Body:
I use <input> to choose a value in a Vue.js context. The context does not matter (I believe) - this is just to say the value of the <input> field is always synchronized with a variable called searchedName and that there is no actual "submission" of the input (as it is already available at all times):

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</datalist>

When choosing from the dropdown a value, it is this exact string which is chosen (One for instance).

I would like, however, this string to just be a display name, and that the actual choice is an Object. As an example, when choosing One from the dropdown, I would like to pass further {"choice": "one", "value": 1, "weather": ["cloudy", "rainy"]} - and not the string "One".

Is this possible?

EDIT: Just in case, I am posting the actual Vue.js code which handle this bit. foundNames is updated somewhere else (in an AJAX call) and is an Array of Objects. The addID method is supposed to use {{name._source}}, which is currently displayed as it. I would like to hide it and display some of its elements instead.

            Input "Something":
            <input v-model="searchedName" list="foundNames">
            <datalist id="foundNames">
                <option v-for="name in foundNames" value="name">{{name._source}}</option>
            </datalist>

        <button v-on:click="addID">add name</button>

Looking at the first answers, the way to go would be something along the lines of

<option v-for="name in foundNames" value="name">{{name._source.interesingelementtodisplay}}</option>

but value="name" sets the value to "name" (verbatim) and not the current value of the variable name in the v-for iteration.

Body:
I had a similar problem once, what I did was something like this

<datalist id="foundNames">
  <option value="{'choice': 'one', 'value': 1, 'weather': ['cloudy', 'rainy']}">One</option>
  <option value="{'choice': 'two', 'value': 2, 'weather': ['cloudy', 'rainy']}">Two</option>
  <option value="{'choice': 'three', 'value': 3, 'weather': ['cloudy', 'rainy']}">Three</option>
</datalist>

Notice I had to change a little that JSON to use just a single quote, and then to parse it back to JSON I had return to double quote. Nowadays it may be some lib to do that, like this https://github.com/jcoc611/cassandraMAP


问:
Good OO practice + Should we implement complicated logic in subclasses for sake of OO?
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

```<code>Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}
</code>```

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?

答:
Employee -> Account[] with Type, currencies -> Entries[]

Employee -> Account[] with currencies-> Entries[] with type

You can use each Account for type (refund) and currencies, or better a Account only for each currencies and the Entry with type (Refund)

The rest should be done by a service!

Body:
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?