问:
Poor performance with DrawText on Win7 x64
I noticed in an MFC application I'm developing that while dragging the scroll bar to smoothly scroll down the document, the framerate drops to choppy levels when a block containing about a paragraph of text is on screen, but silky smooth when it's offscreen.  Investigating the performance, I found the single CDC::DrawText call for the paragraph of text responsible.  This is in an optimised release build.

I used QueryPerformanceCounter to get a high-resolution measurement of just the DrawText call, like this:

```<code>QueryPerformanceCounter(...);
pDC->DrawText(some_cstring, some_crect, DT_WORDBREAK);
QueryPerformanceCounter(...);
</code>```

The text is unicode, lorem-ipsum style filler, 865 characters long and wraps over 7-and-a-bit lines given the rectangle and font (Segoe UI, lfHeight = -12, a standard body text size).  From my measurements, that call alone takes on average 7.5 ms, with the odd peak at 21ms.  (Note to keep up with a 60Hz monitor you get about 16ms to render each update.)

I tried making some changes to improve the performance:

Removing the DT_WORDBREAK improves performance to about 1ms (about 7 times faster), but given only one line of text is making it to the screen, and there were just over 7 lines with word breaking, this seems to suggest to me the bottleneck is elsewhere.

I was drawing text in transparent mode (SetBkMode(TRANSPARENT)).  So I tried opaque mode with a solid background fill.  No improvement.

I thought ClearType rendering might be to blame.  I changed the font lfQuality from CLEARTYPE_QUALITY to NONANTIALIASED_QUALITY.  It looked like crap with sharp edges and all, and no improvement.

As per a comment suggestion, I was using a CMemDC, but I got rid of it and did direct drawing.  It flickered like mad, and no improvement.

This is running on a Windows 7 64-bit laptop with an Intel Core 2 Duo P8400 @ 2.26 GHz and 4 GB RAM - I don't think it counts as a slow system.

I'm calling DrawText() every time it draws and this obviously hammers the performance with such a slow function, especially if several of those text-blocks are visible at once.  It's enough to make the experience feel sluggish.  However, Firefox can render a page like this one in ClearType with much more text, and seems to cope just fine.  What am I doing wrong?  How can I get around the poor performance of an actual DrawText call?

答:
Have you considered Direct2D/DirectWrite?

Anyway it should work better if you just draw the text once to its own mem dc and blit that over to whatever dc you want it painted on with each iteration.

Body:
I noticed in an MFC application I'm developing that while dragging the scroll bar to smoothly scroll down the document, the framerate drops to choppy levels when a block containing about a paragraph of text is on screen, but silky smooth when it's offscreen.  Investigating the performance, I found the single CDC::DrawText call for the paragraph of text responsible.  This is in an optimised release build.

I used QueryPerformanceCounter to get a high-resolution measurement of just the DrawText call, like this:

QueryPerformanceCounter(...);
pDC->DrawText(some_cstring, some_crect, DT_WORDBREAK);
QueryPerformanceCounter(...);

The text is unicode, lorem-ipsum style filler, 865 characters long and wraps over 7-and-a-bit lines given the rectangle and font (Segoe UI, lfHeight = -12, a standard body text size).  From my measurements, that call alone takes on average 7.5 ms, with the odd peak at 21ms.  (Note to keep up with a 60Hz monitor you get about 16ms to render each update.)

I tried making some changes to improve the performance:

Removing the DT_WORDBREAK improves performance to about 1ms (about 7 times faster), but given only one line of text is making it to the screen, and there were just over 7 lines with word breaking, this seems to suggest to me the bottleneck is elsewhere.

I was drawing text in transparent mode (SetBkMode(TRANSPARENT)).  So I tried opaque mode with a solid background fill.  No improvement.

I thought ClearType rendering might be to blame.  I changed the font lfQuality from CLEARTYPE_QUALITY to NONANTIALIASED_QUALITY.  It looked like crap with sharp edges and all, and no improvement.

As per a comment suggestion, I was using a CMemDC, but I got rid of it and did direct drawing.  It flickered like mad, and no improvement.

This is running on a Windows 7 64-bit laptop with an Intel Core 2 Duo P8400 @ 2.26 GHz and 4 GB RAM - I don't think it counts as a slow system.

I'm calling DrawText() every time it draws and this obviously hammers the performance with such a slow function, especially if several of those text-blocks are visible at once.  It's enough to make the experience feel sluggish.  However, Firefox can render a page like this one in ClearType with much more text, and seems to cope just fine.  What am I doing wrong?  How can I get around the poor performance of an actual DrawText call?


来源: stackexchange

问:
WebView and MathML
I have tried putting MathML code into a WebView and it doesn't render properly. What am I doing incorrectly?</p>

```<code>import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class HelloWebView extends Activity {
WebView mWebView;
String mathml = "<html><body><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><msup> <mi>x</mi> <mn>2</mn> </msup></mrow></math> END OF TEST</body></html>";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadData(mathml, "text/html", "utf-8");
   }
}
</code>```

答:
```<code>loadDataWithBaseURL("http://bar",
                "<html><head>" +
                        " <meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" />" +
                        "</head>" +
                        "" +
                        "<body style=\"font-size:18px\" >" +
                        text +
                        "<script type=\"text/x-mathjax-config\">" +
                        "  MathJax.Hub.Config({\n" +
                        "  CommonHTML: { linebreaks: { automatic: true },EqnChunk:(MathJax.Hub.Browser.isMobile?10:50) },displayAlign: \"left\",\n" +
                        "  \"HTML-CSS\": { linebreaks: { automatic: true } ," +
                        "\n" +
                        "    preferredFont: \"STIX\"}," +
                        "extensions: [\"tex2jax.js\"],messageStyle:\"none\"," +
                        "jax: [\"input/TeX\", \"input/MathML\",\"output/HTML-CSS\"]," +
                        "tex2jax: {inlineMath: [['$','$'],['\\\\(','\\\\)']]}" +
                        "});" +
                        "</script>" +
                        "<script type=\"text/javascript\" async src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>" +
                        "" +
                        "</body>" +
                        "</html>", "text/html", "utf-8", "");

        loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
</code>```

ContentLicense: CC BY-SA 3.0

Title: WebView and MathML

Body:
I have tried putting MathML code into a WebView and it doesn't render properly. What am I doing incorrectly?

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class HelloWebView extends Activity {
WebView mWebView;
String mathml = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><msup> <mi>x</mi> <mn>2</mn> </msup></mrow></math> END OF TEST";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadData(mathml, "text/html", "utf-8");
   }
}


问:
Multiple image upload in Django admin for a gallery
I have spent a lot of time trying different ways to upload multiple images in Django admin but I have failed miserably. I have tried django-multiupload-admin which I didn't manage to make it work and inlines is not what I am looking for. I just want to select several images all at once, upload them under one category and them display them into a mansory gallery. I am willing to pay someone to help me find a simple way. Please help!</p>

答:
You can extend the Admin interface pretty easily using Javascript.
Here is the link ... it will help you design django admin with drag and drop method to upload images

Django Snippet Article about Image Upload


问:
Maximum number of lines for a Wrap TextBlock
I have a TextBlock with the following setting:

```<code>TextWrapping="Wrap"
</code>```

Can I determine the maximum number of lines?

for example consider the following string TextBlock.Text:

```<code>This is a very good horse under the blackboard!!
</code>```

It currently has been shows like this:

```<code>This is a very
good horse under
the blackboard!!
</code>```

I need that to become something like:

```<code>This is a very
good horse ...
</code>```

any solution?

答:
Based tobi.at's and gt's answer I have created this MaxLines behaviour. Crucially it doesn't depend upon setting the LineHeight property by calculating the line height from the font. You still need to set TextWrapping and TextTrimming for it the TextBox to be render as you would like.

```<code><TextBlock behaviours:NumLinesBehaviour.MaxLines="3" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" Text="Some text here"/>
</code>```

There in also a MinLines behaviour which can be different or set to the same number as the MaxLines behaviour to set the number of lines.

```<code>public class NumLinesBehaviour : Behavior<TextBlock>
{
    TextBlock textBlock => AssociatedObject;

    public static readonly DependencyProperty MaxLinesProperty =
        DependencyProperty.RegisterAttached(
            "MaxLines",
            typeof(int),
            typeof(NumLinesBehaviour),
            new PropertyMetadata(default(int), OnMaxLinesPropertyChangedCallback));

    public static void SetMaxLines(DependencyObject element, int value)
    {
        element.SetValue(MaxLinesProperty, value);
    }

    public static int GetMaxLines(DependencyObject element)
    {
        return (int)element.GetValue(MaxLinesProperty);
    }

    private static void OnMaxLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock element = d as TextBlock;
        element.MaxHeight = getLineHeight(element) * GetMaxLines(element);
    }

    public static readonly DependencyProperty MinLinesProperty =
        DependencyProperty.RegisterAttached(
            "MinLines",
            typeof(int),
            typeof(NumLinesBehaviour),
            new PropertyMetadata(default(int), OnMinLinesPropertyChangedCallback));

    public static void SetMinLines(DependencyObject element, int value)
    {
        element.SetValue(MinLinesProperty, value);
    }

    public static int GetMinLines(DependencyObject element)
    {
        return (int)element.GetValue(MinLinesProperty);
    }

    private static void OnMinLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock element = d as TextBlock;
        element.MinHeight = getLineHeight(element) * GetMinLines(element);
    }

    private static double getLineHeight(TextBlock textBlock)
    {
        double lineHeight = textBlock.LineHeight;
        if (double.IsNaN(lineHeight))
            lineHeight = Math.Ceiling(textBlock.FontSize * textBlock.FontFamily.LineSpacing);
        return lineHeight;
    }
}
</code>```

Body:
I have a TextBlock with the following setting:

TextWrapping="Wrap"

Can I determine the maximum number of lines?

for example consider the following string TextBlock.Text:

This is a very good horse under the blackboard!!

It currently has been shows like this:

This is a very
good horse under
the blackboard!!

I need that to become something like:

This is a very
good horse ...

any solution?

Body:
Based tobi.at's and gt's answer I have created this MaxLines behaviour. Crucially it doesn't depend upon setting the LineHeight property by calculating the line height from the font. You still need to set TextWrapping and TextTrimming for it the TextBox to be render as you would like.

<TextBlock behaviours:NumLinesBehaviour.MaxLines="3" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" Text="Some text here"/>

There in also a MinLines behaviour which can be different or set to the same number as the MaxLines behaviour to set the number of lines.

public class NumLinesBehaviour : Behavior<TextBlock>
{
    TextBlock textBlock => AssociatedObject;

    public static readonly DependencyProperty MaxLinesProperty =
        DependencyProperty.RegisterAttached(
            "MaxLines",
            typeof(int),
            typeof(NumLinesBehaviour),
            new PropertyMetadata(default(int), OnMaxLinesPropertyChangedCallback));

    public static void SetMaxLines(DependencyObject element, int value)
    {
        element.SetValue(MaxLinesProperty, value);
    }

    public static int GetMaxLines(DependencyObject element)
    {
        return (int)element.GetValue(MaxLinesProperty);
    }

    private static void OnMaxLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock element = d as TextBlock;
        element.MaxHeight = getLineHeight(element) * GetMaxLines(element);
    }

    public static readonly DependencyProperty MinLinesProperty =
        DependencyProperty.RegisterAttached(
            "MinLines",
            typeof(int),
            typeof(NumLinesBehaviour),
            new PropertyMetadata(default(int), OnMinLinesPropertyChangedCallback));

    public static void SetMinLines(DependencyObject element, int value)
    {
        element.SetValue(MinLinesProperty, value);
    }

    public static int GetMinLines(DependencyObject element)
    {
        return (int)element.GetValue(MinLinesProperty);
    }

    private static void OnMinLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock element = d as TextBlock;
        element.MinHeight = getLineHeight(element) * GetMinLines(element);
    }

    private static double getLineHeight(TextBlock textBlock)
    {
        double lineHeight = textBlock.LineHeight;
        if (double.IsNaN(lineHeight))
            lineHeight = Math.Ceiling(textBlock.FontSize * textBlock.FontFamily.LineSpacing);
        return lineHeight;
    }
}

ContentLicense: CC BY-SA 4.0


问:
Object with longer field is returned against an object with a short field
Let's say that we have an index with two objects:

```<code>{
"name": "iPhone 6s Plus big screen, super fast, ultra responsive, blah blah"
}
</code>```

and:

```<code>{
"name" : "iPhone 6s Plus"
}
</code>```

Now, when i search for iPhone 6s Plus, it returns the first object which does not make sense, since the first object contains more words (or noise) than the second object for the given query. In other words, a term appearing in a short name field should carry more ranking points than the same term appearing in a long name field

Algolia uses a TF/IDF algorithm, which takes account of the Field-length norm, so the second object should have higher score than the first one.

So why does the first object has higher score than the second one? Is there any settings option that I am missing?

答:
I found the answer, but I am not sure if it is 100% correct, or if there is a better way to achieve this.

Login to Algolia -> Select Your Instance -> Go to Ranking Tab.

In the Ranking Formula, add a new row. The new row, should have Attribute type {{the name of the column, in this example is "title"}} and set it to Ascending.

With that, you will achieve what we are looking for.

Body:
Let's say that we have an index with two objects:

{
"name": "iPhone 6s Plus big screen, super fast, ultra responsive, blah blah"
}

and:

{
"name" : "iPhone 6s Plus"
}

Now, when i search for iPhone 6s Plus, it returns the first object which does not make sense, since the first object contains more words (or noise) than the second object for the given query. In other words, a term appearing in a short name field should carry more ranking points than the same term appearing in a long name field

Algolia uses a TF/IDF algorithm, which takes account of the Field-length norm, so the second object should have higher score than the first one.

So why does the first object has higher score than the second one? Is there any settings option that I am missing?


问:
Dygraphs - synchronous zooming
I'm trying to render >3 graphs, using Dygraphs in JS.
Using some example codes, I was able to create a dummy for my work, just like this.

The demo works as it should, but here is my scenario:

I am trying to render 3 or more graphs with values from different ranges. I want to zoom in a time peroid on a graph and I want all the other graphs to zoom with it.
Right now, said graph will be zoomed and the others are going to be messed up:

$(document).ready(function() {
  var someData = [
    "2009/01/01,10,11,12\n" +
    "2009/01/02,12,10,11\n" +
    "2009/01/03,9,10,13\n" +
    "2009/01/04,5,20,15\n" +
    "2009/01/05,8,3,12\n",

    "2009/01/01,510,511,512\n" +
    "2009/01/02,518,510,511\n" +
    "2009/01/03,519,510,513\n" +
    "2009/01/04,525,520,515\n" +
    "2009/01/05,508,513,512\n",

    "2009/01/01,0.10,0.11,0.01\n" +
    "2009/01/02,0.12,1,0.11\n" +
    "2009/01/03,0.09,0.10,0.13\n" +
    "2009/01/04,0.05,0.20,0.15\n" +
    "2009/01/05,0.08,0.03,0.12\n",

    "2009/01/01,110,111,112\n" +
    "2009/01/02,112,110,111\n" +
    "2009/01/03,109,110,113\n" +
    "2009/01/04,105,120,115\n" +
    "2009/01/05,108,103,112\n"
  ];
  var graphs = ["x", "foo", "bar", "baz"];
  var titles = ['', '', '', ''];
  var gs = [];
  var blockRedraw = false;
  for (var i = 1; i <= 4; i++) {
    gs.push(
      new Dygraph(
        document.getElementById("div" + i),
        someData[i - 1], {
          labels: graphs,
          title: titles[i - 1],
          legend: 'always'
        }
      )
    );
  }
  var sync = Dygraph.synchronize(gs);

  function update() {
    var zoom = document.getElementById('chk-zoom').checked;
    var selection = document.getElementById('chk-selection').checked;
    sync.detach();
    sync = Dygraph.synchronize(gs, {
      zoom: zoom,
      selection: selection
    });
  }
  $('#chk-zoom, #chk-selection').change(update);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chart {
    width: 500px;
    height: 300px;
  }
  .chart-container {
    overflow: hidden;
  }
  #div1 {
    float: left;
  }
  #div2 {
    float: left;
  }
  #div3 {
    float: left;
    clear: left;
  }
  #div4 {
    float: left;
  }</code>```

Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.

To use this, source extras/synchronizer.js on your page. See the comments in that file for usage.

  Synchronize what?
  <input id="chk-zoom" checked="" type="checkbox">
  Zoom
  <input id="chk-selection" checked="" type="checkbox">
  Selection

```

For me it looks like that, the other graphs want to show the same value range for the selected time peroid. If this is the case, then do I just need to redraw the other graphs somehow?

答:
Below, I have modified your code (only 2 lines) and now I think it is working as you need.

Inside the synchronize options, I have added the option "range" set to false. With this option, the y-axis is not synchronized, which is what you need.

The other thing I´ve done, is to force a call to update() after the graphs synchronization. In the way you had the code, the update was not called until a checkbox was modified, so at the first, the graphs synchronization was not working.

I hope this could help you and sorry for not answering before ;)

$(document).ready(function() {
  var someData = [
    "2009/01/01,10,11,12\n" +
    "2009/01/02,12,10,11\n" +
    "2009/01/03,9,10,13\n" +
    "2009/01/04,5,20,15\n" +
    "2009/01/05,8,3,12\n",

    "2009/01/01,510,511,512\n" +
    "2009/01/02,518,510,511\n" +
    "2009/01/03,519,510,513\n" +
    "2009/01/04,525,520,515\n" +
    "2009/01/05,508,513,512\n",

    "2009/01/01,0.10,0.11,0.01\n" +
    "2009/01/02,0.12,1,0.11\n" +
    "2009/01/03,0.09,0.10,0.13\n" +
    "2009/01/04,0.05,0.20,0.15\n" +
    "2009/01/05,0.08,0.03,0.12\n",

    "2009/01/01,110,111,112\n" +
    "2009/01/02,112,110,111\n" +
    "2009/01/03,109,110,113\n" +
    "2009/01/04,105,120,115\n" +
    "2009/01/05,108,103,112\n"
  ];
  var graphs = ["x", "foo", "bar", "baz"];
  var titles = ['', '', '', ''];
  var gs = [];
  var blockRedraw = false;
  for (var i = 1; i <= 4; i++) {
    gs.push(
      new Dygraph(
        document.getElementById("div" + i),
        someData[i - 1], {
          labels: graphs,
          title: titles[i - 1],
          legend: 'always'
        }
      )
    );
  }
  var sync = Dygraph.synchronize(gs);
  update();

  function update() {
    var zoom = document.getElementById('chk-zoom').checked;
    var selection = document.getElementById('chk-selection').checked;
    sync.detach();
    sync = Dygraph.synchronize(gs, {
      zoom: zoom,
      range: false,
      selection: selection
    });
  }
  $('#chk-zoom, #chk-selection').change(update);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chart {
    width: 500px;
    height: 300px;
  }
  .chart-container {
    overflow: hidden;
  }
  #div1 {
    float: left;
  }
  #div2 {
    float: left;
  }
  #div3 {
    float: left;
    clear: left;
  }
  #div4 {
    float: left;
  }</code>```

Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.

To use this, source extras/synchronizer.js on your page. See the comments in that file for usage.

  Synchronize what?
  <input id="chk-zoom" checked="" type="checkbox">
  Zoom
  <input id="chk-selection" checked="" type="checkbox">
  Selection

```

Title: Dygraphs - synchronous zooming

Body:
I'm trying to render >3 graphs, using Dygraphs in JS.
Using some example codes, I was able to create a dummy for my work, just like this.

The demo works as it should, but here is my scenario:

I am trying to render 3 or more graphs with values from different ranges. I want to zoom in a time peroid on a graph and I want all the other graphs to zoom with it.
Right now, said graph will be zoomed and the others are going to be messed up:

$(document).ready(function() {
  var someData = [
    "2009/01/01,10,11,12\n" +
    "2009/01/02,12,10,11\n" +
    "2009/01/03,9,10,13\n" +
    "2009/01/04,5,20,15\n" +
    "2009/01/05,8,3,12\n",

    "2009/01/01,510,511,512\n" +
    "2009/01/02,518,510,511\n" +
    "2009/01/03,519,510,513\n" +
    "2009/01/04,525,520,515\n" +
    "2009/01/05,508,513,512\n",

    "2009/01/01,0.10,0.11,0.01\n" +
    "2009/01/02,0.12,1,0.11\n" +
    "2009/01/03,0.09,0.10,0.13\n" +
    "2009/01/04,0.05,0.20,0.15\n" +
    "2009/01/05,0.08,0.03,0.12\n",

    "2009/01/01,110,111,112\n" +
    "2009/01/02,112,110,111\n" +
    "2009/01/03,109,110,113\n" +
    "2009/01/04,105,120,115\n" +
    "2009/01/05,108,103,112\n"
  ];
  var graphs = ["x", "foo", "bar", "baz"];
  var titles = ['', '', '', ''];
  var gs = [];
  var blockRedraw = false;
  for (var i = 1; i <= 4; i++) {
    gs.push(
      new Dygraph(
        document.getElementById("div" + i),
        someData[i - 1], {
          labels: graphs,
          title: titles[i - 1],
          legend: 'always'
        }
      )
    );
  }
  var sync = Dygraph.synchronize(gs);

  function update() {
    var zoom = document.getElementById('chk-zoom').checked;
    var selection = document.getElementById('chk-selection').checked;
    sync.detach();
    sync = Dygraph.synchronize(gs, {
      zoom: zoom,
      selection: selection
    });
  }
  $('#chk-zoom, #chk-selection').change(update);
});

.chart {
    width: 500px;
    height: 300px;
  }
  .chart-container {
    overflow: hidden;
  }
  #div1 {
    float: left;
  }
  #div2 {
    float: left;
  }
  #div3 {
    float: left;
    clear: left;
  }
  #div4 {
    float: left;
  }

Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.

To use this, source extras/synchronizer.js on your page. See the comments in that file for usage.

  Synchronize what?
  <input id="chk-zoom" checked="" type="checkbox">
  Zoom
  <input id="chk-selection" checked="" type="checkbox">
  Selection

For me it looks like that, the other graphs want to show the same value range for the selected time peroid. If this is the case, then do I just need to redraw the other graphs somehow?

Body:
Below, I have modified your code (only 2 lines) and now I think it is working as you need.

Inside the synchronize options, I have added the option "range" set to false. With this option, the y-axis is not synchronized, which is what you need.

The other thing I´ve done, is to force a call to update() after the graphs synchronization. In the way you had the code, the update was not called until a checkbox was modified, so at the first, the graphs synchronization was not working.

I hope this could help you and sorry for not answering before ;)

$(document).ready(function() {
  var someData = [
    "2009/01/01,10,11,12\n" +
    "2009/01/02,12,10,11\n" +
    "2009/01/03,9,10,13\n" +
    "2009/01/04,5,20,15\n" +
    "2009/01/05,8,3,12\n",

    "2009/01/01,510,511,512\n" +
    "2009/01/02,518,510,511\n" +
    "2009/01/03,519,510,513\n" +
    "2009/01/04,525,520,515\n" +
    "2009/01/05,508,513,512\n",

    "2009/01/01,0.10,0.11,0.01\n" +
    "2009/01/02,0.12,1,0.11\n" +
    "2009/01/03,0.09,0.10,0.13\n" +
    "2009/01/04,0.05,0.20,0.15\n" +
    "2009/01/05,0.08,0.03,0.12\n",

    "2009/01/01,110,111,112\n" +
    "2009/01/02,112,110,111\n" +
    "2009/01/03,109,110,113\n" +
    "2009/01/04,105,120,115\n" +
    "2009/01/05,108,103,112\n"
  ];
  var graphs = ["x", "foo", "bar", "baz"];
  var titles = ['', '', '', ''];
  var gs = [];
  var blockRedraw = false;
  for (var i = 1; i <= 4; i++) {
    gs.push(
      new Dygraph(
        document.getElementById("div" + i),
        someData[i - 1], {
          labels: graphs,
          title: titles[i - 1],
          legend: 'always'
        }
      )
    );
  }
  var sync = Dygraph.synchronize(gs);
  update();

  function update() {
    var zoom = document.getElementById('chk-zoom').checked;
    var selection = document.getElementById('chk-selection').checked;
    sync.detach();
    sync = Dygraph.synchronize(gs, {
      zoom: zoom,
      range: false,
      selection: selection
    });
  }
  $('#chk-zoom, #chk-selection').change(update);
});

.chart {
    width: 500px;
    height: 300px;
  }
  .chart-container {
    overflow: hidden;
  }
  #div1 {
    float: left;
  }
  #div2 {
    float: left;
  }
  #div3 {
    float: left;
    clear: left;
  }
  #div4 {
    float: left;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph.js"></script>
<script src="http://dygraphs.com/src/extras/synchronizer.js"></script>

<p>Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.</p>
<p>To use this, source <a href="https://github.com/danvk/dygraphs/blob/master/src/extras/synchronizer.js"><code>extras/synchronizer.js</code></a> on your page. See the comments in that file for usage.</p>
<div class="chart-container">
  <div id="div1" class="chart"></div>
  <div id="div2" class="chart"></div>
  <div id="div3" class="chart"></div>
  <div id="div4" class="chart"></div>
</div>
<p>
  Synchronize what?
  <input id="chk-zoom" checked="" type="checkbox">
  <label for="chk-zoom">Zoom</label>
  <input id="chk-selection" checked="" type="checkbox">
  <label for="chk-selection">Selection</label>
</p>


问:
Want to route one component to another component
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>
      </div>
    );
  }
}

export default App;
</code>```

code for index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Respective i have also component class for Login.js and Register.js

答:
You can try below code    </p>

```<code>import { Link } from 'react-router';

<ul>
      <li><Link to="/login" onClick={this.gotoLogin}>Login</Link></li>
      <li><Link to="/register" onClick ={this.gotoRegister}>Register</Link></li>
 </ul>
</code>```

Body:
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (

Welcome to React

        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>

    );
  }
}

export default App;

code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Respective i have also component class for Login.js and Register.js

Body:
You can try below code

import { Link } from 'react-router';

<ul>
      <li><Link to="/login" onClick={this.gotoLogin}>Login</Link></li>
      <li><Link to="/register" onClick ={this.gotoRegister}>Register</Link></li>
 </ul>


问:
Algolia - How do you avoid having synonyms show up in highlighting?
e.g.  "apple" and "orange" are synonyms. I have a searchable attribute named "apple pie". If I search for "orange", the highlight on my attribute is "orange pie".

How do I make it show the original attribute value with highlighting: "apple pie"

答:
There is an option named replaceSynonymsInHighlight that you can turn off.

This option can be configured on the index settings or at query time.

You can also change this option form the dashboard under the "Display" tab of your index configuration.


Title: 31 days on the highcharts x-axis

Body:
I have a graph that i am plotting but i need to show 31 days of the month on the x-axis.

If you look at this  http://jsfiddle.net/codebreaker87/7hq6ueeb/2/show/

it only shows 31 days but the 31st is missing.  This is the code

http://jsfiddle.net/codebreaker87/7hq6ueeb/6/

How can i have the 31st day displayed?.

This is my code so far

Highcharts.chart('container', {
    chart: {
        type: 'line'
    },
    title: {
        text: 'SMS Volumes'
    },
    subtitle: {
        text: 'Source: Textify'
    },
    xAxis: {
        categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24','25','26','27','28','29','30','31']
    },
    yAxis: {
        title: {
            text: 'Volumes(1000)'
        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: true
            },
            enableMouseTracking: false
        }
    },
    series: [{
        name: 'Inbox',
        data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5]
    }, {
        name: 'Outbox',
        data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2]
    }]
});

Body:
only add point to 31 element:-

Highcharts.chart('container', {
    chart: {
        type: 'line',

    },
    title: {
        text: 'SMS Volumes'
    },
    subtitle: {
        text: 'Source: Textify'
    },
    xAxis: {
        categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24','25','26','27','28','29','30','31'],

    },
    yAxis: {
        title: {
            text: 'Volumes(1000)'
        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: true
            },
            enableMouseTracking: false
        }
    },
    series: [{
        name: 'Inbox',
        data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5,21.6]
    }, {
        name: 'Outbox',
        data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2,15.3]
    }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>


问:
In Javascript console.log I am not getting the result
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

```<code>    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };
</code>```

答:
You are using = instead of == (= means assignment and == means comparison)

 document.getElementById("runButton").onclick = function run() {
        var lastName = 'arm';
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName === undefined) {
                console.log("Hello, " + firstName + "!");
            } else if (firstName === undefined) {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName , lastName);
    };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="runButton">Click Me</button></code>```

Body:
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };

Body:
You are using = instead of == (= means assignment and == means comparison)

 document.getElementById("runButton").onclick = function run() {
        var lastName = 'arm';
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName === undefined) {
                console.log("Hello, " + firstName + "!");
            } else if (firstName === undefined) {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName , lastName);
    };

<button id="runButton">Click Me</button>


问:
Why does my list skip certain elements when I iteratate?
I am trying to write some code which adds an element in one list to another list and then removes it from the first list. It also should not add duplicates to the new list which is where the if statement comes in.
However, when adding to the 'individuals' list and removing from the 'sentence_list' list it misses out certain words such as 'not' and 'for'. This is also not random and the same words are missed each time. Any help?</p>

```<code>sentence = "I am a yellow fish"
sentence_list = sentence.lower().split()
individuals = []

for i in sentence_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)
</code>```

答:
In general you should not add or remove elements to a list as you iterate over it. Given that you are removing every single element of the list, just remove the lines with sentence_list.remove(i).

If you actually need to remove just some elements from the list you're iterating I'd either: make a new empty list and add the elements you want to keep to that, or keep a track of which indices in the list you want to remove as you iterate and then remove after the loop.

For the first solution,

```<code>oldList = [1, 2, 3, 4]
newList = []

for i in oldList:
    shouldRemove = i % 2
    if not shouldRemove:
        newList.append(i)
</code>```

For the second,

```<code>oldList = [1, 2, 3, 4]
indicesToKeep = []

for i, e in enumerate(oldList):
    shouldRemove = e % 2
    if not shouldRemove:
        indicesToKeep.append(i)

newList = [e for i, e in enumerate(oldList) if i in indicesToKeep]
</code>```

Body:
I am trying to write some code which adds an element in one list to another list and then removes it from the first list. It also should not add duplicates to the new list which is where the if statement comes in.
However, when adding to the 'individuals' list and removing from the 'sentence_list' list it misses out certain words such as 'not' and 'for'. This is also not random and the same words are missed each time. Any help?

sentence = "I am a yellow fish"
sentence_list = sentence.lower().split()
individuals = []

for i in sentence_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)

Body:
In general you should not add or remove elements to a list as you iterate over it. Given that you are removing every single element of the list, just remove the lines with sentence_list.remove(i).

If you actually need to remove just some elements from the list you're iterating I'd either: make a new empty list and add the elements you want to keep to that, or keep a track of which indices in the list you want to remove as you iterate and then remove after the loop.

For the first solution,

oldList = [1, 2, 3, 4]
newList = []

for i in oldList:
    shouldRemove = i % 2
    if not shouldRemove:
        newList.append(i)

For the second,

oldList = [1, 2, 3, 4]
indicesToKeep = []

for i, e in enumerate(oldList):
    shouldRemove = e % 2
    if not shouldRemove:
        indicesToKeep.append(i)

newList = [e for i, e in enumerate(oldList) if i in indicesToKeep]


问:
Rolled back Sendgrid API via Nuget to old version, now getting hundreds of warnings on build
Using Nuget, I rolled back the Sendgrid API from 9.1 to 9.0.

When I build my project, I now get hundreds of warnings such as:

warning SA1028: Code must not contain trailing whitespace

The file header is missing or not located at the top of the file.

Enable XML documentation output

Closing brace must be followed by blank line

It still builds, but these warnings were not there previously.

I updated back to 9.1 but the warnings still persist.  I'd like to get rid of them, but I'd rather not go through hundreds of files making irrelevant changes.

Does anyone know what happened when I rolled back the package, and what to do now to fix this issue?

答: Fixed, for some reason StyleCop Nuget package was installed at some point during the rollback/rollup.  Removed it from project and messages are gone.


问:
Display database structure from Delphi (rad studio)
Here is my procedure. When I execute it nothing happens; why is this?</p>

```<code> FData.FDQuery1.SQL.Clear;
 FData.FDQuery1.SQL.Add('select StrDBName FROM INFORMATION_SCHEMA.TABLES');

 FData.FDQuery1.ExecSQL;

 while FData.FDQuery1.Eof do
    ShowMessage(FData.FDQuery1.Fields[0].ToString);
     end;
</code>```

答:
As already explained to you in comments, your while loop should look something like this:

```<code> while **not** FData.FDQuery1.Eof do **begin**
    ShowMessage(FData.FDQuery1.Fields[0].ToString);
    **FData.FDQuery1.Next;**
 end;
</code>```

(minus the asterisks, of course).  However, that would not overcome the problem that your SQL is incorrect.

So, try this instead:

In a new Delphi project, place a TFDConnection, TFDQuery, TDataSource,
TDataSource and a TListBox on a form.  Save the form and project.

Double-click FDConnection1 to pop up its connection editor and configure
it so you can successfully connect it to your database.

Connect DBGrid1 to DataSource1 and Datasource1 to FDQuery1.

Add the code below to the form's OnCreate event.

Compile and run.

You should immediately see the cause of your problem.  As the error message
told you, there is no strDBName field in the INFORMATION_SCHEMA.TABLES table.

So you need to backtrack to the MySQL online help, starting e.g. here

https://dev.mysql.com/doc/refman/5.7/en/tables-table.html

and work out exactly what it is that you are looking for,
if you don't already know, and how to get it from within your project.

Btw, if you are not sure what you are doing, you should always try your SQL first in the MySql Workbench utility.

Code

```<code>  FDQuery1.SQL.Text := 'SELECT * FROM INFORMATION_SCHEMA.TABLES';
  FDQuery1.Open;
  FDQuery1.GetFieldNames(ListBox1.Items);
</code>```

I have a MySql database called 'MATestDB'.  To get a list of the fields (columns) in its tables, I would add this code to TForm1.FormCreate:

```<code>  FDQuery2.SQL.Text := 'select * from information_schema.columns where table_schema = ''MATestDB''';
  FDQuery2.Open;
</code>```

If you want FDQuery2 and its grid to track the selected table in FDQuery1, you can use code like the following to set up a master-detail relationship between them:

```<code>procedure TForm1.FormCreate(Sender: TObject);
begin
  FDQuery1.SQL.Text := 'SELECT * FROM INFORMATION_SCHEMA.TABLES';

  FDQuery2.SQL.Text := 'select table_schema, table_name, column_name, data_type, character_maximum_length, ordinal_position from information_schema.columns where table_schema = :Table_Schema and table_name = :Table_Name';
  FDQuery2.IndexFieldNames := 'table_schema;table_name;ordinal_position';
  FDQuery2.MasterFields := 'table_schema;table_name';
  FDQuery2.MasterSource := DataSource1;

  FDQuery1.Open;
  FDQuery1.GetFieldNames(ListBox1.Items);

  FDQuery2.Open;
  FDQuery2.GetFieldNames(ListBox2.Items);

end;
</code>```

Btw, you will not be able to get schema info for a Paradox database in the same way, but you should be able to google how to find out what information you want to gather from Paradox.

Btw #2: In the Sql you quoted in your deleted answer, one problem would be the reference to DBGrid2.SelectedField.ToString.  If DBGrid2 gets its data from FDQuery2, then you may have meant DBGrid**1**.SelectedField.ToString.  If you are still having problem with that, I suggest you ask about it in a new q, but make sure you include all the code necessary to reproduce the problem.

Body:
Here is my procedure. When I execute it nothing happens; why is this?

 FData.FDQuery1.SQL.Clear;
 FData.FDQuery1.SQL.Add('select StrDBName FROM INFORMATION_SCHEMA.TABLES');

 FData.FDQuery1.ExecSQL;

 while FData.FDQuery1.Eof do
    ShowMessage(FData.FDQuery1.Fields[0].ToString);
     end;

Body:
As already explained to you in comments, your while loop should look something like this:

 while **not** FData.FDQuery1.Eof do **begin**
    ShowMessage(FData.FDQuery1.Fields[0].ToString);
    **FData.FDQuery1.Next;**
 end;

(minus the asterisks, of course).  However, that would not overcome the problem that your SQL is incorrect.

So, try this instead:

In a new Delphi project, place a TFDConnection, TFDQuery, TDataSource,
TDataSource and a TListBox on a form.  Save the form and project.

Double-click FDConnection1 to pop up its connection editor and configure
it so you can successfully connect it to your database.

Connect DBGrid1 to DataSource1 and Datasource1 to FDQuery1.

Add the code below to the form's OnCreate event.

Compile and run.

You should immediately see the cause of your problem.  As the error message
told you, there is no strDBName field in the INFORMATION_SCHEMA.TABLES table.

So you need to backtrack to the MySQL online help, starting e.g. here

https://dev.mysql.com/doc/refman/5.7/en/tables-table.html

and work out exactly what it is that you are looking for,
if you don't already know, and how to get it from within your project.

Btw, if you are not sure what you are doing, you should always try your SQL first in the MySql Workbench utility.

Code

  FDQuery1.SQL.Text := 'SELECT * FROM INFORMATION_SCHEMA.TABLES';
  FDQuery1.Open;
  FDQuery1.GetFieldNames(ListBox1.Items);

I have a MySql database called 'MATestDB'.  To get a list of the fields (columns) in its tables, I would add this code to TForm1.FormCreate:

  FDQuery2.SQL.Text := 'select * from information_schema.columns where table_schema = ''MATestDB''';
  FDQuery2.Open;

If you want FDQuery2 and its grid to track the selected table in FDQuery1, you can use code like the following to set up a master-detail relationship between them:

procedure TForm1.FormCreate(Sender: TObject);
begin
  FDQuery1.SQL.Text := 'SELECT * FROM INFORMATION_SCHEMA.TABLES';

  FDQuery2.SQL.Text := 'select table_schema, table_name, column_name, data_type, character_maximum_length, ordinal_position from information_schema.columns where table_schema = :Table_Schema and table_name = :Table_Name';
  FDQuery2.IndexFieldNames := 'table_schema;table_name;ordinal_position';
  FDQuery2.MasterFields := 'table_schema;table_name';
  FDQuery2.MasterSource := DataSource1;

  FDQuery1.Open;
  FDQuery1.GetFieldNames(ListBox1.Items);

  FDQuery2.Open;
  FDQuery2.GetFieldNames(ListBox2.Items);

end;

Btw, you will not be able to get schema info for a Paradox database in the same way, but you should be able to google how to find out what information you want to gather from Paradox.

Btw #2: In the Sql you quoted in your deleted answer, one problem would be the reference to DBGrid2.SelectedField.ToString.  If DBGrid2 gets its data from FDQuery2, then you may have meant DBGrid**1**.SelectedField.ToString.  If you are still having problem with that, I suggest you ask about it in a new q, but make sure you include all the code necessary to reproduce the problem.


问:
Replacing words in text file using a dictionary
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line
</code>```

答:
I used items() to iterate over key and values of your fields dict.

I skip the blank lines with continue and clean the others with rstrip()

I replace every keys found in the line by the values in your fields dict, and I write every lines with print.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    if not line:
        continue
    for f_key, f_value in fields.items():
        if f_key in line:
            line = line.replace(f_key, f_value)
    print line
</code>```

Body:
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line

Body:
I used items() to iterate over key and values of your fields dict.

I skip the blank lines with continue and clean the others with rstrip()

I replace every keys found in the line by the values in your fields dict, and I write every lines with print.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    if not line:
        continue
    for f_key, f_value in fields.items():
        if f_key in line:
            line = line.replace(f_key, f_value)
    print line


问:
RxSwift Text field Delegate Methods
I'm new to RxSwift. I need to ask how can I bind textField delegate methods using RxSwift like textFieldShouldReturn or textViewDidBeginEditing.  </p>

答:
Let's supose you have a viewModel. For instance:

```<code>class ViewModel {
    var name: Variable<String>
    // more properties ...
}
</code>```

Then, in your viewController:

```<code>textField.rx.text.orEmpty
    .bindTo(viewModel.name)
    .addDisposableTo(disposeBag)
</code>```

In your viewController you have to import RxSwift and RxCocoa

Title: RxSwift Text field Delegate Methods

Body:
Let's supose you have a viewModel. For instance:

class ViewModel {
    var name: Variable<String>
    // more properties ...
}

Then, in your viewController:

textField.rx.text.orEmpty
    .bindTo(viewModel.name)
    .addDisposableTo(disposeBag)

In your viewController you have to import RxSwift and RxCocoa


问:
RJDBC: dbReadTable not working
When I upgrade DBI from 0.5.1 to 0.6, whenever I call dbReadTable:

```<code>mv = dbReadTable(conn, "MOVIES")
driver = JDBC("oracle.jdbc.OracleDriver", classPath = class_path)n
conn = dbConnect(driver,
           myhost,
           username, password)
</code>```

It will generate an error such as:

```<code>Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘dbGetQuery’ for signature ‘"character", "missing"’
Traceback:

1. dbReadTable(conn, SQL("MOVIES"))
2. dbReadTable(conn, SQL("MOVIES"))
3. .local(conn, name, ...)
4. dbGetQuery(paste0("SELECT * FROM ", sql_name))
5. (function (classes, fdef, mtable)
 . {
 .     methods <- .findInheritedMethods(classes, fdef, mtable)
 .     if (length(methods) == 1L)
 .         return(methods[[1L]])
 .     else if (length(methods) == 0L) {
 .         cnames <- paste0("\"", vapply(classes, as.character,
 .             ""), "\"", collapse = ", ")
 .         stop(gettextf("unable to find an inherited method for function %s for signature %s",
 .             sQuote(fdef@generic), sQuote(cnames)), domain = NA)
 .     }
 .     else stop("Internal error in finding inherited methods; didn't return a unique method",
 .         domain = NA)
 . })(list("character", structure("missing", package = "methods")),
 .     structure(function (conn, statement, ...)
 .     standardGeneric("dbGetQuery"), generic = structure("dbGetQuery", package = "DBI"), package = "DBI", group = list(), valueClass = character(0), signature = c("conn",
 .     "statement"), default = `\001NULL\001`, skeleton = (function (conn,
 .         statement, ...)
 .     stop("invalid call in method dispatch to 'dbGetQuery' (no default method)",
 .         domain = NA))(conn, statement, ...), class = structure("standardGeneric", package = "methods")),
 .     <environment>)
6. stop(gettextf("unable to find an inherited method for function %s for signature %s",
 .     sQuote(fdef@generic), sQuote(cnames)), domain = NA)
</code>```

Everything is fine for dbGetQuery. What happens?

答: This appears to be a problem in the DBI package that will be fixed soon. DBI 0.6-1 and later should not have this problem anymore. Would you mind filing an issue at https://github.com/rstats-db/DBI/issues?

Title: RJDBC: dbReadTable not working

Body:
When I upgrade DBI from 0.5.1 to 0.6, whenever I call dbReadTable:

mv = dbReadTable(conn, "MOVIES")
driver = JDBC("oracle.jdbc.OracleDriver", classPath = class_path)n
conn = dbConnect(driver,
           myhost,
           username, password)

It will generate an error such as:

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘dbGetQuery’ for signature ‘"character", "missing"’
Traceback:

1. dbReadTable(conn, SQL("MOVIES"))
2. dbReadTable(conn, SQL("MOVIES"))
3. .local(conn, name, ...)
4. dbGetQuery(paste0("SELECT * FROM ", sql_name))
5. (function (classes, fdef, mtable)
 . {
 .     methods <- .findInheritedMethods(classes, fdef, mtable)
 .     if (length(methods) == 1L)
 .         return(methods[[1L]])
 .     else if (length(methods) == 0L) {
 .         cnames <- paste0("\"", vapply(classes, as.character,
 .             ""), "\"", collapse = ", ")
 .         stop(gettextf("unable to find an inherited method for function %s for signature %s",
 .             sQuote(fdef@generic), sQuote(cnames)), domain = NA)
 .     }
 .     else stop("Internal error in finding inherited methods; didn't return a unique method",
 .         domain = NA)
 . })(list("character", structure("missing", package = "methods")),
 .     structure(function (conn, statement, ...)
 .     standardGeneric("dbGetQuery"), generic = structure("dbGetQuery", package = "DBI"), package = "DBI", group = list(), valueClass = character(0), signature = c("conn",
 .     "statement"), default = `\001NULL\001`, skeleton = (function (conn,
 .         statement, ...)
 .     stop("invalid call in method dispatch to 'dbGetQuery' (no default method)",
 .         domain = NA))(conn, statement, ...), class = structure("standardGeneric", package = "methods")),
 .     <environment>)
6. stop(gettextf("unable to find an inherited method for function %s for signature %s",
 .     sQuote(fdef@generic), sQuote(cnames)), domain = NA)

Everything is fine for dbGetQuery. What happens?


问:
Convert array to multiline based on keys in PhpStorm
Is there any way in PhpStorm to convert string

```<code>$arr = array('where' => '{"key_4":' . $this->key_4 . '}', 'key_2' => $this->user->key_2, 'key_3' => $this->user->key_5, 'key_6' => '');
</code>```

into

```<code>$arr = array(
    'where' => '{"key_4":' . $this->key_4 .'}',
    'key_2' => $this->user->key_2,
    'key_3' => $this->user->key_5,
    'key_6' => ''
);
</code>```

Has anyone some ideas?

答:
These are the only changes that I've done in Default scheme to get such formatting:

Results (before and after):

Body:
Is there any way in PhpStorm to convert string

$arr = array('where' => '{"key_4":' . $this->key_4 . '}', 'key_2' => $this->user->key_2, 'key_3' => $this->user->key_5, 'key_6' => '');

into

$arr = array(
    'where' => '{"key_4":' . $this->key_4 .'}',
    'key_2' => $this->user->key_2,
    'key_3' => $this->user->key_5,
    'key_6' => ''
);

Has anyone some ideas?


问:
Create new directory in share-point using SOAP in java
I have just started working on share-point using java my firm uses share-point 2010 version so I have to work using SOAP and I have done following functionality.

Download Document from share-point.

Upload Document to share-point.

But I am stuck at creating new directory, I have tried some code by googling but no luck.
Here is my code:
```<code>
public void createFolder(ListsSoap ls, String filePathToCreate,
            String fileName, LoginDO loginDO, HttpServletResponse response)
            throws Exception {
        try {
            String query = "";
            String folderName = "NewFolder";
            // 1. Prepare Query, Query Options and field Options
            if (CommonUtilities.isValidStr(folderName)) {
                // Prepare Query & Query Options for child folders</p>

            query = "<Batch OnError=\"Continue\" PreCalc=\"TRUE\" ListVersion=\"0\" " +
                    "RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"
                    + "<Method ID=\"1\" Cmd=\"New\">"
                    + "<Field Name=\"FSObjType\">1</Field>"
                    +"<Field Name=\"ID\">New</Field>"
                    + "<Field Name=\"BaseName\">" + folderName + "</Field>"
                    + "</Method></Batch>";
        } else {
            // Prepare Query & Query Options for Parent folders

            query = "<Query><Where><Eq><FieldRef Name=\"FSObjType\" />"
                    + "<Value Type=\"Lookup\">1</Value></Eq></Where></Query>";

        }

        UpdateListItems.Updates updates = null;

        // 2. Prepare Query, QueryOptions & ViewFields object as per options
        if (CommonUtilities.isValidStr(query)) {
            updates = new UpdateListItems.Updates();
            updates.getContent().add(
                    sharepointUtil.createSharePointCAMLNode(query));
        }

        // 3. Call Web service to get result for selected options
        UpdateListItemsResult result = ls
                .updateListItems(SHAREPOINT_FOLDER_NAME,updates);

        /*
         * CommonUtilities
         * .getApplicationProperty(ApplicationConstants.SHAREPOINT_FOLDER_NAME
         * ), "", msQuery, viewFields, "", msQueryOptions, "");
         */
        // 4. Get elements from share point result
        Element element = (Element) result.getContent().get(0);
        NodeList nl = element.getElementsByTagName("z:row");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            System.out.println("Some.!");

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // logger.logMethodEnd();
}`
</code>```

Anyhow updateListItems() method is executed without error but there is nothing in result.

Any help is appreciated.

Thank you :)

答:
seems there was problem in

```<code>
"RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"

</code>```

while passing root directory to create folder within.
found other way around by passing folderName with full directories hierarchy.

Thank you all for your inputs :)

Body:
I have just started working on share-point using java my firm uses share-point 2010 version so I have to work using SOAP and I have done following functionality.

Download Document from share-point.

Upload Document to share-point.

But I am stuck at creating new directory, I have tried some code by googling but no luck.
Here is my code:

public void createFolder(ListsSoap ls, String filePathToCreate,
            String fileName, LoginDO loginDO, HttpServletResponse response)
            throws Exception {
        try {
            String query = "";
            String folderName = "NewFolder";
            // 1. Prepare Query, Query Options and field Options
            if (CommonUtilities.isValidStr(folderName)) {
                // Prepare Query & Query Options for child folders

            query = "<Batch OnError=\"Continue\" PreCalc=\"TRUE\" ListVersion=\"0\" " +
                    "RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"
                    + "<Method ID=\"1\" Cmd=\"New\">"
                    + "<Field Name=\"FSObjType\">1</Field>"
                    +"<Field Name=\"ID\">New</Field>"
                    + "<Field Name=\"BaseName\">" + folderName + "</Field>"
                    + "</Method></Batch>";
        } else {
            // Prepare Query & Query Options for Parent folders

            query = "<Query><Where><Eq><FieldRef Name=\"FSObjType\" />"
                    + "<Value Type=\"Lookup\">1</Value></Eq></Where></Query>";

        }

        UpdateListItems.Updates updates = null;

        // 2. Prepare Query, QueryOptions & ViewFields object as per options
        if (CommonUtilities.isValidStr(query)) {
            updates = new UpdateListItems.Updates();
            updates.getContent().add(
                    sharepointUtil.createSharePointCAMLNode(query));
        }

        // 3. Call Web service to get result for selected options
        UpdateListItemsResult result = ls
                .updateListItems(SHAREPOINT_FOLDER_NAME,updates);

        /*
         * CommonUtilities
         * .getApplicationProperty(ApplicationConstants.SHAREPOINT_FOLDER_NAME
         * ), "", msQuery, viewFields, "", msQueryOptions, "");
         */
        // 4. Get elements from share point result
        Element element = (Element) result.getContent().get(0);
        NodeList nl = element.getElementsByTagName("z:row");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            System.out.println("Some.!");

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // logger.logMethodEnd();
}`

Anyhow updateListItems() method is executed without error but there is nothing in result.

Any help is appreciated.

Thank you :)

Body:
seems there was problem in

"RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"

while passing root directory to create folder within.
found other way around by passing folderName with full directories hierarchy.

Thank you all for your inputs :)


问:
Correct way to register service with discovery server
currently I'm trying the first time to create an api with micro services.
For this I'm using Java with Spring and the Netflix stack.
What I have problems with is to register a service to the discovery server (which works fine).

Discovery Server:

java:

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringCloudApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args){
        System.setProperty("spring.config.name", "heiseTut/registerApplication");
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
</code>```

yml for the discovery-Server:

```<code>eureka:
  instance:
    hostname: localhost
  client:  # Not a client, don't register with yourself!!!!!!!!!!!!
    registerWithEureka: false
    fetchRegistry: false
  server:
      waitTimeInMsWhenSyncEmpty: 0

server:
  port: 1111   # HTTP (Tomcat) port
</code>```

Service wich I want to register:
java:

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableAutoConfiguration
@EnableEurekaClient
public class HelloServiceApplication {
    public static void main(String[] args){
        System.setProperty("spring.config.name", "heiseTut/helloApplication");
        SpringApplication.run(HelloServiceApplication.class, args);
    }
}
</code>```

yml for this service:

```<code>eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

server:
    port: 8888
</code>```

bootstrap for this service:

```<code>spring:
    application:
        name: helloWorld-service
</code>```

Part of the error message (very long so I only include the, hopfully correct, important parts:

```<code>2017-03-31 12:12:39.258  WARN 228 --- [           main] com.netflix.discovery.DiscoveryClient    : Action: Refresh  => returned status of 401 from http://localhost:1111/eureka/apps/
2017-03-31 12:12:39.260 ERROR 228 --- [           main] com.netflix.discovery.DiscoveryClient    : Can't get a response from http://localhost:1111/eureka/apps/
Can't contact any eureka nodes - possibly a security group issue?

java.lang.RuntimeException: Bad status: 401
    at com.netflix.discovery.DiscoveryClient.makeRemoteCall(DiscoveryClient.java:1155)
    at com.netflix.discovery.DiscoveryClient.makeRemoteCall(DiscoveryClient.java:1060)
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:835)
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:746)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:320)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:197)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:193)
    at com.netflix.discovery.DiscoveryManager.initComponent(DiscoveryManager.java:84)
    at org.springframework.cloud.netflix.eureka.DiscoveryManagerInitializer.init(DiscoveryManagerInitializer.java:39)
    at org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration.start(EurekaDiscoveryClientConfiguration.java:126)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:51)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:346)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:770)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at heiseTut.helloService.HelloServiceApplication.main(HelloServiceApplication.java:17)

2017-03-31 12:12:39.260 ERROR 228 --- [           main] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_BOOTSTRAP/DESKTOP-S716PSE - was unable to refresh its cache! status = Bad status: 401

.
. other error messages
.

2017-03-31 12:12:39.356  INFO 228 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2bbaf4f0: startup date [Fri Mar 31 12:12:36 CEST 2017]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Tomcat connector in failed state
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:288)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at heiseTut.helloService.HelloServiceApplication.main(HelloServiceApplication.java:17)
</code>```

Thanks for possible help and replys.

答:
I found a temporary solution.
At least in a devlopment environment you can turn off the security in the application.yml of the discovery server:</p>

```<code>security:
    basic:
        enabled: false
</code>```

Body:
currently I'm trying the first time to create an api with micro services.
For this I'm using Java with Spring and the Netflix stack.
What I have problems with is to register a service to the discovery server (which works fine).

Discovery Server:

java:

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringCloudApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args){
        System.setProperty("spring.config.name", "heiseTut/registerApplication");
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

yml for the discovery-Server:

eureka:
  instance:
    hostname: localhost
  client:  # Not a client, don't register with yourself!!!!!!!!!!!!
    registerWithEureka: false
    fetchRegistry: false
  server:
      waitTimeInMsWhenSyncEmpty: 0

server:
  port: 1111   # HTTP (Tomcat) port

Service wich I want to register:
java:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableAutoConfiguration
@EnableEurekaClient
public class HelloServiceApplication {
    public static void main(String[] args){
        System.setProperty("spring.config.name", "heiseTut/helloApplication");
        SpringApplication.run(HelloServiceApplication.class, args);
    }
}

yml for this service:

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

server:
    port: 8888

bootstrap for this service:

spring:
    application:
        name: helloWorld-service

Part of the error message (very long so I only include the, hopfully correct, important parts:

2017-03-31 12:12:39.258  WARN 228 --- [           main] com.netflix.discovery.DiscoveryClient    : Action: Refresh  => returned status of 401 from http://localhost:1111/eureka/apps/
2017-03-31 12:12:39.260 ERROR 228 --- [           main] com.netflix.discovery.DiscoveryClient    : Can't get a response from http://localhost:1111/eureka/apps/
Can't contact any eureka nodes - possibly a security group issue?

java.lang.RuntimeException: Bad status: 401
    at com.netflix.discovery.DiscoveryClient.makeRemoteCall(DiscoveryClient.java:1155)
    at com.netflix.discovery.DiscoveryClient.makeRemoteCall(DiscoveryClient.java:1060)
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:835)
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:746)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:320)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:197)
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:193)
    at com.netflix.discovery.DiscoveryManager.initComponent(DiscoveryManager.java:84)
    at org.springframework.cloud.netflix.eureka.DiscoveryManagerInitializer.init(DiscoveryManagerInitializer.java:39)
    at org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration.start(EurekaDiscoveryClientConfiguration.java:126)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:51)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:346)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:770)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at heiseTut.helloService.HelloServiceApplication.main(HelloServiceApplication.java:17)

2017-03-31 12:12:39.260 ERROR 228 --- [           main] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_BOOTSTRAP/DESKTOP-S716PSE - was unable to refresh its cache! status = Bad status: 401

.
. other error messages
.

2017-03-31 12:12:39.356  INFO 228 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2bbaf4f0: startup date [Fri Mar 31 12:12:36 CEST 2017]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Tomcat connector in failed state
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:288)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at heiseTut.helloService.HelloServiceApplication.main(HelloServiceApplication.java:17)

Thanks for possible help and replys.

Body:
I found a temporary solution.
At least in a devlopment environment you can turn off the security in the application.yml of the discovery server:

security:
    basic:
        enabled: false


问:
How does -d work in if statements when checking for return codes?
I can across some code in a bash script that has confused me a little.

The code checks to see if the directory/file exists. If the return code is 0 ... success, otherwise the file doesn't exist:

```<code>if [ -d /usr/local/bin ]
then
    echo "Exists"
else
    echo "Does not exist"
fi
</code>```

What program is -d /usr/local/bin using to check if the file exists? The other example in the book is:

```<code>test -d /usr/local/bin

if [ "$?" -eq 0 ]
then
    echo "Exists"
else
    echo "Does not exist"
fi
</code>```

Which leads me to believe the first example us using test within the if. And if so, why does this happen automatically without having to specify the test program?

答:
The square brackets are not part of the shell grammar.  Rather [ is a command with the very odd feature of requiring its last argument to be the literal string ].  The command you are executing is [ with the 4 arguments N, -eq, 0, and ] where N is the value that the shell variable ? currently expands to (likely either 0 or 1).  In the past, /bin/[ was often literally a link to the same file as /bin/test, and that executable behaved slightly differently when it was invoked through that link (it checked that the last argument was ]).  Other than the check on the last argument, [ is exactly the same as the command test.

It might be clearer if the second example did not explicitly check $? but had instead simply been written:

```<code>if test -d /usr/local/bin
then
    echo "Exists"
else
    echo "Does not exist"
fi
</code>```

Body:
I can across some code in a bash script that has confused me a little.

The code checks to see if the directory/file exists. If the return code is 0 ... success, otherwise the file doesn't exist:

if [ -d /usr/local/bin ]
then
    echo "Exists"
else
    echo "Does not exist"
fi

What program is -d /usr/local/bin using to check if the file exists? The other example in the book is:

test -d /usr/local/bin

if [ "$?" -eq 0 ]
then
    echo "Exists"
else
    echo "Does not exist"
fi

Which leads me to believe the first example us using test within the if. And if so, why does this happen automatically without having to specify the test program?

Body:
The square brackets are not part of the shell grammar.  Rather [ is a command with the very odd feature of requiring its last argument to be the literal string ].  The command you are executing is [ with the 4 arguments N, -eq, 0, and ] where N is the value that the shell variable ? currently expands to (likely either 0 or 1).  In the past, /bin/[ was often literally a link to the same file as /bin/test, and that executable behaved slightly differently when it was invoked through that link (it checked that the last argument was ]).  Other than the check on the last argument, [ is exactly the same as the command test.

It might be clearer if the second example did not explicitly check $? but had instead simply been written:

if test -d /usr/local/bin
then
    echo "Exists"
else
    echo "Does not exist"
fi


问:
Python json POST request status 200 while expecting status 201
I'm trying to do a POST request to a web server in an attempt to create a new resource. I'm fairly new to both Python and the platform I'm trying to communicate with on the server, so I'm not sure if it's my python skills require a bit more practice or if I'm just not submitting a request correctly to the server. Here's my code:

```<code>import requests

apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"

values = """
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 10,
    "note": "",
    "invoiceIds": []
  }
"""

headers = {
  'X-Auth-App-Key': apiKey,
  'Content-Type': 'application/json'
}

r = requests.post(serverUrl, data=values, headers=headers)
r
</code>```

The server responds with a Response 200 (OK) message, but since I'm trying to create a new resource it should respond with a Response 201 (Created) message. Any ideas what I'm doing wrong?

答:
Try using https://,

change serverUrl = "http://192.168.0.5/api/v1.0/payments"

to

```<code>serverUrl = "https://192.168.0.5/api/v1.0/payments"
</code>```

Body:
I'm trying to do a POST request to a web server in an attempt to create a new resource. I'm fairly new to both Python and the platform I'm trying to communicate with on the server, so I'm not sure if it's my python skills require a bit more practice or if I'm just not submitting a request correctly to the server. Here's my code:

import requests

apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"

values = """
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 10,
    "note": "",
    "invoiceIds": []
  }
"""

headers = {
  'X-Auth-App-Key': apiKey,
  'Content-Type': 'application/json'
}

r = requests.post(serverUrl, data=values, headers=headers)
r

The server responds with a Response 200 (OK) message, but since I'm trying to create a new resource it should respond with a Response 201 (Created) message. Any ideas what I'm doing wrong?

Body:
Try using https://,

change serverUrl = "http://192.168.0.5/api/v1.0/payments"

to

serverUrl = "https://192.168.0.5/api/v1.0/payments"


问:
Decryption via Multi processing in javascript
I have image data(210KB) that has been encrypted via RSA algorithm. I would like to decrypt that encrypted image data into Javascript using JSEncrypt. I was able to decrypt the image successfully, but it took around 10 seconds. So I thought to use the multiprocessing in Javascript  in which I want to use JSEncrypt functionality which is loaded in script.

How to use parallel processing in Javascript to speedup the processing. Or is there any other way to speedup the RSA decryption in Javascript?

Here is the sample code that I was trying for parallel processing in Javascript, but decrypt.decrypt was not working.

```<code><html>
<head>

</head>

</html>
</code>```

答:
It is possible to utilize multiprocessing in the browser, but browser support is pretty porous, and it will probably feel like a hack. You'll need to use a browser that creates a new process for each tab, and that supports shared worker threads. So basically, Chrome.

Using a Shared Worker object will allow multiple tabs or Windows to share data. So all you need to do is create a script that decrypts a portion of the image (decrypt.js), and sends the clear data back through the worker. Then, have your main script open a few new tabs running decrypt.js and send each one the data to crunch.

However, there are still nuances. The message passing across processes will impact performance for large objects since they must be copied. This can be relieved using Transferable Objects; essentially, you'll have to manage formatting your data into an array buffer and back again.

Also, the browser will probably give those tabs a low execution priority or stop them all together, depending on the implementation. In that case, you'll have to create a worker thread that posts a message to the main thread at regular intervals, for each tab.

This is all assuming that the encryption algorithm you're using can be done in parallel, and that the JSEncrypt library supports it...

My suggestion: decrypt in a standard, dedicated worker thread and show a loading bar. 10 seconds isn't that bad when there's something pretty to look at ;)


问:
How to concatenate variable name AngularJS?
Concatenate variable name in HTML code like:

app.controller code

```<code>  $scope.name ='abc';
  $scope.abc123 = response.data;
</code>```

HTML code

```<code>   <h1>{{name}}</h1>
   <h1>{{{{name}}123}}</h1> <!-- here i need value of abc123 -->
</code>```

答:
You can this with controller as syntax:

```<code>var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl",MyCtrl);

function MyCtrl() {
    this.name = 'abc';
    this.abc123  = 'value';
}
</code>```

vm.name+'123' is dynamic key and then get from vm

```<code><div ng-app="myApp" ng-controller="MyCtrl as vm" >
  Name value: {{vm.name+'123'}} and dynamic value: {{vm[vm.name+'123']}}
</div>
</code>```

Body:
Concatenate variable name in HTML code like:

app.controller code

  $scope.name ='abc';
  $scope.abc123 = response.data;

HTML code

{{name}}

{{{{name}}123}}

Body:
You can this with controller as syntax:

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl",MyCtrl);

function MyCtrl() {
    this.name = 'abc';
    this.abc123  = 'value';
}

vm.name+'123' is dynamic key and then get from vm

<div ng-app="myApp" ng-controller="MyCtrl as vm" >
  Name value: {{vm.name+'123'}} and dynamic value: {{vm[vm.name+'123']}}
</div>


问:
How to hide div when click on anywhere on the display
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </code>```

答:
Hope this helps:

$(document).ready(function () {
  $('#PopupDiv').hide();
  $('#Btn1').click(function () {
    alert();
  $('#PopupDiv').show();
  })
  $(document).click(function (e) {
      alert('o')
      if (e.target.id != "Btn1") {
         $('#PopupDiv').hide();
      }
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>

<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script></code>```

Body:
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

  <input type="button" id="Btn1" value="BtnClick" />

Hello Popup Grid

Body:
Hope this helps:

$(document).ready(function () {
  $('#PopupDiv').hide();
  $('#Btn1').click(function () {
    alert();
  $('#PopupDiv').show();
  })
  $(document).click(function (e) {
      alert('o')
      if (e.target.id != "Btn1") {
         $('#PopupDiv').hide();
      }
  })
})

<div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>

<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>


问:
What is TortoiseHg Overlay Icon Server
I just install TortoiseHg, to act as Mercurial client tool.

However, in my Vista, whenever I start, there is a TortoiseHg Overlay Icon Server at my notification bar.

Is quite annoying. What is the purpose of that? Can I disable it?

答: It is the service, which modifies the icon in the explorer which showes when files are under version control and if they are changed. Let it do its work.</p>

ContentLicense: CC BY-SA 2.5

Title: What is TortoiseHg Overlay Icon Server


问:
cors jquery withCredentials cookie
client:

```<code>$.support.cors = true;

// ajax option
beforeSend: function (XHR) {
  XHR.withCredentials = true;
  XHR.setRequestHeader("Authorization", "Bearer " + base.accessToken);
}
</code>```

I use "fiddler" and catch the request, it shows no cookie included.

AuthN server has set cookie.

答: Actually, preflight requests won't be sent with the cookie, it's just used to check wteather server api support CORS. So maybe you can close authentication of your server for OPTIONS methods</p>

Title: cors jquery withCredentials cookie

Body:
client:

$.support.cors = true;

// ajax option
beforeSend: function (XHR) {
  XHR.withCredentials = true;
  XHR.setRequestHeader("Authorization", "Bearer " + base.accessToken);
}

I use "fiddler" and catch the request, it shows no cookie included.

AuthN server has set cookie.


问:
SES port is blocked in GCP
I have an application that is hosted on a GCP machine.
This application is supposed to send a mail via AWS SES service.

From what I've seen in GCP documentation, all default SMTP ports are blocked in GCP machines.

is it possible to unblock one of the ports or use another port for sending the mail?

Thank you,
Maya

答: Port 2525 is unblocked and all major vendors provide support for the 2525 smtp port.</p>

Title: SES port is blocked in GCP


问:
Why does my list skip certain elements when I iteratate?
I am trying to write some code which adds an element in one list to another list and then removes it from the first list. It also should not add duplicates to the new list which is where the if statement comes in.
However, when adding to the 'individuals' list and removing from the 'sentence_list' list it misses out certain words such as 'not' and 'for'. This is also not random and the same words are missed each time. Any help?</p>

```<code>sentence = "I am a yellow fish"
sentence_list = sentence.lower().split()
individuals = []

for i in sentence_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)
</code>```

答:
The issue is that you are removing items from the list you are looping through. You can fix this just by making a copy of the list and looping through it instead, like this:

```<code>sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
sentence_list = sentence.lower().split()
individuals = []

#We slice with [:] to make a copy of the list
orig_list = sentence_list[:]
for i in orig_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)
</code>```

The lists are now what was expected:

```<code>print(individuals)
print(sentence_list)

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
[]
</code>```

Body:
I am trying to write some code which adds an element in one list to another list and then removes it from the first list. It also should not add duplicates to the new list which is where the if statement comes in.
However, when adding to the 'individuals' list and removing from the 'sentence_list' list it misses out certain words such as 'not' and 'for'. This is also not random and the same words are missed each time. Any help?

sentence = "I am a yellow fish"
sentence_list = sentence.lower().split()
individuals = []

for i in sentence_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)

Body:
The issue is that you are removing items from the list you are looping through. You can fix this just by making a copy of the list and looping through it instead, like this:

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
sentence_list = sentence.lower().split()
individuals = []

#We slice with [:] to make a copy of the list
orig_list = sentence_list[:]
for i in orig_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)

The lists are now what was expected:

print(individuals)
print(sentence_list)

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
[]


问:
How to set volume control in tvOS app?
I am new to tvOS/iOS development. I am using swift.
I am trying to develop a tvOS app. It plays 3 videos in a loop (which is basically 3 versions of same video at different speeds). It has a background music which can be turned on or off.

I have a pending functionality to implement- which is volume control for the background music.
So I am not sure if we can use a Volume Slider in tvOS.
But before that is it possible to increase and decrease the volume of the background music within the app alone? I mean, is there any way to not affect the main TV volume and still control the volume of the music alone inside the app?

I saw this apple documentation, but I am not sure how to use that.
https://developer.apple.com/reference/avfoundation/avplayer/1390127-volume

I also looked at this thread: iPhone: Implement Volume control using buttons

Can this be used for tvOS too?

Can someone help me with this?

答:
So, the solution was quite simple. I used var volume for performing this.
Used two buttons.
I gave an initial value and then wrote the logic inside an if block for changing the volumes on the respective button clicks (add volume by 0.1 and subtract volume by 0.1) :)</p>

Title: How to set volume control in tvOS app?


问:
Can't figure out how to do this all in one function
I am creating a zoo simulation game in Unity 5.4.0f3 using C#. I am trying to spawn a bear prefab clone, do some math, wait for a period of time, do some more math, then destroy the clone object all in one function. Here is what I have right now. The math that I am trying to do in WaitForBearLife() does not happen. Thanks in advance!</p>

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

public class BuyBearButton : MonoBehaviour
{
    [SerializeField] GameManager gameManager;
    [SerializeField] GameObject bearPrefab;
    [SerializeField] Visitor visitor;

    GameObject bearClone;

    float xMin = -15;
    float xMax = 15;
    float yMin = 5;
    float yMax = 6;

    public void BuyBear()
    {
        Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));

        if (gameManager.myMoney >= gameManager.bearCost)
        {
            gameManager.numberOfBears++;
            gameManager.myMoney = gameManager.myMoney - gameManager.bearCost;
            visitor.spawnTime = visitor.spawnTime / visitor.bearAttraction;
            bearClone = (GameObject) Instantiate (bearPrefab, pos, transform.rotation);
            StartCoroutine (WaitForBearLife ());
            Destroy (bearClone, gameManager.bearLife);
        }
    }

    IEnumerator WaitForBearLife()
    {
        yield return new WaitForSeconds (gameManager.bearLife);
        visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    }
}
</code>```

答:
you need to move Destroy function from BuyBear to WaitForBearLife

The problem is that now StartCouroutine call immediately returns and Destroy() gets called right away

Body:
I am creating a zoo simulation game in Unity 5.4.0f3 using C#. I am trying to spawn a bear prefab clone, do some math, wait for a period of time, do some more math, then destroy the clone object all in one function. Here is what I have right now. The math that I am trying to do in WaitForBearLife() does not happen. Thanks in advance!

using UnityEngine;
using System.Collections;

public class BuyBearButton : MonoBehaviour
{
    [SerializeField] GameManager gameManager;
    [SerializeField] GameObject bearPrefab;
    [SerializeField] Visitor visitor;

    GameObject bearClone;

    float xMin = -15;
    float xMax = 15;
    float yMin = 5;
    float yMax = 6;

    public void BuyBear()
    {
        Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));

        if (gameManager.myMoney >= gameManager.bearCost)
        {
            gameManager.numberOfBears++;
            gameManager.myMoney = gameManager.myMoney - gameManager.bearCost;
            visitor.spawnTime = visitor.spawnTime / visitor.bearAttraction;
            bearClone = (GameObject) Instantiate (bearPrefab, pos, transform.rotation);
            StartCoroutine (WaitForBearLife ());
            Destroy (bearClone, gameManager.bearLife);
        }
    }

    IEnumerator WaitForBearLife()
    {
        yield return new WaitForSeconds (gameManager.bearLife);
        visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    }
}