问:
Javascript - Changing string to match regex
I have a text area which I’m getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break.

```<code>This is my string = "282 MDJSL   889 MSHS 888 MSSH";
</code>```

(This string could be random each time ).

So I want to turn this string this so its formated and eventurally put into a JSObject

```<code>282 MDJSL
889 MSHS
888 MSSH
</code>```

This is my current code:

```<code>var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
 if (regex.test(textValue) === true) {

  // Match found
  console.log('Regex match');

  if ((m = regex.exec(textValue)) !== null) {

   // The result can be accessed through the `m`-variable.
   m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
   });

  }
 }

 // Match not found
 else {
  // Not replacing it into the format i want
  str = str.replace(regex, str);
 }
</code>```

thanks

答:
Seems like you can get by with a simpler regex and code.

var str = "282 MDJSL   889 MSHS 888 MSSH";

var regex = /\d+\s+[a-z]+/gi;
var m;
var i = 0;
while ((m = regex.exec(str))) {
  console.log(`Found match, group ${i++}: ${m}`);
}

if (i === 0) {
  // was no match
}```

Body:
I have a text area which I’m getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break.

This is my string = "282 MDJSL   889 MSHS 888 MSSH";

(This string could be random each time ).

So I want to turn this string this so its formated and eventurally put into a JSObject

282 MDJSL
889 MSHS
888 MSSH

This is my current code:

var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
 if (regex.test(textValue) === true) {

  // Match found
  console.log('Regex match');

  if ((m = regex.exec(textValue)) !== null) {

   // The result can be accessed through the `m`-variable.
   m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
   });

  }
 }

 // Match not found
 else {
  // Not replacing it into the format i want
  str = str.replace(regex, str);
 }

thanks


来源: stackexchange

问:
Python selenium print frame source
This is my first foray into Selenium. Apologies in advance if this is a stupid/trivial question.

I am trying to scrape information from a webpage. With Python/Selenium I am able to log on to the site and get to the page with the information I need. After the page I need is displayed, I am issuing

```<code>time.sleep(20)
html_source = driver.page_source
print html_source
</code>```

The "source" that gets printed is different from both the
right click and select view page source and
right click and select This Frame, View Frame source

The required information is in the View Frame source. All of this is in Firefox.

What do I need to do to get to the Frame Source? There is no frame name in the Frame Source.

Additional information below:

When I right click and select view page source I get the below:

```<code><!DOCTYPE html><html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>xxxxxxx Portal</title>
      <base href="https://website.org/page/">
      <link rel="shortcut icon" href="images/logos/xxxxxxx.ico">
      <meta http-equiv="Pragma" content="no-cache">
      <meta http-equiv="Expires" content="-1"><script type="text/javascript" src="https://website.org/page/security/csrf.js"> </script><script type="text/javascript" src="https://website.org/page/security/csrf/execute.js"> </script><script>
                    function pushFocus()
                    {
                        frameDetail.focus();
                    }

                    function addInProgressPanel(doc)
                    {
                        var d = doc.createElement('div');
                        d.id="inProgressPane";
                        d.className="freezeOn";

                        var tbl = doc.createElement("table");
                        var row = tbl.insertRow(-1);
                        var oi = doc.createElement("img");
                        oi.src= 'https://website.org/page/'+ "images/actions/loading2.gif";
                        var td = doc.createElement("td");
                        td.className="detailFormField";
                        td.bgcolor="red";
                        td.appendChild(oi);
                        row.appendChild(td);

                        td = doc.createElement("td");
                        td.className="inProcessing";
                        td.appendChild(doc.createTextNode("Your Request is Being Processed  ..."));
                        row.appendChild(td);

                        d.appendChild(tbl);
                        doc.body.appendChild(d);
                        return d;
                    }

                    function inProgressScreen(type)
                    {
                        var ws = frames["frameDetail"];
                        if(!ws) return true;
                        var ips = ws.document.getElementById("inProgressPane");
                        if(ips)
                        {
                            if(type)  ips.className = 'freezeOn';
                            else      ips.className = 'freezeOff';
                        }else if(type)
                            ips = addInProgressPanel(ws.document);
                    }
                </script></head>
   <frameset id="main" framespacing="0" frameborder="0">
      <frame id="frameDetail" name="frameDetail" scrolling="auto" marginwidth="0" marginheight="0" src="portal/portal.xsl?x=portal.PortalOutline&lang=en&mode=notices">
   </frameset>
</html>
</code>```

When I right click and select This Frame, View Frame source I get

```<code><!DOCTYPE html><html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <base href="https://website.org/xxxxxx/">
      <meta http-equiv="Content-Language" content="en-us">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta http-equiv="Pragma" content="no-cache">
      <meta http-equiv="Expires" content="-1">
      <title>xxxxxxxx Portal</title>
      <link rel="stylesheet" type="text/css" href="styles/portal/menu.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/header.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/footer.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/jquery-ui-1.8.7.portal.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/fg.menu.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/portal.css">
      <link rel="stylesheet" type="text/css" href="styles/icons.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/notifications.css"><script type="text/javascript" src="https://website.org/xxxxxxxx/security/csrf.js"> </script><script type="text/javascript" src="https://website.org/xxxxxxxx/security/csrf/execute.js"> </script><script src="scripts/widgets/common.js"></script><script src="scripts/controller.js"></script><script src="scripts/portal.js"></script><script src="scripts/jquery/jquery-1.7.2.min.js"></script><script type="text/javascript" src="https://website.org/xxxxxxxx/security/csrf/jquery.js"> </script><script src="scripts/jquery/jquery-ui-1.8.16.min.js"></script><script src="scripts/jquery/fg.menu.js"></script><script src="portal/lang/datePickerLanguage.jsp?lang=en"></script><script src="portal/portal.js"></script><script src="portal/portalNoShim.js"></script><script>
</code>```

Lots more code here. Did not paste as it was too long. There is no frame name other than the reference to iSessionFrame below:

```<code>    </script><script language="javascript" src="portal/grades.js"></script></div>
            </div>
         </div>
         <div id="footer">
            <table id="language"><select id="locale" style="width:175px"></select></table>
         </div>
      </div><iframe id="iSessionFrame" name="iSessionFrame" width="0" height="0" src="https://website.org/xxxxxx/white.jsp" style="visibility:hidden;"></iframe></body>
</html>
</code>```

答:
Q: What do I need to do to get to the Frame Source?

A: First you must switch to the wanted frame using the switch_to command and then you should use .page_source to get the html source.

Obs.: take a look at Selenium Docs, more specifically at Moving between windows and frames.

Code:

```<code>driver.switch_to_frame(driver.find_element_by_tag_name("frameDetail"))
driver.page_source
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python selenium print frame source

Body:
This is my first foray into Selenium. Apologies in advance if this is a stupid/trivial question.

I am trying to scrape information from a webpage. With Python/Selenium I am able to log on to the site and get to the page with the information I need. After the page I need is displayed, I am issuing

time.sleep(20)
html_source = driver.page_source
print html_source

The "source" that gets printed is different from both the
right click and select view page source and
right click and select This Frame, View Frame source

The required information is in the View Frame source. All of this is in Firefox.

What do I need to do to get to the Frame Source? There is no frame name in the Frame Source.

Additional information below:

When I right click and select view page source I get the below:

<!DOCTYPE html>

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>xxxxxxx Portal</title>
      <base href="https://website.org/page/">
      <link rel="shortcut icon" href="images/logos/xxxxxxx.ico">
      <meta http-equiv="Pragma" content="no-cache">
      <meta http-equiv="Expires" content="-1">
   <frameset id="main" framespacing="0" frameborder="0">
      <frame id="frameDetail" name="frameDetail" scrolling="auto" marginwidth="0" marginheight="0" src="portal/portal.xsl?x=portal.PortalOutline&lang=en&mode=notices">
   </frameset>

When I right click and select This Frame, View Frame source I get

<!DOCTYPE html>

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <base href="https://website.org/xxxxxx/">
      <meta http-equiv="Content-Language" content="en-us">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta http-equiv="Pragma" content="no-cache">
      <meta http-equiv="Expires" content="-1">
      <title>xxxxxxxx Portal</title>
      <link rel="stylesheet" type="text/css" href="styles/portal/menu.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/header.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/footer.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/jquery-ui-1.8.7.portal.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/fg.menu.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/portal.css">
      <link rel="stylesheet" type="text/css" href="styles/icons.css">
      <link rel="stylesheet" type="text/css" href="styles/portal/notifications.css">

<select id="locale" style="width:175px"></select>

Body:
Q: What do I need to do to get to the Frame Source?

A: First you must switch to the wanted frame using the switch_to command and then you should use .page_source to get the html source.

Obs.: take a look at Selenium Docs, more specifically at Moving between windows and frames.

Code:

driver.switch_to_frame(driver.find_element_by_tag_name("frameDetail"))
driver.page_source


问:
Enforce type safety in C++ without using extra classes
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

```<code>// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);
</code>```

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

答:
BOOST_STRONG_TYPEDEF is precisely a typedef which enforces type safety.

However, this answer provides some caveats related to using this strong typedef for just a function, and argues that the types should be used all over the code to prevent unnecessary castings.

Body:
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.


问:
Launch nightwatch with Selenium Server Usage
I read this - http://nightwatchjs.org/getingstarted#chromedriver
server path in this case is .jar file.
Is it possible to run selenium server without jar file? For example, https://www.npmjs.com/package/selenium-standalone?
How can i point to file of selenium server in json?</p>

答:
Selenium-standalone doesn't run without JARs, it just manages them for you.  You can find them after installing, example:</p>

```<code>% npm install --save-dev selenium-standalone
...
% node_modules/selenium-standalone/bin/selenium-standalone install --silent
% find node_modules -name '*.jar'
node_modules/selenium-standalone/.selenium/selenium-server/3.0.1-server.jar
</code>```

Body:
Selenium-standalone doesn't run without JARs, it just manages them for you.  You can find them after installing, example:

% npm install --save-dev selenium-standalone
...
% node_modules/selenium-standalone/bin/selenium-standalone install --silent
% find node_modules -name '*.jar'
node_modules/selenium-standalone/.selenium/selenium-server/3.0.1-server.jar


问:
Writing to file only writes last item, not all items, why?
i'm trying to write a feed to a file using node.js. the problem is, it doesn't write all the feeds, only the last 1.

```<code>var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.writeFile("articles.json", JSON.stringify(article.title), function(err) {
    if(err) {
          console.log(err);
    }
  });
});
</code>```

Why?

答:
Just change fs.writeFile( to fs.appendFile( and you're fine.

fs.writeFile overwrites your file each time you call it whereas fs.appendFile adds to a file.

Body:
i'm trying to write a feed to a file using node.js. the problem is, it doesn't write all the feeds, only the last 1.

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.writeFile("articles.json", JSON.stringify(article.title), function(err) {
    if(err) {
          console.log(err);
    }
  });
});

Why?


问:
Logging out via a link in Laravel
I have a "Logout" link in my top navigation bar. I'm wondering how I can make it so that while I'm logged in, it'll log me out when I click on it and return me to the homepage.

To be specific, what changes to which files do I make in Laravel? Also, what code do I need to write in the view, which currently contains just HTML, to trigger this?

答:
Edited 28/12/2019: It's work, but This answer contains a serious security issue. Please consider before using it. The Answer by Lucas Bustamante maybe a better choice. Refer to the comment section of this answer.

1) if you are using the auth scaffold that laravel contains. You can do this, in your navigation bar add this:

```<code><a href="{{ url('/logout') }}"> logout </a>
</code>```

then add this to your web.php file

```<code>Route::get('/logout', '\App\Http\Controllers\Auth\LoginController@logout');
</code>```

Done. This will logout you out and redirect to homepage. To get the auth scaffold, from command line, cd into your project root directory and run

```<code>php artisan make:auth
</code>```

2) add this to your navigation bar:

```<code><a href="{{ url('/logout') }}"> logout </a>
</code>```

then add this in your web.php file

```<code>Route::get('/logout', 'YourController@logout');
</code>```

then in the YourController.php file, add this

```<code>public function logout () {
    //logout user
    auth()->logout();
    // redirect to homepage
    return redirect('/');
}
</code>```

Done.

Read:

```<code>https://mattstauffer.co/blog/the-auth-scaffold-in-laravel-5-2
https://www.cloudways.com/blog/laravel-login-authentication/
</code>```

Title: Logging out via a link in Laravel

Body:
Edited 28/12/2019: It's work, but This answer contains a serious security issue. Please consider before using it. The Answer by Lucas Bustamante maybe a better choice. Refer to the comment section of this answer.

1) if you are using the auth scaffold that laravel contains. You can do this, in your navigation bar add this:

<a href="{{ url('/logout') }}"> logout </a>

then add this to your web.php file

Route::get('/logout', '\App\Http\Controllers\Auth\LoginController@logout');

Done. This will logout you out and redirect to homepage. To get the auth scaffold, from command line, cd into your project root directory and run

php artisan make:auth

2) add this to your navigation bar:

<a href="{{ url('/logout') }}"> logout </a>

then add this in your web.php file

Route::get('/logout', 'YourController@logout');

then in the YourController.php file, add this

public function logout () {
    //logout user
    auth()->logout();
    // redirect to homepage
    return redirect('/');
}

Done.

Read:

https://mattstauffer.co/blog/the-auth-scaffold-in-laravel-5-2
https://www.cloudways.com/blog/laravel-login-authentication/

ContentLicense: CC BY-SA 4.0


问:
UITableView with variable width cells
I'm curious how applications create this look, specifically the photo section and the 'skinnier' UITableViewCells. I haven't seen a delegate method for cell width so I'm curious how they are dynamically resizing the cells and putting the image view in the UITableView. Is this some common trick/smoke-n-mirrors/workaround?

答:
if i were to guess, i would say that they have added a UIView with a transparent background, which has a UIImageView for the photo, and a tableView as a subView</p>

```<code>UITableView
|-header UIView
| |-UIImageView
| |-UITableView
|
|-tableViewContents
</code>```

ContentLicense: CC BY-SA 2.5

Title: UITableView with variable width cells

Body:
if i were to guess, i would say that they have added a UIView with a transparent background, which has a UIImageView for the photo, and a tableView as a subView

UITableView
|-header UIView
| |-UIImageView
| |-UITableView
|
|-tableViewContents


问:
Is there any Js event or function which fires or executes before any action?
As there is a directive in AngularJs - onLocationChange() and C# has onActionExecute(), is there any event like these in Javascript which executes just before any action within the entire website.

答:
from your question it seems like you want to observe user navigation i.e: when ever address bar location gets changed.

You can use an older method detecting whenever page gets refresh

```<code>window.addEventListener('beforeunload', function (e) {
    // perform  something here
}, false);
</code>```

for SPAs (Single page applications you can use hashchange

```<code>//detecting hashchange
window.onhashchange = function() {
     //code
}
</code>```

Body:
from your question it seems like you want to observe user navigation i.e: when ever address bar location gets changed.

You can use an older method detecting whenever page gets refresh

window.addEventListener('beforeunload', function (e) {
    // perform  something here
}, false);

for SPAs (Single page applications you can use hashchange

//detecting hashchange
window.onhashchange = function() {
     //code
}


问:
Closest function not working in JQuery
I am making a select list.

Now I want to show the options in select list with class "new" according to change in option in list with class old".

Like, when the option 1 is selected, 3,4,5 are visible and when the option 2 is selected, 6,7,8 are visible.

Also, I want to control the options in corresponding row.

$(document).ready(function() {
  $(".new").children('option:gt(0)').hide();
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();
  $(function() {
    $(".old").change(function() {
      var a = $(this).val();
      if (a == 2) {
        $(".new").children('option:gt(0)').hide();
        $('$(this).closest('tr').find('.new') option[value="select"]').show();
        $('$(this).closest('tr').find('.new') option[value="4"]').show();
        $('$(this).closest('tr').find('.new') option[value="5"]').show();
        $('$(this).closest('tr').find('.new') option[value="6"]').show();
      };
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
</table></code>```

答:
You have some syntax error in jQuery statement

```<code>$(document).ready(function() {
    $(".new").children('option:gt(0)').hide();
    $('.new option[value="select"]').show();
    $('.new option[value="1"]').show();
    $('.new option[value="2"]').show();
    $('.new option[value="3"]').show();
    $(function () {
        $(".old").change(function () {
            var a = $(this).val();
            if (a == 2) {
                $(".new").children('option:gt(0)').hide();
                $(this).closest('tr').find('.new option[value="select"]').show();
                $(this).closest('tr').find('.new option[value="4"]').show();
                $(this).closest('tr').find('.new option[value="5"]').show();
                $(this).closest('tr').find('.new option[value="6"]').show();
            };
        });
    });
});
</code>```

Title: Closest function not working in JQuery

Body:
I am making a select list.

Now I want to show the options in select list with class "new" according to change in option in list with class old".

Like, when the option 1 is selected, 3,4,5 are visible and when the option 2 is selected, 6,7,8 are visible.

Also, I want to control the options in corresponding row.

$(document).ready(function() {
  $(".new").children('option:gt(0)').hide();
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();
  $(function() {
    $(".old").change(function() {
      var a = $(this).val();
      if (a == 2) {
        $(".new").children('option:gt(0)').hide();
        $('$(this).closest('tr').find('.new') option[value="select"]').show();
        $('$(this).closest('tr').find('.new') option[value="4"]').show();
        $('$(this).closest('tr').find('.new') option[value="5"]').show();
        $('$(this).closest('tr').find('.new') option[value="6"]').show();
      };
    });
  });
});

      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>

      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>

Body:
You have some syntax error in jQuery statement

$(document).ready(function() {
    $(".new").children('option:gt(0)').hide();
    $('.new option[value="select"]').show();
    $('.new option[value="1"]').show();
    $('.new option[value="2"]').show();
    $('.new option[value="3"]').show();
    $(function () {
        $(".old").change(function () {
            var a = $(this).val();
            if (a == 2) {
                $(".new").children('option:gt(0)').hide();
                $(this).closest('tr').find('.new option[value="select"]').show();
                $(this).closest('tr').find('.new option[value="4"]').show();
                $(this).closest('tr').find('.new option[value="5"]').show();
                $(this).closest('tr').find('.new option[value="6"]').show();
            };
        });
    });
});


问:
*ngIf window.location.href.indexOf is not working
I need to show one element only if location is right, if not, it shoudn't be shown.

This is not working:

```<code><div *ngIf="!accessTrue() && window.location.href.indexOf('something')" > -1)>
    CODE
</div>
</code>```

答:
you cannot access the window object inside the template.
But you can define a getter in your component :

```<code>get hasSomething(){
    return window.location.href.indexOf('something') > -1
}
</code>```

then :

```<code><div *ngIf="!accessTrue() && hasSomething">
    CODE
</div>
</code>```

Note that it might be cleaner to use an ActivatedRoute if your parameter is accessible through it.

Body:
I need to show one element only if location is right, if not, it shoudn't be shown.

This is not working:

 -1)>
    CODE

Body:
you cannot access the window object inside the template.
But you can define a getter in your component :

get hasSomething(){
    return window.location.href.indexOf('something') > -1
}

then :

<div *ngIf="!accessTrue() && hasSomething">
    CODE
</div>

Note that it might be cleaner to use an ActivatedRoute if your parameter is accessible through it.


问:
Need to create replays of actor movements and actions for game
Here are some basics about the game:

```<code>- RTS (Real-time strategy)
- Every object on the game screen is an "actor".
- Every actor has an (x,y) position, HP, and type.
- Works in rounds. Every round, every actor takes one action (move, shoot, build, etc.)
</code>```

What is the most efficient way to store up to 5000 rounds with the position and relevant information of every actor stored with each round. I would like to be able to scrub back and forth across rounds and be able to call up the relevant information on an actor for that round (i.e. an actors health on a specific round).

I know how I would do this by just writing information to a .txt file and then reading from it (this is how I made preset maps), but for a 5000 round match, the .txt file would be immense. Is there any easier way that people tackle this problem in game development? I've seen it done in RTS games quite often.

Edit - All commands are given at the beginning of the game before the game even starts. For example, the player can command something akin to "if you are a fighter - every round - find the nearest enemy and move towards it if you can't shoot it, or shoot it if you are in range. Otherwise, move south." So, there are no commands inputted after the first round begins. Rather, each actor implements the same logic every round.

答: Assuming that Database is not an option you can create a toXML() or toJSON() method which creates an XML or JSON of the data for each round. After that you have to decide You can store as roundX. JSON or in bundles like roundXtoY.JSON. That depends on the data but it is text data, it should be pretty easy to store 100-500 (maybe a lot more) rounds at once.

Body:
Here are some basics about the game:

- RTS (Real-time strategy)
- Every object on the game screen is an "actor".
- Every actor has an (x,y) position, HP, and type.
- Works in rounds. Every round, every actor takes one action (move, shoot, build, etc.)

What is the most efficient way to store up to 5000 rounds with the position and relevant information of every actor stored with each round. I would like to be able to scrub back and forth across rounds and be able to call up the relevant information on an actor for that round (i.e. an actors health on a specific round).

I know how I would do this by just writing information to a .txt file and then reading from it (this is how I made preset maps), but for a 5000 round match, the .txt file would be immense. Is there any easier way that people tackle this problem in game development? I've seen it done in RTS games quite often.

Edit - All commands are given at the beginning of the game before the game even starts. For example, the player can command something akin to "if you are a fighter - every round - find the nearest enemy and move towards it if you can't shoot it, or shoot it if you are in range. Otherwise, move south." So, there are no commands inputted after the first round begins. Rather, each actor implements the same logic every round.


问:
Cut transparent hole in UIView
Looking to create a view that has a transparent frame inside of it so that the views behind the view can be seen through this transparent frame, but areas outside of this will not show through. So essentially a window within the view.

Hoping to be able to do something like this:

```<code> CGRect hole = CGRectMake(100, 100, 250, 250);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillRect(context, rect);

CGContextAddRect(context, hole);
CGContextClip(context);

CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, rect);
</code>```

but the clear does not override the black so whole background is black. Any ideas along these lines?

答:
Another solution:
The Big rect is all the view (yellow color) and the small is the transparent rect.
The color opacity is settable.

let pathBigRect = UIBezierPath(rect: bigRect)
let pathSmallRect = UIBezierPath(rect: smallRect)

pathBigRect.appendPath(pathSmallRect)
pathBigRect.usesEvenOddFillRule = true

let fillLayer = CAShapeLayer()
fillLayer.path = pathBigRect.CGPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.yellowColor().CGColor
//fillLayer.opacity = 0.4
view.layer.addSublayer(fillLayer)
```

Title: Cut transparent hole in UIView

Body:
Looking to create a view that has a transparent frame inside of it so that the views behind the view can be seen through this transparent frame, but areas outside of this will not show through. So essentially a window within the view.

Hoping to be able to do something like this:

 CGRect hole = CGRectMake(100, 100, 250, 250);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillRect(context, rect);

CGContextAddRect(context, hole);
CGContextClip(context);

CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, rect);

but the clear does not override the black so whole background is black. Any ideas along these lines?


问:
ksoap2 - Same method works wih AsyncTask but no when using inside normal activity
I'm developing an APP and it has a funcionality that can be used by the user in two different ways: do the task in real time, so he/she have to wait till the task finishes; or do the task in background so he/she can do other things in the meanwhile.

I've developed the task in background with AsyncTask and it works, but I don't know why I'm getting and error when I try to call the same method inside a normal activity.

This is the method that uses ksoap2, the value of the param I'm testing with is "http://www.google.com"

```<code>public String sendURL(String url) {
    Log.i("URL", url);
    //Create request
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("url", url);

    //Create envelope
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = false;
    envelope.implicitTypes = true;
    envelope.setAddAdornments(false);
    envelope.setOutputSoapObject(request);

    //Create HTTP call object
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.debug = true;
    androidHttpTransport.setXmlVersionTag("<!--?xml version=\"1.0\" encoding= \"UTF-8\" ?-->");

    SoapPrimitive response = null;
    try {
        //Invoke web service
        androidHttpTransport.call(SOAP_ACTION, envelope);  // HERE is where I'm getting the error
        //Get the response
        response = (SoapPrimitive) envelope.getResponse();
        // Return the response
        return response.toString();
    } catch (SocketException e) {
        e.printStackTrace();
        // TODO Error, el servidor no esta levantado
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

This is the output error I'm getting from Android Studio:

```<code>03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err: java.net.MalformedURLException
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at java.net.URL.<init>(URL.java:152)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at java.net.URL.<init>(URL.java:125)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.<init>(ServiceConnectionSE.java:39)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.HttpTransportSE.getServiceConnection(HttpTransportSE.java:104)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:61)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at es.sia.urlanalyzer.Analyze.sendURL(Analyze.java:377)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at es.sia.urlanalyzer.Analyze$1.onClick(Analyze.java:167)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.view.View.performClick(View.java:5198)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.view.View$PerformClick.run(View.java:21147)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

The same method, exactly the same, is working fine in a custom class that extends AsyncTask. The values of the SOAP calls to the web service are:

```<code>String NAMESPACE = "http://10.0.2.2:4894/AnalyzeURL_WS/services/";
String URL = "http://10.0.2.2:4894/AnalyzeURL_WS/services/AnalyzeURL";
String SOAP_ACTION = "http://10.0.2.2:4894/AnalyzeURL_WS/services/analyze";
String METHOD_NAME = "analyze";
</code>```

答: The reason to this is quite simple, you cannot run network activities on the main thread/ui thread. Network activities should be run on a background service in order for it not to interfere with U.i processes, if this was allowed then a user would have to wait for the network process to be completed before proceeding with using the app. This would be a bad practise, for example if i want to upload alot of data am fetching from the users message box, and i have 1000 messages, if this process is allowed on ui thread, it would take too much time, but when you run the upload service in the background, the user can comfortable use other features of the app while the data is being uplaoded. Therefore network activities are restricted from taking place in the main thread, if you do so you get a network relate exception.</p>

Body:
I'm developing an APP and it has a funcionality that can be used by the user in two different ways: do the task in real time, so he/she have to wait till the task finishes; or do the task in background so he/she can do other things in the meanwhile.

I've developed the task in background with AsyncTask and it works, but I don't know why I'm getting and error when I try to call the same method inside a normal activity.

This is the method that uses ksoap2, the value of the param I'm testing with is "http://www.google.com"

public String sendURL(String url) {
    Log.i("URL", url);
    //Create request
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("url", url);

    //Create envelope
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = false;
    envelope.implicitTypes = true;
    envelope.setAddAdornments(false);
    envelope.setOutputSoapObject(request);

    //Create HTTP call object
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.debug = true;
    androidHttpTransport.setXmlVersionTag("");

    SoapPrimitive response = null;
    try {
        //Invoke web service
        androidHttpTransport.call(SOAP_ACTION, envelope);  // HERE is where I'm getting the error
        //Get the response
        response = (SoapPrimitive) envelope.getResponse();
        // Return the response
        return response.toString();
    } catch (SocketException e) {
        e.printStackTrace();
        // TODO Error, el servidor no esta levantado
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return null;
}

This is the output error I'm getting from Android Studio:

03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err: java.net.MalformedURLException
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at java.net.URL.<init>(URL.java:152)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at java.net.URL.<init>(URL.java:125)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.<init>(ServiceConnectionSE.java:39)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.HttpTransportSE.getServiceConnection(HttpTransportSE.java:104)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:61)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at es.sia.urlanalyzer.Analyze.sendURL(Analyze.java:377)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at es.sia.urlanalyzer.Analyze$1.onClick(Analyze.java:167)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.view.View.performClick(View.java:5198)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.view.View$PerformClick.run(View.java:21147)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-28 09:25:50.291 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-28 09:25:50.292 17894-17894/es.sia.urlanalyzer W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

The same method, exactly the same, is working fine in a custom class that extends AsyncTask. The values of the SOAP calls to the web service are:

String NAMESPACE = "http://10.0.2.2:4894/AnalyzeURL_WS/services/";
String URL = "http://10.0.2.2:4894/AnalyzeURL_WS/services/AnalyzeURL";
String SOAP_ACTION = "http://10.0.2.2:4894/AnalyzeURL_WS/services/analyze";
String METHOD_NAME = "analyze";


问:
How do I disable END blocks in child processes?
I frequently use fork in programs that also have END { ... } blocks:

```<code>...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}
</code>```

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

```<code>END { unless (i_am_a_child_process()) { &some_cleanup_code } }
</code>```

?

答:
This is code used by POE::Wheel::Run to do just what you want.  POE::Kernel::RUNNING_IN_HELL is true when $^O eq 'MSWin32'.  Adapt it to your needs.

```<code>sub _exit_child_any_way_we_can {
  my $class = shift;
  my $exitval = shift || 0;

  # First make sure stdio are flushed.
  close STDIN  if defined fileno(STDIN); # Voodoo?
  close STDOUT if defined fileno(STDOUT);
  close STDERR if defined fileno(STDERR);

  # On Windows, subprocesses run in separate threads.  All the "fancy"
  # methods act on entire processes, so they also exit the parent.

  unless (POE::Kernel::RUNNING_IN_HELL) {
    # Try to avoid triggering END blocks and object destructors.
    eval { POSIX::_exit( $exitval ); };

    # TODO those methods will not exit with $exitval... what to do?
    eval { CORE::kill KILL => $$; };
    eval { exec("$^X -e 0"); };
  } else {
    eval { CORE::kill( KILL => $$ ); };

    # TODO Interestingly enough, the KILL is not enough to terminate this process...
    # However, it *is* enough to stop execution of END blocks/etc
    # So we will end up falling through to the exit( $exitval ) below
  }

  # Do what we must.
  exit( $exitval );
}
</code>```

Body:
I frequently use fork in programs that also have END { ... } blocks:

...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

END { unless (i_am_a_child_process()) { &some_cleanup_code } }

?

Body:
This is code used by POE::Wheel::Run to do just what you want.  POE::Kernel::RUNNING_IN_HELL is true when $^O eq 'MSWin32'.  Adapt it to your needs.

sub _exit_child_any_way_we_can {
  my $class = shift;
  my $exitval = shift || 0;

  # First make sure stdio are flushed.
  close STDIN  if defined fileno(STDIN); # Voodoo?
  close STDOUT if defined fileno(STDOUT);
  close STDERR if defined fileno(STDERR);

  # On Windows, subprocesses run in separate threads.  All the "fancy"
  # methods act on entire processes, so they also exit the parent.

  unless (POE::Kernel::RUNNING_IN_HELL) {
    # Try to avoid triggering END blocks and object destructors.
    eval { POSIX::_exit( $exitval ); };

    # TODO those methods will not exit with $exitval... what to do?
    eval { CORE::kill KILL => $$; };
    eval { exec("$^X -e 0"); };
  } else {
    eval { CORE::kill( KILL => $$ ); };

    # TODO Interestingly enough, the KILL is not enough to terminate this process...
    # However, it *is* enough to stop execution of END blocks/etc
    # So we will end up falling through to the exit( $exitval ) below
  }

  # Do what we must.
  exit( $exitval );
}


问:
Is there an alternative method to apply tf.case, tf.cond, etc. on a tensor?
I'm trying to use tf.case to use a index value in a tensor to direct to different network structure part, get different losses and then sum them up as the final loss for training. Take a simple example, I judge the value in a list and output a different value. For example
[0,1,2,3] -> [0,7,10,13] where
case 0:
output 0
case 1:
output 7
case 2:
output 10
case 3:
output 13.
However, the tf.cond, tf.case seem only to be used on a scalar. How to fulfill the goal?</p>

答:
The only operation I'm aware of that evaluates a condition separately on each element of a vector is tf.where.  You would leave x=None, y=None:

```<code>t_orig = tf.constant([0, 1, 2, 3, 1])
t_filt = tf.where(tf.equal(t_orig, 1))
with tf.Session() as sess:
    print sess.run(t_filt)
</code>```

Output:

```<code>[[1]
 [4]]
</code>```

However, this only evaluates the truth of a single condition.  If you want to evaluate the truth of multiple conditions, over each element of a vector, I think you'll have to use tf.map_fn combined with tf.case.  AFAIK, tf.case is the only operation that evaluates the truth of many conditions on a given value:

```<code>t_orig = tf.constant([0, 1, 2, 3])
t_new = tf.map_fn(
        lambda x: tf.case(
            pred_fn_pairs=[
                (tf.equal(x, 0), lambda: tf.constant(0)),
                (tf.equal(x, 1), lambda: tf.constant(7)),
                (tf.equal(x, 2), lambda: tf.constant(10)),
                (tf.equal(x, 3), lambda: tf.constant(13))],
            default=lambda: tf.constant(-1)),
        t_orig)
with tf.Session() as sess:
    print sess.run(t_new)
</code>```

Output:

```<code>[ 0  7 10 13]
</code>```

Body:
The only operation I'm aware of that evaluates a condition separately on each element of a vector is tf.where.  You would leave x=None, y=None:

t_orig = tf.constant([0, 1, 2, 3, 1])
t_filt = tf.where(tf.equal(t_orig, 1))
with tf.Session() as sess:
    print sess.run(t_filt)

Output:

[[1]
 [4]]

However, this only evaluates the truth of a single condition.  If you want to evaluate the truth of multiple conditions, over each element of a vector, I think you'll have to use tf.map_fn combined with tf.case.  AFAIK, tf.case is the only operation that evaluates the truth of many conditions on a given value:

t_orig = tf.constant([0, 1, 2, 3])
t_new = tf.map_fn(
        lambda x: tf.case(
            pred_fn_pairs=[
                (tf.equal(x, 0), lambda: tf.constant(0)),
                (tf.equal(x, 1), lambda: tf.constant(7)),
                (tf.equal(x, 2), lambda: tf.constant(10)),
                (tf.equal(x, 3), lambda: tf.constant(13))],
            default=lambda: tf.constant(-1)),
        t_orig)
with tf.Session() as sess:
    print sess.run(t_new)

Output:

[ 0  7 10 13]


问:
Removing a (conditional) action from a wordpress woothemes plugin
i simply want to remove a message block by using functions.php.
This is the action i wish to remove:

```<code>    if( empty( $active_ids ) ){
                    add_action( 'sensei_loop_course_inside_before',
                    array( $this, 'active_no_course_message_output' ) );
    }
</code>```

so i figure i had to refer to the class before i could access it's function i wish to remove, so i did:

```<code>function remove_no_active_courses_message(){
    //classname where the function i want to remove is:
    //class Sensei_Shortcode_User_Courses implements Sensei_Shortcode_Interface

    remove_action( 'sensei_loop_course_inside_before', array( 'Sensei_Shortcode_User_Courses', 'active_no_course_message_output' ) );
    remove_action( 'sensei_loop_course_inside_before', array( $Sensei_Shortcode_User_Courses, 'active_no_course_message_output' ) );

}
add_action('sensei_loop_course_inside_before', 'remove_no_active_courses_message');
</code>```

But neither of the 2 worked, any suggestions?

Edit:
source class: https://github.com/Automattic/sensei/blob/master/includes/shortcodes/class-sensei-shortcode-user-courses.php

Edit 2 (note: when i try to global the class object, it var dumps null on this class so maybe the problem is i cant access it's global element? the woothemes sensei object works fine and i can print stuff from that. but not accessing the function via the class object instance)
I tried some of the suggested answers:

```<code>    function remove_no_active_courses_message(){
        //classname where the function i want to remove is:
        //class Sensei_Shortcode_User_Courses implements Sensei_Shortcode_Interface

        global $Sensei_Shortcode_User_Courses; //DOESNT SEEM TO INSTANTIATE?
        global $woothemes_sensei; //WORKS FINE AND CAN ACCES IT'S OBJECTS HERE

        //var_dump($Sensei_Shortcode_User_Courses); //PRINTS NULL
        //var_dump($woothemes_sensei); //PRINTS THE ENTIRE THINGY SUCCESFULLY

        remove_action( 'sensei_loop_course_inside_before', array( $Sensei_Shortcode_User_Courses, 'active_no_course_message_output' ), 99 );

}
    add_action('wp_footer', 'remove_no_active_courses_message');
</code>```

答:
Just asking, its there a way that this files is called after functions.php?

This is ugly but let´s tried,

Create a function that return and empty string:

```<code>   function emptyString(){
      return ' ';
   }
</code>```

Then add to the hook

```<code> add_action('sensei_loop_course_inside_before', 'emptyString', 11)
</code>```

Let's do this and check if something happens

Body:
i simply want to remove a message block by using functions.php.
This is the action i wish to remove:

    if( empty( $active_ids ) ){
                    add_action( 'sensei_loop_course_inside_before',
                    array( $this, 'active_no_course_message_output' ) );
    }

so i figure i had to refer to the class before i could access it's function i wish to remove, so i did:

function remove_no_active_courses_message(){
    //classname where the function i want to remove is:
    //class Sensei_Shortcode_User_Courses implements Sensei_Shortcode_Interface

    remove_action( 'sensei_loop_course_inside_before', array( 'Sensei_Shortcode_User_Courses', 'active_no_course_message_output' ) );
    remove_action( 'sensei_loop_course_inside_before', array( $Sensei_Shortcode_User_Courses, 'active_no_course_message_output' ) );

}
add_action('sensei_loop_course_inside_before', 'remove_no_active_courses_message');

But neither of the 2 worked, any suggestions?

Edit:
source class: https://github.com/Automattic/sensei/blob/master/includes/shortcodes/class-sensei-shortcode-user-courses.php

Edit 2 (note: when i try to global the class object, it var dumps null on this class so maybe the problem is i cant access it's global element? the woothemes sensei object works fine and i can print stuff from that. but not accessing the function via the class object instance)
I tried some of the suggested answers:

    function remove_no_active_courses_message(){
        //classname where the function i want to remove is:
        //class Sensei_Shortcode_User_Courses implements Sensei_Shortcode_Interface

        global $Sensei_Shortcode_User_Courses; //DOESNT SEEM TO INSTANTIATE?
        global $woothemes_sensei; //WORKS FINE AND CAN ACCES IT'S OBJECTS HERE

        //var_dump($Sensei_Shortcode_User_Courses); //PRINTS NULL
        //var_dump($woothemes_sensei); //PRINTS THE ENTIRE THINGY SUCCESFULLY

        remove_action( 'sensei_loop_course_inside_before', array( $Sensei_Shortcode_User_Courses, 'active_no_course_message_output' ), 99 );

}
    add_action('wp_footer', 'remove_no_active_courses_message');

Body:
Just asking, its there a way that this files is called after functions.php?

This is ugly but let´s tried,

Create a function that return and empty string:

   function emptyString(){
      return ' ';
   }

Then add to the hook

 add_action('sensei_loop_course_inside_before', 'emptyString', 11)

Let's do this and check if something happens


问:
Updating database value with button
```<code><?php
include ('session.php');

$connection = mysqli_connect("localhost", "root", "" , "log_database");
$question_id = rand(1,2);
$query = "SELECT * FROM questions WHERE id='$question_id' ";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);

if ($query_row==1) {
    foreach ($query_run as $row ) {
        $option1 = $row['option1'];
        $option2 = $row['option2'];
        $money = $row['money'];
        $option1_clicked = $row['option1_clicked'];
        $option2_clicked = $row['option1_clicked'];
        $id_question = $row['id'];
    }
}

?>
<!DOCTYPE html>
<html>

<head>
    <title>Game</title>
    <link rel="stylesheet" type="text/css" href="game.css"> </head>

<body>

    <div id="content_div">
        <img id="title_img" src="wealthypinguin.png">
    </div>

    <div id="question_div">
        <span id="question">
            <?php echo $username; ?>, <br> for <span id="money">€ <?php echo $money; ?></span>,
        <br>would you rather...</span>
    </div>

    <div id="buttons_div">
        <button onclick="addOption1()" id="button1">
            <?php echo $option1; ?>
        </button>
        <br>
        <button onclick="addOption2()" id="button2">
            <?php echo $option2; ?>
        </button>
        <br>
        <button id="button3">
            Keep your money
        </button>
    </div>

</body>

    <script>
        function addOption1() {
            <?php
                $option1_clicked = $option1_clicked + 1;
                $queryOption1 = "UPDATE `questions` SET `option1_clicked` = '$option1_clicked' WHERE id='$question_id'";
                $query_run_option1 = mysqli_query($connection,$queryOption1);
            ?>
        }

        function addOption2() {
            <?php
                $option2_clicked = $option2_clicked + 1;
                $queryOption2 = "UPDATE `questions` SET `option2_clicked` = '$option2_clicked' WHERE id='$question_id'";
                $query_run_option2 = mysqli_query($connection,$queryOption2);
            ?>
        }
    </script>

</html>
</code>```

What I want to achieve that when my button1 is clicked, my php variable $option1_clicked is raised by one and the new value is updated in my database.
When I click button2 the same result.

The problem is when I click one of them, the value is updated but it automatically updates both values($option1_clicked, $option2_clicked) to the same value.
So when option1_clicked goes from 6 to 7, option2_clicked gets also the value 7.

答:
Ajax is the best way to do that.
Have a look to that:
https://www.w3schools.com/xml/ajax_intro.asp

You will be able to send a POST or GET query to a file (often a PHP file) without leave the current web page.

It's very useful, very plaisant for the users (You can create good and fluid User Interfaces), and quite simple.

Title: Updating database value with button

Body:
<?php
include ('session.php');

$connection = mysqli_connect("localhost", "root", "" , "log_database");
$question_id = rand(1,2);
$query = "SELECT * FROM questions WHERE id='$question_id' ";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);

if ($query_row==1) {
    foreach ($query_run as $row ) {
        $option1 = $row['option1'];
        $option2 = $row['option2'];
        $money = $row['money'];
        $option1_clicked = $row['option1_clicked'];
        $option2_clicked = $row['option1_clicked'];
        $id_question = $row['id'];
    }
}

?>
<!DOCTYPE html>

    <title>Game</title>
    <link rel="stylesheet" type="text/css" href="game.css">

            <?php echo $username; ?>,
 for € <?php echo $money; ?>,

would you rather...

        <button onclick="addOption1()" id="button1">
            <?php echo $option1; ?>
        </button>

        <button onclick="addOption2()" id="button2">
            <?php echo $option2; ?>
        </button>

        <button id="button3">
            Keep your money
        </button>

What I want to achieve that when my button1 is clicked, my php variable $option1_clicked is raised by one and the new value is updated in my database.
When I click button2 the same result.

The problem is when I click one of them, the value is updated but it automatically updates both values($option1_clicked, $option2_clicked) to the same value.
So when option1_clicked goes from 6 to 7, option2_clicked gets also the value 7.


问:
Passing type parameter to interface of base class
StateBase implements iState

WolfState ineherits from StateBase

WolfController inherits from ControllerBase

I want to be able to do a

WolfState that uses WolfController inheriting from State

SheepState
that uses SheepController and inherits from State

WolfController and SheepController would both inherit from StateController.

How should i declare WolfState?

The way i try to do it doesnt work.

```<code>   public interface IState <T> where T : StateController
{
}

public abstract class State<T> where T : StateController,  IState<T>
{
}

// THIS IS HOW I WOULD LIKE TO DO IT BUT ITS NOT ACCEPTED
public class WolfState : State<WolfController>
{
}

public class SheepState : State<SheepController>
{
}
</code>```

答:
It looks like you intend State<T> to implement IState<T>. You currently have a constraint on the type of T. Change the definition of State<T> to:

```<code>public abstract class State<T> : IState<T> where T : StateController
{
}
</code>```

Body:
StateBase implements iState

WolfState ineherits from StateBase

WolfController inherits from ControllerBase

I want to be able to do a

WolfState that uses WolfController inheriting from State

SheepState
that uses SheepController and inherits from State

WolfController and SheepController would both inherit from StateController.

How should i declare WolfState?

The way i try to do it doesnt work.

   public interface IState <T> where T : StateController
{
}

public abstract class State<T> where T : StateController,  IState<T>
{
}

// THIS IS HOW I WOULD LIKE TO DO IT BUT ITS NOT ACCEPTED
public class WolfState : State<WolfController>
{
}

public class SheepState : State<SheepController>
{
}

Body:
It looks like you intend State<T> to implement IState<T>. You currently have a constraint on the type of T. Change the definition of State<T> to:

public abstract class State<T> : IState<T> where T : StateController
{
}


问:
Not same result on the same command in script and out of the script
When i pass this command out of my script :

```<code>transmission-remote -n 'transmission:transmission' -l | awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }' | grep "\b\b" | tail -1
</code>```

The result is :

```<code>Micro Pratique N°247 Avril 2017.pdf
</code>```

But when i pass this command in my script and stock the result in a variable like this :

```<code>test=`transmission-remote -n 'transmission:transmission' -l | awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }' | grep "\b\b" | tail -1`
</code>```

The result is not the same ! Here the script with "set -x" :

```<code>+++ transmission-remote -n transmission:transmission -l
+++ awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }'
+++ grep '\b\b'
+++ tail -1
++ test='Pratique N°247 Avril 2017.pdf '
</code>```

Why it cuts my first word "Micro" ?

Here the result of transmission-remote -n transmission:transmission -l :

```<code>ID     Done       Have  ETA           Up    Down  Ratio  Status       Name
   1   100%    8.30 GB  Done         1.0     0.0    2.8  Seeding      Ghost In The Shell 2 Innocence 2003 MULTi VFF BluRay 1080p AC3 x264
  65   100%    4.86 GB  Done         0.0     0.0    2.9  Idle         WWE.RAW.2017.03.20.720p.HDTV.x264-Ebi.mp4
  71   100%    2.89 GB  Done         0.0     0.0    2.9  Idle         WWE.Smackdown.Live.2017.03.21.720p.HDTV.x264-Ebi.mp4
 106   100%    4.80 GB  Done         0.0     0.0    0.0  Seeding      WWE.RAW.2017.03.27.720p.HDTV.x264-Ebi.mp4
 107   100%    2.90 GB  Done         0.0     0.0    0.9  Idle         WWE.SmackDown.Live.2017.03.28.720p.HDTV.x264-NWCHD.mp4
 113     0%       None  Unknown      0.0     0.0   None  Idle         Micro Pratique N°247 Avril 2017.pdf
Sum:          23.75 GB               1.0     0.0
</code>```

答:
your file is fixed-width format, not properly delimited.  You can utilize gawk's FIELDWIDTHS variable.  Since the other awks don't support it,
here is another approach, assuming you know the header of the field you're trying to extract

```<code>awk 'NR==1        {p=match($0,"Name")}
     length($0)>p {print substr($0,p)}' file

Name
Ghost In The Shell 2 Innocence 2003 MULTi VFF BluRay 1080p AC3 x264
WWE.RAW.2017.03.20.720p.HDTV.x264-Ebi.mp4
WWE.Smackdown.Live.2017.03.21.720p.HDTV.x264-Ebi.mp4
WWE.RAW.2017.03.27.720p.HDTV.x264-Ebi.mp4
WWE.SmackDown.Live.2017.03.28.720p.HDTV.x264-NWCHD.mp4
Micro Pratique N°247 Avril 2017.pdf
</code>```

to get the last entry record either tail or

```<code>awk 'NR==1        {p=match($0,"Name")}
     length($0)>p {last=substr($0,p)}
     END          {print last}' file

Micro Pratique N°247 Avril 2017.pdf
</code>```

Body:
When i pass this command out of my script :

transmission-remote -n 'transmission:transmission' -l | awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }' | grep "\b\b" | tail -1

The result is :

Micro Pratique N°247 Avril 2017.pdf

But when i pass this command in my script and stock the result in a variable like this :

test=`transmission-remote -n 'transmission:transmission' -l | awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }' | grep "\b\b" | tail -1`

The result is not the same ! Here the script with "set -x" :

+++ transmission-remote -n transmission:transmission -l
+++ awk '{ s = ""; for (i = 10; i <= NF; i++) s = s $i " "; print s }'
+++ grep '\b\b'
+++ tail -1
++ test='Pratique N°247 Avril 2017.pdf '

Why it cuts my first word "Micro" ?

Here the result of transmission-remote -n transmission:transmission -l :

ID     Done       Have  ETA           Up    Down  Ratio  Status       Name
   1   100%    8.30 GB  Done         1.0     0.0    2.8  Seeding      Ghost In The Shell 2 Innocence 2003 MULTi VFF BluRay 1080p AC3 x264
  65   100%    4.86 GB  Done         0.0     0.0    2.9  Idle         WWE.RAW.2017.03.20.720p.HDTV.x264-Ebi.mp4
  71   100%    2.89 GB  Done         0.0     0.0    2.9  Idle         WWE.Smackdown.Live.2017.03.21.720p.HDTV.x264-Ebi.mp4
 106   100%    4.80 GB  Done         0.0     0.0    0.0  Seeding      WWE.RAW.2017.03.27.720p.HDTV.x264-Ebi.mp4
 107   100%    2.90 GB  Done         0.0     0.0    0.9  Idle         WWE.SmackDown.Live.2017.03.28.720p.HDTV.x264-NWCHD.mp4
 113     0%       None  Unknown      0.0     0.0   None  Idle         Micro Pratique N°247 Avril 2017.pdf
Sum:          23.75 GB               1.0     0.0

Body:
your file is fixed-width format, not properly delimited.  You can utilize gawk's FIELDWIDTHS variable.  Since the other awks don't support it,
here is another approach, assuming you know the header of the field you're trying to extract

awk 'NR==1        {p=match($0,"Name")}
     length($0)>p {print substr($0,p)}' file

Name
Ghost In The Shell 2 Innocence 2003 MULTi VFF BluRay 1080p AC3 x264
WWE.RAW.2017.03.20.720p.HDTV.x264-Ebi.mp4
WWE.Smackdown.Live.2017.03.21.720p.HDTV.x264-Ebi.mp4
WWE.RAW.2017.03.27.720p.HDTV.x264-Ebi.mp4
WWE.SmackDown.Live.2017.03.28.720p.HDTV.x264-NWCHD.mp4
Micro Pratique N°247 Avril 2017.pdf

to get the last entry record either tail or

awk 'NR==1        {p=match($0,"Name")}
     length($0)>p {last=substr($0,p)}
     END          {print last}' file

Micro Pratique N°247 Avril 2017.pdf


问:
WooCommerce My Account page custom menu item with custom link
I was able to create a new menu item "Special Page" using this:

```<code>add_filter( 'woocommerce_account_menu_items' , 'kc_menu_panel_nav' );

function kc_menu_panel_nav() {
    $items = array(
        'dashboard'       => __( 'Dashboard', 'woocommerce' ),
        'orders'          => __( 'Orders', 'woocommerce' ),
        'downloads'       => __( 'Downloads', 'woocommerce' ),
        'edit-address'    => __( 'Addresses', 'woocommerce' ),
        'payment-methods' => __( 'Payment Methods', 'woocommerce' ),
        'edit-account'    => __( 'Account Details', 'woocommerce' ),
        'special-page' => __( 'Special Page', 'woocommerce' ), // My custom tab here
        'customer-logout' => __( 'Logout', 'woocommerce' ),
    );

    return $items;
}
</code>```

It redirects to my-account/special-page .How do I create a custom link for the special page link ?

答:
Here your page slug name is required.

your code

```<code>'special-page' =>
</code>```

it's your page slug name For example like

```<code>'about-us' => __( 'My Page', 'woocommerce' ), // My custom tab here
</code>```

Body:
I was able to create a new menu item "Special Page" using this:

add_filter( 'woocommerce_account_menu_items' , 'kc_menu_panel_nav' );

function kc_menu_panel_nav() {
    $items = array(
        'dashboard'       => __( 'Dashboard', 'woocommerce' ),
        'orders'          => __( 'Orders', 'woocommerce' ),
        'downloads'       => __( 'Downloads', 'woocommerce' ),
        'edit-address'    => __( 'Addresses', 'woocommerce' ),
        'payment-methods' => __( 'Payment Methods', 'woocommerce' ),
        'edit-account'    => __( 'Account Details', 'woocommerce' ),
        'special-page' => __( 'Special Page', 'woocommerce' ), // My custom tab here
        'customer-logout' => __( 'Logout', 'woocommerce' ),
    );

    return $items;
}

It redirects to my-account/special-page .How do I create a custom link for the special page link ?

Body:
Here your page slug name is required.

your code

'special-page' =>

it's your page slug name For example like

'about-us' => __( 'My Page', 'woocommerce' ), // My custom tab here


问:
Load a dataset into R with data() using a variable instead of the dataset name
I am trying to load a dataset into R using the data() function. It works fine when I use the dataset name (e.g. data(Titanic) or data("Titanic")). What doesn't work for me is loading a dataset using a variable instead of its name. For example:

```<code># This works fine:
> data(Titanic)

# This works fine as well:
> data("Titanic")

# This doesn't work:
> myvar <- Titanic
> data(myvar)
**Warning message:
In data(myvar) : data set ‘myvar’ not found**
</code>```

Why is R looking for a dataset named "myvar" since it is not quoted?
And since this is the default behavior, isn't there a way to load a dataset stored in a variable?

For the record, what I am trying to do is to create a function that uses the "arules" package and mines association rules using Apriori. Thus, I need to pass the dataset as a parameter to that function.

```<code>myfun <- function(mydataset) {
    data(mydataset)    # doesn't work (data set 'mydataset' not found)
    rules <- apriori(mydataset)
}
</code>```

edit - output of sessionInfo():

```<code>> sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] arules_1.0-14   Matrix_1.0-12   lattice_0.20-15 RPostgreSQL_0.4 DBI_0.2-7

loaded via a namespace (and not attached):
[1] grid_3.0.0  tools_3.0.0
</code>```

And the actual errors I am getting (using, for example,  a sample dataset "xyz"):

```<code>xyz <- data.frame(c(1,2,3))
data(list=xyz)
Warning messages:
1: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
2: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
3: In if (name %in% names(rds)) { :
  the condition has length > 1 and only the first element will be used
4: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
5: In if (name %in% names(rds)) { :
  the condition has length > 1 and only the first element will be used
6: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used

...

...

32: In data(list = xyz) :
  c("data set ‘1’ not found", "data set ‘2’ not found", "data set ‘3’ not found")
</code>```

答:
If the package has been loaded, you can use the get() function to assign the data set to a local variable:

```<code>data_object = get(myvar, asNamespace('<package_name>'))
</code>```

or simply:

```<code>data_object = get(myvar)
</code>```

Body:
I am trying to load a dataset into R using the data() function. It works fine when I use the dataset name (e.g. data(Titanic) or data("Titanic")). What doesn't work for me is loading a dataset using a variable instead of its name. For example:

# This works fine:
> data(Titanic)

# This works fine as well:
> data("Titanic")

# This doesn't work:
> myvar <- Titanic
> data(myvar)
**Warning message:
In data(myvar) : data set ‘myvar’ not found**

Why is R looking for a dataset named "myvar" since it is not quoted?
And since this is the default behavior, isn't there a way to load a dataset stored in a variable?

For the record, what I am trying to do is to create a function that uses the "arules" package and mines association rules using Apriori. Thus, I need to pass the dataset as a parameter to that function.

myfun <- function(mydataset) {
    data(mydataset)    # doesn't work (data set 'mydataset' not found)
    rules <- apriori(mydataset)
}

edit - output of sessionInfo():

> sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] arules_1.0-14   Matrix_1.0-12   lattice_0.20-15 RPostgreSQL_0.4 DBI_0.2-7

loaded via a namespace (and not attached):
[1] grid_3.0.0  tools_3.0.0

And the actual errors I am getting (using, for example,  a sample dataset "xyz"):

xyz <- data.frame(c(1,2,3))
data(list=xyz)
Warning messages:
1: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
2: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
3: In if (name %in% names(rds)) { :
  the condition has length > 1 and only the first element will be used
4: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
5: In if (name %in% names(rds)) { :
  the condition has length > 1 and only the first element will be used
6: In grep(name, files, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used

...

...

32: In data(list = xyz) :
  c("data set ‘1’ not found", "data set ‘2’ not found", "data set ‘3’ not found")

Body:
If the package has been loaded, you can use the get() function to assign the data set to a local variable:

data_object = get(myvar, asNamespace('<package_name>'))

or simply:

data_object = get(myvar)


答:
You can use CSV filters like this,</p>

```<code>input {
    file {
        path => "/path/of/your/csv/test.csv"
        sincedb_path => "/path/of/your/csv/test.idx"
        start_position => "beginning"
    }
}

filter {
    csv {
        separator => ","
        columns => ["column1","column2",...]
    }
}

output {

    if [column1] == "value" {
        csv {
        fields => ["column1"]
        path => "/path/to/your/csv"
       }
    }
 }
</code>```

Title: How I can read from CSV and write in other CSV files depends on last column value using logstash

Body:
I am new for logstash.
I have CSV file having following data

22,10.10.193.170,172.23.3.42,NULL,3740,NULL,NULL,NULL,NULL,1
54,10.35.92.87,172.23.3.41,NULL,10492,NULL,NULL,NULL,NULL,2
28,10.34.20.97,172.23.3.42,NULL,7265,NULL,NULL,NULL,NULL,3
24,10.1.160.225,172.23.3.48,NULL,3780,NULL,NULL,NULL,NULL,1
54,10.1.160.225,172.23.3.48,NULL,10463,NULL,NULL,NULL,NULL,1
18,175.100.160.70,104.124.54.17,NULL,9515,NULL,NULL,NULL,NULL,2
2,172.16.3.87,203.175.185.57,NULL,44,NULL,NULL,NULL,NULL,3
10,172.16.4.68,10.1.15.220,NULL,184,NULL,NULL,NULL,NULL,1
26,10.121.6.170,172.23.3.48,NULL,3827,NULL,NULL,NULL,NULL,2
26,10.121.6.134,172.23.3.50,NULL,3764,NULL,NULL,NULL,NULL,1

I want to read the CSV file and on the basis of last column value I want to write data in to corresponding CSV file
like in output_1.csv should contain

22,10.10.193.170,172.23.3.42,NULL,3740,NULL,NULL,NULL,NULL,1
24,10.1.160.225,172.23.3.48,NULL,3780,NULL,NULL,NULL,NULL,1
10,172.16.4.68,10.1.15.220,NULL,184,NULL,NULL,NULL,NULL,1
26,10.121.6.134,172.23.3.50,NULL,3764,NULL,NULL,NULL,NULL,1

in output_2.csv should contain

54,10.35.92.87,172.23.3.41,NULL,10492,NULL,NULL,NULL,NULL,2
18,175.100.160.70,104.124.54.17,NULL,9515,NULL,NULL,NULL,NULL,2
26,10.121.6.170,172.23.3.48,NULL,3827,NULL,NULL,NULL,NULL,2

and output_3.csv contain

28,10.34.20.97,172.23.3.42,NULL,7265,NULL,NULL,NULL,NULL,3
2,172.16.3.87,203.175.185.57,NULL,44,NULL,NULL,NULL,NULL,3

Please help me to solve the above.

Regards,
Vikas

Body:
You can use CSV filters like this,

input {
    file {
        path => "/path/of/your/csv/test.csv"
        sincedb_path => "/path/of/your/csv/test.idx"
        start_position => "beginning"
    }
}

filter {
    csv {
        separator => ","
        columns => ["column1","column2",...]
    }
}

output {

    if [column1] == "value" {
        csv {
        fields => ["column1"]
        path => "/path/to/your/csv"
       }
    }
 }


问:
Powershell exit status
what's the powershell equivalent of simply:

```<code>bash test.sh
</code>```

I'd like to call a powershell script (from outside a powershell environment) and be able to get a return value of 0 if it executed successfully, and otherwise a non-zero value if either:

the powershell executable can't be found or executed

the script test.ps1 can't be found or executed (insufficient permissions, ...)

the script test.ps1 can be read and executed but returns a non zero value

And then, how to access this return value, which in linux would be

```<code>echo $?
</code>```

答:
Provided you can modify the powershell script, you can set the exit code using:

```<code>[Environment]::Exit(yourexitcode)
</code>```

Then read the last exit code with whatever app you are calling it from.

Title: Powershell exit status

Body:
what's the powershell equivalent of simply:

bash test.sh

I'd like to call a powershell script (from outside a powershell environment) and be able to get a return value of 0 if it executed successfully, and otherwise a non-zero value if either:

the powershell executable can't be found or executed

the script test.ps1 can't be found or executed (insufficient permissions, ...)

the script test.ps1 can be read and executed but returns a non zero value

And then, how to access this return value, which in linux would be

echo $?

Body:
Provided you can modify the powershell script, you can set the exit code using:

[Environment]::Exit(yourexitcode)

Then read the last exit code with whatever app you are calling it from.


问:
Garbage channel in Golang?
I accept a done channel in my function, which is nice for notifying callers when some async process has finished, if they care.  This is very useful for writing unit tests for example.

If my caller doesn't need this functionality, is there an idiomatic way to pass a garbage channel, where all values sent to it are discarded immediately?  I was initially surprised sending nil didn't work (sending to nil blocks the sender).  I can think of one gross implementation (like a goroutine always running that consumes from this channel), but I would love to write something like:

```<code>func myFunc(foo int, done chan bool) {
    ....
}

func main() {
    myfunc(4, _)
}
</code>```

Is there a simple way to accomplish this?

答:
How about this:

```<code>func DoAllTheThings(done ...chan<- bool) {

    // do the things

    // all done!
    if len(done) >= 1 {
        done[0] <- true
    }
    return
}
</code>```

If no channel is given in arguments, then nothing is sent. It would be up to the caller to set up a listener for the channel, obviously. Then you could call it as:

```<code>func main() {
    DoAllTheThings()
}
</code>```

or

```<code>func main() {
    ch := make(chan bool)
    go func() {
        done := <- ch
        if done {
            fmt.Println("Yay!")
        }
    }()
    DoAllTheThings(ch)
}
</code>```

https://play.golang.org/p/Ktc977gYpA

Title: Garbage channel in Golang?

Body:
I accept a done channel in my function, which is nice for notifying callers when some async process has finished, if they care.  This is very useful for writing unit tests for example.

If my caller doesn't need this functionality, is there an idiomatic way to pass a garbage channel, where all values sent to it are discarded immediately?  I was initially surprised sending nil didn't work (sending to nil blocks the sender).  I can think of one gross implementation (like a goroutine always running that consumes from this channel), but I would love to write something like:

func myFunc(foo int, done chan bool) {
    ....
}

func main() {
    myfunc(4, _)
}

Is there a simple way to accomplish this?

Body:
How about this:

func DoAllTheThings(done ...chan<- bool) {

    // do the things

    // all done!
    if len(done) >= 1 {
        done[0] <- true
    }
    return
}

If no channel is given in arguments, then nothing is sent. It would be up to the caller to set up a listener for the channel, obviously. Then you could call it as:

func main() {
    DoAllTheThings()
}

or

func main() {
    ch := make(chan bool)
    go func() {
        done := <- ch
        if done {
            fmt.Println("Yay!")
        }
    }()
    DoAllTheThings(ch)
}

https://play.golang.org/p/Ktc977gYpA


问:
How do I shut down my Express server gracefully when its process is killed?
When running my Express application in production, I want to shut down the server gracefully when its process is killed (i.e. a SIGTERM or SIGINT is sent).

Here is a simplified version of my code:

```<code>const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(
    (err, connections) => console.log(`${connections} connections currently open`)
), 1000);

process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);

function shutDown() {
    console.log('Received kill signal, shutting down gracefully');
    server.close(() => {
        console.log('Closed out remaining connections');
        process.exit(0);
    });

    setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
    }, 10000);
}
</code>```

When I run it and call the URL http://localhost:3000/ in a browser, the log statement in the setInterval function will keep printing “1 connection currently open” until I actually close the browser window. Even closing the tab will keep the connection open, apparently.

So when I kill my server by hitting Ctrl+C, it will run into the timeout and print “Could not close connections” after 10 seconds, all the while continuing to print “1 connection open”.

Only if I close the browser window before killing the process I get the “closed out remaining connections” message.

What am I missing here? What is the proper way to shut down an Express server gracefully?

答:
I added a listener for connections opening on the server, storing references to those connections in an array. When the connections are closed, they are removed from the array.

When the server is killed, each of the connection is closed by calling its end methods. For some browsers (e.g. Chrome), this is not enough, so after a timeout, I call destroy on each connection.

```<code>const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(
    (err, connections) => console.log(`${connections} connections currently open`)
), 1000);

process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);

let connections = [];

server.on('connection', connection => {
    connections.push(connection);
    connection.on('close', () => connections = connections.filter(curr => curr !== connection));
});

function shutDown() {
    console.log('Received kill signal, shutting down gracefully');
    server.close(() => {
        console.log('Closed out remaining connections');
        process.exit(0);
    });

    setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
    }, 10000);

    connections.forEach(curr => curr.end());
    setTimeout(() => connections.forEach(curr => curr.destroy()), 5000);
}
</code>```

Body:
When running my Express application in production, I want to shut down the server gracefully when its process is killed (i.e. a SIGTERM or SIGINT is sent).

Here is a simplified version of my code:

const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(
    (err, connections) => console.log(`${connections} connections currently open`)
), 1000);

process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);

function shutDown() {
    console.log('Received kill signal, shutting down gracefully');
    server.close(() => {
        console.log('Closed out remaining connections');
        process.exit(0);
    });

    setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
    }, 10000);
}

When I run it and call the URL http://localhost:3000/ in a browser, the log statement in the setInterval function will keep printing “1 connection currently open” until I actually close the browser window. Even closing the tab will keep the connection open, apparently.

So when I kill my server by hitting Ctrl+C, it will run into the timeout and print “Could not close connections” after 10 seconds, all the while continuing to print “1 connection open”.

Only if I close the browser window before killing the process I get the “closed out remaining connections” message.

What am I missing here? What is the proper way to shut down an Express server gracefully?

Body:
I added a listener for connections opening on the server, storing references to those connections in an array. When the connections are closed, they are removed from the array.

When the server is killed, each of the connection is closed by calling its end methods. For some browsers (e.g. Chrome), this is not enough, so after a timeout, I call destroy on each connection.

const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(
    (err, connections) => console.log(`${connections} connections currently open`)
), 1000);

process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);

let connections = [];

server.on('connection', connection => {
    connections.push(connection);
    connection.on('close', () => connections = connections.filter(curr => curr !== connection));
});

function shutDown() {
    console.log('Received kill signal, shutting down gracefully');
    server.close(() => {
        console.log('Closed out remaining connections');
        process.exit(0);
    });

    setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
    }, 10000);

    connections.forEach(curr => curr.end());
    setTimeout(() => connections.forEach(curr => curr.destroy()), 5000);
}


问:
Display x,y coordinates for loaded image file
I need to load an image file with matplotlib and see the coordinates of points within it, as if it were a simple x,y scatter plot.

I can assume that the x axis extension is [0, 1], and the y axis follows the same scaling. I can load the above image file with

```<code>from PIL import Image
im = Image.open("del.png")
im.show()
</code>```

but this uses ImageMagick (I'm on a Linux system) to display the image, and no coordinates are shown in the bottom left part of the plot window as would for a simple data plot:

答:
Use pyplot for that:</p>

```<code>from matplotlib import pyplot as plt
plt.imshow(plt.imread('del.png'))
</code>```

Body:
I need to load an image file with matplotlib and see the coordinates of points within it, as if it were a simple x,y scatter plot.

I can assume that the x axis extension is [0, 1], and the y axis follows the same scaling. I can load the above image file with

from PIL import Image
im = Image.open("del.png")
im.show()

but this uses ImageMagick (I'm on a Linux system) to display the image, and no coordinates are shown in the bottom left part of the plot window as would for a simple data plot:

Body:
Use pyplot for that:

from matplotlib import pyplot as plt
plt.imshow(plt.imread('del.png'))


问:
How to map json and skip parent property?
I have this json string, which contains two elements each with a Number and a Status:

```<code>var jsonString = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
</code>```

As you see it has a parent property called Errors.

I have prepared this model:

```<code>public class ExceptionStructure
{
    public int Number { get; set; }
    public string Status { get; set; }
}
</code>```

Using NewtonSoft.Json I would like to deserialize the json string into an array of ExceptionStructure objects, without also having to create a model for the parent property (as I don't really need it).

Can I do this (perhaps with some json attribute on the model class)?

I was hoping to do something like this to deserialize:

```<code>var exceptionArr = JsonConvert.DeserializeObject<ExceptionStructure>(jsonString);
</code>```

答:
JSON.NET allows you to deserialize parts of a json file. You can do this by first deserialzing the json string to a JObject, extract the relevant parts, and then deserialize those to your actual object.

```<code>JObject errors = JObject.Parse(jsonString);

IList<JToken> results = errors["Errors"].Children().ToList();

IList<ExceptionStructure> exceptions = new List<ExceptionStructure>();

foreach (JToken result in results)
{
    ExceptionStructure exception= result.ToObject<ExceptionStructure>();
    exceptions.Add(exception);
}
</code>```

Honestly though, in your case it might be easier to just build a Errors parent class

More information can be found at http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm

Body:
I have this json string, which contains two elements each with a Number and a Status:

var jsonString = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";

As you see it has a parent property called Errors.

I have prepared this model:

public class ExceptionStructure
{
    public int Number { get; set; }
    public string Status { get; set; }
}

Using NewtonSoft.Json I would like to deserialize the json string into an array of ExceptionStructure objects, without also having to create a model for the parent property (as I don't really need it).

Can I do this (perhaps with some json attribute on the model class)?

I was hoping to do something like this to deserialize:

var exceptionArr = JsonConvert.DeserializeObject<ExceptionStructure>(jsonString);

Body:
JSON.NET allows you to deserialize parts of a json file. You can do this by first deserialzing the json string to a JObject, extract the relevant parts, and then deserialize those to your actual object.

JObject errors = JObject.Parse(jsonString);

IList<JToken> results = errors["Errors"].Children().ToList();

IList<ExceptionStructure> exceptions = new List<ExceptionStructure>();

foreach (JToken result in results)
{
    ExceptionStructure exception= result.ToObject<ExceptionStructure>();
    exceptions.Add(exception);
}

Honestly though, in your case it might be easier to just build a Errors parent class

More information can be found at http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm


问:
Expanding a list based on a number per line
So I have a file similar to this

A 1 foo bar 1
A 1 foo bar 2
B 3 foo bar 5
B 3 foo bar 6

Where the first column is an ID, the second column is the number of times I need the line repeated. The output should look like this

A foo bar 1
A foo bar 2
B foo bar 5
B foo bar 6
C foo bar 5
C foo bar 6
D foo bar 5
D foo bar 6

However, since the files I am trying to use are rather big, the expanding is ultra slow. Any ideas? :)

EDIT1: Code I did, I did have two inputs, one file with the columns i showed before and one with just IDs and counts separated by a dash.

for ID in $(cat $ID_File);do
 grep "^$ID[^0-9]" $IN > temp2.txt
 Cycles=$(echo $ID| sed 's/.*-//')
 for i in $(seq 1 1 $Cycles);do
  cut -f2- temp2.txt| awk '{print '$Start_ID'"\t"$0}'>> $OUT
  Start_ID=$(( $Start_ID + 1 ))
 done
done

答:
I found the answer! Instead of looking through the file several times with grep I used the following Python script that goes through the file just once.

```<code>FILE='A.txt'
ID=''
Prefix='A'

Number=1
First=1
Current=[]
OUT='B.txt'
f=open(File,'w')

for line in open(FILE):
 line1=line.split('\t')
 if ID!=line1[0] and First==0:
  ID=line1[0]
  for i in range(0,int(Current[0][1])):
   for j in range(0,len(Current)):
    f.write(' '.join([Prefix+str(Number)]+Current[j][2:]))
  Number=Number+1
  Current=[]
  Current.append(line1)
 elif ID!=line1[0] and First==1:
  ID=line1[0]
  First=0
  Current.append(line1)
 elif ID==line1[0]:
  Current.append(line1)
</code>```

Not the most elegant way to do it, but it gets the job done fast relatively quickly.

Body:
I found the answer! Instead of looking through the file several times with grep I used the following Python script that goes through the file just once.

FILE='A.txt'
ID=''
Prefix='A'

Number=1
First=1
Current=[]
OUT='B.txt'
f=open(File,'w')

for line in open(FILE):
 line1=line.split('\t')
 if ID!=line1[0] and First==0:
  ID=line1[0]
  for i in range(0,int(Current[0][1])):
   for j in range(0,len(Current)):
    f.write(' '.join([Prefix+str(Number)]+Current[j][2:]))
  Number=Number+1
  Current=[]
  Current.append(line1)
 elif ID!=line1[0] and First==1:
  ID=line1[0]
  First=0
  Current.append(line1)
 elif ID==line1[0]:
  Current.append(line1)

Not the most elegant way to do it, but it gets the job done fast relatively quickly.


问:
Kibana integrated with Firehose
I am pushing two different tools data in Elastic search using Kinesis Firehose. I need to display data in Kibana and I am able to do it separately But i want these two indexes to display in single index that means want to merge index and display.

Both the indexes names are different from each other. Example:

1st index- animal

2nd index- Human

To display in single index, Species.

答:
You can create an alias in ElasticSearch for your indices, something like
POST to

```<code>your.elasticsearch.domain/_aliases
</code>```

Body:

```<code>{
    "actions" : [
        { "add" : { "indices" : ["Animal", "Human"], "alias" : "Species" } },
    ]
}
</code>```

Then you should be able to use Species as a index pattern in Kibana.

Title: Kibana integrated with Firehose

Body:
You can create an alias in ElasticSearch for your indices, something like
POST to

your.elasticsearch.domain/_aliases

Body:

{
    "actions" : [
        { "add" : { "indices" : ["Animal", "Human"], "alias" : "Species" } },
    ]
}

Then you should be able to use Species as a index pattern in Kibana.


问:
NSlog does not print new lines \r\n
I try to add new lines to NSlog.

I run:

```<code>NSLog(@"\n%@\r\n\r\n", json1);
NSLog(@"\n%@\r\n\r\n", json2);
</code>```

However The output is:

```<code>2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"true"}
2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"false"}
</code>```

It ignores new line as \r\n (tried also \n only) but 1st \n before string works

I expect:

```<code>2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"true"}

2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"false"}

017-03-29 16:09:50 InAppTestAfApp2[312:33527] other logs ...
</code>```

I use Xcode 8.3

[Edit 1]

I tried to run:

```<code>NSLog(@"%@ %@",type, @"xxxxx\n\n");
</code>```

Still I see:

```<code>2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
xxxxx
017-03-29 16:09:50 InAppTestAfApp2[312:33527] other logs ...
</code>```

[EDIT 2]

As work around I add garbage at the end but it looks messy:

```<code>NSLog(@"%@ %@\r\n\r\n%s",type, json, @"`");
</code>```

答:
Carriage return/linefeed pairs (CR+LF) have never been needed on the Mac. Classic MacOS used CR, and MacOS X uses LF (due to its Unix heritage). So it's not surprising that NSLog() strips the CR characters out of the text that you're logging.

It's also not surprising that NSLog() trims the white space from the end of your log statements. NSLog() is meant for logging messages -- it's not a general-purpose print statement. Keeping logs compact is useful, and trimming blank lines from the end of a message serves that purpose.

If you really want to include blank space in your messages, perhaps to make certain log messages stand out more, you can do it by including a printing character after the blank lines. For example:

```<code>    NSLog(@"\n\nMy Really Important Message\n\n.");
</code>```

The result:

```<code>2017-03-29 09:28:12.898 MessageTest[13407:2524935]

My Really Important Message

.
</code>```

Title: NSlog does not print new lines \r\n

Body:
I try to add new lines to NSlog.

I run:

NSLog(@"\n%@\r\n\r\n", json1);
NSLog(@"\n%@\r\n\r\n", json2);

However The output is:

2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"true"}
2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"false"}

It ignores new line as \r\n (tried also \n only) but 1st \n before string works

I expect:

2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"true"}

2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
{"attribution":"false"}

017-03-29 16:09:50 InAppTestAfApp2[312:33527] other logs ...

I use Xcode 8.3

[Edit 1]

I tried to run:

NSLog(@"%@ %@",type, @"xxxxx\n\n");

Still I see:

2017-03-29 16:09:50 InAppTestAfApp2[312:33527]
xxxxx
017-03-29 16:09:50 InAppTestAfApp2[312:33527] other logs ...

[EDIT 2]

As work around I add garbage at the end but it looks messy:

NSLog(@"%@ %@\r\n\r\n%s",type, json, @"`");

Body:
Carriage return/linefeed pairs (CR+LF) have never been needed on the Mac. Classic MacOS used CR, and MacOS X uses LF (due to its Unix heritage). So it's not surprising that NSLog() strips the CR characters out of the text that you're logging.

It's also not surprising that NSLog() trims the white space from the end of your log statements. NSLog() is meant for logging messages -- it's not a general-purpose print statement. Keeping logs compact is useful, and trimming blank lines from the end of a message serves that purpose.

If you really want to include blank space in your messages, perhaps to make certain log messages stand out more, you can do it by including a printing character after the blank lines. For example:

    NSLog(@"\n\nMy Really Important Message\n\n.");

The result:

2017-03-29 09:28:12.898 MessageTest[13407:2524935]

My Really Important Message

.