问:
Got string Url but the url have "\/".How to get each correct value in string like array type swift3
I got a string from server,but the url string looks strange, and it also like array type. I don't know how to get each value. Sorry I am beginner.Thanks.

```<code>let string:String = "[\"http:\/\/aaa.com\/user\/head\/111.jpg?1495612713419\",\"http:\/\/aaa.com\/user\/head\/222.jpg?1496215823622\",\"http:\/\/aaa.com\/user\/head\/333.jpg?1495251220764\",\"http:\/\/aaa.com\/user\/head\/444.jpg?1495773694237\",\"http:\/\/aaa.com\/user\/head\/555.jpg?1495597839001\"]"

let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()

for a in tempArr {
    var b = a.replacingOccurrences(of: "\"", with: "")
    b = b.replacingOccurrences(of: "[", with: "")
    b = b.replacingOccurrences(of: "]", with: "")
    stringArr.append(b)
}
print(stringArr)
</code>```

print log

```<code>["http:\\/\\/aaa.com\\/user\\/head\\/111.jpg?1495612713419", "http:\\/\\/aaa.com\\/user\\/head\\/222.jpg?1496215823622", "http:\\/\\/aaa.com\\/user\\/head\\/333.jpg?1495251220764", "http:\\/\\/aaa.com\\/user\\/head\\/444.jpg?1495773694237", "http:\\/\\/aaa.com\\/user\\/head\\/555.jpg?1495597839001"]
</code>```

答:
The server is sending the url of images that converted into the string and string have by default property to add \ in Json so just convert the string into the url the \ will auto remove.
eg.
let url = NSURL(string: urlstring)
print("the url = (url)")

Thanks

Body:
I got a string from server,but the url string looks strange, and it also like array type. I don't know how to get each value. Sorry I am beginner.Thanks.

let string:String = "[\"http:\/\/aaa.com\/user\/head\/111.jpg?1495612713419\",\"http:\/\/aaa.com\/user\/head\/222.jpg?1496215823622\",\"http:\/\/aaa.com\/user\/head\/333.jpg?1495251220764\",\"http:\/\/aaa.com\/user\/head\/444.jpg?1495773694237\",\"http:\/\/aaa.com\/user\/head\/555.jpg?1495597839001\"]"

let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()

for a in tempArr {
    var b = a.replacingOccurrences(of: "\"", with: "")
    b = b.replacingOccurrences(of: "[", with: "")
    b = b.replacingOccurrences(of: "]", with: "")
    stringArr.append(b)
}
print(stringArr)

print log

["http:\\/\\/aaa.com\\/user\\/head\\/111.jpg?1495612713419", "http:\\/\\/aaa.com\\/user\\/head\\/222.jpg?1496215823622", "http:\\/\\/aaa.com\\/user\\/head\\/333.jpg?1495251220764", "http:\\/\\/aaa.com\\/user\\/head\\/444.jpg?1495773694237", "http:\\/\\/aaa.com\\/user\\/head\\/555.jpg?1495597839001"]


来源: stackexchange

问:
Simple Javascript enable/disable button program?
I want a simple program that basically enables/disables buttons as each button is pressed.
So, there are three buttons. The left button is enabled at the start of the program and I want to disable it and enable the button next to it onclick. The same when I press on the second button.

Can anyone show me where I'm going wrong in my code?

```<code><html>
<head>
    <button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button>
</head>

<body>
<script>
var number = '';

function func(number)

if(number == '1'){ //Sets button setting to disabled or enabled when wanted
after particular parts of the program are run.
                document.getElementById('func1').disabled = true;
                document.getElementById('func2').disabled = false;
                document.getElementById('output').disabled = true;
             }

         else if(number == '2'){
            document.getElementById('func1').disabled = true;
            document.getElementById('func2').disabled = true;
            document.getElementById('func3').disabled = false;
         }

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

Thanks again  :)

答:
I think better to use something universal, like this:</p>

```<code><html>
<body>
    <button class="myButton" onclick="myHandler(this)" >func 1</button>
    <button class="myButton" onclick="myHandler(this)" disabled>func 2</button>
    <button class="myButton" onclick="myHandler(this)" disabled>func 3</button>
    <script>
    function myHandler (e) {
        // Toggle disabled property of current button.
        e.disabled = !e.disabled;
        // Toggle disabled property for next sibling if it has class 'myButton'.
        if (e.nextElementSibling.className === 'myButton') {
            e.nextElementSibling.disabled = !e.nextElementSibling.disabled;
        // Otherwise toggle first button with class 'myButton'.
        } else {
            var b = document.getElementsByClassName('myButton')[0];
            b.disabled = !b.disabled;
        }
    }
    </script>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want a simple program that basically enables/disables buttons as each button is pressed.
So, there are three buttons. The left button is enabled at the start of the program and I want to disable it and enable the button next to it onclick. The same when I press on the second button.

Can anyone show me where I'm going wrong in my code?

    <button id="func1" onclick="func(1)">func 1</button>
    <button id="func2" disabled="false" onclick="func(2)">func 2</button>
    <button id="func3" disabled="false" onclick="func()">func 3</button>

Thanks again  :)

Body:
I think better to use something universal, like this:

<html>
<body>
    <button class="myButton" onclick="myHandler(this)" >func 1</button>
    <button class="myButton" onclick="myHandler(this)" disabled>func 2</button>
    <button class="myButton" onclick="myHandler(this)" disabled>func 3</button>
    <script>
    function myHandler (e) {
        // Toggle disabled property of current button.
        e.disabled = !e.disabled;
        // Toggle disabled property for next sibling if it has class 'myButton'.
        if (e.nextElementSibling.className === 'myButton') {
            e.nextElementSibling.disabled = !e.nextElementSibling.disabled;
        // Otherwise toggle first button with class 'myButton'.
        } else {
            var b = document.getElementsByClassName('myButton')[0];
            b.disabled = !b.disabled;
        }
    }
    </script>
</body>
</html>


问:
Some strings in a array match another array
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}
</code>```

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

答:
```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
    var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

    for user in usersInData {
        if verifiedUsers.contains(user){
        print("\(user) is a special user")
    } else {
        print("\(user) is a regular user")
    }
    }
</code>```

try this. it ll work

Body:
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

Body:
var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
    var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

    for user in usersInData {
        if verifiedUsers.contains(user){
        print("\(user) is a special user")
    } else {
        print("\(user) is a regular user")
    }
    }

try this. it ll work


问:
backup of Domain controller on Jboss eap6
I have 4 remote jboss eap6 with deployed application. First one is working as Domain Controller. In host.xml I declared backup of DC (example):

```<code><domain-controller>
    <remote security-realm="ManagementRealm">
          <discovery-options>
              <static-discovery name="primary" host="172.16.81.100" port="9999"/>
              <static-discovery name="backup" host="172.16.81.101" port="9999"/>
          </discovery-options>
    </remote>
</domain-controller>
</code>```

For more info: link

What if 172.16.81.100 will be down? Is there any place on 172.16.81.101 to put actual copy of domain.xml with configuration of app-profiles and locally deployed HornetQ server?
Is there possibility to change configuration of connection factories of any working profile during switching to backup?

答: When you start "172.16.81.101" with --backup option domain.xml from DC will be cashed at remote HC under configuration directory with name 'domain.cached-remote.xml'. Once you reload HC it will act as DC for rest of the HC's. Can you please be specific what connection factory changes you want to done in cashed domain.xml file.</p>

Body:
I have 4 remote jboss eap6 with deployed application. First one is working as Domain Controller. In host.xml I declared backup of DC (example):

<domain-controller>
    <remote security-realm="ManagementRealm">
          <discovery-options>
              <static-discovery name="primary" host="172.16.81.100" port="9999"/>
              <static-discovery name="backup" host="172.16.81.101" port="9999"/>
          </discovery-options>
    </remote>
</domain-controller>

For more info: link

What if 172.16.81.100 will be down? Is there any place on 172.16.81.101 to put actual copy of domain.xml with configuration of app-profiles and locally deployed HornetQ server?
Is there possibility to change configuration of connection factories of any working profile during switching to backup?


问:
Microsoft Installer Appears to be behind updated Code-base
I am developing a C# .NET desktop app in a team and we use TFS to do versioning. We work on our individual machine and give the build(make Setup) from a machine where no one works.

It's happening that, every now and then a change we recently checked in does not appear in the setup file created after getting the latest version.
I am quite sure about getting latest version, because the last build I made had changes in only one of the file and i verified that this was updated properly.

Is there some issue as to why the setup file created always seems to be a bit behind. Is it using codes that last compiled successfully and not the latest. I can also assure you that there were no compile error.

答:
Sounds like you're running into a wonderful problem known as "Checking Binaries Into Source Control"!

You're best best is to always do a clean/build before each checkin. VS2008 has a nasty habit of not wanting to build from TFS if you end up with an older checkin. Doing a clean/rebuild all should do the trick.

ContentLicense: CC BY-SA 2.5


问:
Bootstrap modal does not popup but pushes html content
Modal content displays fine when triggered by a clicking button via Ajax. However, instead of the modal popping up and making the entire page behind it grey and inactive the modal content appears within the HTML content and pushes the other contents down. I had run a similar modal on a different framework (Shiny) other than rails and it worked fine. I came across a similar question: Twitter Bootstrap modal pushes html content to the left. The working solution was do this in CSS: html{overflow:hidden;height:100%;} and

```<code>body{overflow:auto;
  height:100%;}
</code>```

which I tried but did not work. Other similar posts conclude that issues are due to bugs in Bootstrap and suggest to modify bootstraps source code but I suppose they were fixed since the posts date like more than 2 years ago.

My code:
/app/assets/javascripts/application.js

```<code>//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require d3
//= require_tree .
</code>```

app/views/indicators/index.html.erb

```<code><%= link_to 'Add release', new_release_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'} %>
<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
</code>```

/app/controllers/indicators_controller.rb

```<code>def new_release
    respond_to do |format|
      format.html
      format.js
    end
  end
</code>```

app/views/indicators/new_release.js.erb

```<code>$("#modal-window").html("<%= escape_javascript(render 'indicators/indicator_modal') %>");
$("#modal-window").modal('show');
</code>```

/app/views/indicators/_indicator_modal.html.erb

```<code><div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
   <h3 id="myModalLabel">Modal header</h3>
 </div>
 <div class="modal-body">
   **here comes whatever you want to show!**
 </div>
 <div class="modal-footer">
   <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
   <button class="btn btn-primary">Save changes</button>
 </div>
</code>```

Could it be a Rails specific issue? How can I make the modal pop-up?

答:
If your using bootstrap gem try to add following line to /app/assets/javascripts/application.js

here are the https://github.com/twbs/bootstrap-sass

```<code>//= require bootstrap-sprockets
</code>```

or else if manually using boostrap by using source code try to add below file to javascript directory in your application

```<code>bootstrap/js/modal.js
</code>```

Body:
Modal content displays fine when triggered by a clicking button via Ajax. However, instead of the modal popping up and making the entire page behind it grey and inactive the modal content appears within the HTML content and pushes the other contents down. I had run a similar modal on a different framework (Shiny) other than rails and it worked fine. I came across a similar question: Twitter Bootstrap modal pushes html content to the left. The working solution was do this in CSS: html{overflow:hidden;height:100%;} and

body{overflow:auto;
  height:100%;}

which I tried but did not work. Other similar posts conclude that issues are due to bugs in Bootstrap and suggest to modify bootstraps source code but I suppose they were fixed since the posts date like more than 2 years ago.

My code:
/app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require d3
//= require_tree .

app/views/indicators/index.html.erb

<%= link_to 'Add release', new_release_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'} %>

/app/controllers/indicators_controller.rb

def new_release
    respond_to do |format|
      format.html
      format.js
    end
  end

app/views/indicators/new_release.js.erb

$("#modal-window").html("<%= escape_javascript(render 'indicators/indicator_modal') %>");
$("#modal-window").modal('show');

/app/views/indicators/_indicator_modal.html.erb

   <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

   **here comes whatever you want to show!**

   <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
   <button class="btn btn-primary">Save changes</button>

Could it be a Rails specific issue? How can I make the modal pop-up?

Body:
If your using bootstrap gem try to add following line to /app/assets/javascripts/application.js

here are the https://github.com/twbs/bootstrap-sass

//= require bootstrap-sprockets

or else if manually using boostrap by using source code try to add below file to javascript directory in your application

bootstrap/js/modal.js


问:
DCOS/Mesos doesn't unreserve resources on framework delete
Hi after delete of a framework (e.g. Cassandra or Kafka) the resources for them are still reserved. This makes me impossible to install another framework because of lack of free resources.

Using this to check:

```<code>    curl master.mesos/mesos/slaves
    ....
      "reserved_resources": {
      "cassandra-role": {
        "disk": 10240.0,
        "mem": 5376.0,
        "gpus": 0.0,
        "cpus": 1.5,
        "ports": "[7000-7001, 7199-7199, 9001-9001, 9042-9042, 9160-9160]"
      }
    },
    "unreserved_resources": {
      "disk": 32503.0,
      "mem": 567.0,
      "gpus": 0.0,
      "cpus": 0.5,
      "ports": "[1025-2180, 2182-3887, 3889-5049, 5052-6999, 7002-7198, 7200-8079, 8082-8180, 8182-9000, 9002-9041, 9043-9159, 9161-32000]"
    }
</code>```

How do I can free these resources and is it normal that Mesos doesn't unreserve them on a framework deletion?

答:
You can use Janitor as described in https://dcos.io/docs/1.8/usage/managing-services/uninstall/

The deletion of a framework and the unreservation of resources are two different things.

Body:
Hi after delete of a framework (e.g. Cassandra or Kafka) the resources for them are still reserved. This makes me impossible to install another framework because of lack of free resources.

Using this to check:

    curl master.mesos/mesos/slaves
    ....
      "reserved_resources": {
      "cassandra-role": {
        "disk": 10240.0,
        "mem": 5376.0,
        "gpus": 0.0,
        "cpus": 1.5,
        "ports": "[7000-7001, 7199-7199, 9001-9001, 9042-9042, 9160-9160]"
      }
    },
    "unreserved_resources": {
      "disk": 32503.0,
      "mem": 567.0,
      "gpus": 0.0,
      "cpus": 0.5,
      "ports": "[1025-2180, 2182-3887, 3889-5049, 5052-6999, 7002-7198, 7200-8079, 8082-8180, 8182-9000, 9002-9041, 9043-9159, 9161-32000]"
    }

How do I can free these resources and is it normal that Mesos doesn't unreserve them on a framework deletion?


问:
Repeat state until it doesn't change / is stable
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

```<code>Eq s => State s () -> State s ()
</code>```

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

答:
Taking inspiration from https://stackoverflow.com/a/44378096/1319998 and https://stackoverflow.com/a/23924238/1319998, you can do this out of State but using some function monad magic...

```<code>untilStable :: Eq a => (a -> a) -> a -> a
untilStable = until =<< ((==) =<<)
</code>```

... extracting the s -> s from a state using execState

```<code>untilStable (execState stateTransformToRunRepeatedly) initialState
</code>```

Body:
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

Eq s => State s () -> State s ()

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

Body:
Taking inspiration from https://stackoverflow.com/a/44378096/1319998 and https://stackoverflow.com/a/23924238/1319998, you can do this out of State but using some function monad magic...

untilStable :: Eq a => (a -> a) -> a -> a
untilStable = until =<< ((==) =<<)

... extracting the s -> s from a state using execState

untilStable (execState stateTransformToRunRepeatedly) initialState


问:
Cassandra Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY
This is the query I used to create the table:

```<code>CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (timestamp, msguuid));
</code>```

then I create a materialized view:

```<code>CREATE MATERIALIZED VIEW test.comments_by_page AS
    SELECT *
    FROM test.comments
    WHERE page IS NOT NULL AND msguuid IS NOT NULL
    PRIMARY KEY (page, timestamp, msguuid)
    WITH CLUSTERING ORDER BY (msguuid DESC);
</code>```

I want to get the last 50 rows sorted by timestamp in ascending order.

This is the query I'm trying:

SELECT * FROM test.comments_by_page WHERE page = 'test' AND timestamp < 1496707057 ORDER BY timestamp ASC LIMIT 50;

which then gives this error: InvalidRequest: code=2200 [Invalid query] message="Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY"

How can I accomplish this?

答:
Materialized View rules are basically the same of "standard" tables ones. If you want a specific order you must specify that in the clustering key.

So you have to put your timestamp into the clustering section.

Body:
This is the query I used to create the table:

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (timestamp, msguuid));

then I create a materialized view:

CREATE MATERIALIZED VIEW test.comments_by_page AS
    SELECT *
    FROM test.comments
    WHERE page IS NOT NULL AND msguuid IS NOT NULL
    PRIMARY KEY (page, timestamp, msguuid)
    WITH CLUSTERING ORDER BY (msguuid DESC);

I want to get the last 50 rows sorted by timestamp in ascending order.

This is the query I'm trying:

SELECT * FROM test.comments_by_page WHERE page = 'test' AND timestamp < 1496707057 ORDER BY timestamp ASC LIMIT 50;

which then gives this error: InvalidRequest: code=2200 [Invalid query] message="Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY"

How can I accomplish this?


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
```<code>List<string> nameslist = new List<string> {"one", "two", "three"} ?
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?


问:
Retrieving variables from a text file through a hashmap
I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.

If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.

Thank-you so much :D

答:
You can use java.util.HashMap to store user words and related translations:

```<code>String userWord = null;
        String translation = null, translation1 = null;

        Map<String, String[]> map = new HashMap();
        map.put(userWord, new String[] { translation, translation1 });

        String[] translations = map.get(userWord);
</code>```

This map lets you map single userWord to multiple translations.

Body:
You can use java.util.HashMap to store user words and related translations:

String userWord = null;
        String translation = null, translation1 = null;

        Map<String, String[]> map = new HashMap();
        map.put(userWord, new String[] { translation, translation1 });

        String[] translations = map.get(userWord);

This map lets you map single userWord to multiple translations.


问:
How to get data from firebase in c# mvc web project?
I am building a website using c# mvc and firebase. Is there any methods to access firebase data from c# controller?</p>

答:
Here's an answer from a similar question: https://stackoverflow.com/a/41676797/8094831

That answer provides a list of several libraries to choose from:

FireSharp - An asynchronous .Net client library for Firebase

FirebaseSharp - A C# client for Firebase.io

firebase-database-dotnet - C# library for Firebase Realtime Database

Firebase Database REST API - The REST API for Firebase


问:
Auto attachment file for email service c# asp.net
I have generated a PDF file from my gridview. My task is to send the PDF file that I have generated to a specific email without the user to use the upload control and select the PDF file I generated. I am able to do the normal email with the user manually browse and select the PDF as attachment. Is there a way to achieve the auto attachment of a PDF file to the email?

```<code>SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        this.Page.Controls.Add(SqlDataSource1);
        SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlDataSource1.SelectCommand = "SELECT Id, msgContent, msgDate from Message where msgDate between '" + dateFrom + "' and '" + dateTo + "'";
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
</code>```

This my data binding to the gridview.

```<code>StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlworker = new HTMLWorker(pdfDoc);

        using (MemoryStream ObjememoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
            pdfDoc.Open();
            htmlworker.Parse(sr);
            pdfDoc.Close();
            byte[] Filebytes = ObjememoryStream.ToArray();
            ObjememoryStream.Close();
            using (MemoryStream inputData = new MemoryStream(Filebytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string PDFFileword = txtPassword.Text;//you can also generate Dynamic word
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                    Filebytes = outputData.ToArray();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(Filebytes);
                    Response.End();
                    GridView1.AllowPaging = true;
                    GridView1.DataBind();
                }
            }
        }
</code>```

This is the way I generate the PDF file.

```<code>using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            }
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
        }
</code>```

This is the way I am sending email by upload control the attachment file. "fuAttachment" is the ID of my upload control, is there a way to make the attachment became automatically?

答:
You just need to create new Attachment instance and add it to the collection of attatchments in mailmessage instance like this.

if you have file physically stored on hard drive and you know the path then:

```<code>Attachment attachment = new Attachment("FILE_PATH",
                     MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);
</code>```

if you have byte array in memory then:

```<code>Stream stream = new MemoryStream(byteArray);
Attachment attachment = new Attachment(stream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);
</code>```

if you have stream then:

```<code>Attachment attachment = new Attachment(fileStream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have generated a PDF file from my gridview. My task is to send the PDF file that I have generated to a specific email without the user to use the upload control and select the PDF file I generated. I am able to do the normal email with the user manually browse and select the PDF as attachment. Is there a way to achieve the auto attachment of a PDF file to the email?

SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        this.Page.Controls.Add(SqlDataSource1);
        SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlDataSource1.SelectCommand = "SELECT Id, msgContent, msgDate from Message where msgDate between '" + dateFrom + "' and '" + dateTo + "'";
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();

This my data binding to the gridview.

StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlworker = new HTMLWorker(pdfDoc);

        using (MemoryStream ObjememoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
            pdfDoc.Open();
            htmlworker.Parse(sr);
            pdfDoc.Close();
            byte[] Filebytes = ObjememoryStream.ToArray();
            ObjememoryStream.Close();
            using (MemoryStream inputData = new MemoryStream(Filebytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string PDFFileword = txtPassword.Text;//you can also generate Dynamic word
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                    Filebytes = outputData.ToArray();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(Filebytes);
                    Response.End();
                    GridView1.AllowPaging = true;
                    GridView1.DataBind();
                }
            }
        }

This is the way I generate the PDF file.

using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            }
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
        }

This is the way I am sending email by upload control the attachment file. "fuAttachment" is the ID of my upload control, is there a way to make the attachment became automatically?

Body:
You just need to create new Attachment instance and add it to the collection of attatchments in mailmessage instance like this.

if you have file physically stored on hard drive and you know the path then:

Attachment attachment = new Attachment("FILE_PATH",
                     MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);

if you have byte array in memory then:

Stream stream = new MemoryStream(byteArray);
Attachment attachment = new Attachment(stream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);

if you have stream then:

Attachment attachment = new Attachment(fileStream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);


问:
Trouble forming post to get Azure token using Guzzle6 (Error: AADSTS90014)
We're moving from Guzzle3 to Guzzle6. I wrote a process to authenticate and access the Azure Management API that worked fine in Guzzle3. However, I'm unable to figure out how to get it to work in Guzzle6. The purpose is to get the access token which is then use in subsequent requests to the Azure Management API.

Original Code:

```<code>$client = new Guzzle\Http\Client();
$request = $client->post("https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        'Accept' => 'application/json',
    ),
    Array(
        'grant_type'    => 'client_credentials',
        'client_id'     => $application_id,
        'client_secret' => $application_secret,
        'resource'      => 'https://management.core.windows.net/',
    )
);

$response = $request->send();
$body = $response->getBody(true);
</code>```

New code I'm working on:

```<code>$client = new GuzzleHttp\Client();
$response = $client->request(
    'POST',
    "https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        GuzzleHttp\RequestOptions::JSON => Array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $application_id,
            'client_secret' => $application_secret,
            'resource'      => 'https://management.core.windows.net/',
        )
    )
);
</code>```

I've tried so many variations with no luck. I would be grateful for any insight anyone could provide.

Thanks!

答:
Well, I guess posting on here helped guide my thoughts on this. I was able to get it to work. For anyone else in the same boat, here's the solution I came up with:</p>

```<code>$client = new GuzzleHttp\Client();
$response = $client->request(
    'POST',
    "https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        'form_params' => Array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $application_id,
            'client_secret' => $application_secret,
            'resource'      => 'https://management.core.windows.net/',
        )
    )
);
</code>```

Body:
We're moving from Guzzle3 to Guzzle6. I wrote a process to authenticate and access the Azure Management API that worked fine in Guzzle3. However, I'm unable to figure out how to get it to work in Guzzle6. The purpose is to get the access token which is then use in subsequent requests to the Azure Management API.

Original Code:

$client = new Guzzle\Http\Client();
$request = $client->post("https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        'Accept' => 'application/json',
    ),
    Array(
        'grant_type'    => 'client_credentials',
        'client_id'     => $application_id,
        'client_secret' => $application_secret,
        'resource'      => 'https://management.core.windows.net/',
    )
);

$response = $request->send();
$body = $response->getBody(true);

New code I'm working on:

$client = new GuzzleHttp\Client();
$response = $client->request(
    'POST',
    "https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        GuzzleHttp\RequestOptions::JSON => Array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $application_id,
            'client_secret' => $application_secret,
            'resource'      => 'https://management.core.windows.net/',
        )
    )
);

I've tried so many variations with no luck. I would be grateful for any insight anyone could provide.

Thanks!

Body:
Well, I guess posting on here helped guide my thoughts on this. I was able to get it to work. For anyone else in the same boat, here's the solution I came up with:

$client = new GuzzleHttp\Client();
$response = $client->request(
    'POST',
    "https://login.microsoftonline.com/{$tenant_id}/oauth2/token",
    Array(
        'form_params' => Array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $application_id,
            'client_secret' => $application_secret,
            'resource'      => 'https://management.core.windows.net/',
        )
    )
);


问:
Can I set ng-model to two values?
I have an input

```<code><input type="text" ng-model="choice.text">
</code>```

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

```<code><input type="text" ng-model="choice.text name"></p>
<p ng-bind="name"></p>
</code>```

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1> <!-- I would like to add the dynamic element here -->
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
</div>
</code>```

EDIT 3: Same code, but with the ng-bind:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1>
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
    <p ng-bind="temp"></p>
    <p ng-bind="choice.text"></p>
</div>
</code>```

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

答:
Use ng-change to update other model

```<code><input type="text"
       ng-model="choice.text"
       ng-change="temp=choice.text"/>
</code>```

Now for testing, use:

```<code><p ng-bind="temp"></p>
<p ng-bind="choice.text"></p>
</code>```

Title: Can I set ng-model to two values?

Body:
I have an input

<input type="text" ng-model="choice.text">

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

<input type="text" ng-model="choice.text name">

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

EDIT 3: Same code, but with the ng-bind:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

Body:
Use ng-change to update other model

<input type="text"
       ng-model="choice.text"
       ng-change="temp=choice.text"/>

Now for testing, use:

<p ng-bind="temp"></p>
<p ng-bind="choice.text"></p>


问:
How can I Make multiple asynchronous call to python cgi script
I have a CGI form which takes a CSV sheet and email and calls two individual python scripts which run in the background. These take about 15 minutes to execute. I want to make an asynchronous call to these scripts so that I can display some message and prevent apache timeout.

Here is my code

```<code>import os
import cgi, cgitb
import csv
import sys
import subprocess
import io

cgitb.enable()
form = cgi.FieldStorage()
filedata = form['file']
filecontent = filedata.file.read().splitlines()
email=form.getvalue('email_address')

email = str(email)

subprocess.Popen([sys.executable, 'giw.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)

subprocess.Popen([sys.executable, 'mailer.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)
</code>```

答:
This worked for me:-

Run background process in Python and do NOT wait

```<code>import subprocess
import sys

subprocess.Popen([sys.executable, 'giw.py', str(email)],  stdout=subprocess.PIPE, stderr=subprocess.STDOUT);
</code>```

Body:
I have a CGI form which takes a CSV sheet and email and calls two individual python scripts which run in the background. These take about 15 minutes to execute. I want to make an asynchronous call to these scripts so that I can display some message and prevent apache timeout.

Here is my code

import os
import cgi, cgitb
import csv
import sys
import subprocess
import io

cgitb.enable()
form = cgi.FieldStorage()
filedata = form['file']
filecontent = filedata.file.read().splitlines()
email=form.getvalue('email_address')

email = str(email)

subprocess.Popen([sys.executable, 'giw.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)

subprocess.Popen([sys.executable, 'mailer.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)

Body:
This worked for me:-

Run background process in Python and do NOT wait

import subprocess
import sys

subprocess.Popen([sys.executable, 'giw.py', str(email)],  stdout=subprocess.PIPE, stderr=subprocess.STDOUT);


问:
greedy regular expression or logic
Consider the string 'X Y Z' and the substitution

```<code>re.sub('Y|Y Z', '', 'X Y Z')
</code>```

This returns

```<code>'X  Z'
</code>```

When it could have returned 'X ' as well.  Obviously it took the first thing it matched, substituted, and afterwards the pattern for the other alternative no longer matched.

Is there a way to tell the substitution to prefer the longest substitution?

答:
That would be…

```<code>re.sub('Y( Z)*','','X Y Z')
</code>```

Title: greedy regular expression or logic

Body:
Consider the string 'X Y Z' and the substitution

re.sub('Y|Y Z', '', 'X Y Z')

This returns

'X  Z'

When it could have returned 'X ' as well.  Obviously it took the first thing it matched, substituted, and afterwards the pattern for the other alternative no longer matched.

Is there a way to tell the substitution to prefer the longest substitution?

Body:
That would be…

re.sub('Y( Z)*','','X Y Z')


问:
Dart Element: call function on embedded JS Object
In this particular case, it's for SVG.  I can get an SVG Element via a query as follows:

```<code>Element svgEL = querySelector('svg');
</code>```

If I look at the 'svgEL' object, it contains (in brief):

```<code>[[javascript view]]: svg
[[class]]: SvgSvgElementImpl
  ...
  getScreenCTM: function()       // I want to call this
  ...
</code>```

I presume I'd instantiate a JsObject on something and then do a callMethod on that, but I don't seem to be able to figure out how to make that work.

Any ideas?

答:
Easiest is to use the corresponding Dart class GraphicsElement,  this has the method getScreenCTM https://api.dartlang.org/stable/1.23.0/dart-svg/GraphicsElement-class.html

So cast to this type:

```<code>GraphicsElement gElem = svgEL as GraphicsElement;
gElem.getScreenCTM();
</code>```

Body:
In this particular case, it's for SVG.  I can get an SVG Element via a query as follows:

Element svgEL = querySelector('svg');

If I look at the 'svgEL' object, it contains (in brief):

[[javascript view]]: svg
[[class]]: SvgSvgElementImpl
  ...
  getScreenCTM: function()       // I want to call this
  ...

I presume I'd instantiate a JsObject on something and then do a callMethod on that, but I don't seem to be able to figure out how to make that work.

Any ideas?

Body:
Easiest is to use the corresponding Dart class GraphicsElement,  this has the method getScreenCTM https://api.dartlang.org/stable/1.23.0/dart-svg/GraphicsElement-class.html

So cast to this type:

GraphicsElement gElem = svgEL as GraphicsElement;
gElem.getScreenCTM();


问:
Rails 5 ActiveRecord, how to include fields from associated tables?
With Rails 5, Given the models:

```<code>chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id
</code>```

I have a controller method to return the chef_position_skills by chef_position_id:

```<code>  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end
</code>```

This returns:

```<code> [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]
</code>```

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

答:
Use

```<code>render json: chef_position.chef_position_skills.
  map {|s| s.slice(:id, :chef_position_id, :skill_id).merge s.skill.slice(:name) }
</code>```

I don't have the same models but here is a similar example:

```<code>irb(main):026:0> u.slice(:id, :email).merge u.funds.slice(:min)
=> {"id"=>1, "email"=>"test@example.com", "min"=>1000000}
</code>```

But I think you'll really like JBuilder which is included in Rails 5.

https://github.com/rails/jbuilder

Body:
With Rails 5, Given the models:

chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id

I have a controller method to return the chef_position_skills by chef_position_id:

  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end

This returns:

 [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

Body:
Use

render json: chef_position.chef_position_skills.
  map {|s| s.slice(:id, :chef_position_id, :skill_id).merge s.skill.slice(:name) }

I don't have the same models but here is a similar example:

irb(main):026:0> u.slice(:id, :email).merge u.funds.slice(:min)
=> {"id"=>1, "email"=>"test@example.com", "min"=>1000000}

But I think you'll really like JBuilder which is included in Rails 5.

https://github.com/rails/jbuilder


问:
Custom iterator on a namedtuple
Is there a pythonic way to have a custom iterator on a namedtuple?

A custom iterator appears to require an index attribute. Normally a namedtuple has a "__slots__ = ()" declaration, which avoids the overhead of a dynamic dict and reduces latency in attribute lookup. However, this breaks the iterator (AttributeError: 'Path' object has no attribute '_iidx'). Adding _iidx to the slots results in nonempty __slots__ not supported

Context: I will be working with a large number of Bezier splines. Each spline consists of a list of 'knot' points, and list of pairs of control points. By commenting out the __slots__ = () declaration, my code works. But, at the cost of having a per-instance dynamic dict. The overhead from the dict in attribute lookup is probably negligible compared to everything else, but it doesn't seem pythonic.

```<code>class Path(namedtuple('Path', "knots ctrl_pts")):
#    __slots__ = ()

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        self._iidx = 0
        return self

    def __next__(self):
        if self._iidx == len(self.ctrl_pts):
            raise StopIteration
        i = self._iidx
        self._iidx += 1
        return (self.ctrl_pts[i], self.knots[i+1])
</code>```

The SVG method uses the iterator to make SVG formating trivial. This:

```<code>print('<path d="%s" stroke="black" stroke-width="1" fill="blue" />'
       % path.SVG)
</code>```

Results in:

```<code><path d="M 318.9 179.4 C 279.1 177.6 199.2 270.3 222.4 298.1 C 245.5
326.0 371.6 289.1 420.4 297.0 C 469.2 304.9 440.6 357.6 399.6 352.4
C 388.5 350.9 389.7 345.0 400.4 347.6 C 440.1 357.4 469.4 309.2 419.6
303.0 C 369.8 296.7 240.9 332.5 217.6 301.9 C 194.4 271.2 276.9 174.1
319.1 174.6 C 330.3 174.7 329.9 179.9 318.9 179.4" stroke="black"
stroke-width="1" fill="blue" />
</code>```

But it also is trivial to use in the on_draw(self, wid, cr): of a Gtk.DrawingArea:

```<code>        path = self.coords.outline_path
        cr.set_source_rgb(*LT_BLUE)
        cr.move_to(*path.knots[0])
        for (c,k) in path:
            cr.curve_to(*c.P1, *c.P2, *k)
        cr.fill_preserve()
        cr.set_source_rgb(*BLACK)
        cr.stroke()
</code>```

Note: the 'knots' is a List[Point] and 'ctrl_pts' is a List[ControlPoints]:

```<code>class Point(namedtuple('Point', "x y")):
    __slots__ = ()
    """<bunch of stuff not shown>"""
    @property
    def bare(self):
        return '%.1f %.1f' % (self.x, self.y)

class ControlPoints(namedtuple('ControlPoints', "P1 P2")):
    __slots__ = ()
    @property
    def bare(self):
        return '%s %s' % (self.P1.bare, self.P2.bare)
</code>```

I am very new to python and I am certain this can be done in a more pythonic way.

答:
To make your code work as is, add _iidx to the attribute list in the call to namedtuple().

Note that inheriting from a namedtuple class makes further sub-classing less useful because inheritors can not add new attributes. This may or may not matter in your application. As an alternative you can inherit from object and call out the attribute names in __slots__. This will preserve much of the performance benefits of inheriting from a namedtuple, and make it so that inheritors can define new attributes in their __slots__.

Changes below include:

__iter__ now returns a generator that manages looping for you so you don't need _iidx anymore. Check out itertools for interesting ways of creating iterators. Defining __next__ is often more work than is necessary.

The svg property now accumulates strings in a list and then joins them. This is usually faster than the increment operator on str.

The last bit is changing the svg property to lowercase. This is purely style but it is more in line with the core language's style guide.

.

```<code>from itertools import izip    # python 2 only

class Path(namedtuple('Path', "knots ctrl_pts")):
    __slots__ = ()

    @property
    def svg(self):    # attribute names are usually lower case
        # accumulating strings with += is slow
        # use a list insted
        s = ['M %s' % self.knots[0].bare]
        for cps, k in self:
            s.append('C %s %s' % (cps.bare, k.bare))
        return ' '.join(s)

    def __iter__(self):
        # python 3
        return zip(self.ctrl_pts, self.knots[1:])

        # python 2
        return izip(self.ctrl_pts, self.knots[1:])
</code>```

Title: Custom iterator on a namedtuple

Body:
Is there a pythonic way to have a custom iterator on a namedtuple?

A custom iterator appears to require an index attribute. Normally a namedtuple has a "__slots__ = ()" declaration, which avoids the overhead of a dynamic dict and reduces latency in attribute lookup. However, this breaks the iterator (AttributeError: 'Path' object has no attribute '_iidx'). Adding _iidx to the slots results in nonempty __slots__ not supported

Context: I will be working with a large number of Bezier splines. Each spline consists of a list of 'knot' points, and list of pairs of control points. By commenting out the __slots__ = () declaration, my code works. But, at the cost of having a per-instance dynamic dict. The overhead from the dict in attribute lookup is probably negligible compared to everything else, but it doesn't seem pythonic.

class Path(namedtuple('Path', "knots ctrl_pts")):
#    __slots__ = ()

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        self._iidx = 0
        return self

    def __next__(self):
        if self._iidx == len(self.ctrl_pts):
            raise StopIteration
        i = self._iidx
        self._iidx += 1
        return (self.ctrl_pts[i], self.knots[i+1])

The SVG method uses the iterator to make SVG formating trivial. This:

print('<path d="%s" stroke="black" stroke-width="1" fill="blue" />'
       % path.SVG)

Results in:

<path d="M 318.9 179.4 C 279.1 177.6 199.2 270.3 222.4 298.1 C 245.5
326.0 371.6 289.1 420.4 297.0 C 469.2 304.9 440.6 357.6 399.6 352.4
C 388.5 350.9 389.7 345.0 400.4 347.6 C 440.1 357.4 469.4 309.2 419.6
303.0 C 369.8 296.7 240.9 332.5 217.6 301.9 C 194.4 271.2 276.9 174.1
319.1 174.6 C 330.3 174.7 329.9 179.9 318.9 179.4" stroke="black"
stroke-width="1" fill="blue" />

But it also is trivial to use in the on_draw(self, wid, cr): of a Gtk.DrawingArea:

        path = self.coords.outline_path
        cr.set_source_rgb(*LT_BLUE)
        cr.move_to(*path.knots[0])
        for (c,k) in path:
            cr.curve_to(*c.P1, *c.P2, *k)
        cr.fill_preserve()
        cr.set_source_rgb(*BLACK)
        cr.stroke()

Note: the 'knots' is a List[Point] and 'ctrl_pts' is a List[ControlPoints]:

class Point(namedtuple('Point', "x y")):
    __slots__ = ()
    """<bunch of stuff not shown>"""
    @property
    def bare(self):
        return '%.1f %.1f' % (self.x, self.y)

class ControlPoints(namedtuple('ControlPoints', "P1 P2")):
    __slots__ = ()
    @property
    def bare(self):
        return '%s %s' % (self.P1.bare, self.P2.bare)

I am very new to python and I am certain this can be done in a more pythonic way.

Body:
To make your code work as is, add _iidx to the attribute list in the call to namedtuple().

Note that inheriting from a namedtuple class makes further sub-classing less useful because inheritors can not add new attributes. This may or may not matter in your application. As an alternative you can inherit from object and call out the attribute names in __slots__. This will preserve much of the performance benefits of inheriting from a namedtuple, and make it so that inheritors can define new attributes in their __slots__.

Changes below include:

__iter__ now returns a generator that manages looping for you so you don't need _iidx anymore. Check out itertools for interesting ways of creating iterators. Defining __next__ is often more work than is necessary.

The svg property now accumulates strings in a list and then joins them. This is usually faster than the increment operator on str.

The last bit is changing the svg property to lowercase. This is purely style but it is more in line with the core language's style guide.

.

from itertools import izip    # python 2 only

class Path(namedtuple('Path', "knots ctrl_pts")):
    __slots__ = ()

    @property
    def svg(self):    # attribute names are usually lower case
        # accumulating strings with += is slow
        # use a list insted
        s = ['M %s' % self.knots[0].bare]
        for cps, k in self:
            s.append('C %s %s' % (cps.bare, k.bare))
        return ' '.join(s)

    def __iter__(self):
        # python 3
        return zip(self.ctrl_pts, self.knots[1:])

        # python 2
        return izip(self.ctrl_pts, self.knots[1:])


问:
Service Contracts not visible in Customer Portal
I'm running Vtiger 7 on PHP 7.

Service contracts can be enabled from the admin configuration

But Service Contracts are not visible in the Customer Portal

Is this because of some bug or is this feature not fully added to Customer Portal yet ?

答:
Hi panchtatva please execute this Queries in your database

```<code>INSERT INTO `sandeep_forexcrmdb`.`vtiger_customerportal_prefs` (`tabid`, `prefkey`, `prefvalue`) VALUES ('35', 'showrelatedinfo', '1');
INSERT INTO `sandeep_forexcrmdb`.`vtiger_customerportal_tabs` (`tabid`, `visible`, `sequence`) VALUES ('35', '1', '12');
</code>```

and check Service Contract Module display or not

Body:
Hi panchtatva please execute this Queries in your database

INSERT INTO `sandeep_forexcrmdb`.`vtiger_customerportal_prefs` (`tabid`, `prefkey`, `prefvalue`) VALUES ('35', 'showrelatedinfo', '1');
INSERT INTO `sandeep_forexcrmdb`.`vtiger_customerportal_tabs` (`tabid`, `visible`, `sequence`) VALUES ('35', '1', '12');

and check Service Contract Module display or not


问:
"No project ID could be determined from the Cloud SDK configuration" when running psqworker
When I was going through the Google Cloud tutorial: https://cloud.google.com/python/getting-started/using-pub-sub#running_the_app_on_your_local_machine

I got the following error:

google.auth._default No project ID could be determined from the Cloud SDK configuration. Consider running gcloud config set project or setting the GOOGLE_CLOUD_PROJECT environment variable

I did 'gcloud config set project [my project name]' with no success.

What's the problem?

Update: I've deployed app engines previously without any problem. The problem only happens when I run the psqworker for this Pub/Sub function. I know my project ID and used it before.

答:
Locate the project ID and project number

There are two ways to identify your project: the project number and project ID.

The project number is automatically assigned when you create a project.

The project ID is a unique identifier for a project. When you first create a project, you can accept the default generated project ID or create your own. A project ID cannot be changed after the project is created, so if you are creating a new project, be sure to choose an ID that you'll be comfortable using for the lifetime of the project.

Note: You should be aware that some resource identifiers (such as project IDs) might be retained beyond the life of your project. For
  this reason, avoid storing sensitive information in resource
  identifiers.

To locate your project ID and project number:

Go to the Cloud Platform Console

From the projects list, select the name of your project.

On the left, click Dashboard. The project name and ID are displayed in the Dashboard.


问:
how to filter the query when an object is related to multiple categories?
I want to fetch the movie results that are related to two categories for
   example the "Romance" & "Drama".. if I say something like
   $genre->with("movie")->where("genre","Romance")->where("genre","Drama")->get();
     Naturally it won't work so is not there any simple way to do it?

```<code>  <!-- my controller -->
   public function show()
      {
            $genres = new genres;
             $y = $genre->with("movie")->where("genre","Romance")->get();
             return $y;
       }
    <!-- model -->
   <?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;
    use App\movies;
     class genres extends Model
       {
         public $table ="genres";
         public function movie(){
             return $this->belongsToMany(movies::class,
                   "relation","genre_id","movie_id");
                                 }
       }
</code>```

答:
```<code>public function show()
{
    $search = ['Romance'];
    // Or
    $search = ['Action', 'Romance'];

    $genres = genres::with('movie')->whereIn('genre', $search)->get();
    return $genres;
}
</code>```

Body:
I want to fetch the movie results that are related to two categories for
   example the "Romance" & "Drama".. if I say something like
   $genre->with("movie")->where("genre","Romance")->where("genre","Drama")->get();
     Naturally it won't work so is not there any simple way to do it?

   public function show()
      {
            $genres = new genres;
             $y = $genre->with("movie")->where("genre","Romance")->get();
             return $y;
       }

   <?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;
    use App\movies;
     class genres extends Model
       {
         public $table ="genres";
         public function movie(){
             return $this->belongsToMany(movies::class,
                   "relation","genre_id","movie_id");
                                 }
       }


问:
JQUERY load vs get
I have this line of code

```<code>$('#findemail').load('findemail.php', {id: this.id, tabla: $(this).attr("rel")});
</code>```

which loads alright the data in the anchor div. However, it turns out that I need to utilize that data, namely it displays an email address and I need to "grab" that email address and send it through a "hidden submit" from the webform to the mail processing script. That line above is sending two parameters, the ID and the tablename, that are used by a SQL query, which selects me the email I want to use, in the form of $destination_email

Someone told me that in order to do that, I just need to use "get" instead of "load" like here below, but putting together that I am a bit retard and that I have about an hour "experience"  with JQUERY I dont know how to benefit from that code. My webform is some hundreds of lines below in that same page, so I dont know how to fully finish that JQUERY code so that I can fetch it from my HTML form to forward it, as I said. Please, if you want to help dont just give me a hint, I still dont know the syntax of JQUERY although I am struggling to learn as much as I can. The code is nearly finished anyway.

The full code is here below. The first line does the load alright, it fills me a div box with that and that is all I need. But the second line, as I have explained, fetches an email address in the form of a variable, and I need to work with that, that is why it uses "get"

```<code><script type="text/javascript">
$(document).ready(function(){
$('a.flip').live('click',function(){
    $(".panel").slideToggle("slow");

$('#reviews').load('SendIdToDatabase.php', {id: this.id, tabla: $(this).attr("rel")});

$.get('findemail.php', {id: 'findemail', tabla: $('#findemail').attr('rel')}, function(data) {
      // data contains the response
});

  });
});

</script>
</code>```

UPDATE TO 99,99% FINISHED CODE

HERE is what I have. It seems fine to me, however, hm, still is not sending that email away

only below the dotted line is interesting, the rest works perfect. Below the dotted line is the code that fetches the email. It does load it perfect, it displays it so as if hardocoded on the surface of my HTML form as alvaro@mygmail.com but there probably is very minor thing impeding that to be passed on.

```<code><script type="text/javascript">

$(document).ready(function(){
$('a.flip').live('click',function(){
    $(".panel").slideToggle("slow");

$('#reviews').load('SendIdToDatabase.php', {id: this.id, tabla: $(this).attr("rel")});
................................................................................

$('#findemail').load('findemail.php',
                   {id: this.id, tabla: $(this).attr("rel")},
                   function() {
                     var email = $(this).find(".email").val();

                 });

          });

  });

</script>

<?php
echo '<div id ="findemail" class="email">';

echo '<input type="hidden" name = "country" class="email" value= "'.$destination_email.'"/>';

echo '</div>';
?>

<div id="form-submit"><input type="submit" id="submit-form" name="submit" value="Submit" /></div>
</form>
</code>```

Grasping the idea from Nick

it can also be that the SQL query issues not just an email alone, but the whole

```<code>echo '"<input type = "hidden" val=\"' .addslashes($aRow['email']) .'\" class=\"email\" .>"';
</code>```

=======================================================================================

So There seem to be 2 different solutions that you Brian and Nick are proposing:

NICKS

```<code>$('#findemail').load('findemail.php',
                   {id: this.id, tabla: $(this).attr("rel")},
                   function() {
                     var email = $(this).find(".email").val();
</code>```

AND THEN THIS:

```<code><?php
echo '<div id ="findemail" class="email">';

echo '<input type="hidden" name = "country" class="email" value= "'.$destination_email.'"/>';

echo '</div>';
?>
</code>```

AND THEN BRIANS:

```<code>var email = $('#reviews').html(); // this to grab the email
</code>```

and here below embedded in my webform

but, is the syntax correct ? where is the start of the <input>?

```<code>$('#my-form').append($('<input/>').attr('type', 'hidden').val(email))
</code>```

答:
You can still get the data with .load(), if it was returned to load in your element, for example:

```<code>$('#reviews').load('findemail.php',
                   {id: this.id, tabla: $(this).attr("rel")},
                   function() {
                     var email = $(this).find(".email").val();
                   });
</code>```

The concept is pretty simple, if it's in the response, it was already loaded in the HTML of your #reviewsElement, so just grab it from wherever it was in there.

Title: JQUERY load vs get

Body:
I have this line of code

$('#findemail').load('findemail.php', {id: this.id, tabla: $(this).attr("rel")});

which loads alright the data in the anchor div. However, it turns out that I need to utilize that data, namely it displays an email address and I need to "grab" that email address and send it through a "hidden submit" from the webform to the mail processing script. That line above is sending two parameters, the ID and the tablename, that are used by a SQL query, which selects me the email I want to use, in the form of $destination_email

Someone told me that in order to do that, I just need to use "get" instead of "load" like here below, but putting together that I am a bit retard and that I have about an hour "experience"  with JQUERY I dont know how to benefit from that code. My webform is some hundreds of lines below in that same page, so I dont know how to fully finish that JQUERY code so that I can fetch it from my HTML form to forward it, as I said. Please, if you want to help dont just give me a hint, I still dont know the syntax of JQUERY although I am struggling to learn as much as I can. The code is nearly finished anyway.

The full code is here below. The first line does the load alright, it fills me a div box with that and that is all I need. But the second line, as I have explained, fetches an email address in the form of a variable, and I need to work with that, that is why it uses "get"

UPDATE TO 99,99% FINISHED CODE

HERE is what I have. It seems fine to me, however, hm, still is not sending that email away

only below the dotted line is interesting, the rest works perfect. Below the dotted line is the code that fetches the email. It does load it perfect, it displays it so as if hardocoded on the surface of my HTML form as alvaro@mygmail.com but there probably is very minor thing impeding that to be passed on.

<?php
echo '
';

echo '<input type="hidden" name = "country" class="email" value= "'.$destination_email.'"/>';

echo '
';
?>

<input type="submit" id="submit-form" name="submit" value="Submit" />

</form>

Grasping the idea from Nick

it can also be that the SQL query issues not just an email alone, but the whole

echo '"<input type = "hidden" val=\"' .addslashes($aRow['email']) .'\" class=\"email\" .>"';

=======================================================================================

So There seem to be 2 different solutions that you Brian and Nick are proposing:

NICKS

$('#findemail').load('findemail.php',
                   {id: this.id, tabla: $(this).attr("rel")},
                   function() {
                     var email = $(this).find(".email").val();

AND THEN THIS:

<?php
echo '
';

echo '<input type="hidden" name = "country" class="email" value= "'.$destination_email.'"/>';

echo '
';
?>

AND THEN BRIANS:

var email = $('#reviews').html(); // this to grab the email

and here below embedded in my webform

but, is the syntax correct ? where is the start of the <input>?

$('#my-form').append($('<input/>').attr('type', 'hidden').val(email))

Body:
You can still get the data with .load(), if it was returned to load in your element, for example:

$('#reviews').load('findemail.php',
                   {id: this.id, tabla: $(this).attr("rel")},
                   function() {
                     var email = $(this).find(".email").val();
                   });

The concept is pretty simple, if it's in the response, it was already loaded in the HTML of your #reviewsElement, so just grab it from wherever it was in there.


问:
Divide and conquer algorithm
I had a job interview a few weeks ago and I was asked to design a divide and conquer algorithm. I could not solve the problem, but they just called me for a second interview! Here is the question:

we are giving as input two n-element arrays A[0..n − 1] and B[0..n − 1] (which
are not necessarily sorted) of integers, and an integer value. Give an O(nlogn) divide and conquer algorithm that determines if there exist distinct values i, j (that is, i != j) such that A[i] + B[j] = value. Your algorithm should return True if i, j exists, and return False otherwise. You may assume that the elements in A are distinct, and the elements in B are distinct.

can anybody solve the problem? Thanks

答:
The following algorithm does not use Divide and Conquer but it is one of the solutions.
You need to sort both the arrays, maintaining the indexes of the elements maybe sorting an array of pairs (elem, index). This takes O(n log n) time.

Then you can apply the merge algorithm to check if there two elements such that A[i]+B[j] = value. This would O(n)

Overall time complexity will be O(n log n)

Title: Divide and conquer algorithm


问:
My scrapy can't get valid response
When i use scrapy to get some stocks information from 'http://quote.eastmoney.com/stocklist.html',I can't get right response. Actually, I get nothing when I run it.
Here is the contents of stocks.py:

```<code>import scrapy
from scrapy.selector import Selector
import re

class StocksSpider(scrapy.Spider):
name = "stocks"

start_urls = ['http://quote.eastmoney.com/stocklist.html']

def parse(self, response):

    for i in Selector(response).xpath('//div[@id="quotesearch"]/ul/li/a/@href').extract():
        try:
            stock=re.split(r'[./]',i)[5]

            url='https://gupiao.baidu.com/stock/'+stock+'.html'
            yield scrapy.Rquest(url,callback=self.parse_stock)
        except:
            continue

def parse_stock(self,response):
    infoDict={}

    name=Selector(response).xpath('//a[@class="bets-name"]/text()').extract()[0]
    keylist=Selector(response).xpath('//dl/dt/text()').extract()

    for i in range(len(keylist)):
        try:
            val=Selector(response).xpath('//dl/dd/text()').extract()[0]
        except:
            val='--'
        infoDict[keylist[i]]=val
    infoDict.update({'股票名称':name[0].split()[0]+'('+Selector(response).xpath('//a[@class="bets-name"]/span/text()')[0].extract()[0]+')'})

    yield infoDict
</code>```

Here is what I get when I run it:

```<code>2017-06-05 20:28:32 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: BaiduStocks)
    2017-06-05 20:28:32 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'BaiduStocks', 'FEED_EXPORT_ENCODING': 'utf-8', 'NEWSPIDER_MODULE': 'BaiduStocks.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['BaiduStocks.spiders']}
2017-06-05 20:28:32 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled item pipelines:
['BaiduStocks.pipelines.BaidustocksInfoPipeline']
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Spider opened
2017-06-05 20:28:33 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-06-05 20:28:33 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-06-05 20:28:33 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quote.eastmoney.com/robots.txt> (referer: None)
2017-06-05 20:28:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quote.eastmoney.com/stocklist.html> (referer: None)
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Closing spider (finished)
2017-06-05 20:28:33 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 458,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 570201,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/404': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 6, 5, 12, 28, 33, 930937),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 6, 5, 12, 28, 33, 28477)}
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

I have been working on it for a few days, but I can't tell what's wrong. So I really need your help.
Thank you all!

答:
Here, I did a short code review:

```<code>import scrapy
from scrapy.selector import Selector
import re

class StocksSpider(scrapy.Spider):
    name = "stocks"

    start_urls = ['http://quote.eastmoney.com/stocklist.html']

    def parse(self, response):
        # response has a shortcut for selector
        for i in response.xpath('//div[@id="quotesearch"]/ul/li/a/@href').extract():
            # never silently catch and drop errors
            stock = re.split(r'[./]', i)[5]
            url = 'https://gupiao.baidu.com/stock/' + stock + '.html'
            yield scrapy.Request(url, callback=self.parse_stock)

    def parse_stock(self, response):
        # objects should be lowercase in python
        item = dict()
        # there's extract_first shortcut for extract()[0]
        name = response.xpath('//a[@class="bets-name"]/text()').extract_first('')
        keylist = response.xpath('//dl/dt/text()').extract()

        # for each is preferred loop style.
        for key in keylist:
            # extract_first allows a default argument to be set
            item[key] = response.xpath('//dl/dd/text()').extract_first('--')
        data = Selector(response).xpath('//a[@class="bets-name"]/span/text()').extract_first('') + ')'
        item['data'] = '{}({})'.format(name.split()[0], data)
        yield item
</code>```

Aside from minor issues the biggest one was that your try/except clause in parse() method just quit silenty and you had a typo Rquest, so the spider just went on - you should never have silent blanket exceptions for this very reason :)

Title: My scrapy can't get valid response

Body:
When i use scrapy to get some stocks information from 'http://quote.eastmoney.com/stocklist.html',I can't get right response. Actually, I get nothing when I run it.
Here is the contents of stocks.py:

import scrapy
from scrapy.selector import Selector
import re

class StocksSpider(scrapy.Spider):
name = "stocks"

start_urls = ['http://quote.eastmoney.com/stocklist.html']

def parse(self, response):

    for i in Selector(response).xpath('//div[@id="quotesearch"]/ul/li/a/@href').extract():
        try:
            stock=re.split(r'[./]',i)[5]

            url='https://gupiao.baidu.com/stock/'+stock+'.html'
            yield scrapy.Rquest(url,callback=self.parse_stock)
        except:
            continue

def parse_stock(self,response):
    infoDict={}

    name=Selector(response).xpath('//a[@class="bets-name"]/text()').extract()[0]
    keylist=Selector(response).xpath('//dl/dt/text()').extract()

    for i in range(len(keylist)):
        try:
            val=Selector(response).xpath('//dl/dd/text()').extract()[0]
        except:
            val='--'
        infoDict[keylist[i]]=val
    infoDict.update({'股票名称':name[0].split()[0]+'('+Selector(response).xpath('//a[@class="bets-name"]/span/text()')[0].extract()[0]+')'})

    yield infoDict

Here is what I get when I run it:

2017-06-05 20:28:32 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: BaiduStocks)
    2017-06-05 20:28:32 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'BaiduStocks', 'FEED_EXPORT_ENCODING': 'utf-8', 'NEWSPIDER_MODULE': 'BaiduStocks.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['BaiduStocks.spiders']}
2017-06-05 20:28:32 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-06-05 20:28:33 [scrapy.middleware] INFO: Enabled item pipelines:
['BaiduStocks.pipelines.BaidustocksInfoPipeline']
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Spider opened
2017-06-05 20:28:33 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-06-05 20:28:33 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-06-05 20:28:33 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quote.eastmoney.com/robots.txt> (referer: None)
2017-06-05 20:28:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quote.eastmoney.com/stocklist.html> (referer: None)
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Closing spider (finished)
2017-06-05 20:28:33 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 458,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 570201,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/404': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 6, 5, 12, 28, 33, 930937),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 6, 5, 12, 28, 33, 28477)}
2017-06-05 20:28:33 [scrapy.core.engine] INFO: Spider closed (finished)

I have been working on it for a few days, but I can't tell what's wrong. So I really need your help.
Thank you all!

Body:
Here, I did a short code review:

import scrapy
from scrapy.selector import Selector
import re

class StocksSpider(scrapy.Spider):
    name = "stocks"

    start_urls = ['http://quote.eastmoney.com/stocklist.html']

    def parse(self, response):
        # response has a shortcut for selector
        for i in response.xpath('//div[@id="quotesearch"]/ul/li/a/@href').extract():
            # never silently catch and drop errors
            stock = re.split(r'[./]', i)[5]
            url = 'https://gupiao.baidu.com/stock/' + stock + '.html'
            yield scrapy.Request(url, callback=self.parse_stock)

    def parse_stock(self, response):
        # objects should be lowercase in python
        item = dict()
        # there's extract_first shortcut for extract()[0]
        name = response.xpath('//a[@class="bets-name"]/text()').extract_first('')
        keylist = response.xpath('//dl/dt/text()').extract()

        # for each is preferred loop style.
        for key in keylist:
            # extract_first allows a default argument to be set
            item[key] = response.xpath('//dl/dd/text()').extract_first('--')
        data = Selector(response).xpath('//a[@class="bets-name"]/span/text()').extract_first('') + ')'
        item['data'] = '{}({})'.format(name.split()[0], data)
        yield item

Aside from minor issues the biggest one was that your try/except clause in parse() method just quit silenty and you had a typo Rquest, so the spider just went on - you should never have silent blanket exceptions for this very reason :)


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
1) When X=0 function should return 1;
2) Added return;

```<code> function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    else
        x=1;
    return x;
 }
</code>```

usage

```<code><input type="button" value="Find factiorial" onclick="alert(run(fact.value));">
</code>```

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>

Body:
1) When X=0 function should return 1;
2) Added return;

 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    else
        x=1;
    return x;
 }

usage

<input type="button" value="Find factiorial" onclick="alert(run(fact.value));">


问:
Cannot get full result while "grep file"
I want to get the lines which contain "myString" in file "1.txt", and save the result to "2.txt". So I write these in a bash file:

```<code>#!/bin/sh
grep "myString" 1.txt > 2.txt
</code>```

But I only got half of the "1.txt" grepped, it stopped with incomplete result in "2.txt". Using the commond instead of bash file didn't help.

I am doing this with cygwin64 on windows7.

Is there some terminator that would stop the "grep" commond, or a size limit on windows7, or something else?

Thanks a lot.

答:
Because of some Chinese characters, the file was recognized as a binary file.

It would be fine with "-a".

Also it worked just fine on Linux, with or without "-a".

So the windows7 or cygwin took a part in it too.

Thanks to @Sundeep for the help.

Body:
I want to get the lines which contain "myString" in file "1.txt", and save the result to "2.txt". So I write these in a bash file:

#!/bin/sh
grep "myString" 1.txt > 2.txt

But I only got half of the "1.txt" grepped, it stopped with incomplete result in "2.txt". Using the commond instead of bash file didn't help.

I am doing this with cygwin64 on windows7.

Is there some terminator that would stop the "grep" commond, or a size limit on windows7, or something else?

Thanks a lot.


答:
My approach is..

Sort any of the array. Here we sort array A. Sort it with the Merge Sort algorithm which is a Divide and Conquer algorithm.

Then for each element of B, Search for Required Value- Element of B in array A by Binary Search. Again this is a Divide and Conquer algorithm.

If you find the element Required Value - Element of B from an Array A then Both element makes pair such that Element of A + Element of B = Required Value.

So here for Time Complexity, A has N elements so Merge Sort will take O(N log N) and We do Binary Search for each element of B(Total N elements) Which takes O(N log N). So total time complexity would be O(N log N).

As you have mentioned you require to check for i != j if A[i] + B[j] = value then here you can take 2D array of size N * 2. Each element is paired with its original index as second element of the each row. Sorting would be done according the the data stored in the first element. Then when you find the element, You can compare both elements original indexes and return the value accordingly.

Title: Divide and conquer algorithm

Body:
I had a job interview a few weeks ago and I was asked to design a divide and conquer algorithm. I could not solve the problem, but they just called me for a second interview! Here is the question:

we are giving as input two n-element arrays A[0..n − 1] and B[0..n − 1] (which
are not necessarily sorted) of integers, and an integer value. Give an O(nlogn) divide and conquer algorithm that determines if there exist distinct values i, j (that is, i != j) such that A[i] + B[j] = value. Your algorithm should return True if i, j exists, and return False otherwise. You may assume that the elements in A are distinct, and the elements in B are distinct.

can anybody solve the problem? Thanks


问:
How to replace using for loop in range(len) by using enumerate
Is there a simple way to use enumerate instead of for loop with range(len)? For example, here I loop to replace all values of each element in subarrays by the index of its subarray.

```<code>list = []
for i in range(len(nparray)):
    j = [i]*(len(nparray[i]))
    list.append(j)
</code>```

My nparray is np.array with 6 subarrays, and each subarray has different size.

答:
enumerate won't replace the use of for, just make it arguably nicer. You can use list comprehension however:
[[i]*len(x) for i,x in enumerate(nparray)]

And avoid using list as variable name since it's alrteady used as an builtin.

Body:
Is there a simple way to use enumerate instead of for loop with range(len)? For example, here I loop to replace all values of each element in subarrays by the index of its subarray.

list = []
for i in range(len(nparray)):
    j = [i]*(len(nparray[i]))
    list.append(j)

My nparray is np.array with 6 subarrays, and each subarray has different size.


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
```<code>var list = new List<string> { "One", "Two", "Three" };
</code>```

Essentially the syntax is:

```<code>new List<Type> { Instance1, Instance2, Instance3 };
</code>```

Which is translated by the compiler as

```<code>List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

Body:
var list = new List<string> { "One", "Two", "Three" };

Essentially the syntax is:

new List<Type> { Instance1, Instance2, Instance3 };

Which is translated by the compiler as

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");


问:
Implement OpenID Connect without oidc-client-js
I am busy integrating a new React front end with a .net Core API, using Identity Server 4.

The flow type we are using is Resource Owner Password Credentials.

There are two reasons I do not wish to use oidc-client-js:

It is 433 KB

It does not support our flow type

At the moment I am able to get the discovery document and login using the token_endpoint. The return after I login contains: access_token, expires_in and token_type but not session_state.

I am currently attempting to replicate the CheckSessionIFrame as can be seen in the oidc-client-js repository.

It is constructed with callback, client_id, url & interval and started by passing in the session_state.

My problem is that I cannot figure out how to get the session_state from Identity Server 4.

I would appreciate any advice on the situation as a whole.

Can you explain to me how I can get the session_state?

Many thanks

Charles

答:
Resource Owner Flow does not allow for sessions because it is a browserless flow much like the client credentials flow. In other words, IdentityServer4 cannot issue a cookie for your session.

oidc-js probably does not support password grant because it is a simple restful call, nothing too complicated.

If you want checksession you will need to use a human interaction based flow like implicit flow.


问:
TensorFlow: initializing state for RNN between inferences in Android
We have a working TensorFlow network (graphdef) running on Android and I'm noting that the inference results over time tend to be correlated.  That is if label A is returned there will tend to be a stream of A's that follow in time, even when the input data switches to data that should generate B labels.  Eventually, the results will switch to B but there seems to be a lag and suggests the RNN is stateful between inference calls.  Our network is using RNN/LSTMs.

```<code>cellLSTM    = tf.nn.rnn_cell.BasicLSTMCell(nHidden)
cellsLSTM   = tf.nn.rnn_cell.MultiRNNCell([cellLSTM] * 2)
RNNout, RNNstates = tf.nn.rnn(cellsLSTM, Xin)
</code>```

I'm wondering if I need to reinitialize the RNN state between inference calls.  I will note that no such method is available in the TensorFlowInferenceInterface.java interface.   I imagine that it would be possible to insert an RNN cell initialization node into the graph that could be activated with a node value (using FillNodeInt or similar).

So my question is: what is best practise with RNN/LSTMs in Tensorflow. Does one need to clear state between inferences?  If so, how does one do it?

答:
While I can't comment on general practice for RNN state initialization, here is how we managed to force the initial state definition.  The problem was that while the batch size was indeed a constant parameter for the training set, it was not for the Test set.  The test set is always 20% of the data corpus and so its size is different with each change to the corpus.

The solution was to create a new variable for the batchsize:

```<code>batch_size_T  = tf.shape(Xin)[0]
</code>```

where Xin is the input Tensor of size [b x m x n] where b is the batch size and m x n is the size of the training frame.  Xin is fed in from the feed_dict.

The initial state can then be defined as:

```<code>initial_state = lstm_cells.zero_state(batch_size_T, tf.float32)
</code>```

Finally, the RNN is defined in terms of the new Dynamic RNN:

```<code>outputs, state = tf.nn.dynamic_rnn(cell=lstm_cells, inputs=Xin, dtype=tf.float32, initial_state=initial_state)
</code>```

Body:
We have a working TensorFlow network (graphdef) running on Android and I'm noting that the inference results over time tend to be correlated.  That is if label A is returned there will tend to be a stream of A's that follow in time, even when the input data switches to data that should generate B labels.  Eventually, the results will switch to B but there seems to be a lag and suggests the RNN is stateful between inference calls.  Our network is using RNN/LSTMs.

cellLSTM    = tf.nn.rnn_cell.BasicLSTMCell(nHidden)
cellsLSTM   = tf.nn.rnn_cell.MultiRNNCell([cellLSTM] * 2)
RNNout, RNNstates = tf.nn.rnn(cellsLSTM, Xin)

I'm wondering if I need to reinitialize the RNN state between inference calls.  I will note that no such method is available in the TensorFlowInferenceInterface.java interface.   I imagine that it would be possible to insert an RNN cell initialization node into the graph that could be activated with a node value (using FillNodeInt or similar).

So my question is: what is best practise with RNN/LSTMs in Tensorflow. Does one need to clear state between inferences?  If so, how does one do it?

Body:
While I can't comment on general practice for RNN state initialization, here is how we managed to force the initial state definition.  The problem was that while the batch size was indeed a constant parameter for the training set, it was not for the Test set.  The test set is always 20% of the data corpus and so its size is different with each change to the corpus.

The solution was to create a new variable for the batchsize:

batch_size_T  = tf.shape(Xin)[0]

where Xin is the input Tensor of size [b x m x n] where b is the batch size and m x n is the size of the training frame.  Xin is fed in from the feed_dict.

The initial state can then be defined as:

initial_state = lstm_cells.zero_state(batch_size_T, tf.float32)

Finally, the RNN is defined in terms of the new Dynamic RNN:

outputs, state = tf.nn.dynamic_rnn(cell=lstm_cells, inputs=Xin, dtype=tf.float32, initial_state=initial_state)