问:
How to create a per-user Startup folder shortcut in a per-machine installation?
I am installing an application using WiX 3 for all users (property ALLUSERS=1). I would like to create a shortcut to my application in the current user's Startup folder. How can I override the ALLUSERS=1 for my Startup folder shortcut only?

I am using the WiX Shortcut element:

```<code><Shortcut Id="MyAppShortcut" Directory="StartupFolder" ... />
</code>```

but the "StartupFolder" resolves to the 'All Users' Startup folder because of the per-machine installation.

Any suggestions?

答:
Installing the shortcut only for the current user doesn't seem like a good idea: what if I install your software under an account I only use for administrative tasks such as installing software? Because I try to follow best practices and Don't Run as Administrator!

If you're trying to run a single instance of the software in the background for the whole system, then you probably should write your software as a Windows Service instead of creating startup shortcuts. Wix has support for installing a service.

If you want a UI component to configure/manage the service to live in the tray, then you can then still install a shortcut for a separate executable to the All Users start up folder. That way all users can interact with the service, but the service itself is launched only once.

Body:
I am installing an application using WiX 3 for all users (property ALLUSERS=1). I would like to create a shortcut to my application in the current user's Startup folder. How can I override the ALLUSERS=1 for my Startup folder shortcut only?

I am using the WiX Shortcut element:

<Shortcut Id="MyAppShortcut" Directory="StartupFolder" ... />

but the "StartupFolder" resolves to the 'All Users' Startup folder because of the per-machine installation.

Any suggestions?


来源: stackexchange

问:
Preview is unavailable until a successful build
I tried fixing this for ages now, but I don't know what to do. How do I get it to display a preview? Here is a screenshot of the code:

答:
Follow these steps-

If you have any incomplete statement(s) in your code (probably where
you left it last time) then comment those lines to make them
inactive.

Go to Build=>Rebuild to rebuild the project.

Uncomment those lines to make them active again and you are done!!

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Filter pcap pap protocol without pyshark
I want to access data in pap packets, currently i'm using pyshark with the following code

```<code>import pyshark,sys

cap = pyshark.FileCapture('test.pcap',display_filter='ppp && not ppp.length')

for packet in cap:
        if packet.pap.get_field_value('peer_id'):
            print ('user: '+packet.pap.peer_id+" logged in")
</code>```

and it works fine on my pc and raspberrypi unfortunately i want to use this code on openwrt/lede router on which pyshark can't be installed due to ccache error:

```<code>unable to execute 'ccache_cc': no such file or directory
</code>```

which i assumed that openwrt lacks some compiler features so I tried to install other pcap parsing libraries and could install scapy, dpkt and pypcapfile and they all installed fine so how can I convert my code to use one of these libraries

答:
Thanks to @pierre I found out that the development version of scapy has some new usefull classes (PPP_PAP and PPP_PAP_Request) so I was able to write a working code for my problem and it works in python2 and python3

```<code>from scapy.all import PPP,PPP_PAP_Request,sniff

def logusers(pkt):
        if PPP_PAP_Request in pkt:
                print(pkt[PPP_PAP_Request].username.decode()+" logged in")
sniff(count=0,offline='all.pcap',prn=logusers,filter="pppoes",store=0)
</code>```

I used sniff function  because i found it a bit lightweight and fast(i'm trying to run the code on an embedded system after all) But nevertheless it's still a bit slow and i don't know if there is something faster (maybe other than scapy) so i'm not going to accept this answer for a while

Body:
I want to access data in pap packets, currently i'm using pyshark with the following code

import pyshark,sys

cap = pyshark.FileCapture('test.pcap',display_filter='ppp && not ppp.length')

for packet in cap:
        if packet.pap.get_field_value('peer_id'):
            print ('user: '+packet.pap.peer_id+" logged in")

and it works fine on my pc and raspberrypi unfortunately i want to use this code on openwrt/lede router on which pyshark can't be installed due to ccache error:

unable to execute 'ccache_cc': no such file or directory

which i assumed that openwrt lacks some compiler features so I tried to install other pcap parsing libraries and could install scapy, dpkt and pypcapfile and they all installed fine so how can I convert my code to use one of these libraries

Body:
Thanks to @pierre I found out that the development version of scapy has some new usefull classes (PPP_PAP and PPP_PAP_Request) so I was able to write a working code for my problem and it works in python2 and python3

from scapy.all import PPP,PPP_PAP_Request,sniff

def logusers(pkt):
        if PPP_PAP_Request in pkt:
                print(pkt[PPP_PAP_Request].username.decode()+" logged in")
sniff(count=0,offline='all.pcap',prn=logusers,filter="pppoes",store=0)

I used sniff function  because i found it a bit lightweight and fast(i'm trying to run the code on an embedded system after all) But nevertheless it's still a bit slow and i don't know if there is something faster (maybe other than scapy) so i'm not going to accept this answer for a while


问:
Restricting access to a PHP script
I have a security-related question - I'm developing an app that populates its database by using a PHP script on a remote server. I wouldn't like to make the PHP script publicly available, but just use it from the specific mobile application (written with TypeScript using the Ionic Framework). How could I accomplish this?</p>

答:
Make your mobile application to provide with the query some kind of secret string / token. And your server side PHP script will not proceed without valid token provided from the request.

The token can be part of your POST/GET/HTTP header or so.

Title: Restricting access to a PHP script


问:
How to pass multiple arguments with url (routing) in laravel 5.1
LARAVEL 5.1

I want to edit my table which having ID and TktID.

I want to pass this two parameters to edit method of my TestController.

My link:

```<code><a href="/sig/edit?id={{$value->id}}&ticketid={{$value->ticketid}}" title="Edit signature">
</code>```

My route.php

```<code>Route::get('sig/edit{id}{ticketid}','TicketsController@edit');
</code>```

edit method of controller:

```<code> public function edit($id, $ticketid)
    {
        //
    }
</code>```

How do I pass here two arguments in route.php to controller.

答:
Route

Route::get('sig/edit{id}{ticketid}','TicketsController@edit')->name(sig.edit);

link

href="{{route('sig.edit',[$value->id,$value->ticketid])}}" title="Edit signature">

Body:
LARAVEL 5.1

I want to edit my table which having ID and TktID.

I want to pass this two parameters to edit method of my TestController.

My link:

id}}&ticketid={{$value->ticketid}}" title="Edit signature">

My route.php

Route::get('sig/edit{id}{ticketid}','TicketsController@edit');

edit method of controller:

 public function edit($id, $ticketid)
    {
        //
    }

How do I pass here two arguments in route.php to controller.

Body:
Route

Route::get('sig/edit{id}{ticketid}','TicketsController@edit')->name(sig.edit);

link

<a href="{{route('sig.edit',[$value->id,$value->ticketid])}}" title="Edit signature">


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
```<code>$string = 'foo,bar,';
if(substr($string, -1) === ','){
    // it ends with ','
}
</code>```

Title: how to know if a $string ends with ','?

ContentLicense: CC BY-SA 2.5


答:
What I've done in the past to achieve something like this is to setup an API key system. You generate API keys server-side, and you lease out valid keys that you have generated to your application(s). You would then use that key in your application, and that would get sent to the server and parsed by a php script whenever you call the script from your mobile application. If the key is valid, then the request is valid.

There are some security considerations to think about, i.e what happens if someone gets your API key? Are you logging remote IP's (and fully qualified domain names) and API usage, will your system be able to invalidate the key whenever necessary? Is the API request utilising TLS connections?

Title: Restricting access to a PHP script

Body: I have a security-related question - I'm developing an app that populates its database by using a PHP script on a remote server. I wouldn't like to make the PHP script publicly available, but just use it from the specific mobile application (written with TypeScript using the Ionic Framework). How could I accomplish this?


问:
json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?
So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.

The data I send through the ajax call is, according to console.log(noBrack):

```<code>{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
</code>```

My Ajax call is:

```<code>$.ajax({
  url: 'quickGrade.php',
  type: 'POST',
  data: noBrack,
  datatype: 'json',
  success:function(data){
    alert(data );
  }
});
</code>```

My PHP code is:

```<code>$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
</code>```

Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.

答:
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.

Your code will become this:

```<code>$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
</code>```

You can read more about:

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-decode.php

Body:
So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.

The data I send through the ajax call is, according to console.log(noBrack):

{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}

My Ajax call is:

$.ajax({
  url: 'quickGrade.php',
  type: 'POST',
  data: noBrack,
  datatype: 'json',
  success:function(data){
    alert(data );
  }
});

My PHP code is:

$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);

Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.

Body:
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.

Your code will become this:

$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));

You can read more about:

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-decode.php


问:
jsoup posting and cookie
I'm trying to use jsoup to login to a site and then scrape information, I am running into in a problem, I can login successfully and create a Document from index.php but I cannot get other pages on the site. I know I need to set a cookie after I post and then load it when I'm trying to open another page on the site. But how do I do this? The following code lets me login and get index.php

Document doc = Jsoup.connect("http://www.example.com/login.php")
               .data("username", "myUsername",
                     "password", "myPassword")
               .post();
```

I know I can use apache httpclient to do this but I don't want to.

答:
Here is what you can try...

```<code>import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("http://www.example.com/login.php")
                .data("username", "your login id", "password", "your password")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Now save all your cookies and make request to the other page you want.

```<code>//Store Cookies
cookies = res.cookies();
</code>```

Making request to another page.

```<code>try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}
</code>```

Ask if further help needed.

Title: jsoup posting and cookie

Body:
I'm trying to use jsoup to login to a site and then scrape information, I am running into in a problem, I can login successfully and create a Document from index.php but I cannot get other pages on the site. I know I need to set a cookie after I post and then load it when I'm trying to open another page on the site. But how do I do this? The following code lets me login and get index.php

Document doc = Jsoup.connect("http://www.example.com/login.php")
               .data("username", "myUsername",
                     "password", "myPassword")
               .post();

I know I can use apache httpclient to do this but I don't want to.

Body:
Here is what you can try...

import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("http://www.example.com/login.php")
                .data("username", "your login id", "password", "your password")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

Now save all your cookies and make request to the other page you want.

//Store Cookies
cookies = res.cookies();

Making request to another page.

try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}

Ask if further help needed.


问:
update multiple rows using dbgrid
I'm super new at coding and I'm making a simple apps now.

So as you can see in the pic, I have multiple data in selected date. If I wanted to update every row with different values and do it with save button, what code should I do?

Does my dbgrid need more setting at its properties?

I'm using Delphi 7 and zeos as db connection as well as oracle as db. Thanks in advance.

答:
There are different ways depends of what you want and what you use.

If you wish to edit several rows into DBGrid and save them simultaneously, most dataset components supports a CachedUpdate mode (look into the Zeos documentation for details). In this mode dataset holds all changes made until you call ApplyUpdates method to put these changes into DB using one batch.

Using Oracle, you can do it without cached updates, just use 'long transaction'. In this case you should start transaction when form opens, edit and post data at usual way and commit them when Save pressed. This way have some disadvantages, but I doubt you'll face them.

If you wish to do some sort of mass update when pressing Save button, you have two ways. First of all, you can set up a query component, set it's SQL property into something like

```<code>update My_Table set My_Field_1 = :Value1, My_Field_2 = :Value2
</code>```

and call it into save action handler:

```<code>qUpdate.Params.ParamByName('Value1').AsString := edFirstValue.Text;
qUpdate.Params.ParamByName('Value2').AsString := edSecondValue.Text;
qUpdate.ExecSQL;
qMain.Refresh; { we're in need to see updates values, yeah? }
</code>```

Otherwise, you can do it from client:

```<code>qMain.DisableControls;
try
  Bookmark := qMain.Bookmark;
  qMain.First;
  while not qMain.Eof do
  begin
    qMain.Edit;
    qMain.FieldByName('My_Field_1').AsString := edFirstValue.Text;
    qMain.FieldByName('My_Field_2').AsString := edSecondValue.Text;
    qMain.Post;
    qMain.Next;
  end;
finally
  qMain.Bookmark := Bookmark;
  qMain.EnableControls;
end;
</code>```

That's, generally, not so good way, so don't addict of that.

Title: update multiple rows using dbgrid

Body:
There are different ways depends of what you want and what you use.

If you wish to edit several rows into DBGrid and save them simultaneously, most dataset components supports a CachedUpdate mode (look into the Zeos documentation for details). In this mode dataset holds all changes made until you call ApplyUpdates method to put these changes into DB using one batch.

Using Oracle, you can do it without cached updates, just use 'long transaction'. In this case you should start transaction when form opens, edit and post data at usual way and commit them when Save pressed. This way have some disadvantages, but I doubt you'll face them.

If you wish to do some sort of mass update when pressing Save button, you have two ways. First of all, you can set up a query component, set it's SQL property into something like

update My_Table set My_Field_1 = :Value1, My_Field_2 = :Value2

and call it into save action handler:

qUpdate.Params.ParamByName('Value1').AsString := edFirstValue.Text;
qUpdate.Params.ParamByName('Value2').AsString := edSecondValue.Text;
qUpdate.ExecSQL;
qMain.Refresh; { we're in need to see updates values, yeah? }

Otherwise, you can do it from client:

qMain.DisableControls;
try
  Bookmark := qMain.Bookmark;
  qMain.First;
  while not qMain.Eof do
  begin
    qMain.Edit;
    qMain.FieldByName('My_Field_1').AsString := edFirstValue.Text;
    qMain.FieldByName('My_Field_2').AsString := edSecondValue.Text;
    qMain.Post;
    qMain.Next;
  end;
finally
  qMain.Bookmark := Bookmark;
  qMain.EnableControls;
end;

That's, generally, not so good way, so don't addict of that.


问:
Use regex to add empty groups
I'm a beginner python programmer. I'm trying to use a regular expression to build groups to append to a list. I'm not sure whether what I want to do can be covered with a single regex, or if I need to pass the text through more than one regex.

Test data:

yada yada 0.003 40 40.00

yadayada ya 55

yaaaaaaya 100.0000 4

My regex:

```<code>(\w+ *\w* *\w*) (\d*\.*\d*) *(\d*\.*\d*) *(\d*\.*\d*)\n
</code>```

The groups that I get:

'yada yada','0.003','40','40.00'

'yadayada ya','55',empty,empty

'yaaaaaaya','100.0000','4',empty

BUT the groups that I want are:

'yada yada','0.003','40','40.00'

'yadayada ya',empty,empty,'55'

'yaaaaaaya',empty,'100.0000','4'

Is it possible to change the regex to introduce empty (\d*.*\d*) groups into those lines that have less than 3 of those groups? So that the number groups are "right-justified"?

I tried to add ? to the end of the first two (\d*) groups, but get the same empty groups.

答:
The simplest way to perform what you are colloquially describing as "right-justifying" the matches, i. e. prioritize the matching of later optional subexpressions, is to reverse the "greediness" of the optional components. In Python regex, this is accomplished by adding ? to each quantified element:

```<code>(\w+ *\w* *\w*) (\d*?\.*?\d*?) *?(\d*?\.*?\d*?) *?(\d*?\.*?\d*?)\n
</code>```

Note that your expression is quite liberal and will not validate certain poorly-formed input. If this works for you, great, otherwise you may want to consider sticking certain parts in optional groups, such as (| \d+(?:\.\d+)?) to lazily match a space and number, for example (the construct (|x) is equivalent to ((?:x)??)).

Edit: As Tim pointed out, the shortcomings of this regex entail more than just permissiveness and could invoke catastrophic backtracking if the input is even slightly malformed. I'd recommend something a little more precise if you plan to stick with this method:

```<code>(\w+(?: \w+){0,2}) (|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?)\n
</code>```

It can still match malformed input but at least it's a bit tighter now.

Title: Use regex to add empty groups

Body:
I'm a beginner python programmer. I'm trying to use a regular expression to build groups to append to a list. I'm not sure whether what I want to do can be covered with a single regex, or if I need to pass the text through more than one regex.

Test data:

yada yada 0.003 40 40.00

yadayada ya 55

yaaaaaaya 100.0000 4

My regex:

(\w+ *\w* *\w*) (\d*\.*\d*) *(\d*\.*\d*) *(\d*\.*\d*)\n

The groups that I get:

'yada yada','0.003','40','40.00'

'yadayada ya','55',empty,empty

'yaaaaaaya','100.0000','4',empty

BUT the groups that I want are:

'yada yada','0.003','40','40.00'

'yadayada ya',empty,empty,'55'

'yaaaaaaya',empty,'100.0000','4'

Is it possible to change the regex to introduce empty (\d*.*\d*) groups into those lines that have less than 3 of those groups? So that the number groups are "right-justified"?

I tried to add ? to the end of the first two (\d*) groups, but get the same empty groups.

Body:
The simplest way to perform what you are colloquially describing as "right-justifying" the matches, i. e. prioritize the matching of later optional subexpressions, is to reverse the "greediness" of the optional components. In Python regex, this is accomplished by adding ? to each quantified element:

(\w+ *\w* *\w*) (\d*?\.*?\d*?) *?(\d*?\.*?\d*?) *?(\d*?\.*?\d*?)\n

Note that your expression is quite liberal and will not validate certain poorly-formed input. If this works for you, great, otherwise you may want to consider sticking certain parts in optional groups, such as (| \d+(?:\.\d+)?) to lazily match a space and number, for example (the construct (|x) is equivalent to ((?:x)??)).

Edit: As Tim pointed out, the shortcomings of this regex entail more than just permissiveness and could invoke catastrophic backtracking if the input is even slightly malformed. I'd recommend something a little more precise if you plan to stick with this method:

(\w+(?: \w+){0,2}) (|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?)\n

It can still match malformed input but at least it's a bit tighter now.


问:
Displaying error message in JSON in web browser
I have an ASP.NET Web API, which calls a java web service. When I run the ASP.NET Web API, I will get a JSON string as an output. Right now, I want to do error handling where when the java web service is down and when I run the API, I want it to show output as {"Error": Java web service is down} (In JSON) instead of a whole chunk of error message which the user will not understand.

Here are my codes:

RestfulClient.cs (model class)

```<code>using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ApiClientJavaWebService.Models
{
public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            //What do i code here?
        }
        return null;
    }
  }
}
</code>```

AdditionController.cs (controller class)

```<code>using ApiClientJavaWebService.Models;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Web.Http;

namespace ApiClientJavaWebService.Controllers
{
public class Temp
{
    public string firstNumber { get; set; }
    public string secondNumber { get; set; }
    public string sum { get; set; }
}

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
    }
  }
}
</code>```

WebApiConfig.cs

```<code>using System;
using System.Web.Http;

namespace ApiClientJavaWebService
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "AdditionApi",
            routeTemplate: "api/serveraddition/{firstNumber}/{secondNumber}",
            defaults: new { action = "Get", controller = "Addition" }
        );

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", "text/html",
            StringComparison.InvariantCultureIgnoreCase, true, "application/json")
        );
    }
  }
}
</code>```

Someone please do help me. Thank you so much.

答:
You will need to include using System.Web.Script.Serialization. </p>

```<code>public async Task<JsonResult> addition(int firstNumber, int secondNumber)
       {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            var result=await response.Content.ReadAsStringAsync();
            return new (JavaScriptSerializer().Serialize(new { Result = result});
        }

        catch (Exception e)
        {
          return new (JavaScriptSerializer().Serialize(new { status =
         "error", message = "Server is not running" });
        }

   }
</code>```

Body:
I have an ASP.NET Web API, which calls a java web service. When I run the ASP.NET Web API, I will get a JSON string as an output. Right now, I want to do error handling where when the java web service is down and when I run the API, I want it to show output as {"Error": Java web service is down} (In JSON) instead of a whole chunk of error message which the user will not understand.

Here are my codes:

RestfulClient.cs (model class)

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ApiClientJavaWebService.Models
{
public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            //What do i code here?
        }
        return null;
    }
  }
}

AdditionController.cs (controller class)

using ApiClientJavaWebService.Models;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Web.Http;

namespace ApiClientJavaWebService.Controllers
{
public class Temp
{
    public string firstNumber { get; set; }
    public string secondNumber { get; set; }
    public string sum { get; set; }
}

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
    }
  }
}

WebApiConfig.cs

using System;
using System.Web.Http;

namespace ApiClientJavaWebService
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "AdditionApi",
            routeTemplate: "api/serveraddition/{firstNumber}/{secondNumber}",
            defaults: new { action = "Get", controller = "Addition" }
        );

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", "text/html",
            StringComparison.InvariantCultureIgnoreCase, true, "application/json")
        );
    }
  }
}

Someone please do help me. Thank you so much.

Body:
You will need to include using System.Web.Script.Serialization.

public async Task<JsonResult> addition(int firstNumber, int secondNumber)
       {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            var result=await response.Content.ReadAsStringAsync();
            return new (JavaScriptSerializer().Serialize(new { Result = result});
        }

        catch (Exception e)
        {
          return new (JavaScriptSerializer().Serialize(new { status =
         "error", message = "Server is not running" });
        }

   }


问:
SCTP server has an abnormal behaviour when connecting with a client
I have this code on a small server that is getting requests from a client using SCTP connection, I keep getting this error every now and then.

```<code>BlockingIOError: [Errno 11] Resource temporarily unavailable
</code>```

I know that I can avoid it by using Try-except but I wanna have a deep understanding of the issue. any help?

my code is here. this is the server

```<code>server = ('', 29168)
sk = sctpsocket_tcp(socket.AF_INET)
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bindx([server])
sk.listen(5)
connection, addr = sk.accept()
while c:
      a,b,c,d = connection.sctp_recv(1024)
      print(c)
</code>```

答: After going again through the SCTP library, I found a closed issue on Github with the solution </p>

Body:
I have this code on a small server that is getting requests from a client using SCTP connection, I keep getting this error every now and then.

BlockingIOError: [Errno 11] Resource temporarily unavailable

I know that I can avoid it by using Try-except but I wanna have a deep understanding of the issue. any help?

my code is here. this is the server

server = ('', 29168)
sk = sctpsocket_tcp(socket.AF_INET)
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bindx([server])
sk.listen(5)
connection, addr = sk.accept()
while c:
      a,b,c,d = connection.sctp_recv(1024)
      print(c)


问:
Calculations based on Region and Cluster query SQL
I've table like this:

```<code>Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3
</code>```

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

```<code>Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5
</code>```

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

答:
Try:  </p>

```<code>SELECT
A."Region", round((A."Region_VALUE"*100/B."CLUSTER_VALUE"),2) AS GROWTH_VALUE,
round((A."Region_VOLUME"*100/B."CLUSTER_VOLUME"),2) AS GROWTH_VOLUME
FROM
  ( SELECT "Region", SUM("Value") AS "Region_VALUE", SUM("Volume") AS "Region_VOLUME"
  FROM cals
  GROUP BY "Region"
  ) A,
  ( SELECT SUM("Value") AS "CLUSTER_VALUE", SUM("Volume") AS "CLUSTER_VOLUME"
  FROM cals
  ) B;
</code>```

Body:
I've table like this:

Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

Body:
Try:

SELECT
A."Region", round((A."Region_VALUE"*100/B."CLUSTER_VALUE"),2) AS GROWTH_VALUE,
round((A."Region_VOLUME"*100/B."CLUSTER_VOLUME"),2) AS GROWTH_VOLUME
FROM
  ( SELECT "Region", SUM("Value") AS "Region_VALUE", SUM("Volume") AS "Region_VOLUME"
  FROM cals
  GROUP BY "Region"
  ) A,
  ( SELECT SUM("Value") AS "CLUSTER_VALUE", SUM("Volume") AS "CLUSTER_VOLUME"
  FROM cals
  ) B;


问:
Select a row from rows with similar data
I hope someone will be able to solve my issue with knex.js

There is a table-"task_history" and it has following columns:
id, task_id, duration, date, start_time, finish_time

Let's say I have three rows inside task_history table:

```<code>row 1 - id(1) task_id(3333), duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time("2017-12-05 00:59:18.943+11")

row 2 - id(2) task_id(3333),  duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

row 3 - id(3) task_id(4444), duration(100), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()
</code>```

As you can see, row 1 and row 2 are almost same except id, finish_time.
row 2 has "null" value for the finish_time column.

When I try the following query it returns me the row2 and row3.

```<code>select * from task_history where date=20171204 and finish_time is null
</code>```

But, that's not what I want. I don't want to get any row if its task_id exists in another row, but also it has value for the finish_time column.

The query should return row 3 only.
But row 1 and 2, because row 1 has finish_time value and the same task_id with the row2.

Thank you in advance!

答:
try DISTINCT ON?..

```<code>select  distinct on (task_id) * from task_history
where date=20171204
order by tastk_id, finish_time  nulls last;
</code>```

Body:
I hope someone will be able to solve my issue with knex.js

There is a table-"task_history" and it has following columns:
id, task_id, duration, date, start_time, finish_time

Let's say I have three rows inside task_history table:

row 1 - id(1) task_id(3333), duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time("2017-12-05 00:59:18.943+11")

row 2 - id(2) task_id(3333),  duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

row 3 - id(3) task_id(4444), duration(100), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

As you can see, row 1 and row 2 are almost same except id, finish_time.
row 2 has "null" value for the finish_time column.

When I try the following query it returns me the row2 and row3.

select * from task_history where date=20171204 and finish_time is null

But, that's not what I want. I don't want to get any row if its task_id exists in another row, but also it has value for the finish_time column.

The query should return row 3 only.
But row 1 and 2, because row 1 has finish_time value and the same task_id with the row2.

Thank you in advance!

Body:
try DISTINCT ON?..

select  distinct on (task_id) * from task_history
where date=20171204
order by tastk_id, finish_time  nulls last;


问:
Django override default form error messages
How can I overwrite the default form error messages (for example: need them in other language) for the all apps in my project (or at least for 1 app)

Thanks!

答:
Also come here from google and what I need is to overwrite the default required messages for all fields in my form rather than passing the error_messages argument everytime I defined new form fields. Also, I'm not ready yet to delve into i18n, this apps not required to be multilingual. The comment in this blog post is the closest to what I want:-

http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/

For all form fields that has required messages, this is what I did:-

```<code>class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for k, field in self.fields.items():
            if 'required' in field.error_messages:
                field.error_messages['required'] = 'You have to field this.'

class MUserForm(MyForm):
    user = forms.CharField(
        label="Username",
    )
    ....
</code>```

Body:
Also come here from google and what I need is to overwrite the default required messages for all fields in my form rather than passing the error_messages argument everytime I defined new form fields. Also, I'm not ready yet to delve into i18n, this apps not required to be multilingual. The comment in this blog post is the closest to what I want:-

http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/

For all form fields that has required messages, this is what I did:-

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for k, field in self.fields.items():
            if 'required' in field.error_messages:
                field.error_messages['required'] = 'You have to field this.'

class MUserForm(MyForm):
    user = forms.CharField(
        label="Username",
    )
    ....


问:
MySQL trigger on insert of text going into infinite loop
There are three tables: users, ap_name_bank_m and ap_name_bank_h. users table has three columns 'name_eng' (name of user in english), 'name_gdn_eng'(name of user's guardian in english) and 'category'.

ap_name_bank_m and ap_name_bank_h are corpus of names for each category of name: 'm' or 'h'.

When a row is updated I want to check if each word of both names in present in either of two tables ap_name_bank_m and ap_name_bank_h.

Whichever count is higher that category will be assigned. The below code which I have written is going into infnite loop and I am getting "MySQL server has gone away error". Can someone tell me where I am wrong?

Assume name_eng and name_gdn_eng will only contain words with spaces and nothing else.

```<code>DELIMITER $$
create trigger set_cat before update on users_table for each row
BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;
declare len int default 0;

set words = concat(new.name_eng,' ',new.name_gdn_eng);

iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;

set words = trim(replace(words,word,''));
END LOOP iterator;

if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END $$
DELIMITER ;
</code>```

答:
I found a better way to do this. No need for loop.</p>

```<code>BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;

set words = concat(new.name_eng,' ',new.name_gdn_eng);

set num_h = (select count(*) from ap_name_bank_h where match(name) against (words in natural language mode));

set num_m = (select count(*) from ap_name_bank_m where match(name) against(words in natural language mode));

/*
iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;

set words = trim(replace(words,word,''));
END LOOP iterator;*/

if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END
</code>```

Body:
There are three tables: users, ap_name_bank_m and ap_name_bank_h. users table has three columns 'name_eng' (name of user in english), 'name_gdn_eng'(name of user's guardian in english) and 'category'.

ap_name_bank_m and ap_name_bank_h are corpus of names for each category of name: 'm' or 'h'.

When a row is updated I want to check if each word of both names in present in either of two tables ap_name_bank_m and ap_name_bank_h.

Whichever count is higher that category will be assigned. The below code which I have written is going into infnite loop and I am getting "MySQL server has gone away error". Can someone tell me where I am wrong?

Assume name_eng and name_gdn_eng will only contain words with spaces and nothing else.

DELIMITER $$
create trigger set_cat before update on users_table for each row
BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;
declare len int default 0;

set words = concat(new.name_eng,' ',new.name_gdn_eng);

iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;

set words = trim(replace(words,word,''));
END LOOP iterator;

if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END $$
DELIMITER ;

Body:
I found a better way to do this. No need for loop.

BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;

set words = concat(new.name_eng,' ',new.name_gdn_eng);

set num_h = (select count(*) from ap_name_bank_h where match(name) against (words in natural language mode));

set num_m = (select count(*) from ap_name_bank_m where match(name) against(words in natural language mode));

/*
iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;

set words = trim(replace(words,word,''));
END LOOP iterator;*/

if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END


问:
How to concatenate columns on top of each other in an array
Say I have the following array:

```<code>a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
</code>```

How can I stack the columns on top of each other to form a single column vector to produce the following?

```<code>b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
</code>```

答:
To stick with the stacking idea, a list of a.T is:

```<code>In [87]: list(a.T)
Out[87]:
[array([1, 3, 1]),
 array([3, 2, 7]),
 array([5, 5, 3]),
 array([2, 6, 6]),
 array([3, 7, 5])]
</code>```

which can then be concatenated on the one axis

```<code>In [90]: np.concatenate(a.T)
Out[90]: array([1, 3, 1, 3, 2, 7, 5, 5, 3, 2, 6, 6, 3, 7, 5])
</code>```

And turn it into a column vector by adding a dimension:

```<code>In [91]: _[:,None]
Out[91]:
array([[1],
       [3],
       [1],
       [3],
       [2],
       [7],
       [5],
       [5],
       [3],
       [2],
       [6],
       [6],
       [3],
       [7],
       [5]])
</code>```

It may be worth noting that a.T, the transpose, is produced by changing the order to F.  So this is a variation on the a.ravel(order='F') approach.  In order to stack the columns it has to reorder the elements of the array (default is 'c' row oriented).

Body:
Say I have the following array:

a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);

How can I stack the columns on top of each other to form a single column vector to produce the following?

b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);

Body:
To stick with the stacking idea, a list of a.T is:

In [87]: list(a.T)
Out[87]:
[array([1, 3, 1]),
 array([3, 2, 7]),
 array([5, 5, 3]),
 array([2, 6, 6]),
 array([3, 7, 5])]

which can then be concatenated on the one axis

In [90]: np.concatenate(a.T)
Out[90]: array([1, 3, 1, 3, 2, 7, 5, 5, 3, 2, 6, 6, 3, 7, 5])

And turn it into a column vector by adding a dimension:

In [91]: _[:,None]
Out[91]:
array([[1],
       [3],
       [1],
       [3],
       [2],
       [7],
       [5],
       [5],
       [3],
       [2],
       [6],
       [6],
       [3],
       [7],
       [5]])

It may be worth noting that a.T, the transpose, is produced by changing the order to F.  So this is a variation on the a.ravel(order='F') approach.  In order to stack the columns it has to reorder the elements of the array (default is 'c' row oriented).


问:
Best practices for ElasticSearch initial bulk import
I'm running a docker setup with ElasticSearch, Logstash, Filebeat and Kibana inspired by the Elastic Docker Compose. I need to initial load 15 GB og logfiles into the system (Filebeat->Logstash->ElasticSearch) but I'm having some issues with performance.

It seems that Filebeat/Logstash is outputting too much work for ElasticSearch. After some time I begin to see a bunch of errors in ElasticSearch like this:

[INFO ][o.e.i.IndexingMemoryController] [f8kc50d] now throttling indexing for shard [log-2017.06.30]: segment writing can't keep up

I've found this old documentation article on how to disable merge throttling: https://www.elastic.co/guide/en/elasticsearch/guide/master/indexing-performance.html#segments-and-merging.

```<code>PUT /_cluster/settings
{
    "transient" : {
        "indices.store.throttle.type" : "none"
    }
}
</code>```

But in current version (ElasticSearch 6) it gives me this error:

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "transient setting [indices.store.throttle.type], not dynamically updateable"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "transient setting [indices.store.throttle.type], not dynamically updateable"
  },
"status": 400
}
</code>```

How can I solve the above issue?

The VM has 4 CPU cores (Intel Xeon E5-2650) and ElasticSearch is assigned 4GB of RAM, Logstash and Kibana 1GB each. Swapping is disabled using "swapoff -a". X-pack and monitoring is enabled. I only have one ES node for this log server. Do I need to have multiple node for this initial bulk import?

EDIT1:

Changing the number_of_replicas and refresh_interval seems to make it perform better. Still testing.

```<code>PUT /log-*/_settings
{
    "index.number_of_replicas" : "0",
    "index.refresh_interval" : "-1"
}
</code>```

答:
Most likely the bottleneck is IO (you can confirm this running iostat, also it would be useful if you post ES monitoring screenshots), so you need to reduce pressure on it.

Default ES configuration causes generation of many index segments during a bulk load. To fix this, for the bulk load, increase index.refresh_interval (or set it to -1) - see doc. The default value is 1 sec, which causes new segment to be created every 1 second, also try to increase batch size and see if it helps.

Also if you use spinning disks,set index.merge.scheduler.max_thread_count to 1. This will allow only one thread to perform segments merging and will reduce contention for IO between segments merging and indexing.

Body:
I'm running a docker setup with ElasticSearch, Logstash, Filebeat and Kibana inspired by the Elastic Docker Compose. I need to initial load 15 GB og logfiles into the system (Filebeat->Logstash->ElasticSearch) but I'm having some issues with performance.

It seems that Filebeat/Logstash is outputting too much work for ElasticSearch. After some time I begin to see a bunch of errors in ElasticSearch like this:

[INFO ][o.e.i.IndexingMemoryController] [f8kc50d] now throttling indexing for shard [log-2017.06.30]: segment writing can't keep up

I've found this old documentation article on how to disable merge throttling: https://www.elastic.co/guide/en/elasticsearch/guide/master/indexing-performance.html#segments-and-merging.

PUT /_cluster/settings
{
    "transient" : {
        "indices.store.throttle.type" : "none"
    }
}

But in current version (ElasticSearch 6) it gives me this error:

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "transient setting [indices.store.throttle.type], not dynamically updateable"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "transient setting [indices.store.throttle.type], not dynamically updateable"
  },
"status": 400
}

How can I solve the above issue?

The VM has 4 CPU cores (Intel Xeon E5-2650) and ElasticSearch is assigned 4GB of RAM, Logstash and Kibana 1GB each. Swapping is disabled using "swapoff -a". X-pack and monitoring is enabled. I only have one ES node for this log server. Do I need to have multiple node for this initial bulk import?

EDIT1:

Changing the number_of_replicas and refresh_interval seems to make it perform better. Still testing.

PUT /log-*/_settings
{
    "index.number_of_replicas" : "0",
    "index.refresh_interval" : "-1"
}


问:
Why do i get the error AttributeError: 'Response' object has no attribute 'type'?
i am trying to download the images from 'https://pokemondb.net/pokedex/national'.I had to open each pokemon and then save the image from there. Here is the code:

```<code>import requests, re
from bs4 import BeautifulSoup
import urllib
import requests
import shutil

#opening the websited
r=requests.get("https://pokemondb.net/pokedex/national")
c=r.content

soup=BeautifulSoup(c,"html.parser")

all=soup.find_all("span",{"class":"infocard-tall"})

for item in all:
    name = item.find("a", {"class":"ent-name"}).text
    print(name)

    #Opening onto the site for each pokemon
    #urllib.request.urlretrieve("https://img.pokemondb.net/artwork/"
           +name.lower() + ".jpg")

    r1 = requests.get("https://img.pokemondb.net/artwork/" + name.lower() +
    ".jpg",
             stream=True, headers={'User-agent': 'Mozilla/5.0'})
#where i save the file to
    fileName = "D:/Desining/Neural
     Networks/PokemonProject/artANN/PokemonANN/Images/"
    #opening the file and saving it
    imageFile = open(fileName + name + ".jpg", 'wb')
    imageFile.write(urllib.request.urlopen(r1).read())
    imageFile.close()
</code>```

I would expect the images to save to the file, however it gives me this error instead:

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-29-500d49264e5f> in <module>()
     14     #opening the file and saving it
     15     imageFile = open(fileName + name + ".jpg", 'wb')
 ---> 16
   imageFile.write(urllib.request.urlopen(r1).response.encoding.read())
     17     imageFile.close()
     18

d:\desining\coding\python\software\lib\urllib\request.py in urlopen(url,
data, timeout, cafile, capath, cadefault, context)
    221     else:
    222         opener = _opener
--> 223     return opener.open(url, data, timeout)
    224
    225 def install_opener(opener):

d:\desining\coding\python\software\lib\urllib\request.py in open(self,
fullurl, data, timeout)
    516
    517         req.timeout = timeout
--> 518         protocol = req.type
    519
    520         # pre-process request

 AttributeError: 'Response' object has no attribute 'type'
</code>```

I have tried updating request but it is already updated to the latest version. I have also tried using the following:
urllib.request.urlretrieve(r1, fileName + name + ".jpg")

instead of:

```<code>imageFile = open(fileName + name + ".jpg", 'wb')
imageFile.write(urllib.request.urlopen(r1).read())
imageFile.close()
</code>```

Thank you in advance.

答:
requests.get returns a response object which can be read with the content attribute. In your code you try then to open the requests response object with urlopen and then read that.

Try this on line 16 instead.

```<code>imageFile.write(r1.content)
</code>```

Body:
i am trying to download the images from 'https://pokemondb.net/pokedex/national'.I had to open each pokemon and then save the image from there. Here is the code:

import requests, re
from bs4 import BeautifulSoup
import urllib
import requests
import shutil

#opening the websited
r=requests.get("https://pokemondb.net/pokedex/national")
c=r.content

soup=BeautifulSoup(c,"html.parser")

all=soup.find_all("span",{"class":"infocard-tall"})

for item in all:
    name = item.find("a", {"class":"ent-name"}).text
    print(name)

    #Opening onto the site for each pokemon
    #urllib.request.urlretrieve("https://img.pokemondb.net/artwork/"
           +name.lower() + ".jpg")

    r1 = requests.get("https://img.pokemondb.net/artwork/" + name.lower() +
    ".jpg",
             stream=True, headers={'User-agent': 'Mozilla/5.0'})
#where i save the file to
    fileName = "D:/Desining/Neural
     Networks/PokemonProject/artANN/PokemonANN/Images/"
    #opening the file and saving it
    imageFile = open(fileName + name + ".jpg", 'wb')
    imageFile.write(urllib.request.urlopen(r1).read())
    imageFile.close()

I would expect the images to save to the file, however it gives me this error instead:

AttributeError                            Traceback (most recent call last)
<ipython-input-29-500d49264e5f> in <module>()
     14     #opening the file and saving it
     15     imageFile = open(fileName + name + ".jpg", 'wb')
 ---> 16
   imageFile.write(urllib.request.urlopen(r1).response.encoding.read())
     17     imageFile.close()
     18

d:\desining\coding\python\software\lib\urllib\request.py in urlopen(url,
data, timeout, cafile, capath, cadefault, context)
    221     else:
    222         opener = _opener
--> 223     return opener.open(url, data, timeout)
    224
    225 def install_opener(opener):

d:\desining\coding\python\software\lib\urllib\request.py in open(self,
fullurl, data, timeout)
    516
    517         req.timeout = timeout
--> 518         protocol = req.type
    519
    520         # pre-process request

 AttributeError: 'Response' object has no attribute 'type'

I have tried updating request but it is already updated to the latest version. I have also tried using the following:
urllib.request.urlretrieve(r1, fileName + name + ".jpg")

instead of:

imageFile = open(fileName + name + ".jpg", 'wb')
imageFile.write(urllib.request.urlopen(r1).read())
imageFile.close()

Thank you in advance.

Body:
requests.get returns a response object which can be read with the content attribute. In your code you try then to open the requests response object with urlopen and then read that.

Try this on line 16 instead.

imageFile.write(r1.content)


问:
Tooltip appears over the element in intro.js mobile view
I am using intro.js for an initial tour of a page on my website. The tour looks good on Desktop but on mobile, the tool-tip appears right above the element it is describing. The user cannot see the element in mobile view as tool-tip appears right above the element. See image below:

I tried customizing the postitions of tool-tip but the output remains the same. The script that I used to customize the position is given:

```<code>var tour = introJs();
tour.setOption('positionPrecedence', ['top', 'bottom', 'left', 'right']);
</code>```

Also, I cannot see the numbers of data-steps above tool-tip. No such problem exists on Desktop version.

Can someone please explain what the issue is?
Thanks in advance!

答:
The source code for the 2.5.0 version states:

```<code>/* Precedence of positions, when auto is enabled */
positionPrecedence: ["bottom", "top", "right", "left"]
</code>```

If you want your customization to work try setting in each step item the
position field to auto as the default position is set to bottom.

e.g:

```<code>tour.setOption('steps', [
    {
      intro: '...'
      position: 'auto'
    }
])

tour.setOption('positionPrecedence', ['top', 'bottom', 'left', 'right'])
</code>```

Also try to set the element property which takes the first element from the document on the given selector.

Body:
I am using intro.js for an initial tour of a page on my website. The tour looks good on Desktop but on mobile, the tool-tip appears right above the element it is describing. The user cannot see the element in mobile view as tool-tip appears right above the element. See image below:

I tried customizing the postitions of tool-tip but the output remains the same. The script that I used to customize the position is given:

var tour = introJs();
tour.setOption('positionPrecedence', ['top', 'bottom', 'left', 'right']);

Also, I cannot see the numbers of data-steps above tool-tip. No such problem exists on Desktop version.

Can someone please explain what the issue is?
Thanks in advance!

Body:
The source code for the 2.5.0 version states:

/* Precedence of positions, when auto is enabled */
positionPrecedence: ["bottom", "top", "right", "left"]

If you want your customization to work try setting in each step item the
position field to auto as the default position is set to bottom.

e.g:

tour.setOption('steps', [
    {
      intro: '...'
      position: 'auto'
    }
])

tour.setOption('positionPrecedence', ['top', 'bottom', 'left', 'right'])

Also try to set the element property which takes the first element from the document on the given selector.


问:
Retrieving YAML from a text field
The serialize method allows an object like a hash to be stored in the database as a YAML string.  However, I recently found myself wanting to have a text field to allow a user to input their own string and have the controller create a hash off of that string.

```<code><%= f.text_field :yaml, :value => '--- \nlast_name: Smith\nfirst_name: Joe\n' %>
</code>```

Yes, I want single quotes: I want to preserve the \n in the display.  But the problem is that, as a result, the resultant string object gets escaped:

```<code>--- \\nlast_name: Smith\\nfirst_name: Joe\\n
</code>```

I run the string through two regexes:  The first replaces the double backslash with a single backslash.  Then next converts \n (two characters) into \n (special single character).

So in my controller:

```<code>yhash = YAML.load(params[:form][:yaml].gsub(/\\\\/, "\\").gsub(/\\n/, "\n"))
</code>```

This now works, but seems awfully convoluted.  Is there a more elegant way for a user to submit yaml?

答:
Are you saying you want the users to be able to write \n to mark the newlines in the yaml they are entering? Because in that case the way you are doing it now with regexps is very straightforward.

The escape sequence \n is a feature of Ruby strings. If you want to implement it in your web form yaml interface too, a regexp is a valid way to do that.

Are you sure you have to do the double-slash replacement? I think it should only show up as double-slash if you do .inspect.

Title: Retrieving YAML from a text field

Body:
The serialize method allows an object like a hash to be stored in the database as a YAML string.  However, I recently found myself wanting to have a text field to allow a user to input their own string and have the controller create a hash off of that string.

<%= f.text_field :yaml, :value => '--- \nlast_name: Smith\nfirst_name: Joe\n' %>

Yes, I want single quotes: I want to preserve the \n in the display.  But the problem is that, as a result, the resultant string object gets escaped:

--- \\nlast_name: Smith\\nfirst_name: Joe\\n

I run the string through two regexes:  The first replaces the double backslash with a single backslash.  Then next converts \n (two characters) into \n (special single character).

So in my controller:

yhash = YAML.load(params[:form][:yaml].gsub(/\\\\/, "\\").gsub(/\\n/, "\n"))

This now works, but seems awfully convoluted.  Is there a more elegant way for a user to submit yaml?


问:
Localizable.strings keys and good practices
For the first time I have to localize an app, and I studied a little the docs, red some tutorials and, of course, met Localizable.strings.

Now, look at this image (this is from one of the tutorials):

The author puts a string on the left and a translation on the right side, and that's ok. Then, he "feeds" NSLocalizedString, passing an "understandable" key (a word or an entire sentence).

Is it considered a bad practice to have a different kind of key, eg. "t1", "t2", "t3", etc, instead of inserting real content as a key? If I have a very large text, this would help me not to have my code full of text.

答: Having a different kind of key is not at all a bad practice. But having a key name similar to the text is a good practice. For eg. If you want to localize this string: "Thank you for using the app. You are a great person." An appropriate key could be "Thanks_text" or "Thanks_message" or "Thanks_label" etc. Its not required to write the full string as a key.</p>


问:
How to use homebrew to downgrade postgresql from 10.1 to 9.6 on Mac OS
My mac has postgresql 10.1 on it, and I need 9.6 for my work website to function on my local machine.  Can't find easy instructions on how to uninstall or downgrade to 9.6. Any help would be appreciated! </p>

答:
I got this issue as well after running brew upgrade. Following commands worked for me:

```<code>brew uninstall postgresql
brew install postgresql@9.6
brew services start postgresql@9.6
brew link postgresql@9.6 --force
</code>```

Body:
I got this issue as well after running brew upgrade. Following commands worked for me:

brew uninstall postgresql
brew install postgresql@9.6
brew services start postgresql@9.6
brew link postgresql@9.6 --force


问:
How to customize rails application template
I tried to split my app in to two versions.
One is use CDN and the other use assets script and css.

For the CDN, Is there anyway I can split all the CDN lines to other file and set link in application.haml to make it clean.

Here the application.haml (or html)

```<code>%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    = csrf_meta_tags
    %link{:href => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css", :rel => "stylesheet"}/
    Optional Theme
    %link{:href => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css", :rel => "stylesheet"}/
    %link{:href => "https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css", :rel => "stylesheet"}/
    %link{:href => "https://cdnjs.cloudflare.com/ajax/libs/admin-lte/2.4.2/css/AdminLTE.css", :rel => "stylesheet"}/
    %link{:href => "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css\n", :rel => "stylesheet"}/
    %link{:href => "https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic", :rel => "stylesheet"}/

    %script{:crossorigin => "anonymous", :integrity => "sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=", :src => "https://code.jquery.com/jquery-3.2.1.min.js"}
    %script{:crossorigin => "anonymous", :integrity => "sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=", :src => "https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.13.0/popper.min.js"}
    %script{:crossorigin => "anonymous", :integrity => "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa", :src => "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"}

    = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag "application", 'data-turbolinks-track': 'reload'

  %body.hold-transition.skin-yellow.sidebar-mini
    .wrapper
      = render "layouts/navigation/header"
      = render "layouts/navigation/sidebar"
      .content-wrapper
        = yield
      = render 'layouts/navigation/footer'
</code>```

答:
You could create a separate controller for the other version that uses separate assets.

Create versionb_controller.rb and update the routes.rb

Add the folder /views/versionb

Add your view /views/versionb/index.html.erb

Lastly, under layouts add your other version's layout and save as /layouts/versionb.html.erb

Body:
I tried to split my app in to two versions.
One is use CDN and the other use assets script and css.

For the CDN, Is there anyway I can split all the CDN lines to other file and set link in application.haml to make it clean.

Here the application.haml (or html)

%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    = csrf_meta_tags
    %link{:href => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css", :rel => "stylesheet"}/
    Optional Theme
    %link{:href => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css", :rel => "stylesheet"}/
    %link{:href => "https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css", :rel => "stylesheet"}/
    %link{:href => "https://cdnjs.cloudflare.com/ajax/libs/admin-lte/2.4.2/css/AdminLTE.css", :rel => "stylesheet"}/
    %link{:href => "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css\n", :rel => "stylesheet"}/
    %link{:href => "https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic", :rel => "stylesheet"}/

    %script{:crossorigin => "anonymous", :integrity => "sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=", :src => "https://code.jquery.com/jquery-3.2.1.min.js"}
    %script{:crossorigin => "anonymous", :integrity => "sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=", :src => "https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.13.0/popper.min.js"}
    %script{:crossorigin => "anonymous", :integrity => "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa", :src => "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.js"}
    %script{:src => "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"}

    = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag "application", 'data-turbolinks-track': 'reload'

  %body.hold-transition.skin-yellow.sidebar-mini
    .wrapper
      = render "layouts/navigation/header"
      = render "layouts/navigation/sidebar"
      .content-wrapper
        = yield
      = render 'layouts/navigation/footer'


问:
java synchronization with executor framework
What's wrong with this code?

```<code>public class SimpleThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2000; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        WorkerThread obj = new WorkerThread();
        System.out.println(obj.getCount());
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String command;
    private volatile static int count;
    public WorkerThread(){
    }
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        try {
            synchronized (this) {
                processCommand();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void processCommand() throws InterruptedException {
        count++;
        System.out.println("count " + count);
        //Thread.sleep(500);
    }

    @Override
    public String toString(){
        return this.command;
    }

    public int getCount(){
        return count;
    }
}
</code>```

I am trying to get the result of count as 2000 and that too at end... What's wrong with my code??

How can I make sure that the count is always incremented in correct order??

When should I use volatile or synchronized block or both??

答:
```<code>    public class IncrementThread implements Runnable{
    private static volatile int count;
    private String name;
    public IncrementThread(String name) {
    this.name = name;
    }
    public void run() {
        synchronized (IncrementThread.class) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //count = count + 1;
            count++;
            System.out.println("count is : "+count);
        }
    }
    public int getCount() {
        return count;
    }
}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestIncrementThread {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Runnable threadToRun = new IncrementThread("Increment");
        for(int i=0;i <2000; i++){
            executor.execute(threadToRun);
        }
        IncrementThread it = new IncrementThread("Increment");
        executor.shutdown();
        if(executor.isTerminated())
            System.out.println("Final count: "+it.getCount());
    }
}

The above code will help you to achieve your goal.
</code>```

Body:
What's wrong with this code?

public class SimpleThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2000; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        WorkerThread obj = new WorkerThread();
        System.out.println(obj.getCount());
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String command;
    private volatile static int count;
    public WorkerThread(){
    }
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        try {
            synchronized (this) {
                processCommand();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void processCommand() throws InterruptedException {
        count++;
        System.out.println("count " + count);
        //Thread.sleep(500);
    }

    @Override
    public String toString(){
        return this.command;
    }

    public int getCount(){
        return count;
    }
}

I am trying to get the result of count as 2000 and that too at end... What's wrong with my code??

How can I make sure that the count is always incremented in correct order??

When should I use volatile or synchronized block or both??


问:
How to get select/dropdown value and pass it to url parameter using laravel?
View

```<code>{!! Form::open(['method'=>'get']) !!}
<div class='col-md-4'>
    <div class="form-group">
        <label for="title">Food</label>
        {!!  Form::select('food', ['1' => 'Western', '0' => 'Eastern'], null, ['class'=>'form-control']) !!}
    </div>
</div>

<div class='col-md-4'>
    <div class="form-group">
        <label for="title">Beverage</label>
        {!!  Form::select('beverage', ['1' => 'Hot', '0' => 'Cold'], null, ['class'=>'form-control']) !!}
    </div>
</div>

<div class="pull-left">
    <a type="button" href="WHAT_SHOULD_I_PUT_HERE_?"></a>
</div>
{!! Form::close() !!}
</code>```

Route

```<code>Route::get("eat/choose/{food}/{beverage}", "Restaurant@eatAndDrink");
</code>```

As you can see my codes in views, I have 2 select/dropdown which is Food and Beverage. How do I get these value (after user choose) and send them in the url?

For example if user choose Food(Western) and Beverage(Hot), I guess the url will be like this?  correct me if im wrong.

答:
In this case, maybe you can redirect to the page using jquery or you can create a form using jquery and submit it dynamically.

For example if you want to redirect you can do like this:

```<code>$('button').click(function(e){
    e.preventDefault();
    var food = $('[name="food"]').val();
    var beverage = $('[name="beverage"]').val();
    var linkURL = '/eat/choose/'+food+'/'+beverage; //Your route url
    window.location.href=linkURL;
});
</code>```

or if you want like submit form you can do like this:

```<code>var food = $('[name="food"]').val();
var beverage = $('[name="beverage"]').val();
var linkURL = '/eat/choose/'+food+'/'+beverage; //Your route url
$('<form action="'+linkURL+'"></form>').appendTo('body').submit();
</code>```

This is just an example you can also add validations if you want but I think you will get an idea. Hope that can help you.
Good luck !

Body:
View

{!! Form::open(['method'=>'get']) !!}

        Food
        {!!  Form::select('food', ['1' => 'Western', '0' => 'Eastern'], null, ['class'=>'form-control']) !!}

        Beverage
        {!!  Form::select('beverage', ['1' => 'Hot', '0' => 'Cold'], null, ['class'=>'form-control']) !!}

{!! Form::close() !!}

Route

Route::get("eat/choose/{food}/{beverage}", "Restaurant@eatAndDrink");

As you can see my codes in views, I have 2 select/dropdown which is Food and Beverage. How do I get these value (after user choose) and send them in the url?

For example if user choose Food(Western) and Beverage(Hot), I guess the url will be like this?  correct me if im wrong.

Body:
In this case, maybe you can redirect to the page using jquery or you can create a form using jquery and submit it dynamically.

For example if you want to redirect you can do like this:

$('button').click(function(e){
    e.preventDefault();
    var food = $('[name="food"]').val();
    var beverage = $('[name="beverage"]').val();
    var linkURL = '/eat/choose/'+food+'/'+beverage; //Your route url
    window.location.href=linkURL;
});

or if you want like submit form you can do like this:

var food = $('[name="food"]').val();
var beverage = $('[name="beverage"]').val();
var linkURL = '/eat/choose/'+food+'/'+beverage; //Your route url
$('<form action="'+linkURL+'"></form>').appendTo('body').submit();

This is just an example you can also add validations if you want but I think you will get an idea. Hope that can help you.
Good luck !


问:
Unable to start mongod service getting connection error message
I am trying to run start mongo from the folder with command

```<code>./mongod --dbpath /opt/mangodb_install/data/db/ --logpath /opt/mangodb_install/mongod.log --port 27018 --fork
</code>```

but i m getting an error

[root@staging bin]# ./mongo MongoDB shell version v3.4.2-rc0
  connecting to: mongodb://127.0.0.1:27017 2017-12-05T12:30:30.978+0530
  W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking
  socket for error after poll), reason: Connection refused
  2017-12-05T12:30:30.979+0530 E QUERY    [thread1] Error: couldn't
  connect to server 127.0.0.1:27017, connection attempt failed :
  connect@src/mongo/shell/mongo.js:237:13 @(connect):1:6 exception:
  connect failed

答:
You changed port from the standard (27017) into 27018. So you must to define the port for mongo.

Try this:

```<code>mongo --port 27018
</code>```

Body:
I am trying to run start mongo from the folder with command

./mongod --dbpath /opt/mangodb_install/data/db/ --logpath /opt/mangodb_install/mongod.log --port 27018 --fork

but i m getting an error

[root@staging bin]# ./mongo MongoDB shell version v3.4.2-rc0
  connecting to: mongodb://127.0.0.1:27017 2017-12-05T12:30:30.978+0530
  W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking
  socket for error after poll), reason: Connection refused
  2017-12-05T12:30:30.979+0530 E QUERY    [thread1] Error: couldn't
  connect to server 127.0.0.1:27017, connection attempt failed :
  connect@src/mongo/shell/mongo.js:237:13 @(connect):1:6 exception:
  connect failed

Body:
You changed port from the standard (27017) into 27018. So you must to define the port for mongo.

Try this:

mongo --port 27018


问:
BASH: If condition uses result from find command to determine which file will be written
I want to list all files in a nested directory, but in that directory has some files which having space in their name. So I wanna write down the paths of which files don't have space in their name and which have in 2 different files.

So far, I just know how to find those having space in their name by this command:

```<code>find /<my directory> -type f -name * *
</code>```

I want something like:

```<code>find /<my directory> -type f
   if [ name has space]
   then > a.txt
   else > b.txt
   fi
</code>```

Thank you in advance.

答:
You can put a condition in a brief -exec.  This is somewhat more complex than you would hope because -exec cannot directly contain shell builtins.

```<code>find "$path" -type f -exec sh -c 'for f; do
    case $f in *\ *) dest=a;; *) dest=b;; esac;
    echo "$f" >>$dest.txt
  done' _ {} +
</code>```

In other words, pass the found files to the following sh -c ... script. (The underscore is to populate $0 with something inside the subshell.)

If the directory tree isn't too deep, perhaps it would be a lot easier to just run find twice.

```<code>find "$path" -type f -name '* *' >a.txt
find "$path" -type f \! -name '* *' >b.txt
</code>```

Body:
I want to list all files in a nested directory, but in that directory has some files which having space in their name. So I wanna write down the paths of which files don't have space in their name and which have in 2 different files.

So far, I just know how to find those having space in their name by this command:

find /<my directory> -type f -name * *

I want something like:

find /<my directory> -type f
   if [ name has space]
   then > a.txt
   else > b.txt
   fi

Thank you in advance.

Body:
You can put a condition in a brief -exec.  This is somewhat more complex than you would hope because -exec cannot directly contain shell builtins.

find "$path" -type f -exec sh -c 'for f; do
    case $f in *\ *) dest=a;; *) dest=b;; esac;
    echo "$f" >>$dest.txt
  done' _ {} +

In other words, pass the found files to the following sh -c ... script. (The underscore is to populate $0 with something inside the subshell.)

If the directory tree isn't too deep, perhaps it would be a lot easier to just run find twice.

find "$path" -type f -name '* *' >a.txt
find "$path" -type f \! -name '* *' >b.txt


问:
Get Usable Co-efficient Weights from Keras/Tensor Flow Model
I've created a classification model using Keras (with tensorFlow backend).  At this point, I'm looking to use model coefficients to create an web API service for my new model.  However, when I attempt to get these weights, these are not as simple as multiply these coefficients * features to get expected results.

My training input matrix is a grayscale image of 128 x 128 = 16,384.

```<code> model.get_weights()
 [array([[[[-0.03603082,  0.1334779 ,  0.10018548, -0.14283592, -0.0429921 ,
       -0.03080634,  0.06451669, -0.09407537,  0.04878693, -0.14003059,
        0.04794825,  0.06447313, -0.01520954, -0.10879657,  0.13521752,
       -0.03230923, -0.01395164,  0.04935856,  0.06434418, -0.02601192,
        0.03416487,  0.08788931,  0.0723172 , -0.12923865,  0.04022292,
       -0.1328591 , -0.05803869, -0.01380468, -0.10409287,  0.14212781,
       -0.08511351, -0.03992498]],

     [[-0.11669005,  0.088085  , -0.......

  len(model.get_weights())
  #10

  len(model.get_weights()[0])
  #3

  len(model.get_weights()[0][0])
  #3

  len(model.get_weights()[0][0][0])
  #1

  len(model.get_weights()[0][0][0][0])
  #32

  len(model.get_weights()[0][0][0][0][0])
  #TypeError: object of type 'numpy.float32' has no len()
</code>```

If I take all those level 10 * 3 * 3 * 1 * 32 = 2880.

So this is telling me the numpy array has 5 dimensions with only 2880 values?  Maybe I'm missing something here or perhaps a much easier way.  Any thoughts on how this could be applied to a new test image via an API?

答:
The first layer has 288 (3*3*1*32) parameters, but following layers usually have much more parameters especially if your model is CNN.

To print numbers of parameters for all layers (which include bias terms):

```<code>weights = model.get_weights()
for i in range(len(weights)):
    print(weights[i].shape)
</code>```

Alternatively you can check the number of parameters by model.summary()

To apply the model to new images, just run model.predict(image)

Body:
I've created a classification model using Keras (with tensorFlow backend).  At this point, I'm looking to use model coefficients to create an web API service for my new model.  However, when I attempt to get these weights, these are not as simple as multiply these coefficients * features to get expected results.

My training input matrix is a grayscale image of 128 x 128 = 16,384.

 model.get_weights()
 [array([[[[-0.03603082,  0.1334779 ,  0.10018548, -0.14283592, -0.0429921 ,
       -0.03080634,  0.06451669, -0.09407537,  0.04878693, -0.14003059,
        0.04794825,  0.06447313, -0.01520954, -0.10879657,  0.13521752,
       -0.03230923, -0.01395164,  0.04935856,  0.06434418, -0.02601192,
        0.03416487,  0.08788931,  0.0723172 , -0.12923865,  0.04022292,
       -0.1328591 , -0.05803869, -0.01380468, -0.10409287,  0.14212781,
       -0.08511351, -0.03992498]],

     [[-0.11669005,  0.088085  , -0.......

  len(model.get_weights())
  #10

  len(model.get_weights()[0])
  #3

  len(model.get_weights()[0][0])
  #3

  len(model.get_weights()[0][0][0])
  #1

  len(model.get_weights()[0][0][0][0])
  #32

  len(model.get_weights()[0][0][0][0][0])
  #TypeError: object of type 'numpy.float32' has no len()

If I take all those level 10 * 3 * 3 * 1 * 32 = 2880.

So this is telling me the numpy array has 5 dimensions with only 2880 values?  Maybe I'm missing something here or perhaps a much easier way.  Any thoughts on how this could be applied to a new test image via an API?

Body:
The first layer has 288 (3*3*1*32) parameters, but following layers usually have much more parameters especially if your model is CNN.

To print numbers of parameters for all layers (which include bias terms):

weights = model.get_weights()
for i in range(len(weights)):
    print(weights[i].shape)

Alternatively you can check the number of parameters by model.summary()

To apply the model to new images, just run model.predict(image)


问:
Printing an Array List full of a new type of object
I am working on a Java program, where I have an ArrayList called "CD" and inside this CD there are "Songs", and each song is an object in my Song class, and it has the arguments: String artist, String album, and int year. Any general suggestions about how to print this such that it also prints the contents of each song?

P.S. I know there are similar questions on here but I am still having trouble getting it to print exactly what I am wanting it to, and I have tried using iterator.

Thanks for all help in advance!

答:
Simply use foreach

```<code>for (Song s:CD) {
    System.out.println(s);
}
</code>```

And in your Song class, add the following:

```<code>public String toString() {
    return artist+" "+album+" "+year;
}
</code>```

When you print an object, the printer first looks to the toString method, which is inherited by every object from the class Object. Overriding the toString method, changes representation of the given object.

Lastly, I'd recommend your songs had a field "name". I mean, isn't that the most important part of the printable data?

Body:
Simply use foreach

for (Song s:CD) {
    System.out.println(s);
}

And in your Song class, add the following:

public String toString() {
    return artist+" "+album+" "+year;
}

When you print an object, the printer first looks to the toString method, which is inherited by every object from the class Object. Overriding the toString method, changes representation of the given object.

Lastly, I'd recommend your songs had a field "name". I mean, isn't that the most important part of the printable data?


问:
how to count number values' frequency using python pandas

I want to count the frequency of number values of csv data in my computer.
I tried this code:

```<code>import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)
</code>```

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

答:
Are you already trying:</p>

```<code>df['column name'].value_counts()
</code>```

Body:
I want to count the frequency of number values of csv data in my computer.
I tried this code:

import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

Body:
Are you already trying:

df['column name'].value_counts()


问:
Tokenize a String and Keep Delimiters Using Regular Expression in C++
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

```<code>((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)
</code>```

Test String

```<code>a < b | c | d > e >> f && ((g) || h) ; i
</code>```

Expected Matches

```<code>a < b | c | d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

Actual Matches

```<code>a < b
|
 c
|
 d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

I am trying to implement a custom tokenizer for a program in C++.

Example Code

```<code>std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}
</code>```

Example Driver Code

```<code>//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;
</code>```

Produced Output

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]
</code>```

What I Want the Output to be

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]
</code>```

答:
I suggest a splitting approach by passing {-1,0} to the sregex_token_iterator to collect both non-matched and matched substrings, and using a much simpler regex like &&|\|\||[;()] while discarding the empty substrings (that are due to the way strings are split when consecutive matches are found):

```<code>std::regex rx(R"(&&|\|\||[();])");
std::string exp = "a < b | c | d > e >> f && ((g) || h) ; i";
std::sregex_token_iterator srti(exp.begin(), exp.end(), rx, {-1, 0});
std::vector<std::string> tokens;
std::remove_copy_if(srti, std::sregex_token_iterator(),
                std::back_inserter(tokens),
                [](std::string const &s) { return s.empty(); });
for( auto & p : tokens ) std::cout <<"'"<< p <<"'"<< std::endl;
</code>```

See the C++ demo, output:

```<code>'a < b | c | d > e >> f '
'&&'
' '
'('
'('
'g'
')'
' '
'||'
' h'
')'
' '
';'
' i'
</code>```

Special credit for the empty string removal code goes to Jerry Coffin.

Body:
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)

Test String

a  e >> f && ((g) || h) ; i

Expected Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

Actual Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

I am trying to implement a custom tokenizer for a program in C++.

Example Code

std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}

Example Driver Code

//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;

Produced Output

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]

What I Want the Output to be

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]

Body:
I suggest a splitting approach by passing {-1,0} to the sregex_token_iterator to collect both non-matched and matched substrings, and using a much simpler regex like &&|\|\||[;()] while discarding the empty substrings (that are due to the way strings are split when consecutive matches are found):

std::regex rx(R"(&&|\|\||[();])");
std::string exp = "a < b | c | d > e >> f && ((g) || h) ; i";
std::sregex_token_iterator srti(exp.begin(), exp.end(), rx, {-1, 0});
std::vector<std::string> tokens;
std::remove_copy_if(srti, std::sregex_token_iterator(),
                std::back_inserter(tokens),
                [](std::string const &s) { return s.empty(); });
for( auto & p : tokens ) std::cout <<"'"<< p <<"'"<< std::endl;

See the C++ demo, output:

'a < b | c | d > e >> f '
'&&'
' '
'('
'('
'g'
')'
' '
'||'
' h'
')'
' '
';'
' i'

Special credit for the empty string removal code goes to Jerry Coffin.


问:
C++ Why I can't use the loop: while(fin>>x) for twice
I have some question about file I/O in c++.
When I use while(fin>>x) for twice in my program and cout two times, only the first time will display on my screen.

And my test.txt is:

```<code>I like eat banana
I like eat apple
</code>```

My code:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(){
  ifstream fin;
  fin.open("test.txt");
  if(fin.fail()){
    cout<<"Error!"<<endl;
    exit(1);
  }
      else{
    int i=0,j=0;
    string x,y,a[20],b[20];
    while(fin>>x){
    a[i]=x;
    i++;
    }
    fin.
    while(fin>>y){
    b[j]=y;
    j++;
    }
for(int q=0;q<20;q++){
cout<<a[q]<<" ";
}
for(int w=0;w<20;w++){
cout<<b[w]<<" ";
}
  }
  fin.close();
  return 0;
}
</code>```

答: The reason making fin >> x return false (and exiting the first loop) still exists when you write fin >> y right afterwards. Hence, once fin >> x-loop is left, fin >> y-loop will not be entered.

Body:
I have some question about file I/O in c++.
When I use while(fin>>x) for twice in my program and cout two times, only the first time will display on my screen.

And my test.txt is:

I like eat banana
I like eat apple

My code:

#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(){
  ifstream fin;
  fin.open("test.txt");
  if(fin.fail()){
    cout<<"Error!"<<endl;
    exit(1);
  }
      else{
    int i=0,j=0;
    string x,y,a[20],b[20];
    while(fin>>x){
    a[i]=x;
    i++;
    }
    fin.
    while(fin>>y){
    b[j]=y;
    j++;
    }
for(int q=0;q<20;q++){
cout<<a[q]<<" ";
}
for(int w=0;w<20;w++){
cout<<b[w]<<" ";
}
  }
  fin.close();
  return 0;
}