问:
HTML link to local file in WebView with target API 24
How can one use HTML links to navigate to local files (HTML pages) in WebView if targeting API 24 or higher?

This has been discussed before and solutions use the file:// URI scheme.
What worked so far was using

```<code><a href="file:///android_asset/my_page.html">Go to local page</a>
</code>```

in an HTML file that is displayed in a WebView and clicking the link would load the local page app/src/main/assets/my_page.html.

However, starting from API 24, a FileUriExposedException is raised when clicking such a link. From logcat:

```<code>mypackage.myapp W/System.err: android.os.FileUriExposedException: file:///android_asset/my_page.html exposed beyond app through Intent.getData()
...
mypackage.myapp W/System.err:     at org.chromium.android_webview.ResourcesContextWrapperFactory$WebViewContextWrapper.startActivity(ResourcesContextWrapperFactory.java:121)
mypackage.myapp W/System.err:     at org.chromium.android_webview.AwContentsClient.sendBrowsingIntent(AwContentsClient.java:203)
</code>```

According to the documentation, this is thrown when "an application exposes a file:// Uri to another app.". I wonder why this is the case, because according to the log everything seems to happen inside mypackage.myapp.

The documentation suggests using the content:// URI scheme instead, but this does not work in HTML files.

答:
The following workaround (based on this answer) intercepts the loading of a file:// URI in the WebView and then loads it directly by app code with WebView.loadUrl(...). This is possible by overriding WebView.shouldOverrideUrlLoading in a WebViewClient passed to the WebView, e.g. when initializing it.

As there was an API change for this method in API 24, for compatibility there are two versions in the code (technically in the API<24 case one could also do as before, letting WebView open the file:// URI because the exception is not raised on devices running API<24).

```<code>if (android.os.Build.VERSION.SDK_INT >= 24) {
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            if (webResourceRequest.getUrl().getScheme().equals("file")) {
                webView.loadUrl(webResourceRequest.getUrl().toString());
            } else {
                // If the URI is not pointing to a local file, open with an ACTION_VIEW Intent
                webView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, webResourceRequest.getUrl()));
            }
            return true; // in both cases we handle the link manually
        }
    });
} else {
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if (Uri.parse(url).getScheme().equals("file")) {
                webView.loadUrl(url);
            } else {
                // If the URI is not pointing to a local file, open with an ACTION_VIEW Intent
                webView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
            return true; // in both cases we handle the link manually
        }
    });
}
</code>```

The reason why there is an exception when letting the WebView open the link must have something to do with the Intent created by the WebView but I don't see whether or how it is exposed to another app.

That the workaround works is then because the WebView does not do anything with the link (no Intent is created), instead, when the link is clicked, the app gets control and opens the file:// URI direclty by passing it to WebView.loadUrl(...) - which seems to be fine.

I assume (but do not claim) that regarding security this is fine because the URI is only used to load the file it points to in this single WebView (and if this was problematic the system should throw the FileUriExposedException).

Body:
How can one use HTML links to navigate to local files (HTML pages) in WebView if targeting API 24 or higher?

This has been discussed before and solutions use the file:// URI scheme.
What worked so far was using

Go to local page

in an HTML file that is displayed in a WebView and clicking the link would load the local page app/src/main/assets/my_page.html.

However, starting from API 24, a FileUriExposedException is raised when clicking such a link. From logcat:

mypackage.myapp W/System.err: android.os.FileUriExposedException: file:///android_asset/my_page.html exposed beyond app through Intent.getData()
...
mypackage.myapp W/System.err:     at org.chromium.android_webview.ResourcesContextWrapperFactory$WebViewContextWrapper.startActivity(ResourcesContextWrapperFactory.java:121)
mypackage.myapp W/System.err:     at org.chromium.android_webview.AwContentsClient.sendBrowsingIntent(AwContentsClient.java:203)

According to the documentation, this is thrown when "an application exposes a file:// Uri to another app.". I wonder why this is the case, because according to the log everything seems to happen inside mypackage.myapp.

The documentation suggests using the content:// URI scheme instead, but this does not work in HTML files.

Body:
The following workaround (based on this answer) intercepts the loading of a file:// URI in the WebView and then loads it directly by app code with WebView.loadUrl(...). This is possible by overriding WebView.shouldOverrideUrlLoading in a WebViewClient passed to the WebView, e.g. when initializing it.

As there was an API change for this method in API 24, for compatibility there are two versions in the code (technically in the API<24 case one could also do as before, letting WebView open the file:// URI because the exception is not raised on devices running API<24).

if (android.os.Build.VERSION.SDK_INT >= 24) {
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            if (webResourceRequest.getUrl().getScheme().equals("file")) {
                webView.loadUrl(webResourceRequest.getUrl().toString());
            } else {
                // If the URI is not pointing to a local file, open with an ACTION_VIEW Intent
                webView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, webResourceRequest.getUrl()));
            }
            return true; // in both cases we handle the link manually
        }
    });
} else {
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if (Uri.parse(url).getScheme().equals("file")) {
                webView.loadUrl(url);
            } else {
                // If the URI is not pointing to a local file, open with an ACTION_VIEW Intent
                webView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
            return true; // in both cases we handle the link manually
        }
    });
}

The reason why there is an exception when letting the WebView open the link must have something to do with the Intent created by the WebView but I don't see whether or how it is exposed to another app.

That the workaround works is then because the WebView does not do anything with the link (no Intent is created), instead, when the link is clicked, the app gets control and opens the file:// URI direclty by passing it to WebView.loadUrl(...) - which seems to be fine.

I assume (but do not claim) that regarding security this is fine because the URI is only used to load the file it points to in this single WebView (and if this was problematic the system should throw the FileUriExposedException).


来源: stackexchange

问:
Menubar based on links. Doesn't work background changing on click
Menubar is based on a list of links. It's needed change background color on clicked item and leave it. In my case a color changes for a short time and gets back to CSS background.

$(function() {
  $(".menu a").bind("click", function() {
    $(".menu a").removeClass("clicked");
    $(this).addClass("clicked");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu {
  width: auto;
  display: block;
}

.menu li {
  display: inline;
}

.menu li a {
  border: solid 2px white;
  color: white;
  text-decoration: none;
  background: #a0a0a0;
  width: 100px;
  float: left;
}

.menu a.clicked {
  background: #b34a4a;
}

.menu {
  width: auto;
  display: block;
}

.menu li {
  display: inline;
}

.menu li a {
  border: solid 2px white;
  color: white;
  text-decoration: none;
  background: #a0a0a0;
  width: 100px;
  float: left;
}

.menu a.clicked {
  background: #b34a4a;
}</code>```

 ITEM 1
      ITEM 2
      ITEM 3
      ITEM 4
      EXIT

```

Added link to jsfiddle.

答:
The first thing you're missing is the href attribute on menu elements. When you click on them if you don't set them at least to "#" the page will reload, and so they won't have the class "clicked"

Second thing I wrote a different js for you

```<code> $(function(){ $(".menu a").click(function() {
   $(".menu a").removeClass("clicked");
   $(this).addClass("clicked");
   });
 })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Menubar is based on a list of links. It's needed change background color on clicked item and leave it. In my case a color changes for a short time and gets back to CSS background.

$(function() {
  $(".menu a").bind("click", function() {
    $(".menu a").removeClass("clicked");
    $(this).addClass("clicked");
  });
});

.menu {
  width: auto;
  display: block;
}

.menu li {
  display: inline;
}

.menu li a {
  border: solid 2px white;
  color: white;
  text-decoration: none;
  background: #a0a0a0;
  width: 100px;
  float: left;
}

.menu a.clicked {
  background: #b34a4a;
}

.menu {
  width: auto;
  display: block;
}

.menu li {
  display: inline;
}

.menu li a {
  border: solid 2px white;
  color: white;
  text-decoration: none;
  background: #a0a0a0;
  width: 100px;
  float: left;
}

.menu a.clicked {
  background: #b34a4a;
}

 ITEM 1
      ITEM 2
      ITEM 3
      ITEM 4
      EXIT

Added link to jsfiddle.

Body:
The first thing you're missing is the href attribute on menu elements. When you click on them if you don't set them at least to "#" the page will reload, and so they won't have the class "clicked"

Second thing I wrote a different js for you

 $(function(){ $(".menu a").click(function() {
   $(".menu a").removeClass("clicked");
   $(this).addClass("clicked");
   });
 })


问:
How To Properly Create a Histogram: Displaying the Frequency of the Tweets for Each Day Spanning 2 Years
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

```<code>timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']
</code>```

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

答:
The simplest solution is probably to parse the strings into date objects and create a histogram using pyplot's hist from this data:

from datetime import date, timedelta
import matplotlib.pyplot as plt

# these lines are just there to create some data
from random import randint
from datetime import datetime
timestamp_list = [datetime(2017,randint(4,6),randint(1,30),randint(0,23),randint(0,59)).strftime("%Y-%m-%d %h:%m") for i in range(1000)]

# here the real code starts
dates = []
for t in timestamp_list:
    # extract the date part of the timestamp
    date_str = t.split(' ')[0]
    # extract the numbers from the date
    year,month,day = [int(i) for i in date_str.split('-')]
    # create a date object
    d = date(year, month, day)
    # and store it
    dates.append(d)

# sort the dates
dates.sort()

# extract the first and last date
min_date = dates[0]
max_date = dates[-1]

# compute the number of days
length = (max_date - min_date).days + 1

# show the histogram
plt.hist(dates, bins=length)
plt.show()
```

<p>If you want a little bit more control over how your plot looks, I would recommend that you create the buckets for your histogram yourself and plot them using a <code>bar</code> plot:</p>

<pre class="lang-py prettyprint-override"><code># initialize one empty bucket per day
buckets = [0 for i in range(length)]
days = [(min_date + timedelta(i)).isoformat() for i in range(length)]

for d in dates:
    days_from_begin = (d - min_date).days
    buckets[days_from_begin] += 1

# print a bar plot of the results
plt.bar(range(length), buckets)
# add x-axis ticks (dates)
plt.xticks(range(length), days, rotation=70)

# some cosmetics: hide all ticks
plt.setp(plt.gca().get_xticklabels(), visible=False)
# show every 4th tick again
plt.setp(plt.gca().get_xticklabels()[::4],visible=True)

# show the result
plt.show()
</code>```

The output might look something like this:

Body:
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

Body:
The simplest solution is probably to parse the strings into date objects and create a histogram using pyplot's hist from this data:

from datetime import date, timedelta
import matplotlib.pyplot as plt

# these lines are just there to create some data
from random import randint
from datetime import datetime
timestamp_list = [datetime(2017,randint(4,6),randint(1,30),randint(0,23),randint(0,59)).strftime("%Y-%m-%d %h:%m") for i in range(1000)]

# here the real code starts
dates = []
for t in timestamp_list:
    # extract the date part of the timestamp
    date_str = t.split(' ')[0]
    # extract the numbers from the date
    year,month,day = [int(i) for i in date_str.split('-')]
    # create a date object
    d = date(year, month, day)
    # and store it
    dates.append(d)

# sort the dates
dates.sort()

# extract the first and last date
min_date = dates[0]
max_date = dates[-1]

# compute the number of days
length = (max_date - min_date).days + 1

# show the histogram
plt.hist(dates, bins=length)
plt.show()

If you want a little bit more control over how your plot looks, I would recommend that you create the buckets for your histogram yourself and plot them using a bar plot:

# initialize one empty bucket per day
buckets = [0 for i in range(length)]
days = [(min_date + timedelta(i)).isoformat() for i in range(length)]

for d in dates:
    days_from_begin = (d - min_date).days
    buckets[days_from_begin] += 1

# print a bar plot of the results
plt.bar(range(length), buckets)
# add x-axis ticks (dates)
plt.xticks(range(length), days, rotation=70)

# some cosmetics: hide all ticks
plt.setp(plt.gca().get_xticklabels(), visible=False)
# show every 4th tick again
plt.setp(plt.gca().get_xticklabels()[::4],visible=True)

# show the result
plt.show()

The output might look something like this:


问:
recursive mapping in python
What is the most pythonic way to apply a recursive function to structured/nested lists/list comprehension and return a structured/nested list/list comprehension of the same structure?

A minimal working example:

```<code>list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]
list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]
</code>```

I need a recursive function that is robust to the the structure of list1,
 list2 and possibly more, and to the vanilla function lambda x,y: x*y. The desired result in this tiny example is:

```<code>result = [[[3,4,12],[4,3,5],[10,4,4]],[[3,6],[6,2],[3,4]],[[4,6,8]]]
</code>```

Another example using list1 and list3 where list3 is:

```<code>list3 = [[[3],[2],[2]],[[3],[2],[1]],[[2]]]
</code>```

and the desired result is:

```<code>result = [[[3,6,9],[4,6,10],[10,4,5]], [[3,6],[6,2],[3,4]], [[4,6,8]]
</code>```

答:
If you want to see a recursive solution to this, in case your lists can be arbitrarily nested, you may prefer something like:

```<code>>>> list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]]
>>> list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]
>>> def parallel_apply(l1, l2, f):
...     if isinstance(l1, list) and isinstance(l2, list):
...         return [parallel_apply(x,y, f) for x,y in zip(l1,l2)]
...     elif not isinstance(l1, list) and not isinstance(l2, list):
...         return f(l1, l2)
...     else:
...         raise ValueError("Structures incompatible for parallel apply")
...
>>> parallel_apply(list1, list2, lambda x,y: x*y)
[[[3, 4, 12], [4, 3, 5], [10, 4, 4]], [[3, 6], [6, 2], [3, 4]], [[4, 6, 8]]]
</code>```

Note, Python has a maximum recursion depth and no tail-call optimization. If your lists can be nested very deep then you may have to transform this into an iterative solution.

Title: recursive mapping in python

Body:
What is the most pythonic way to apply a recursive function to structured/nested lists/list comprehension and return a structured/nested list/list comprehension of the same structure?

A minimal working example:

list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]
list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]

I need a recursive function that is robust to the the structure of list1,
 list2 and possibly more, and to the vanilla function lambda x,y: x*y. The desired result in this tiny example is:

result = [[[3,4,12],[4,3,5],[10,4,4]],[[3,6],[6,2],[3,4]],[[4,6,8]]]

Another example using list1 and list3 where list3 is:

list3 = [[[3],[2],[2]],[[3],[2],[1]],[[2]]]

and the desired result is:

result = [[[3,6,9],[4,6,10],[10,4,5]], [[3,6],[6,2],[3,4]], [[4,6,8]]

Body:
If you want to see a recursive solution to this, in case your lists can be arbitrarily nested, you may prefer something like:

>>> list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]]
>>> list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]
>>> def parallel_apply(l1, l2, f):
...     if isinstance(l1, list) and isinstance(l2, list):
...         return [parallel_apply(x,y, f) for x,y in zip(l1,l2)]
...     elif not isinstance(l1, list) and not isinstance(l2, list):
...         return f(l1, l2)
...     else:
...         raise ValueError("Structures incompatible for parallel apply")
...
>>> parallel_apply(list1, list2, lambda x,y: x*y)
[[[3, 4, 12], [4, 3, 5], [10, 4, 4]], [[3, 6], [6, 2], [3, 4]], [[4, 6, 8]]]

Note, Python has a maximum recursion depth and no tail-call optimization. If your lists can be nested very deep then you may have to transform this into an iterative solution.


问:
goodFeaturesToTrack() works only on greyscale?
I am new to working in openCV. I was trying to detect features in an image using goodFeaturesToTrack() in c++ in a colored image but it gave me the following error:

" OpenCV Error: Assertion failed (src.type() == CV_8UC1 || src.type() == CV_32FC1) in cv::cornerEigenValsVecs, file D:\cs436\opencv-3.2.0\modules\imgproc\src\corner.cpp, line 287 "

Then I tried it on a greyscale image and it found the features. Can anyone please tell if we can use the function on a colored image? and what does the error mean?

答:
From the documentation of goodFeaturesToTrack(), the image parameters takes in a 8-bit or 32-bit single channel image. single channel implies grayscale.

So yes, the function only works for grayscale images. The error message also indicates that by saying that the src.type() must have 1 channel as indicated by CV_8UC1 and CV_32FC1


问:
Re-call matplotlib graphs after inital call
I have a Tkinter GUI which creates a budget calculator and stores transactions. One of the buttons on the GUI is a call to a script that creates charts from the transaction data.

The first time I click the button, the graphs open up fine. If I attempt to click the button again, a blank figure comes up. I believe this comes from my initial,

```<code>plt.show()
</code>```

call where I draw the graphs. Has anyone ran into a problem like this before?

GUI code:

```<code>ViewCharts = Button(win,text = 'View Spending Charts')
ViewCharts.grid(row = 21,column = 1)

def view_charts():
    Graphs.plot_charts()

ViewCharts.configure(command = view_charts)
</code>```

Charts code:

```<code>global fig
fig = plt.figure(figsize=(12, 9))
fig.subplots_adjust(hspace=.5)
global ax1
ax1 = fig.add_subplot(1,2,1)
global ax2
ax2 = fig.add_subplot(1,2,2)

def plot_charts():
    category_bar_chart()
    category_pie_chart()
    fig = plt.show()
</code>```

Where category_bar_chart() and category_pie_chart() are just functions to add plots into ax1 and ax2.

Any help or advice is greatly appreciated! I am working on Python3 on a Mac/PC depending on the time of day. Thanks!

答: The problem is you are redefining fig when you do fig = plt.show() so after the first call, you no longer have the plots stored anywhere. Simply do plt.show() instead.

Body:
I have a Tkinter GUI which creates a budget calculator and stores transactions. One of the buttons on the GUI is a call to a script that creates charts from the transaction data.

The first time I click the button, the graphs open up fine. If I attempt to click the button again, a blank figure comes up. I believe this comes from my initial,

plt.show()

call where I draw the graphs. Has anyone ran into a problem like this before?

GUI code:

ViewCharts = Button(win,text = 'View Spending Charts')
ViewCharts.grid(row = 21,column = 1)

def view_charts():
    Graphs.plot_charts()

ViewCharts.configure(command = view_charts)

Charts code:

global fig
fig = plt.figure(figsize=(12, 9))
fig.subplots_adjust(hspace=.5)
global ax1
ax1 = fig.add_subplot(1,2,1)
global ax2
ax2 = fig.add_subplot(1,2,2)

def plot_charts():
    category_bar_chart()
    category_pie_chart()
    fig = plt.show()

Where category_bar_chart() and category_pie_chart() are just functions to add plots into ax1 and ax2.

Any help or advice is greatly appreciated! I am working on Python3 on a Mac/PC depending on the time of day. Thanks!


问:
Permission Denied while trying to connect to Docker Daemon while running Jenkins pipeline in Macbook
I am trying to run Jenkins pipeline job in my macbook. I also have docker instance running locally. Initially I got the "docker command not found" error while running the Jenkins Job. I fixed the error by adding a symlink "ln -f -s /Applications/Docker.app/Contents/Resources/bin/* /usr/local/bin"

I also applied these two changes so that jenkins user has the access to the docker directory

chmod -R 777 /Users/myUserName/Library/Containers/com.docker.docker/

chmod -R 777 /Users/myUserName/Library/Containers/com.docker.helper/

I am getting below errors:

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/containers/openjdk:8/json:
  dial unix /var/run/docker.sock: connect: permission denied
      [Pipeline] sh
      [test] Running shell script
      + docker pull openjdk:8
      Warning: failed to get default registry endpoint from daemon (Got permission denied while trying to connect to the Docker daemon socket
  at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/info: dial unix
  /var/run/docker.sock: connect: permission denied). Using system
  default: https://index.docker.io/v1/
      Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/images/create?fromImage=openjdk&tag=8:
  dial unix /var/run/docker.sock: connect: permission denied
      [Pipeline] }
      [Pipeline] // node
      [Pipeline] End of Pipeline
      ERROR: script returned exit code 1
      Finished: FAILURE

答:
There are any ways to solve this issue, I faced it last week, I solved but with docker-compose this setup is replicable to docker, you can create a shared volume that points from the location of docker.sock in your host /var/run/docker.sock to location of docker.sock in your container /var/run/docker.sock. Something like this:

```<code>version: '2'
services:
  jenkins:
    build:
      context: ./jenkins
    ports:
      - "8080:8080"
    expose:
      - "8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /usr/bin/docker:/usr/bin/docker
      - /usr/local/bin/docker-compose:/usr/local/bin/docker-compose

  nginx:
    build:
      context: ./nginx
    container_name: "prueba"
    links:
      - jenkins
    ports:
      - "80:80"
    depends_on:
      - jenkins
</code>```

To works well you have to give permissons of user to the socketsudo chown $USER:$USER /var/run/docker.sock and to the group of docker , as Innocent Anigbo mentioned.

Body:
There are any ways to solve this issue, I faced it last week, I solved but with docker-compose this setup is replicable to docker, you can create a shared volume that points from the location of docker.sock in your host /var/run/docker.sock to location of docker.sock in your container /var/run/docker.sock. Something like this:

version: '2'
services:
  jenkins:
    build:
      context: ./jenkins
    ports:
      - "8080:8080"
    expose:
      - "8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /usr/bin/docker:/usr/bin/docker
      - /usr/local/bin/docker-compose:/usr/local/bin/docker-compose

  nginx:
    build:
      context: ./nginx
    container_name: "prueba"
    links:
      - jenkins
    ports:
      - "80:80"
    depends_on:
      - jenkins

To works well you have to give permissons of user to the socketsudo chown $USER:$USER /var/run/docker.sock and to the group of docker , as Innocent Anigbo mentioned.


问:
extract phone number from string format either (xxx)xxxxxxx or (xxx)xxx-xxxx
I have phone number field in either of these two formats
 (xxx)xxxxxxx or (xxx)xxx-xxxx

I want to extract and format the number as xxxxxxxxxx, number only. Is there a simple way in sql select statement?

答:
```<code>SELECT
column_sample,
REPLACE(REPLACE(REPLACE(phone , '(', '') , ')', '') , '-', '') as phone
FROM tbl_sample;
</code>```


问:
Cocoa Touch - Display an Activity Indicator while loading a UITabBar View
I have a UITabBar Application with two views that load large amounts of data from the web in their "viewWillAppear" methods. I want to show a progress bar or an activity indicator while this data is being retrieved, to make sure the user knows the app isn't frozen.

I am aware that this has been asked before. I simply need some clarification on what seems to be a rather good solution.

I have implimented the code in the example. The question's original asker later solved their problem, by putting the retrieval of data into another "thread". I understand the concept of threads, but I do not know how I would impliment this.

With research, I have found that I need to move all of my heavy data retrieval into a background thread, as all of the UI updating occurs in the main thread.

If one would be so kind as to provide an example for me, I would be very appreciative. I can provide parts of my existing code as necessary.

答:
If you use NSURLConnection it runs on another thread automatically.

in your viewDidLoad:

```<code>NSURLRequest *req = [NSURLRequest requestWithURL:theURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
</code>```

then you need some custom methods. If you type in -connection and press Esc you'll see all the different methods you can use. There are three you will need with this:

```<code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // this is called when there is a response
        // if you're collecting data init your NSMutableData here
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // each time the connection downloads a
        // packet of data it gets send here
        // so you can do [myData appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
        // the connection has finished so you can
        // do what you want with the data here
}
</code>```

That is basically all there is to it. NSURLConnection handles all the multithreading itself and you don't have to worry. Now you can create an activity indicator and display it and it will work because the main thread is empty. :)

ContentLicense: CC BY-SA 2.5

Body:
If you use NSURLConnection it runs on another thread automatically.

in your viewDidLoad:

NSURLRequest *req = [NSURLRequest requestWithURL:theURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];

then you need some custom methods. If you type in -connection and press Esc you'll see all the different methods you can use. There are three you will need with this:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // this is called when there is a response
        // if you're collecting data init your NSMutableData here
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // each time the connection downloads a
        // packet of data it gets send here
        // so you can do [myData appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
        // the connection has finished so you can
        // do what you want with the data here
}

That is basically all there is to it. NSURLConnection handles all the multithreading itself and you don't have to worry. Now you can create an activity indicator and display it and it will work because the main thread is empty. :)


问:
Filtering empty strings from a string containing emojis using spread syntax
I'm trying to stay hip, so I've been playing with the spread operator and emojis. I noticed that when I want to filter empty strings ('') out the resulting "spread-ed" array, the empty strings are not being removed. Why is that?

console.log([...'']);                 // ['', '']
console.log([...''].filter(String));  // ['', '']
console.log(['', ''].filter(String)); // ['']```

答:
There is in your string an invisible character, which is a variation selector. You can see this if you print the character codes:

console.log([...''].map(s => s.charCodeAt(0)));```
</div>
</div>
</p>

<p>If your goal is to remove that particular variation selector 15, then you could just use a <code>replace</code>:</p>

```s.replace(/\ufe0e/g, '')
```

<p>Note how the emoji is slightly different in the output of the third statement you have. This is the effect of that variation selector, which you take away from the first character in the first two statements. Although that special character does not print anything on itself, and shows as an empty string when isolated, it really is not empty, and so <code>filter</code> will not exclude it.</p>

<p>Emoji characters themselves lie outside the single word UTF-16 range, and so they occupy two words. </p>

<p>When you split such a single-character string with <code>split</code>, you get two separate characters (a historic oddity of JavaScript), which represent the UTF encoding. If your goal is to count emojis (and other high-range characters) in your string, you could use this code:</p>

```console.log(s.split('').length - [...s].length);
```

Body:
There is in your string an invisible character, which is a variation selector. You can see this if you print the character codes:

console.log([...''].map(s => s.charCodeAt(0)));

If your goal is to remove that particular variation selector 15, then you could just use a replace:

s.replace(/\ufe0e/g, '')

Note how the emoji is slightly different in the output of the third statement you have. This is the effect of that variation selector, which you take away from the first character in the first two statements. Although that special character does not print anything on itself, and shows as an empty string when isolated, it really is not empty, and so filter will not exclude it.

Emoji characters themselves lie outside the single word UTF-16 range, and so they occupy two words.

When you split such a single-character string with split, you get two separate characters (a historic oddity of JavaScript), which represent the UTF encoding. If your goal is to count emojis (and other high-range characters) in your string, you could use this code:

console.log(s.split('').length - [...s].length);


问:
MAMP MySQL innodb and missing errors
I was running MAMP fine until I brought in one particular Drupal site. The site started white-screening, loading with no CSS, and occasionally throwing a PDO error, but only on the front site of the application. I could access the administration part of the site fine.

In the mysql error log I found a bunch of errors like InnoDB: Error: Table "mysql"."innodb_table_stats" not found. and ...required persistent statistics storage is not present or is corrupted. Using transient stats instead.

I dug through some of the Drupal views and found one that executes php from the database (big no-no!). I removed that from the database but I was still getting the same innodb errors.

Next I found this question. Similar sounding issue though different circumstances. I've seen a bunch of issues that seems related, though often involving upgrading to MySQL 5.6. The gist of the issue seems to be a list of tables in the mysql tables are improperly formatted. The solution suggested there and elsewhere is to delete the .frm, .ibd files associated with those tables, then recreate the tables using the query provided.

I did all that ^, and now all the sites in MAMP are sending 500 errors. Bigger than that, the error logs are totally silent, and I'm stuck with no idea where to turn.

NOTE: I uninstalled MAMP, reinstalled it, and the same thing occured.

答:
So, I will happily accept an answer that has a better explanation than what I'm giving here, but I "solved" this issue in the following manner:

The site was also running a module called "Sassy" that compiled CSS on the server, I was suspicious because of the missing CSS, so I configured the module to only compile when I explicitly tell it to.

I dropped and reimported each site's database.

I noticed as stated above I would get different responses on each page load. I persisted on going through the site, both admin and front side, by repeatedly reloading the pages.

In conclusion, I'm no longer getting the innodb errors, pushing through and disabling a sketchy(IMO) module seems to have fixed the white screen and 500 errors and brought back the styling. Which brings me to the big question I have which is, why wasn't I getting any error messages in the logs?

Title: MAMP MySQL innodb and missing errors


问:
UICollectionView Spacing Not Equal
I have a vertical UICollectionView with standard width and variable height cells. I have an issue with the spacing. For each height of a cell the spacing after the cell is different:

Screenshot of the UICollectionView

答:
An UICollectionView has the delegate property. You should implement the UICollectionViewDelegateFlowLayout in some class, for example the View Controller.

This methods are responsible for spacing:

```<code>// Space around the section.
func collectionView(_ collectionView: UICollectionView,
                   layout collectionViewLayout: UICollectionViewLayout,
                   insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
}

// In case of vertical layout this is a vertical space between horizontal rows inside of each section
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}

// Horizontal space between items in row
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}
</code>```

Title: UICollectionView Spacing Not Equal

Body:
An UICollectionView has the delegate property. You should implement the UICollectionViewDelegateFlowLayout in some class, for example the View Controller.

This methods are responsible for spacing:

// Space around the section.
func collectionView(_ collectionView: UICollectionView,
                   layout collectionViewLayout: UICollectionViewLayout,
                   insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
}

// In case of vertical layout this is a vertical space between horizontal rows inside of each section
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}

// Horizontal space between items in row
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}


问:
Powershell hyphen argument color
I want to change the color of the -a, --All arguments in Powershell. I have changed the string and command colors of my in Powershell like this.

```<code>Set-PSReadlineOption -TokenKind String -ForegroundColor Cyan
Set-PSReadlineOption -TokenKind Command -ForegroundColor Magenta
</code>```

I cannot find how to change the hyphen arguments color.

Is it under Set-PSReadlineOption or somewhere else?

答:
You're looking for the Parameter token kind:

```<code>Set-PSReadlineOption -TokenKind Parameter -ForegroundColor Red
</code>```

The above will color parameter tokens (like -a) red, but not bare string tokens prefixed with -- (like --All), since they're technically not considered parameter tokens by the parser.

As Rabeez Riaz notes, in PSReadLine 2.0 the syntax is slightly different:

```<code>Set-PSReadLineOption -Colors @{ Parameter = 'Red' }
</code>```

The new syntax allows you to set multiple token colors simultaneously:

```<code>Set-PSReadLineOption -Colors @{
  Parameter  = 'Red'
  String     = 'Cyan'
  Command    = 'Green'
}
</code>```

Title: Powershell hyphen argument color

Body:
I want to change the color of the -a, --All arguments in Powershell. I have changed the string and command colors of my in Powershell like this.

Set-PSReadlineOption -TokenKind String -ForegroundColor Cyan
Set-PSReadlineOption -TokenKind Command -ForegroundColor Magenta

I cannot find how to change the hyphen arguments color.

Is it under Set-PSReadlineOption or somewhere else?

Body:
You're looking for the Parameter token kind:

Set-PSReadlineOption -TokenKind Parameter -ForegroundColor Red

The above will color parameter tokens (like -a) red, but not bare string tokens prefixed with -- (like --All), since they're technically not considered parameter tokens by the parser.

As Rabeez Riaz notes, in PSReadLine 2.0 the syntax is slightly different:

Set-PSReadLineOption -Colors @{ Parameter = 'Red' }

The new syntax allows you to set multiple token colors simultaneously:

Set-PSReadLineOption -Colors @{
  Parameter  = 'Red'
  String     = 'Cyan'
  Command    = 'Green'
}

ContentLicense: CC BY-SA 4.0


问:
numpy corrcoef causes computer to hang
When trying to calculate numpy corrcoef

```<code>cc = np.corrcoef(y, y2)
</code>```

where shapes of y and y2 are

```<code><class 'tuple'>: (32383, 1)
</code>```

My computer hangs. Not only interpreter but entire computer.

How can this be and how to fix?

答:
According to documentation, by default "each row represents a variable, with observations in the columns". Having shape (32383, 1) means 32383 variables with 1 observation for each, which is totally meaningless for correlation purposes. So, the computer behavior aside, the way to proceed is

```<code>cc = np.corrcoef(y, y2, rowvar=False)
</code>```

indicating that your columns correspond to variables.

Title: numpy corrcoef causes computer to hang

Body:
When trying to calculate numpy corrcoef

cc = np.corrcoef(y, y2)

where shapes of y and y2 are

<class 'tuple'>: (32383, 1)

My computer hangs. Not only interpreter but entire computer.

How can this be and how to fix?

Body:
According to documentation, by default "each row represents a variable, with observations in the columns". Having shape (32383, 1) means 32383 variables with 1 observation for each, which is totally meaningless for correlation purposes. So, the computer behavior aside, the way to proceed is

cc = np.corrcoef(y, y2, rowvar=False)

indicating that your columns correspond to variables.


问:
Combining two similar entries in a row and output their sum
I want to fetch entries in a table that are the same and combine their values into one on display. I am using laravel framework.
This what did so far

```<code>public function material_approve($id)
{$totalcost = DB::table('tbl_material_requests')
->where('m1number', $id)
->sum(DB::raw('tbl_material_requests.material_quantity * tbl_material_requests.material_cost'));
$material = DB::table('tbl_material_requests')
->where('m1number', $id)
->get();
$m1_no = $id;}
</code>```

Here is the table migration

```<code>Schema::create('tbl_material_requests', function (Blueprint $table) {
$table->increments('id');
$table->integer('m1number');
$table->string('material_unit');
$table->integer('material_status');
$table->integer('material_quantity');
$table->integer('material_cost');
$table->string('material_name');
$table->timestamps();});
</code>```

Here is the screen shot of the result

Thank you in advance

答:
Perhaps GROUP BY is the technique you are looking for:

```<code>SELECT material,
       SUM(quantity) as TotQuantity,
       SUM(material_cost) as TotCost
    FROM tbl
    GROUP BY material;
</code>```

(No, I can't translate that into Lavavel; it adds complexity that I don't need.)

OwnerDisplayName: Abednego

Body:
I want to fetch entries in a table that are the same and combine their values into one on display. I am using laravel framework.
This what did so far

public function material_approve($id)
{$totalcost = DB::table('tbl_material_requests')
->where('m1number', $id)
->sum(DB::raw('tbl_material_requests.material_quantity * tbl_material_requests.material_cost'));
$material = DB::table('tbl_material_requests')
->where('m1number', $id)
->get();
$m1_no = $id;}

Here is the table migration

Schema::create('tbl_material_requests', function (Blueprint $table) {
$table->increments('id');
$table->integer('m1number');
$table->string('material_unit');
$table->integer('material_status');
$table->integer('material_quantity');
$table->integer('material_cost');
$table->string('material_name');
$table->timestamps();});

Here is the screen shot of the result

Thank you in advance

Body:
Perhaps GROUP BY is the technique you are looking for:

SELECT material,
       SUM(quantity) as TotQuantity,
       SUM(material_cost) as TotCost
    FROM tbl
    GROUP BY material;

(No, I can't translate that into Lavavel; it adds complexity that I don't need.)


问:
How to get job execution time from sidekiq?
I'd like to know execution time every time I run my jobs. Seems like there is a gem sidekiq-statistic that does what I want and even has GUI, but unfortunately it doesn't work with sidekiq 5. Can I get such info from inside perform method somehow? I'd prefer to avoid writing benchmarking code manually, wrapping up my method into Benchmark block

答:
You can do your computations within the perform method and then log those to your rails logs.

```<code>def preform(task,*params)
   ...start metric times...
   ... do your computations ...
   ...end metric times...
   Rails.logger.info "Your Metrics..."
end
</code>```

I have had success using Paper-trail on heroku and just look at the start and completion times of the jobs from the worker.

Body:
You can do your computations within the perform method and then log those to your rails logs.

def preform(task,*params)
   ...start metric times...
   ... do your computations ...
   ...end metric times...
   Rails.logger.info "Your Metrics..."
end

I have had success using Paper-trail on heroku and just look at the start and completion times of the jobs from the worker.


问:
Extracting ASX data using pandas
I am trying to extract stock market data from yahoo finance following is the link https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX

My code is as follows

```<code>import pandas as pd
dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
print(dfs)
</code>```

The above code leads to following error

```<code>Traceback (most recent call last):
  File "/home/furqan/Desktop/Data/Fundamental Analysis/get_data/ax_data.py", line 5, in <module>
    dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 874, in read_html
    parse_dates, tupleize_cols, thousands, attrs, encoding)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 747, in _parse
    thousands=thousands))
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 628, in _data_to_frame
    _expand_elements(body)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 611, in _expand_elements
    body[ind] += empty * (lens_max - length)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U47') dtype('<U47') dtype('<U47')
</code>```

How can I solve this issue?

答:
It's probably easier to use the pandas_datareader package for this:

```<code>pip3 install pandas_datareader

from pandas_datareader import yahoo
In [13]: yahoo.quotes.YahooQuotesReader('ABP.AX').read()
Out[13]:
          PE change_pct  last  short_ratio    time
ABP.AX  5.65     -1.94%  3.04          0.0  4:10pm
</code>```

Title: Extracting ASX data using pandas

Body:
I am trying to extract stock market data from yahoo finance following is the link https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX

My code is as follows

import pandas as pd
dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
print(dfs)

The above code leads to following error

Traceback (most recent call last):
  File "/home/furqan/Desktop/Data/Fundamental Analysis/get_data/ax_data.py", line 5, in <module>
    dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 874, in read_html
    parse_dates, tupleize_cols, thousands, attrs, encoding)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 747, in _parse
    thousands=thousands))
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 628, in _data_to_frame
    _expand_elements(body)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 611, in _expand_elements
    body[ind] += empty * (lens_max - length)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U47') dtype('<U47') dtype('<U47')

How can I solve this issue?

Body:
It's probably easier to use the pandas_datareader package for this:

pip3 install pandas_datareader

from pandas_datareader import yahoo
In [13]: yahoo.quotes.YahooQuotesReader('ABP.AX').read()
Out[13]:
          PE change_pct  last  short_ratio    time
ABP.AX  5.65     -1.94%  3.04          0.0  4:10pm


问:
Unable to load multiple scenes from a primary scene in Unity?
My gameplay is such that I want my scenes to perform this flow:

Scene1 -> Scene2 -> Scene1

Scene1 -> Scene3 -> Scene1

Scene1 -> Scene4 -> Scene1

Scene1 -> Scene5 -> Scene1

I have 4 different triggers leading to 4 diffferent scenes. But every time I start Scene1, the scene which gets instantiated on coming in contact with any of the triggers for the first time, just gets instantiated again no matter whichever scene the next trigger leads to.
What am I doing wrong here?
How to solve it?

The colliders that you see in the picture above are the 4 triggers. And the code on each of these trigger is below:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class enter4kWorld : MonoBehaviour {

   //Orb Transform
   public GameObject targetGO;
   public GameObject otherTargetGO1;
   public GameObject otherTargetGO2;
   public GameObject otherTargetGO3;

   public Animator LightBurst;
   public GameObject Processor;
   public GameObject SceneExitGO;

   public float CountDownTimer;

   // Use this for initialization
   void Start () {

}

   void OnTriggerEnter(Collider other)
   {
       if (other.tag == "GameController")
       {
           Debug.Log("Teleporter works");
           SceneExitGO.SetActive(true);

           targetGO.SetActive(true);
           otherTargetGO1.SetActive(false);
           otherTargetGO2.SetActive(false);
           otherTargetGO3.SetActive(false);
       }
   }

   // Update is called once per frame
   void Update()
   {
       if (SceneExitGO.activeSelf)
       {
           //float step = speed * Time.deltaTime;
           //transform.position = Vector3.MoveTowards(transform.position, target.position, step);

           CountDownTimer -= Time.deltaTime;

           if (Processor.transform.position.y <= 9f)
           {
               Processor.transform.Translate(Vector3.up * Time.deltaTime * 1.5f, Space.World);
           }

           if (CountDownTimer <= 4.5)
           {
               LightBurst.SetTrigger("TriggerLightBurst");
           }

           if (CountDownTimer <= 0)
           {
               ChangeScene();
               CountDownTimer = 0;
           }
       }
   }

   public void ChangeScene()
   {
       SceneManager.LoadScene("Scene2");
       //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
   }
}
</code>```

答:
Write yourself a real trigger that fires a UnityEvent on enter.

Have a separate MonoBehaviour that starts new scenes.

In your editor, just drag the scene starting component mentioned above onto the UnityEvent and let the event call the method that loads the next scene. Something like this:

```<code>public class Trigger : MonoBehaviour
{
    public UnityEvent OnEnter;

    [SerializeField]
    private string tag;

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag(tag) && OnEnter != null)
            OnEnter.Invoke();
    }
}
</code>```

And here is the class to call:

```<code>public class SceneManagement : MonoBehaviour
{
    public void LoadScene(string name)
    {
        SceneManager.LoadScene(name);
    }
}
</code>```

Note: I give no guarantee that this is without errors, I didn't check if it works, I just wrote it down out of experience. But I hope you get the concept.

Body:
My gameplay is such that I want my scenes to perform this flow:

Scene1 -> Scene2 -> Scene1

Scene1 -> Scene3 -> Scene1

Scene1 -> Scene4 -> Scene1

Scene1 -> Scene5 -> Scene1

I have 4 different triggers leading to 4 diffferent scenes. But every time I start Scene1, the scene which gets instantiated on coming in contact with any of the triggers for the first time, just gets instantiated again no matter whichever scene the next trigger leads to.
What am I doing wrong here?
How to solve it?

The colliders that you see in the picture above are the 4 triggers. And the code on each of these trigger is below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class enter4kWorld : MonoBehaviour {

   //Orb Transform
   public GameObject targetGO;
   public GameObject otherTargetGO1;
   public GameObject otherTargetGO2;
   public GameObject otherTargetGO3;

   public Animator LightBurst;
   public GameObject Processor;
   public GameObject SceneExitGO;

   public float CountDownTimer;

   // Use this for initialization
   void Start () {

}

   void OnTriggerEnter(Collider other)
   {
       if (other.tag == "GameController")
       {
           Debug.Log("Teleporter works");
           SceneExitGO.SetActive(true);

           targetGO.SetActive(true);
           otherTargetGO1.SetActive(false);
           otherTargetGO2.SetActive(false);
           otherTargetGO3.SetActive(false);
       }
   }

   // Update is called once per frame
   void Update()
   {
       if (SceneExitGO.activeSelf)
       {
           //float step = speed * Time.deltaTime;
           //transform.position = Vector3.MoveTowards(transform.position, target.position, step);

           CountDownTimer -= Time.deltaTime;

           if (Processor.transform.position.y <= 9f)
           {
               Processor.transform.Translate(Vector3.up * Time.deltaTime * 1.5f, Space.World);
           }

           if (CountDownTimer <= 4.5)
           {
               LightBurst.SetTrigger("TriggerLightBurst");
           }

           if (CountDownTimer <= 0)
           {
               ChangeScene();
               CountDownTimer = 0;
           }
       }
   }

   public void ChangeScene()
   {
       SceneManager.LoadScene("Scene2");
       //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
   }
}

Body:
Write yourself a real trigger that fires a UnityEvent on enter.

Have a separate MonoBehaviour that starts new scenes.

In your editor, just drag the scene starting component mentioned above onto the UnityEvent and let the event call the method that loads the next scene. Something like this:

public class Trigger : MonoBehaviour
{
    public UnityEvent OnEnter;

    [SerializeField]
    private string tag;

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag(tag) && OnEnter != null)
            OnEnter.Invoke();
    }
}

And here is the class to call:

public class SceneManagement : MonoBehaviour
{
    public void LoadScene(string name)
    {
        SceneManager.LoadScene(name);
    }
}

Note: I give no guarantee that this is without errors, I didn't check if it works, I just wrote it down out of experience. But I hope you get the concept.


问:
Traversing / Editing DOM in React JS
I am new to React JS and planning to use it in one of my projects. I have gone through the docs and have a slight idea of React. I have a scenario with the following details :

Server pushes array of items / list to UI in frequent intervals.

The items in the list are not similar to each other or multiple lists      but will be displayed in the order they are received.

Items will have to appended to DOM upon AJAX response / push notification from server.

Few cases, will have to edit / delete the items from DOM based on a reference.

I was going through few articles in stack overflow for appending data dynamically and few of them are below :

Can I append my component to a div's existing content in ReactJS?.

ReactJS component rendering and how to append elements to the div the component is mounted on.

React.js: How to append a component on click?.

How to append to dom in React?.

All the above solutions doesn't provide a direct option for appending. They recommend to create a map / array and add the values to the map and re-render the values.

I am not very comfortable in using maps as I won't be passing the details to server and its only shown to user. I think creating a map will have redundant values which occupies memory if the list grows huge.

I dont want to mix jQuery / any other library along with React. Is there any possibility where a render function / component will append to DOM instead of maintaining in an array as the items in the list are not similar.

Why there isn't any option to traverse / edit DOM directly instead of maintaining a list. Can you guide me if there is an option so that I will be able to understand its advantages.

答:
Hi I was in the exact situation. Switched from jQuery to React recently. The solution is Redux. React wont have any DOM manipulation whatsoever. So forget about the .parent().child().next() things we had before.

Theres this concept in Redux's core. State management. So basically state is a little tool you need to manipulate through the React 'tree'. Kinda like the DOM manipulation in jQuery but not totally the same. The state will flow between siblings, up to parent or down to child

Title: Traversing / Editing DOM in React JS


问:
Bash script - Lookup one variable from source .csv file to provide the other
What we want to accomplish. Have one source file (data.csv) to be referenced with the following data:

```<code>userone,password1
usertwo,password2
userthree,password3
</code>```

Use the source file to find a username and then provide the password after the comma as another variable.
Example

```<code>Variables:
User1=userone
User1Password=password1

#!/usr/bin/env bash
source data.csv
read data.csv
If $User1=userone
    then
$User1Password=password1
</code>```

We are using this to create a local user account on a Mac with a different line of code but need to reference a .csv file to get the variables.

Thanks in advance for any support.

答:
Use awk

```<code>user=userone
pass=$(awk -F, -v user="$user" '$1 == user { print $2; exit }' data.csv)
</code>```

-F, sets the field separator to comma. -v user="user" sets the awk variable from the bash variable. $1 and $2 are the contents of those fields of the CSV.

Body:
What we want to accomplish. Have one source file (data.csv) to be referenced with the following data:

userone,password1
usertwo,password2
userthree,password3

Use the source file to find a username and then provide the password after the comma as another variable.
Example

Variables:
User1=userone
User1Password=password1

#!/usr/bin/env bash
source data.csv
read data.csv
If $User1=userone
    then
$User1Password=password1

We are using this to create a local user account on a Mac with a different line of code but need to reference a .csv file to get the variables.

Thanks in advance for any support.

Body:
Use awk

user=userone
pass=$(awk -F, -v user="$user" '$1 == user { print $2; exit }' data.csv)

-F, sets the field separator to comma. -v user="user" sets the awk variable from the bash variable. $1 and $2 are the contents of those fields of the CSV.


问:
how can i make the View do NOT expand over its sibling View
I have a layout similiar to this:

```<code><RelativeLayout ...>
     <EditText android:id="@+id/editbox"
            android:layout_width="wrap_content" .../>
     <Button android:layout_right="@id/editbox"
            android:layout_width="wrap_content"
            android:text="Button" />
 </RelativeLayout>
</code>```

The button is at the right of the edit text. And the edit text is 'wrap_content'. When i type texts into the edit view, the view's width increase and will expand to my button. I want the two views (button and edit text) have their own area. How to configure this?

答: Instead of using  android:layout_right="@id/editbox use this android:layout_alignParentRight="true" so that the Button will be always placed at right side of the EditText

Body:
I have a layout similiar to this:

<RelativeLayout ...>
     <EditText android:id="@+id/editbox"
            android:layout_width="wrap_content" .../>
     <Button android:layout_right="@id/editbox"
            android:layout_width="wrap_content"
            android:text="Button" />
 </RelativeLayout>

The button is at the right of the edit text. And the edit text is 'wrap_content'. When i type texts into the edit view, the view's width increase and will expand to my button. I want the two views (button and edit text) have their own area. How to configure this?


问:
JPA Criteria Query - How to join on only a subclass of the association entity type?
I'm using Spring, Hibernate and the JPA Criteria API.

Let's say I have a Vehicle class hierarchy and a Tire class. Each Vehicle can have multiple Tires.

Vehicle -- Tanker, Motorcylce

Tire

I want to query for small tires that are on Tankers with a capacity over 100 gallons.
But the vehicle property for Tire is of type Vehicle. Only one of the Vehicle subclasses (Tanker) has the "capacity" property.
How do I tell the criteria api to join ONLY on Tankers?

Thanks!

I'm sure this is has been asked/answered before, but I think I'm missing the right terminology to have a successful search.

答:
Try this:

```<code>@Entity
public class Vehicle {
    @OneToMany
    private Set<Tire> tires;
}

@Entity
public class Tank extends Vehicle {
    private int gallons;
}

@Entity
public class Motorcycle extends Vehicle {
}

@Entity
public class Tire {
}

public interface VehicleRepo extends JpaRepository<Vehicle, Long> {

    @Query("select v.tires from Vehicle v where v.gallons > ?1")
    List<Tire> findByGallonsIsGreaterThan(int gallons);
}
</code>```

If you need select only subclass type in JPQL query you can use this approach:

```<code>select v from Vehicle v where type(v) = Tank
select v from Vehicle v where v.class = Tank
</code>```

Example and test.

Body:
Try this:

@Entity
public class Vehicle {
    @OneToMany
    private Set<Tire> tires;
}

@Entity
public class Tank extends Vehicle {
    private int gallons;
}

@Entity
public class Motorcycle extends Vehicle {
}

@Entity
public class Tire {
}

public interface VehicleRepo extends JpaRepository<Vehicle, Long> {

    @Query("select v.tires from Vehicle v where v.gallons > ?1")
    List<Tire> findByGallonsIsGreaterThan(int gallons);
}

If you need select only subclass type in JPQL query you can use this approach:

select v from Vehicle v where type(v) = Tank
select v from Vehicle v where v.class = Tank

Example and test.


问:
Why is skrollr preventing scrolling on ipad?
I'm trying to create a simple parallax animation with skrollr: my site is working well on Chrome/Mac but I'm seeing unusual behaviour on the ipad..

On ipad (testing on the IOS simulator),

the main body of the page doesn't skroll at all (or may scroll in the background, underneath the animated div?)

the animated background position (origami pattern) scrolls in the opposite direction (down is up) within the bounds defined in data-start / data-top-bottom

On desktop, the effect I can simulate the effect if I hack the div#hero to be position: fixed; in chrome dev tools.

The skrollr examples work as expected in the IOS simulator.

I have

 just before the closing  tag

Any suggestions?

答: adding a div wrapper with skrollr-body id did absolutely nothing for, scroll just doesn't work on mobile</p>


问:
Why doesn't HttpRequest.getSession(true) get new session when old one null/invalid
Can anybody explain, when I run this java code:

```<code>    HttpSession session = request.getSession(false);
    if (session != null)
    {
            s_log.debug("Session has id: " + session.getId());
            session.invalidate();
    }
    s_log.debug("Request Session ID is: "+  request.getRequestedSessionId());
    s_log.debug("Request isRequestedSessionIdValid(): " + request.isRequestedSessionIdValid());
    HttpSession _session = request.getSession(true);
     s_log.debug("New Session is :" + _session.getId());
</code>```

Why I don't get a new session from the request.getSession(true) when the current request session is null and is invalid?  I see this in the log:

Request Session ID is: 0000MYF8m5fpUjrzUHIp93yshSh:5e7fcdcf-2274-43bb-83d9-4d9b9a1d766a

Request isRequestedSessionIdValid(): false

New Session is :MYF8m5fpUjrzUHIp93yshSh

答:
It's the session ID that is being reused. The actual session is being invalidated and recreated.

This behaviour can be changed by setting HttpSessionIdReuse property value to false.

Body:
Can anybody explain, when I run this java code:

    HttpSession session = request.getSession(false);
    if (session != null)
    {
            s_log.debug("Session has id: " + session.getId());
            session.invalidate();
    }
    s_log.debug("Request Session ID is: "+  request.getRequestedSessionId());
    s_log.debug("Request isRequestedSessionIdValid(): " + request.isRequestedSessionIdValid());
    HttpSession _session = request.getSession(true);
     s_log.debug("New Session is :" + _session.getId());

Why I don't get a new session from the request.getSession(true) when the current request session is null and is invalid?  I see this in the log:

Request Session ID is: 0000MYF8m5fpUjrzUHIp93yshSh:5e7fcdcf-2274-43bb-83d9-4d9b9a1d766a

Request isRequestedSessionIdValid(): false

New Session is :MYF8m5fpUjrzUHIp93yshSh


问:
goodFeaturesToTrack() works only on greyscale?
I am new to working in openCV. I was trying to detect features in an image using goodFeaturesToTrack() in c++ in a colored image but it gave me the following error:

" OpenCV Error: Assertion failed (src.type() == CV_8UC1 || src.type() == CV_32FC1) in cv::cornerEigenValsVecs, file D:\cs436\opencv-3.2.0\modules\imgproc\src\corner.cpp, line 287 "

Then I tried it on a greyscale image and it found the features. Can anyone please tell if we can use the function on a colored image? and what does the error mean?

答:
That right the function is defined for grayscale images only. To apply colored images you have to convert the rgb image to a grayscaled image by:</p>

```<code>cv::cvtColor(rgbImage, grayImage, CV_BGR2GRAY);
</code>```

Body:
That right the function is defined for grayscale images only. To apply colored images you have to convert the rgb image to a grayscaled image by:

cv::cvtColor(rgbImage, grayImage, CV_BGR2GRAY);


问:
"Error L10 (output buffer overflow)" when writing to Splunk drain
I'm pushing my logs to a local splunk installation. Recently I found that the following error repeats a lot (about once every minute):

Error L10
  (output buffer overflow): 7150 messages dropped since
  2013-06-26T19:19:52+00:00.134 <13>1 2013-07-08T14:59:47.162084+00:00
  host app web.1 - [\x1B[37minfo\x1B[0m] application - Perf - it took 31
  milliseconds to fetch row IDs ...

The errors repeat quite a lot, and in the documentation it is said that these errors happen when your application produces a lot of logs.

Thing is, I barely have 20-30 logs per second, which isn't really considered a lot. I tested with other drains (added the built-in papertrail plugin), and these errors do not happen there - so they are specific to the outgoing splunk drain.

I thought maybe the splunk machine was loaded and thus not accepting logs fast enough, but its CPU is idle, and it has plenty of disk & memory.

Also, I believe the app (Play 2 app) is auto-flushing logs to console all the time, so there is no big buildup of unflushed logs followed by a release.

What can cause a slow drain speed for the outgoing splunk drain? How should I debug it?

答: My POV is that just because the errors went away, does not mean that you solved the problem.  The HTTP protocol give a synchronous response. So, if you are reaching a threshold, whether it be a capacity limitation, or a business agreement threshold, the HTTP response code will be the indication.  With Sumo Logic, if you are over exceeding your bursting rate limits, we will return a 429 response code.  Heroku Logplex is not tuned for negative response codes, and will drop data.  With a syslog endpoint, you may be losing data as well, except that syslog does not have a response channel, so its only option is to drop the data.  For Sumo Logic, you will see notifications in the Audit Log indicating that throttling is being applied. When this happens you should contact support, or your account team, to either make adjustments to your limits, or increase your plan.</p>


问:
Unable to install an npm package
I tried many different ways to install this package:
npm install cloud-print
npm install https://github.com/postmen/node-cloud-print.git
and so on...

And every time i get the following output:

`npm WARN addRemoteGit Error: Command failed: git -c core.longpaths=true config --get remote.origin.url
npm WARN addRemoteGit
npm WARN addRemoteGit     at ChildProcess.exithandler (child_process.js:211:12)
npm WARN addRemoteGit     at emitTwo (events.js:106:13)
npm WARN addRemoteGit     at ChildProcess.emit (events.js:191:7)
npm WARN addRemoteGit     at maybeClose (internal/child_process.js:885:16)
npm WARN addRemoteGit     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
npm WARN addRemoteGit  git+ssh://git@github.com/postmen/google-api-nodejs-client.git resetting remote C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46 because of error: { Error: Command failed: git -c core.longpaths=true config --get remote.origin.url
npm WARN addRemoteGit
npm WARN addRemoteGit     at ChildProcess.exithandler (child_process.js:211:12)
npm WARN addRemoteGit     at emitTwo (events.js:106:13)
npm WARN addRemoteGit     at ChildProcess.emit (events.js:191:7)
npm WARN addRemoteGit     at maybeClose (internal/child_process.js:885:16)
npm WARN addRemoteGit     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
npm WARN addRemoteGit   killed: false,
npm WARN addRemoteGit   code: 1,
npm WARN addRemoteGit   signal: null,
npm WARN addRemoteGit   cmd: 'git -c core.longpaths=true config --get remote.origin.url' }
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Cloning into bare repository 'C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46'...
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Host key verification failed.
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: fatal: Could not read from remote repository.
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46:
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Please make sure you have the correct access rights
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: and the repository exists.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "cloud-print"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code 128
npm ERR! Command failed: git -c core.longpaths=true clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46
npm ERR! Cloning into bare repository 'C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46'...
npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
npm ERR!     D:\Tmunot\npm-debug.log````

I also tried to download the directory to node_modules and configure it manually in package.json, but i didn't have success doing that.

Any ideas?

答:
Not all packages support installation from github. If it's available in npm (correct package now linked), I'd favor that.

Should it not be available in npm, then know that it appears to have a build process (given the existence of grunt commands). You should clone it, build it and use NPM to pull in a "built" copy.

You'd use the method described here once built: npm install <folder>

Title: Unable to install an npm package

Body:
I tried many different ways to install this package:
npm install cloud-print
npm install https://github.com/postmen/node-cloud-print.git
and so on...

And every time i get the following output:

`npm WARN addRemoteGit Error: Command failed: git -c core.longpaths=true config --get remote.origin.url
npm WARN addRemoteGit
npm WARN addRemoteGit     at ChildProcess.exithandler (child_process.js:211:12)
npm WARN addRemoteGit     at emitTwo (events.js:106:13)
npm WARN addRemoteGit     at ChildProcess.emit (events.js:191:7)
npm WARN addRemoteGit     at maybeClose (internal/child_process.js:885:16)
npm WARN addRemoteGit     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
npm WARN addRemoteGit  git+ssh://git@github.com/postmen/google-api-nodejs-client.git resetting remote C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46 because of error: { Error: Command failed: git -c core.longpaths=true config --get remote.origin.url
npm WARN addRemoteGit
npm WARN addRemoteGit     at ChildProcess.exithandler (child_process.js:211:12)
npm WARN addRemoteGit     at emitTwo (events.js:106:13)
npm WARN addRemoteGit     at ChildProcess.emit (events.js:191:7)
npm WARN addRemoteGit     at maybeClose (internal/child_process.js:885:16)
npm WARN addRemoteGit     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
npm WARN addRemoteGit   killed: false,
npm WARN addRemoteGit   code: 1,
npm WARN addRemoteGit   signal: null,
npm WARN addRemoteGit   cmd: 'git -c core.longpaths=true config --get remote.origin.url' }
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Cloning into bare repository 'C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46'...
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Host key verification failed.
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: fatal: Could not read from remote repository.
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46:
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: Please make sure you have the correct access rights
npm ERR! git clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46: and the repository exists.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "cloud-print"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code 128
npm ERR! Command failed: git -c core.longpaths=true clone --template=C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\_templates --mirror ssh://git@github.com/postmen/google-api-nodejs-client.git C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46
npm ERR! Cloning into bare repository 'C:\Users\User\AppData\Roaming\npm-cache\_git-remotes\git-ssh-git-github-com-postmen-google-api-nodejs-client-git-21a89f46'...
npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
npm ERR!     D:\Tmunot\npm-debug.log`

I also tried to download the directory to node_modules and configure it manually in package.json, but i didn't have success doing that.

Any ideas?


问:
Jenkins Error 503 on AWS EC2 Instance
I have created an AWS Ec2 instance using the following documentation:

https://d0.awsstatic.com/Projects/P5505030/aws-project_Jenkins-build-server.pdf

However, when I get to the stage where I connect from my web browser to Jenkins using http://:8080 I get HTTP Error: 503.

I originally taught it was down to my network settings/security group settings on my AWS EC2 instance but I have installed Apache and I can access the Apache test page from port 80. I have allowed traffic from HTTP, SSH and TCP and set the appropriate ports as per the guide.

I have tried curl http://localhost:8080 on the putty instance connected to my EC2 instance and I get the same error. Also, I have checked the /var/lib/jenkins folder and it is empty.

Any help or direction in the right path would be greatly appreciated,

Thank you.

答:
The problem is resolved by installing Java 8.

https://issues.jenkins-ci.org/browse/JENKINS-43609

Title: Jenkins Error 503 on AWS EC2 Instance


问:
Rxjs Retry with Delay function
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

```<code>canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }
</code>```

and console result is :

答:
delay() is used to introduce a delay between events emitted by the observable. But the observable never emits any event. It just errors immediately.

What you're looking for is retryWhen(), which allows deciding after how long to retry:

RxJS 5:

```<code>  .retryWhen(errors => errors.delay(1000).take(10))
</code>```

RxJS 6:

```<code>import { retryWhen, delay, take } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10)))
)
</code>```

This will complete the whole observable after 10 attempts. If you want to error the whole observable after 10 attempts, the observable returned by the retryWhen callback must throw:

RxJS 5:

```<code>  .retryWhen(errors => errors.delay(1000).take(10).concat(Observable.throw()))
</code>```

RxJS 6:

```<code>import { retryWhen, delay, take, concatMap, throwError } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10), concatMap(throwError)))
)
</code>```

Title: Rxjs Retry with Delay function

Body:
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }

and console result is :

Body:
delay() is used to introduce a delay between events emitted by the observable. But the observable never emits any event. It just errors immediately.

What you're looking for is retryWhen(), which allows deciding after how long to retry:

RxJS 5:

  .retryWhen(errors => errors.delay(1000).take(10))

RxJS 6:

import { retryWhen, delay, take } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10)))
)

This will complete the whole observable after 10 attempts. If you want to error the whole observable after 10 attempts, the observable returned by the retryWhen callback must throw:

RxJS 5:

  .retryWhen(errors => errors.delay(1000).take(10).concat(Observable.throw()))

RxJS 6:

import { retryWhen, delay, take, concatMap, throwError } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10), concatMap(throwError)))
)


问:
How to set target fragment
I have two fragments: the fragmentA and the dialogFragmentB in one Activity.
fragmentB has two alertDialogs, it starts from dialogA and then dialogA call dismiss() and generates dialogB.
fragmentA has method onActivityResult() and dialogB (from dialogFragmentB) has to send some intent-result there after button's click. But before i send that result i have to set target fragmentA. How to do it in onClick method of dialogB?

i think i need something like this:

```<code>public void onClick(){
     ...
     dialogB.dismiss();
     fragmentA.setTargetFragment(FragmentA, requestCode);
}
</code>```

But i have an Error: cannot find symbol variable FragmentA

Thank you!

答:
Use the variable reference instead of the class name: </p>

```<code>public void onClick(){
     ...
     dialogB.dismiss();
     // note the lowercase "f"
     fragmentA.setTargetFragment(fragmentA, requestCode);
}
</code>```

Title: How to set target fragment

Body:
I have two fragments: the fragmentA and the dialogFragmentB in one Activity.
fragmentB has two alertDialogs, it starts from dialogA and then dialogA call dismiss() and generates dialogB.
fragmentA has method onActivityResult() and dialogB (from dialogFragmentB) has to send some intent-result there after button's click. But before i send that result i have to set target fragmentA. How to do it in onClick method of dialogB?

i think i need something like this:

public void onClick(){
     ...
     dialogB.dismiss();
     fragmentA.setTargetFragment(FragmentA, requestCode);
}

But i have an Error: cannot find symbol variable FragmentA

Thank you!

Body:
Use the variable reference instead of the class name:

public void onClick(){
     ...
     dialogB.dismiss();
     // note the lowercase "f"
     fragmentA.setTargetFragment(fragmentA, requestCode);
}


问:
Undoing bitwise operations
I have a Java function written by another programmer, which uses bitwise manipulation.  I need a function that will undo the process (if possible).  Perhaps some of you are more savvy than I with these operators.  Here's what needs to be undone:</p>

```<code>public void someFunc(int[] msg, int[] newMsg) {
    int i = SOME_LENGTH_CONSTANT;
    for (int j = 0; j < newMsg.length; j++) {
        // msg[i] Shift left by 8 bits bitwise or with next msg[i+1]
        // then bitwise not (~) and bitwise and with $FFF
        newMsg[j] = (~(((msg[i] & 0x0f) << 8) | (msg[i + 1]))) & 0xfff;
        i += 2;
    }
}
</code>```

答:
I just wanted to try to do it, here is the results of my attempt.

In the beginning I split the expression into single operations:

int t1 = msg[i] & 0x0f;

Here is we lose all except for the last 4 bits.

int t2 = t1 << 8;

Clear low 8 bits by shifting t1.

int t3 = t2 | msg[i + 1];

Here we should understand if m[i + 1] is large than 255 (particularly m[i + 1] & 0xf00 > 0), we are not able to restore the low 4 bits of m[i] because they are irreversibly overwritten.

int t4 = ~t3;

Just a negation.

newMsg[j] = t4 & 0xfff;

Take low 12 bits.

Just did these steps in reverse order:

```<code>public static void someFuncRev(int[] msg, int[] newMsg) {
    for (int i = 0; i < msg.length; ++i) {
        newMsg[2 * i] = (~msg[i] >> 8) & 0xf; // take 11-8 bits
        newMsg[2 * i + 1] = ~msg[i] & 0xff; // take 7-0 bits
    }
}
</code>```

I assumed SOME_LENGTH_CONSTANT == 0. It is easy to adjust the constant.

So, when the values inside msg are <=15, the function above recovers the initial sequence.
In case when the values are >15 and <=255, for msg[i] we can restore only 4 bits, msg[i + 1] are restored completely.
If the values are >255, we can't restore msg[i] because it was correpted by bits of msg[i + 1] (look above at the point no. 3); can restore 8 bits of msg[i + 1].

I hope this helps you.

Title: Undoing bitwise operations

Body:
I have a Java function written by another programmer, which uses bitwise manipulation.  I need a function that will undo the process (if possible).  Perhaps some of you are more savvy than I with these operators.  Here's what needs to be undone:

public void someFunc(int[] msg, int[] newMsg) {
    int i = SOME_LENGTH_CONSTANT;
    for (int j = 0; j < newMsg.length; j++) {
        // msg[i] Shift left by 8 bits bitwise or with next msg[i+1]
        // then bitwise not (~) and bitwise and with $FFF
        newMsg[j] = (~(((msg[i] & 0x0f) << 8) | (msg[i + 1]))) & 0xfff;
        i += 2;
    }
}

Body:
I just wanted to try to do it, here is the results of my attempt.

In the beginning I split the expression into single operations:

int t1 = msg[i] & 0x0f;

Here is we lose all except for the last 4 bits.

int t2 = t1 << 8;

Clear low 8 bits by shifting t1.

int t3 = t2 | msg[i + 1];

Here we should understand if m[i + 1] is large than 255 (particularly m[i + 1] & 0xf00 > 0), we are not able to restore the low 4 bits of m[i] because they are irreversibly overwritten.

int t4 = ~t3;

Just a negation.

newMsg[j] = t4 & 0xfff;

Take low 12 bits.

Just did these steps in reverse order:

public static void someFuncRev(int[] msg, int[] newMsg) {
    for (int i = 0; i < msg.length; ++i) {
        newMsg[2 * i] = (~msg[i] >> 8) & 0xf; // take 11-8 bits
        newMsg[2 * i + 1] = ~msg[i] & 0xff; // take 7-0 bits
    }
}

I assumed SOME_LENGTH_CONSTANT == 0. It is easy to adjust the constant.

So, when the values inside msg are <=15, the function above recovers the initial sequence.
In case when the values are >15 and <=255, for msg[i] we can restore only 4 bits, msg[i + 1] are restored completely.
If the values are >255, we can't restore msg[i] because it was correpted by bits of msg[i + 1] (look above at the point no. 3); can restore 8 bits of msg[i + 1].

I hope this helps you.


问:
Return name in ActiveRecord relation along with foreign key id
I have a Sub-Component model which can belong to other sub-components. My Model looks like this:

```<code>class SubComponent < ApplicationRecord
  belongs_to :parent, class_name: "SubComponent", foreign_key: "parent_sub_component_id", optional: true
  has_many :child_sub_components, class_name: "SubComponent", foreign_key: "parent_sub_component_id"

  validates_presence_of :name
end
</code>```

This model is fairly simple, it has a name field and a parent_sub_component_id which as the name suggests is an id of another SubComponent.

I'd like to generate a query that returns all of the SubComponents (with their id, name, and parent_sub_component_id) but also includes the actual name of it's parent_sub_component.

This seems like it should be pretty simple but for the life of me I can't figure out how to do it. I'd like for this query to be done in the database rather than doing an each loop in Ruby or something like that.

EDIT:

I'd like for the output to look something like this:

#<ActiveRecord::Relation [#<SubComponent id: 1, name: "Parent Sub", parent_sub_component_id: nil, parent_sub_component_name: nil created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">, #<SubComponent id: 2, name: "Child Sub", parent_sub_component_id: 1, parent_sub_component_name: "Parent Sub" created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">]>

答:
You can do this efficiently using an each loop if you use includes:

SubComponent.all.includes(:parent).each do |comp|
  comp.parent.name  # this gives you the name of the parent
end
```

<p>What <code>includes</code> does is it <em>pre-fetches</em> the specified association. That is, ActiveRecord will query all subcomponents, and then in a <em>single query</em> also pull down all the parents of those subcomponents. When you subsequently access <code>comp.parent</code> in the loop, the associated parent will already be loaded, so this will not result in a so-called <em>N+1 query</em>.</p>

<p>The queries that AR will generate for you automatically will look something like this:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT `subcomponents`.* FROM `subcomponents`
SELECT `subcomponents`.* FROM `subcomponents` WHERE `subcomponents`.`id` IN (1, 3, 9, 14)
</code>```

If you need to use the name of the parent in a where condition, includes will not work and you will have to use joins instead to actually generate an SQL JOIN.

Body:
I have a Sub-Component model which can belong to other sub-components. My Model looks like this:

class SubComponent < ApplicationRecord
  belongs_to :parent, class_name: "SubComponent", foreign_key: "parent_sub_component_id", optional: true
  has_many :child_sub_components, class_name: "SubComponent", foreign_key: "parent_sub_component_id"

  validates_presence_of :name
end

This model is fairly simple, it has a name field and a parent_sub_component_id which as the name suggests is an id of another SubComponent.

I'd like to generate a query that returns all of the SubComponents (with their id, name, and parent_sub_component_id) but also includes the actual name of it's parent_sub_component.

This seems like it should be pretty simple but for the life of me I can't figure out how to do it. I'd like for this query to be done in the database rather than doing an each loop in Ruby or something like that.

EDIT:

I'd like for the output to look something like this:

#<ActiveRecord::Relation [#<SubComponent id: 1, name: "Parent Sub", parent_sub_component_id: nil, parent_sub_component_name: nil created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">, #<SubComponent id: 2, name: "Child Sub", parent_sub_component_id: 1, parent_sub_component_name: "Parent Sub" created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">]>

Body:
You can do this efficiently using an each loop if you use includes:

SubComponent.all.includes(:parent).each do |comp|
  comp.parent.name  # this gives you the name of the parent
end

What includes does is it pre-fetches the specified association. That is, ActiveRecord will query all subcomponents, and then in a single query also pull down all the parents of those subcomponents. When you subsequently access comp.parent in the loop, the associated parent will already be loaded, so this will not result in a so-called N+1 query.

The queries that AR will generate for you automatically will look something like this:

SELECT `subcomponents`.* FROM `subcomponents`
SELECT `subcomponents`.* FROM `subcomponents` WHERE `subcomponents`.`id` IN (1, 3, 9, 14)

If you need to use the name of the parent in a where condition, includes will not work and you will have to use joins instead to actually generate an SQL JOIN.