问:
How to sum all the column wise values of html table and display the sum in particular column's footer
My html table goes like below, In the footer of my table i want to add the "Total" and sum of all the values at the footer of particular "quarters"

```<code>"quarter1"  "quarter2" "quarter3" "quarter4"
 250000      115000
             175000      600000     275000
 300000      150000      750000
 650000                              450000
 850000      290000      145000
</code>```

my view code is like below
How to overcome my issue, please suggest me. Any helps are appreciated,
Thank you

```<code><table class="table table-bordered" id="referListTable">
                        <thead>
                            <tr>
                            <th>SI.No</th>
                              <th>Jan-Mar</th>
                              <th>Apr-Jun</th>
                              <th>Jul-Sep</th>
                              <th>Oct-Dec</th>

                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $i=1;
                            foreach($dashboardDetails as $llist){
                            ?>
                            <tr>
                              <td><?php echo $i; ?></td>
                              <td align="right">$llist['previous']; ?></td>
                              <td align="right">$llist['quarter1'];?></td>
                              <td align="right">$llist['quarter2'];?></td>
                              <td align="right">$llist['quarter3'];?></td>
                              <td align="right">$llist['quarter4'];?></td>

                              </tr>
                            <?php
                                $i++;
                            }
                            ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>Total</th>

                                <td id="total" ></td>
                                <td id="total" ></td>
                                <td id="total" ></td>
                                <td id="total" ></td>
                                <td id="total" ></td>

                            </tr>
                         </tfoot>
                    </table>
</code>```

答:
Try something like this

```<code>var sums = []
$("table tbody tr").each(function() {
  $(this).find("td").each(function(i, x) {
    if ($(x).html().length) {
      var tdValue = parseInt($(x).html());
      tdValue = (tdValue + parseInt(sums[i] == undefined ? 0 : sums[i]))
      sums[i] = tdValue
    }
  })
})
$.each(sums,function(i,x) {
  $("tfoot tr").append("<td>"+x+"</td>")
})
</code>```

Note this is created before we had your html code in the question, but it should be able to give you an idea how to make it work with your own html code

var sums = []
$("table tbody tr").each(function() {
  $(this).find("td").each(function(i, x) {
    if ($(x).html().length) {
      var tdValue = parseInt($(x).html());
      tdValue = (tdValue + parseInt(sums[i] == undefined ? 0 : sums[i]))
      sums[i] = tdValue
    }
  })
})
$.each(sums,function(i,x) {
  $("tfoot tr").append(""+x+"	")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>quarter1</td>
      <td>quarter2</td>
      <td>quarter3</td>
      <td>quarter4</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>250000</td>
      <td>115000</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>175000</td>
      <td>600000</td>
      <td>275000</td>
    </tr>
    <tr>
      <td>300000</td>
      <td>150000</td>
      <td>750000</td>
      <td></td>
    </tr>
    <tr>
      <td>650000</td>
      <td></td>
      <td></td>
      <td>450000</td>
    </tr>
    <tr>
      <td>850000</td>
      <td>290000</td>
      <td>145000</td>
      <td></td>
    </tr>
  </tbody>
  <tfoot>
  <tr>
  </tr>
  </tfoot>

</table></code>```

Body:
My html table goes like below, In the footer of my table i want to add the "Total" and sum of all the values at the footer of particular "quarters"

"quarter1"  "quarter2" "quarter3" "quarter4"
 250000      115000
             175000      600000     275000
 300000      150000      750000
 650000                              450000
 850000      290000      145000

my view code is like below
How to overcome my issue, please suggest me. Any helps are appreciated,
Thank you

                            SI.No
                              Jan-Mar
                              Apr-Jun
                              Jul-Sep
                              Oct-Dec

                            <?php
                            $i=1;
                            foreach($dashboardDetails as $llist){
                            ?>

                              <?php echo $i; ?>
                              $llist['previous']; ?>
                              $llist['quarter1'];?>
                              $llist['quarter2'];?>
                              $llist['quarter3'];?>
                              $llist['quarter4'];?>

                            <?php
                                $i++;
                            }
                            ?>

                                Total

Body:
Try something like this

var sums = []
$("table tbody tr").each(function() {
  $(this).find("td").each(function(i, x) {
    if ($(x).html().length) {
      var tdValue = parseInt($(x).html());
      tdValue = (tdValue + parseInt(sums[i] == undefined ? 0 : sums[i]))
      sums[i] = tdValue
    }
  })
})
$.each(sums,function(i,x) {
  $("tfoot tr").append("<td>"+x+"</td>")
})

Note this is created before we had your html code in the question, but it should be able to give you an idea how to make it work with your own html code

var sums = []
$("table tbody tr").each(function() {
  $(this).find("td").each(function(i, x) {
    if ($(x).html().length) {
      var tdValue = parseInt($(x).html());
      tdValue = (tdValue + parseInt(sums[i] == undefined ? 0 : sums[i]))
      sums[i] = tdValue
    }
  })
})
$.each(sums,function(i,x) {
  $("tfoot tr").append("<td>"+x+"</td>")
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>quarter1</td>
      <td>quarter2</td>
      <td>quarter3</td>
      <td>quarter4</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>250000</td>
      <td>115000</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>175000</td>
      <td>600000</td>
      <td>275000</td>
    </tr>
    <tr>
      <td>300000</td>
      <td>150000</td>
      <td>750000</td>
      <td></td>
    </tr>
    <tr>
      <td>650000</td>
      <td></td>
      <td></td>
      <td>450000</td>
    </tr>
    <tr>
      <td>850000</td>
      <td>290000</td>
      <td>145000</td>
      <td></td>
    </tr>
  </tbody>
  <tfoot>
  <tr>
  </tr>
  </tfoot>

</table>


来源: stackexchange

问:
How to parse this XML in Android?
I am quite new to XML parsing and I have my method of parsing XML. Only that method is for simple XML layouts with just 1 child node.

I now have to parse an XML file with childs that have childs that have childs (got it :)?)

This is the parse-method I have now:

```<code>protected Map<String, Maatschappij> getAutopechTel() {
    Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(getAssets().open("autopech.xml"));
        NodeList nl = doc.getElementsByTagName("dienst");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Maatschappij maat = new Maatschappij();

            maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
            maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));

            telVoorAutopech.put(maat.getTel(), maat);
        }
    } catch (Exception e) {
    }
    return telVoorAutopech;
}
</code>```

How must I adjust this in order to parse this type of XML file:

```<code>   <Message>

    <Service>Serviceeee</Service>

      <Owner>Bla</Owner>

      <LocationFeedTo>Too</LocationFeedTo>

      <Location>http://maps.google.com/?q=52.390001,4.890145</Location>

      <Child1>

        <Child1_1>

          <Child1_1_1>ANWB</Child1_1_1>

        </Child1_1>
      </Child1>
<Message>
</code>```

答:
You can use SAXParser to parse XML in Android :

Here is a detailed tutorial with example and also another one here by IBM developerWorks.

DOM Parser is slow and consume a lot
  memory if it load a XML document
  which contains a lot of data. Please
  consider SAX parser as solution for
  it,  SAX is faster than DOM and use
  less memory.

Try this one out but I haven't tested this code yet. It recursively traverses all the nodes and adds which are ELEMENT_NODE to the Vector<Node>.

```<code>public void traverseNodes(Node node, Vector<Node> nodeList)
{
    if(node.getNodeType() == Node.ELEMENT_NODE)
    {
        nodeList.add(node);
        if(node.getChildNodes().getLength() >= 1)
        {
            NodeList childNodeList = node.getChildNodes();
            for(int nodeIndex = 1;nodeIndex < childNodeList.getLength(); nodeIndex++)
            {
                traverseNodes(childNodeList.item(nodeIndex),nodeList);
            }
        }
    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to parse this XML in Android?

Body:
I am quite new to XML parsing and I have my method of parsing XML. Only that method is for simple XML layouts with just 1 child node.

I now have to parse an XML file with childs that have childs that have childs (got it :)?)

This is the parse-method I have now:

protected Map<String, Maatschappij> getAutopechTel() {
    Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(getAssets().open("autopech.xml"));
        NodeList nl = doc.getElementsByTagName("dienst");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Maatschappij maat = new Maatschappij();

            maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
            maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));

            telVoorAutopech.put(maat.getTel(), maat);
        }
    } catch (Exception e) {
    }
    return telVoorAutopech;
}

How must I adjust this in order to parse this type of XML file:

   <Message>

    <Service>Serviceeee</Service>

      <Owner>Bla</Owner>

      <LocationFeedTo>Too</LocationFeedTo>

      <Location>http://maps.google.com/?q=52.390001,4.890145</Location>

      <Child1>

        <Child1_1>

          <Child1_1_1>ANWB</Child1_1_1>

        </Child1_1>
      </Child1>
<Message>

Body:
You can use SAXParser to parse XML in Android :

Here is a detailed tutorial with example and also another one here by IBM developerWorks.

DOM Parser is slow and consume a lot
  memory if it load a XML document
  which contains a lot of data. Please
  consider SAX parser as solution for
  it,  SAX is faster than DOM and use
  less memory.

Try this one out but I haven't tested this code yet. It recursively traverses all the nodes and adds which are ELEMENT_NODE to the Vector<Node>.

public void traverseNodes(Node node, Vector<Node> nodeList)
{
    if(node.getNodeType() == Node.ELEMENT_NODE)
    {
        nodeList.add(node);
        if(node.getChildNodes().getLength() >= 1)
        {
            NodeList childNodeList = node.getChildNodes();
            for(int nodeIndex = 1;nodeIndex < childNodeList.getLength(); nodeIndex++)
            {
                traverseNodes(childNodeList.item(nodeIndex),nodeList);
            }
        }
    }

}

ContentLicense: CC BY-SA 3.0


问:
nifi: how to change value of json?
i have processor InvokeHTTP which gives json result.
for instance:

```<code>{
  "revision" : {
    "clientId" : "dc572274-4b71-11b6-e415-b91e391bcf4d",
    "version" : 7
  },
  "id" : "dc572260-4b71-11b6-0371-f73573ab44fe",
  "uri" : "http://x.x.x.x:9090/nifi-api/processors/dc572260-4b71-0371-73ab44fe",
  "position" : {
    "x" : -1021.9568138214972,
    "y" : 333.2029958718132
  }
}
</code>```

i want to change the value of version dynamically for each incoming response of InvokeHTTP.
how to achieve this?

答:
you can use this sequence of processors: EvaluateJsonPath to get value of attribute, UpdateAttribute to change it, and ReplaceText to substitute old value in content with new one using regular expression.

For the ReplaceText processor use following parameters:

Regexp Replace strategy

Search Value : (?s)("version"\s*:\s*)(\d+)

Replacement Value : $1${VERSION}  (where VERSION is an attribute name that holds new value)

Here is a nice resource to test the regular expressions:
https://regex101.com/r/JOrZNp/1

Title: nifi: how to change value of json?

Body:
i have processor InvokeHTTP which gives json result.
for instance:

{
  "revision" : {
    "clientId" : "dc572274-4b71-11b6-e415-b91e391bcf4d",
    "version" : 7
  },
  "id" : "dc572260-4b71-11b6-0371-f73573ab44fe",
  "uri" : "http://x.x.x.x:9090/nifi-api/processors/dc572260-4b71-0371-73ab44fe",
  "position" : {
    "x" : -1021.9568138214972,
    "y" : 333.2029958718132
  }
}

i want to change the value of version dynamically for each incoming response of InvokeHTTP.
how to achieve this?


问:
How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?
I'm implementing socket.io in my swift ios app.

Currently on several panels I'm listening to the server and wait for incoming messages. I'm doing so by calling the getChatMessage function in each panel:

```<code>func getChatMessage(){
    SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //do sth depending on which panel user is
        })
    }
}
</code>```

However I noticed it's a wrong approach and I need to change it - now I want to start listening for incoming messages only once and when any message comes - pass this message to any panel that listens to it.

So I want to pass the incoming message through the NSNotificationCenter. So far I was able to pass the information that something happened, but not pass the data itself. I was doing that by:

```<code>NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
</code>```

then I had a function called:

```<code>func showSpinningWheel(notification: NSNotification) {
}
</code>```

and any time I wanted to call it I was doing:

```<code>NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
</code>```

So how can I pass the object messageInfo and include it in the function that gets called?

答:
Hello @sahil I update your answer for swift 3

```<code>let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }
</code>```

Hope it's helpful. Thanks

ContentLicense: CC BY-SA 4.0

Body:
I'm implementing socket.io in my swift ios app.

Currently on several panels I'm listening to the server and wait for incoming messages. I'm doing so by calling the getChatMessage function in each panel:

func getChatMessage(){
    SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //do sth depending on which panel user is
        })
    }
}

However I noticed it's a wrong approach and I need to change it - now I want to start listening for incoming messages only once and when any message comes - pass this message to any panel that listens to it.

So I want to pass the incoming message through the NSNotificationCenter. So far I was able to pass the information that something happened, but not pass the data itself. I was doing that by:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)

then I had a function called:

func showSpinningWheel(notification: NSNotification) {
}

and any time I wanted to call it I was doing:

NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)

So how can I pass the object messageInfo and include it in the function that gets called?

Body:
Hello @sahil I update your answer for swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Hope it's helpful. Thanks


问:
Search stops working for "Entire Solution"
Somehow Visual Studio search has stopped working for me. Anytime I search "Entire Solution" for some text I get this result:

Find all "[Whatever I was searching for]", Subfolders, Find Results
  1, "Entire Solution"   No matching text found to look in.   Find was
  stopped in progress.

Why does it suddenly say "No files were found to look in"?

I've found a number of links on Google that say to press Ctrl + Break or Ctrl + Scroll Lock, but none of them seem to work for me.

答:
That Ctrl+Break trick worked for me for years, it's really interesting to finally understand why this happens. With VS2015 I have somewhat related problem with search: my Ctrl+Shift+F simply does not work, this key combination seems to be ignored when I press it. I tried to reinstall even VS 2015 and I still got that same broken behavior.

In case somebody has identical problem, here's what was the reason:

I turns out that for whatever random reason VS2015 shows that "find in files" dialog on another monitor that's attached to my PC. That other monitor is 4K Samsung TV that normally stays "Off" and I have no clue why VS 2015 sends that search dialog box to that monitor. Surprisingly, when I turn on my TV the search dialog moves to the primary monitor on its own!


问:
How to acquire DualEELS spectra by DM script?
I would like to acquire both low-loss and high-loss EELS spectra simultaneously in DualEELS mode by DM script. However, the command for acquiring an EELS spectrum EELSAcquireSpectrum() can obtain only single EELS spectrum.

Is there an appropriate scripting commands for DualEELS acquisition?

My system is GMS2.x, but please tell me even if such a command is available in only GMS3.x.

答:
GMS 3.2 (Possible also for GMS 2.3)

I am not aware of any specific command for DualEELS. As a rought workaround: When you start the acquistions via EELSInvokeCaptureButton() or EELSInvokeViewButton() the mode you have set on your UI will be followed. You then need to grab the two front-most images per script.

This is a rough example script:

```<code>EELSInvokeCaptureButton()
image low,high
while ( EELSAcquisitionIsActive() )
{
    Result(" \n waiting..." )
    sleep( 0.1 )
}

high := GetImageDocument( 0 ).ImageDocumentGetImage( 0 )
low := GetImageDocument( 1 ).ImageDocumentGetImage( 0 )

low.ImageSetName( low.ImageGetName() + " - l" )
high.ImageSetName( high.ImageGetName() + " - h" )
</code>```

Body:
GMS 3.2 (Possible also for GMS 2.3)

I am not aware of any specific command for DualEELS. As a rought workaround: When you start the acquistions via EELSInvokeCaptureButton() or EELSInvokeViewButton() the mode you have set on your UI will be followed. You then need to grab the two front-most images per script.

This is a rough example script:

EELSInvokeCaptureButton()
image low,high
while ( EELSAcquisitionIsActive() )
{
    Result(" \n waiting..." )
    sleep( 0.1 )
}

high := GetImageDocument( 0 ).ImageDocumentGetImage( 0 )
low := GetImageDocument( 1 ).ImageDocumentGetImage( 0 )

low.ImageSetName( low.ImageGetName() + " - l" )
high.ImageSetName( high.ImageGetName() + " - h" )


问:
MVC Angular JS - $get calling
I have $get calling un my C#- MVC - Angular Js Proj .
The url for request is incorrect for me and routing to the root proj folder on computer

```<code>   $http.get('../Home/GetResponse').success(function (response) {
            alert(response);
        });
</code>```

How I should write the url given that the my controller name is 'HomeController' and the function is 'GetResponse' ?

Thanks .

答:
```<code>$http.get(baseurl+'Home/GetResponse').success(function (response) {
            alert(response);
        });
</code>```

just add baseurl in the layout page as

var baseurl=@Url.Content("~/");

Title: MVC Angular JS - $get calling

Body:
I have $get calling un my C#- MVC - Angular Js Proj .
The url for request is incorrect for me and routing to the root proj folder on computer

   $http.get('../Home/GetResponse').success(function (response) {
            alert(response);
        });

How I should write the url given that the my controller name is 'HomeController' and the function is 'GetResponse' ?

Thanks .

Body:
$http.get(baseurl+'Home/GetResponse').success(function (response) {
            alert(response);
        });

just add baseurl in the layout page as

var baseurl=@Url.Content("~/");


问:
WPF ListView: Custom Scrolling Behavior
Is there a way to keep a ListView scrolling vertically as data is updated via a binding to the ListView's ItemsSource property? I can't seem to find a property in either the ListView or its underlying GridView control to achieve the desired result. I would like it to scroll so that the newest information is always visible to the user. A scroll bar already appears as the rows add to the control but the most current row is not presented.

Should I consider using a different type of control that has auto-scroll capability? I only have two columns: one contains DateTimes and the other contains a simple string. I'm starting to think that my control choice may be too limited.

My XAML looks roughly like this:

```<code><ListView ItemsSource="{Binding Updates}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Timestamp" DisplayMemberBinding="{Binding TimeStamp}"/>
            <GridViewColumn DisplayMemberBinding="{Binding UpdateString}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

答:
I found away to expose the ListView's ScrollViewer object to manipulate scrolling. My DataContext contains a collection derived from ObservableCollection and in the code behind I wired an eventhandler to the CollectionChanged event. I used a Decorator to expose the the first child of the ListView (the border) and it's child is the ScrollViewer. From there I call the ScrollToBottom() method to attain the desired behavior.

In the code behind for my View which contains the ListView, this is how it's coded

```<code>MyViewModel viewModel = DataContext as MyViewModel;

viewModel.MyCollection.CollectionChanged += (sender,e) =>
{
    if(e.NewItems != null)
    {
        Decorator border = VisualTreeHelper.GetChild(SummaryListView, 0) as Decorator;
        ScrollViewer scroll = border.Child as ScrollViewer;
        scroll.ScrollToBottom();
    }
};
</code>```

I found how to expose the ScrollViewer on Anshulee's WindowsClient blog post.

Edit
Previously, I was checking if the max number of items in the custom collection was met and then scrolled to bottom. That did not work so well with different screen resolutions because the app might display 15 lines in the ListView on one machine and 25 lines on another. So now I always have it scroll to bottom to bring the newest item into view.

Title: WPF ListView: Custom Scrolling Behavior

Body:
Is there a way to keep a ListView scrolling vertically as data is updated via a binding to the ListView's ItemsSource property? I can't seem to find a property in either the ListView or its underlying GridView control to achieve the desired result. I would like it to scroll so that the newest information is always visible to the user. A scroll bar already appears as the rows add to the control but the most current row is not presented.

Should I consider using a different type of control that has auto-scroll capability? I only have two columns: one contains DateTimes and the other contains a simple string. I'm starting to think that my control choice may be too limited.

My XAML looks roughly like this:

<ListView ItemsSource="{Binding Updates}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Timestamp" DisplayMemberBinding="{Binding TimeStamp}"/>
            <GridViewColumn DisplayMemberBinding="{Binding UpdateString}" />
        </GridView>
    </ListView.View>
</ListView>

Body:
I found away to expose the ListView's ScrollViewer object to manipulate scrolling. My DataContext contains a collection derived from ObservableCollection and in the code behind I wired an eventhandler to the CollectionChanged event. I used a Decorator to expose the the first child of the ListView (the border) and it's child is the ScrollViewer. From there I call the ScrollToBottom() method to attain the desired behavior.

In the code behind for my View which contains the ListView, this is how it's coded

MyViewModel viewModel = DataContext as MyViewModel;

viewModel.MyCollection.CollectionChanged += (sender,e) =>
{
    if(e.NewItems != null)
    {
        Decorator border = VisualTreeHelper.GetChild(SummaryListView, 0) as Decorator;
        ScrollViewer scroll = border.Child as ScrollViewer;
        scroll.ScrollToBottom();
    }
};

I found how to expose the ScrollViewer on Anshulee's WindowsClient blog post.

Edit
Previously, I was checking if the max number of items in the custom collection was met and then scrolled to bottom. That did not work so well with different screen resolutions because the app might display 15 lines in the ListView on one machine and 25 lines on another. So now I always have it scroll to bottom to bring the newest item into view.


问:
Change parent div size when child is rotating
I have block wrapper and div inside it.
To child I apply CSS rotate, and I want that parent div will change it width and height - child div must be inside parent always (like on pictures).

#wrap {
  margin-top: 100px;
  width: auto;
  height: auto;
  position: relative;
  border: 1px solid red;
  box-sizing: border-box;
}
#div {
  position: relative;
  top: 0;
  left: 0;
  background-color: green;
  width: 200px;
  height: 80px;
  display: block;
  transform: rotate(120deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="div">123</div>
</div></code>```

Example: https://jsfiddle.net/y2mw3wxn/

Example how it must be:

答:
Heavily copying from this answer:

Basically, when you transform (rotate or scale or any other transform value), you are not touching the normal document flow, you are just changing the visual appearance of that element.

So, to answer your question:

Can we adjust the parent when the child is rotating? No, you can't just by CSS. (Anyone who know, please correct me if I am wrong about this.)

You may need to use JavaScript for the same. Do some calculations and apply width and height style to the parent element.

Ref:
from MDN:

The CSS transform property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed according to the values set.

and

By modifying the coordinate space, CSS transforms change the position and shape of the affected content without disrupting the normal document flow. This guide provides an introduction to using transforms.

Body:
I have block wrapper and div inside it.
To child I apply CSS rotate, and I want that parent div will change it width and height - child div must be inside parent always (like on pictures).

#wrap {
  margin-top: 100px;
  width: auto;
  height: auto;
  position: relative;
  border: 1px solid red;
  box-sizing: border-box;
}
#div {
  position: relative;
  top: 0;
  left: 0;
  background-color: green;
  width: 200px;
  height: 80px;
  display: block;
  transform: rotate(120deg);
}

123

Example: https://jsfiddle.net/y2mw3wxn/

Example how it must be:


问:
How to implement ASP.NET Web API Authentication by username/Password & ClientID/ClientSecret
My Web API serve 2 different category of consumer.
1. Actual end-user that login with ID and Password.
2. Another application that integrate with my application via the API.

What is the best practice when implementing the Authentication and Authorization for such a system?

I have two solution here:

Figure 1. Using the same Web API project for both web app and API

Figure 2. Using different Web API project for web app and API separately.

The solution in Figure 2 is more straight forward to implement the authentication layer. But it might have duplicate APIs endpoint in both project (although most of the business logic is contain in Service layer).

What is the best solution here?
If Figure 1 is the better solution, then how can i implement the authorization layer? Any library that can achieve that?
Please advice.

答:
for you Authentication and Authorization , you can use identity and Owin in asp.net

check this link for Authentication and Authorization

http://johnatten.com/2014/10/26/asp-net-web-api-and-identity-2-0-customizing-identity-models-and-implementing-role-based-authorization/

or
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

or you can try to generate token using guid();


问:
specified JRE installation does not exist
I'm trying to launch a server on my tomcat 7 on my eclipse indigo EE

and I get the following error:

"'starting Tomcat v7.0 server at localhost' has encountered a problem.

The specified JRE installation does not exist"

I checked the build path configuration and on the libraries section I have the

JDK7 as JRE System Libraray and when I check "Installed JREs..." the correct

path is there -  "C:\Program Files\Java\jdk1.7.0_01".

What else can be done? Many thanks.

p.s. - I'm also using maven 3.0.3

答: Updated the Java , JRE. so I have faced this same issue, I have tried all this but i continued with this issue. then after that, i have removed the server from application and then added new server and with that i have mentioned new JRE version now its working fine.</p>


问:
Is it possible to host an ASPX web site on Linux?
We are trying to convert a lot of things at work over to Linux Red hat.  Recently Windows Server 2003 was installed.  We are currently hosting an asp .net web site on the windows server machine, what I'm wondering is if there is any software that will allow you to host the same web site on linux?</p>

答: To a certain extent, yes. The Mono Project has support for ASP.NET 2.0 web sites.</p>

OwnerDisplayName: Kyle

OwnerDisplayName: Jason Miesionczek


问:
crypto.randomBytes does not accept md5 generated utf8 string
My code is as shown below:

```<code>let createCipher = (req, res) => {
    const token = req.body.token;
    let keyVal = req.body.keyVal;
    const codeToken = utf8.encode(token);
    keyVal = utf8.encode(keyVal);
    console.log("keyVal " + keyVal);
    let hash = crypto.createHash('md5').update(codeToken).digest('hex');
    console.log("hash " + hash);
    var sharedSecret = crypto.randomBytes(hash);
    var initializationVector = crypto.randomBytes(hash);
    console.log("iv " + initializationVector);
    var encrypted;
    cipher = crypto.Cipheriv('aes-128-cbc', sharedSecret, initializationVector);
    encrypted += cipher.update(keyVal, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    res.json({
        status: '200',
        cipher: encrypted
    });
}
</code>```

I have written the above code as per the steps given below:

UTF-8 encode the TempToken string and generate an MD5 hash of it.

UTF-8 encode the Key-Value Pair string and encrypt using AES-128 encryption using Cipher Block Chaining (CBC) mode.
a. Set both the key and initialization vector (IV) equal to result from step 1.

Base64 encode the result of 2

But the above code gives me the error as shown below:

```<code>TypeError: size must be a number >= 0
            <br>    at TypeError (native)
            <br>    at createCipher (C:\Users\anand\quFlipApi\controller\test.js:17:31)
            <br>    at Layer.handle [as handle_request] (C:\Users\anand\quFlipApi\node_modules\express\lib\router\layer.js:95:5)
            <br>    at trim_prefix (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:317:13)
            <br>    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:284:7
            <br>    at Function.process_params (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:335:12)
            <br>    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:275:10)
            <br>    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:635:15
            <br>    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:260:14)
            <br>    at Function.handle (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:174:3)
            <br>    at router (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:47:12)
            <br>    at Layer.handle [as handle_request] (C:\Users\anand\quFlipApi\node_modules\express\lib\router\layer.js:95:5)
            <br>    at trim_prefix (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:317:13)
            <br>    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:284:7
            <br>    at Function.process_params (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:335:12)
            <br>    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:275:10)
            <br>    at C:\Users\anand\quFlipApi\node_modules\body-parser\lib\read.js:129:5
            <br>    at invokeCallback (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:262:16)
            <br>    at done (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:251:7)
            <br>    at IncomingMessage.onEnd (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:307:7)
            <br>    at emitNone (events.js:86:13)
            <br>    at IncomingMessage.emit (events.js:185:7)
</code>```

Here my code does not accept hash generated from previous step in crypto.randomBytes(hash). Is there any method missing in this execution?

答:
crypto.randomBytes takes a number as argument, and it returns random bytes as the name says.

You cannot give it a string as argument.

I don't really understand, why you generate two times random bytes. Maybe this is sufficient?

```<code>let hash = crypto.createHash('md5').update(codeToken).digest();
console.log("hash" + hash.toString('hex'));
var initializationVector = crypto.randomBytes(16);
console.log("iv " + initializationVector);
var encrypted = crypto.Cipheriv('aes-128-cbc', hash, initializationVector);
</code>```

Body:
My code is as shown below:

let createCipher = (req, res) => {
    const token = req.body.token;
    let keyVal = req.body.keyVal;
    const codeToken = utf8.encode(token);
    keyVal = utf8.encode(keyVal);
    console.log("keyVal " + keyVal);
    let hash = crypto.createHash('md5').update(codeToken).digest('hex');
    console.log("hash " + hash);
    var sharedSecret = crypto.randomBytes(hash);
    var initializationVector = crypto.randomBytes(hash);
    console.log("iv " + initializationVector);
    var encrypted;
    cipher = crypto.Cipheriv('aes-128-cbc', sharedSecret, initializationVector);
    encrypted += cipher.update(keyVal, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    res.json({
        status: '200',
        cipher: encrypted
    });
}

I have written the above code as per the steps given below:

UTF-8 encode the TempToken string and generate an MD5 hash of it.

UTF-8 encode the Key-Value Pair string and encrypt using AES-128 encryption using Cipher Block Chaining (CBC) mode.
a. Set both the key and initialization vector (IV) equal to result from step 1.

Base64 encode the result of 2

But the above code gives me the error as shown below:

TypeError: size must be a number >= 0

    at TypeError (native)

    at createCipher (C:\Users\anand\quFlipApi\controller\test.js:17:31)

    at Layer.handle [as handle_request] (C:\Users\anand\quFlipApi\node_modules\express\lib\router\layer.js:95:5)

    at trim_prefix (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:317:13)

    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:284:7

    at Function.process_params (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:335:12)

    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:275:10)

    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:635:15

    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:260:14)

    at Function.handle (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:174:3)

    at router (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:47:12)

    at Layer.handle [as handle_request] (C:\Users\anand\quFlipApi\node_modules\express\lib\router\layer.js:95:5)

    at trim_prefix (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:317:13)

    at C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:284:7

    at Function.process_params (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:335:12)

    at next (C:\Users\anand\quFlipApi\node_modules\express\lib\router\index.js:275:10)

    at C:\Users\anand\quFlipApi\node_modules\body-parser\lib\read.js:129:5

    at invokeCallback (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:262:16)

    at done (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:251:7)

    at IncomingMessage.onEnd (C:\Users\anand\quFlipApi\node_modules\raw-body\index.js:307:7)

    at emitNone (events.js:86:13)

    at IncomingMessage.emit (events.js:185:7)

Here my code does not accept hash generated from previous step in crypto.randomBytes(hash). Is there any method missing in this execution?

Body:
crypto.randomBytes takes a number as argument, and it returns random bytes as the name says.

You cannot give it a string as argument.

I don't really understand, why you generate two times random bytes. Maybe this is sufficient?

let hash = crypto.createHash('md5').update(codeToken).digest();
console.log("hash" + hash.toString('hex'));
var initializationVector = crypto.randomBytes(16);
console.log("iv " + initializationVector);
var encrypted = crypto.Cipheriv('aes-128-cbc', hash, initializationVector);


问:
Google-cloud + Node, grpc error
I am creating a sample desktop application using electron framework. When i include google-cloud node library in application i got this error.

Uncaught Error:
  /home/user/Desktop/projects/sample_desktop_app/node_modules/grpc/src/node/extension_binary/grpc_node.node:
  undefined symbol: GENERAL_NAME_free

OS: Ubuntu

Node Version: v7.10.0

Your help would be appreciated

答:
Grpc id a native module that also is not officially supported for electron. This is because native modules are generally hard with electron as they need special treatment or recompilation for the respective platform.

Best way is to follow this thread https://github.com/grpc/grpc/issues/6138 but you are more or less on your own with it. I would try to have your own backend and proxy grpc calls.

Title: Google-cloud + Node, grpc error


问:
Date picker month selection animation
Can you set the datepicker to have no animation when selecting the month?  The scroll animation is a bit distracting and slow.</p>

答:
Currently, the Calendar component doesn't expose any animation configuration. I am afraid that there is no easy way to disable scroll animation.

I would suggest you post your request in the Kendo UserVoice portal:

http://kendoui-feedback.telerik.com/forums/555517-kendo-ui-for-angular-feedback

Thus more people could cast their vote for this functionality.

Title: Date picker month selection animation


问:
docker-compose unsupported config for services
I am using below version of docker and docker-compose -

```<code>Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.11.2, build dfed245
</code>```

I still face issues with -

```<code>ERROR: The Compose file './docker-compose.yml' is invalid because:
Unsupported config option for services.web: 'version'
</code>```

below is my docker file -

```<code>version: '2'
services:
  web:
    build: .
    ports:
      - "80:80"
      - "443:443"
    links:
      - memache:memcahced
      - solr:solr
      - dev_mysql:dev_mysql
    container_name: xyz
    hostname: XYZ
    image: XYZ/mono
    version: latest
    privileged: true
 ...
 ...
</code>```

Need some assistance.

答:
Don't know if it's just your question, but the indentation of your compose file is off, and there are a number of typos.

Not clear what you're trying to do with that version property in the service definition (no such property is documented), but if you want to specify the version of the image to be used, you do that as follows:

```<code>services:
  web:
    image: XYZ/mono:latest
</code>```

Body:
I am using below version of docker and docker-compose -

Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.11.2, build dfed245

I still face issues with -

ERROR: The Compose file './docker-compose.yml' is invalid because:
Unsupported config option for services.web: 'version'

below is my docker file -

version: '2'
services:
  web:
    build: .
    ports:
      - "80:80"
      - "443:443"
    links:
      - memache:memcahced
      - solr:solr
      - dev_mysql:dev_mysql
    container_name: xyz
    hostname: XYZ
    image: XYZ/mono
    version: latest
    privileged: true
 ...
 ...

Need some assistance.

Body:
Don't know if it's just your question, but the indentation of your compose file is off, and there are a number of typos.

Not clear what you're trying to do with that version property in the service definition (no such property is documented), but if you want to specify the version of the image to be used, you do that as follows:

services:
  web:
    image: XYZ/mono:latest


问:
How do I calculate output of a Neural Network?
I just started learning about ANNs about a week ago with no classical training. Just by watching videos and reading blogs/white papers, I've gotten this far.

I have a question about the final output of the ANN.

Say for instance I was building a XOR with two input node, 3 nodes in one hidden layer and one node in the output layer. A 2 x 3 x 1.

First I would like to make sure I have the first part right.

So each node has a weight associated with it for each node in the hidden layer, if you have 5 nodes in the hidden layer, the input node would calculate it's input and multiply it by a weight associated with each node in the hidden layer.

So to calculate the sigmoid for the first node, you would take all the inputs and multiply it by the weight (no + for a bias) and apply the sigmoid function for the sum of the inputs * weights. Then we would squash that value with a sigmoid and get 0.5866175789173301.

Essentially, it would be, (1 x .25) + (1 x .10) = .35.

Now, that I just do this three times for each node
and get 3 squashed numbers.

```<code>  // (input1 * HiddenNode(x)Weight) + (input2 * HiddenNode(x)Weight)
  activationFunction((1 * .25) + (1 * .10)) // 0.5866175789173301
  activationFunction((0 * .40) + (1 * .60)) // 0.6456563062257954
  activationFunction((1 * .20) + (0 * .80)) // 0.549833997312478
</code>```

Now from what I understand, I again sum & squash those answers:

```<code>  activationFunction(hidden1 + hidden2 + hidden3) // 0.8559569515861635
</code>```

Do I have it correct so far?

My question is, if you're feeding in two scaled numbers to predict grades, 89 & 6.5 = (grade/hours of sleep)

How would you calculate the output from .8559 to a number like 93 and calculate the error on that value? Am I missing anything besides a bias?

If I entered in the percent of change for the last 3 stock price changes, and I wanted it to guess the fourth price, how would I convert an answer like this:

```<code> activationFunction(hidden1 + hidden2 + hidden3) // 0.8559569515861635
</code>```

to an answer to like .10 (percent change in stock price) or any other real world answer?

Thanks in advance!

答:
Unlike people mentioned. Inputs should not be binary. They should be between a certain range (0,1 for sigmoid, -1,1 for TanH).

On the first part you are exactly right if you don't account for bias.

```<code>// Completely right, each hidden node gets input from 2 input nodes
activationFunction((1 * .25) + (1 * .10)) // 0.5866175789173301
activationFunction((0 * .40) + (1 * .60)) // 0.6456563062257954
activationFunction((1 * .20) + (0 * .80)) // 0.549833997312478

// However, all the hidden nodes are connected the output node
output = activationFunction((0.59 * weight1) + (0.64 * weight2) + (0.55 * weight3))
</code>```

Always keep in mind that nodes can only be connected to other nodes by connections, which always have a weight.

My question is, if you're feeding in two scaled numbers to predict grades, 89 & 6.5 = (grade/hours of sleep)

First you scale the inputs (read more here):

```<code>89 > 0.89
6.5 > 6.4 / 24 = 0.27
</code>```

So if the new grade you got was 100, and your output was 0.8559 then the error on your output node is 1.00 - 0.8559 = 0.1441. Then you backpropagate this through the network, but i'm not the right one to explain that for you.

Body:
I just started learning about ANNs about a week ago with no classical training. Just by watching videos and reading blogs/white papers, I've gotten this far.

I have a question about the final output of the ANN.

Say for instance I was building a XOR with two input node, 3 nodes in one hidden layer and one node in the output layer. A 2 x 3 x 1.

First I would like to make sure I have the first part right.

So each node has a weight associated with it for each node in the hidden layer, if you have 5 nodes in the hidden layer, the input node would calculate it's input and multiply it by a weight associated with each node in the hidden layer.

So to calculate the sigmoid for the first node, you would take all the inputs and multiply it by the weight (no + for a bias) and apply the sigmoid function for the sum of the inputs * weights. Then we would squash that value with a sigmoid and get 0.5866175789173301.

Essentially, it would be, (1 x .25) + (1 x .10) = .35.

Now, that I just do this three times for each node
and get 3 squashed numbers.

  // (input1 * HiddenNode(x)Weight) + (input2 * HiddenNode(x)Weight)
  activationFunction((1 * .25) + (1 * .10)) // 0.5866175789173301
  activationFunction((0 * .40) + (1 * .60)) // 0.6456563062257954
  activationFunction((1 * .20) + (0 * .80)) // 0.549833997312478

Now from what I understand, I again sum & squash those answers:

  activationFunction(hidden1 + hidden2 + hidden3) // 0.8559569515861635

Do I have it correct so far?

My question is, if you're feeding in two scaled numbers to predict grades, 89 & 6.5 = (grade/hours of sleep)

How would you calculate the output from .8559 to a number like 93 and calculate the error on that value? Am I missing anything besides a bias?

If I entered in the percent of change for the last 3 stock price changes, and I wanted it to guess the fourth price, how would I convert an answer like this:

 activationFunction(hidden1 + hidden2 + hidden3) // 0.8559569515861635

to an answer to like .10 (percent change in stock price) or any other real world answer?

Thanks in advance!

Body:
Unlike people mentioned. Inputs should not be binary. They should be between a certain range (0,1 for sigmoid, -1,1 for TanH).

On the first part you are exactly right if you don't account for bias.

// Completely right, each hidden node gets input from 2 input nodes
activationFunction((1 * .25) + (1 * .10)) // 0.5866175789173301
activationFunction((0 * .40) + (1 * .60)) // 0.6456563062257954
activationFunction((1 * .20) + (0 * .80)) // 0.549833997312478

// However, all the hidden nodes are connected the output node
output = activationFunction((0.59 * weight1) + (0.64 * weight2) + (0.55 * weight3))

Always keep in mind that nodes can only be connected to other nodes by connections, which always have a weight.

My question is, if you're feeding in two scaled numbers to predict grades, 89 & 6.5 = (grade/hours of sleep)

First you scale the inputs (read more here):

89 > 0.89
6.5 > 6.4 / 24 = 0.27

So if the new grade you got was 100, and your output was 0.8559 then the error on your output node is 1.00 - 0.8559 = 0.1441. Then you backpropagate this through the network, but i'm not the right one to explain that for you.


问:
Accessing shared variables from two threads in Java
I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?

Here are the some parts of the code of my application
This is the class which stores the HashMap:

```<code>public class DataStore {
public Map ChatWindows ;
public DataStore()
{
    ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
    ChatWindows.put(with,t);
    notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
    notifyAll();
    return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
    {
       //    chatWith = with;
        ChatWindow t;
        System.out.println(with);
            t = getWindow(with);
           if(t == null)
           {
               t = new ChatWindow(cc,with,msg);
         //      th = new Thread(t);
               putWindow(with, t);
         //      th.start();
           }
           else
           {
              t.setVisible(true);

            }
}
}
</code>```

Two classes which access 'ChatWindows' HashMap

```<code>public class chatClient extends javax.swing.JFrame implements

Runnable,ListSelectionListener,MouseListener,WindowListener{

  static String LoginName,chatWith,msgToChatWindow;
    Thread listThread=null,th,chatListen;
static  Socket soc;
static  DataOutputStream dout,dout1;
static  DataInputStream din,din1;
        DefaultListModel listModel;

        ChatWindow t;

    public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
    listModel = new DefaultListModel();
    initComponents();
    clientList.addListSelectionListener(this);

     clientList.addMouseListener(this);
     addWindowListener(this);
      this.LoginName=l.loginName;

        soc = l.soc2;
        din = l.din2;
        dout = l.dout2;
        dout1 = l.dout1;
        din1 = l.din1;
        super.setTitle(LoginName);

        listThread = new Thread(this);
        listThread.start();
        this.ds = ds;

}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
    chatWith = (String)clientList.getSelectedValue();
    ds.ChatWindowOpen(this,chatWith,"");
}
</code>```

This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.

```<code>public class ChatListenThread implements Runnable{

DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
    public ChatListenThread(Login l,DataStore ds)
    {
        din1 = l.din1;
        dout1= l.dout1;
        this.ds = ds;
    }
.
.
.
.
public void run(){
   while(true)
   {
       try{
                    String msgFromServer=new String();
                    msgFromServer = din1.readUTF();
                    StringTokenizer st=new StringTokenizer(msgFromServer);
        String msgFrom=st.nextToken();
        String MsgType=st.nextToken();
                    String msg = "";
                   while(st.hasMoreTokens())
        {
            msg=msg+" " +st.nextToken();
        }

                    ds.ChatWindowOpen(cc,msgFrom,msg);

       }
       catch(IOException e)
       {
            System.out.println("Read failed");

       }
   }
</code>```

}
}

答:
Okey, I couldn't use your code because I don't understand, what I did see was that you want something like this:

Create a empty JFrame with a JTabbedPane and start a thread that connects to a Socket

When input comes on the socket, create a ChatPanel (~JTextArea) and add it to one of the tabs

Add the ChatPanel to  a Map that handles the messages from "from"

Pass the message to the newly created ChatPanel

So I did that and I'm posting the code below! Hope that you can use it!

If you like to test this, first start the TestChatServer (code below) and then the ChatSupervisor.

This is the code for the client

```<code>public class ChatSupervisor extends JFrame implements Runnable {

    JTabbedPane tabs = new JTabbedPane();
    Map<String, ChatPanel> chats = new ConcurrentHashMap<String, ChatPanel>();

    public ChatSupervisor() {
        super("Test Chat");
        add(tabs, BorderLayout.CENTER);

        new Thread(this).start();
    }

    public void run() {
        Socket sock = null;
        try {
            sock = new Socket("localhost", 32134);

            Scanner s = new Scanner(sock.getInputStream());
            while (true) {

                String from = s.next();
                String type = s.next();
                String message = s.nextLine();

                getChat(from).incomingMessage(type, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sock != null) try { sock.close(); } catch (IOException e) {}
        }
    }

    public ChatPanel getChat(String from) {
        if (!chats.containsKey(from))
            chats.put(from, new ChatPanel(from));

        return chats.get(from);
    }

    public static void main(String[] args) {
        ChatSupervisor cs = new ChatSupervisor();
        cs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cs.setSize(400, 300);
        cs.setVisible(true);
    }

    class ChatPanel extends JTextArea {
        public ChatPanel(final String from) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    tabs.addTab(from, ChatPanel.this);
                }
            });
        }
        public void incomingMessage(final String type, final String message) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    append("[" + type + "]" + message);
                    append("\n");
                }
            });
        }
    }
}
</code>```

This is the code for the test server:

```<code>public class TestChatServer {
    public static void main(String[] args) throws Exception {
        Socket s = new ServerSocket(32134).accept();
        System.out.println("connected");
        PrintWriter p = new PrintWriter(s.getOutputStream());
        while (true) {

            p.println("hello info Hello World!");
            p.flush();
            Thread.sleep(1000);

            for (int i = 0; i < 10; i++) {
                p.println("test" + i + " warn Testing for testing " + i);
                p.flush();
                Thread.sleep(100);
            }
        }
    }
}
</code>```

Body:
I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?

Here are the some parts of the code of my application
This is the class which stores the HashMap:

public class DataStore {
public Map ChatWindows ;
public DataStore()
{
    ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
    ChatWindows.put(with,t);
    notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
    notifyAll();
    return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
    {
       //    chatWith = with;
        ChatWindow t;
        System.out.println(with);
            t = getWindow(with);
           if(t == null)
           {
               t = new ChatWindow(cc,with,msg);
         //      th = new Thread(t);
               putWindow(with, t);
         //      th.start();
           }
           else
           {
              t.setVisible(true);

            }
}
}

Two classes which access 'ChatWindows' HashMap

public class chatClient extends javax.swing.JFrame implements

Runnable,ListSelectionListener,MouseListener,WindowListener{

  static String LoginName,chatWith,msgToChatWindow;
    Thread listThread=null,th,chatListen;
static  Socket soc;
static  DataOutputStream dout,dout1;
static  DataInputStream din,din1;
        DefaultListModel listModel;

        ChatWindow t;

    public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
    listModel = new DefaultListModel();
    initComponents();
    clientList.addListSelectionListener(this);

     clientList.addMouseListener(this);
     addWindowListener(this);
      this.LoginName=l.loginName;

        soc = l.soc2;
        din = l.din2;
        dout = l.dout2;
        dout1 = l.dout1;
        din1 = l.din1;
        super.setTitle(LoginName);

        listThread = new Thread(this);
        listThread.start();
        this.ds = ds;

}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
    chatWith = (String)clientList.getSelectedValue();
    ds.ChatWindowOpen(this,chatWith,"");
}

This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.

public class ChatListenThread implements Runnable{

DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
    public ChatListenThread(Login l,DataStore ds)
    {
        din1 = l.din1;
        dout1= l.dout1;
        this.ds = ds;
    }
.
.
.
.
public void run(){
   while(true)
   {
       try{
                    String msgFromServer=new String();
                    msgFromServer = din1.readUTF();
                    StringTokenizer st=new StringTokenizer(msgFromServer);
        String msgFrom=st.nextToken();
        String MsgType=st.nextToken();
                    String msg = "";
                   while(st.hasMoreTokens())
        {
            msg=msg+" " +st.nextToken();
        }

                    ds.ChatWindowOpen(cc,msgFrom,msg);

       }
       catch(IOException e)
       {
            System.out.println("Read failed");

       }
   }

}
}

Body:
Okey, I couldn't use your code because I don't understand, what I did see was that you want something like this:

Create a empty JFrame with a JTabbedPane and start a thread that connects to a Socket

When input comes on the socket, create a ChatPanel (~JTextArea) and add it to one of the tabs

Add the ChatPanel to  a Map that handles the messages from "from"

Pass the message to the newly created ChatPanel

So I did that and I'm posting the code below! Hope that you can use it!

If you like to test this, first start the TestChatServer (code below) and then the ChatSupervisor.

This is the code for the client

public class ChatSupervisor extends JFrame implements Runnable {

    JTabbedPane tabs = new JTabbedPane();
    Map<String, ChatPanel> chats = new ConcurrentHashMap<String, ChatPanel>();

    public ChatSupervisor() {
        super("Test Chat");
        add(tabs, BorderLayout.CENTER);

        new Thread(this).start();
    }

    public void run() {
        Socket sock = null;
        try {
            sock = new Socket("localhost", 32134);

            Scanner s = new Scanner(sock.getInputStream());
            while (true) {

                String from = s.next();
                String type = s.next();
                String message = s.nextLine();

                getChat(from).incomingMessage(type, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sock != null) try { sock.close(); } catch (IOException e) {}
        }
    }

    public ChatPanel getChat(String from) {
        if (!chats.containsKey(from))
            chats.put(from, new ChatPanel(from));

        return chats.get(from);
    }

    public static void main(String[] args) {
        ChatSupervisor cs = new ChatSupervisor();
        cs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cs.setSize(400, 300);
        cs.setVisible(true);
    }

    class ChatPanel extends JTextArea {
        public ChatPanel(final String from) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    tabs.addTab(from, ChatPanel.this);
                }
            });
        }
        public void incomingMessage(final String type, final String message) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    append("[" + type + "]" + message);
                    append("\n");
                }
            });
        }
    }
}

This is the code for the test server:

public class TestChatServer {
    public static void main(String[] args) throws Exception {
        Socket s = new ServerSocket(32134).accept();
        System.out.println("connected");
        PrintWriter p = new PrintWriter(s.getOutputStream());
        while (true) {

            p.println("hello info Hello World!");
            p.flush();
            Thread.sleep(1000);

            for (int i = 0; i < 10; i++) {
                p.println("test" + i + " warn Testing for testing " + i);
                p.flush();
                Thread.sleep(100);
            }
        }
    }
}


问:
Proper way to add an image file inside a PDF document generated with Reportlab on AppEngine Python
I'm trying to generate a PDF report using reportlab on App Engine Python.

But I don't know how to attach an image properly.

The image is static.

This is the directory tree of my project.

and this is what I do (inside 'chipas.py') to get the image:

```<code>im = Image('../static/logo.png',1*inch, 1*inch)
story.append(im)
...
</code>```

The stack trace I get:

Traceback (most recent call last):   File
  "C:\Users\Lucas\Dropbox\Desarrollo\Python\windows\AppEngine\google\appengine\ext\webapp_webapp25.py",
  line 701, in call
      handler.get(*groups)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\chipas.py",
  line 1035, in get
      doc.build(story)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 1117, in build
      BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)   File
  "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 880, in build
      self.handle_flowable(flowables)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 763, in handle_flowable
      if frame.add(f, canv, trySplit=self.allowSplitting):   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\frames.py",
  line 159, in _add
      w, h = flowable.wrap(aW, h)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 408, in wrap
      return self.drawWidth, self.drawHeight   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 402, in getattr
      self._setup_inner()   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 368, in _setup_inner
      img = self._img   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 398, in getattr
      self._img = ImageReader(self._file)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\lib\utils.py",
  line 541, in init
      if _isPILImage(fileName):   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\lib\utils.py",
  line 521, in _isPILImage
      return isinstance(im,Image.Image) AttributeError: 'NoneType' object has no attribute 'Image' INFO     2012-02-29 19:54:37,276
  dev_appserver.py:4247] "GET
  /pdf?pedido=ahVkZXZ-Y2hpcGFzLWludGhlY2xvdWRyLwsSBlBlZGlkbyIjMjAxMi0wMi0yOSAxOTo1NDoxOHRlc3RAZXhhbXBsZS5jb20M
  HTTP/1.1" 500 -

What's the proper way to add an image file inside a pdf document generated with reportlab?
Many thanks in advance!

答:
Try this simple function:
This Worked For me....

```<code>def PrintImage(request):
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,topMargin=2)

    doc.pagesize = landscape(A6)
    elements = []
    I = Image('http://demoschoolzen.educationzen.com/images/tia.png')
    I.drawHeight =  0.7*inch
    I.drawWidth = 0.7*inch
    elements.append(I)
    doc.build(elements)
    return response
</code>```

and Call it from your URLs

Body:
I'm trying to generate a PDF report using reportlab on App Engine Python.

But I don't know how to attach an image properly.

The image is static.

This is the directory tree of my project.

and this is what I do (inside 'chipas.py') to get the image:

im = Image('../static/logo.png',1*inch, 1*inch)
story.append(im)
...

The stack trace I get:

Traceback (most recent call last):   File
  "C:\Users\Lucas\Dropbox\Desarrollo\Python\windows\AppEngine\google\appengine\ext\webapp_webapp25.py",
  line 701, in call
      handler.get(*groups)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\chipas.py",
  line 1035, in get
      doc.build(story)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 1117, in build
      BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)   File
  "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 880, in build
      self.handle_flowable(flowables)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\doctemplate.py",
  line 763, in handle_flowable
      if frame.add(f, canv, trySplit=self.allowSplitting):   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\frames.py",
  line 159, in _add
      w, h = flowable.wrap(aW, h)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 408, in wrap
      return self.drawWidth, self.drawHeight   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 402, in getattr
      self._setup_inner()   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 368, in _setup_inner
      img = self._img   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\platypus\flowables.py",
  line 398, in getattr
      self._img = ImageReader(self._file)   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\lib\utils.py",
  line 541, in init
      if _isPILImage(fileName):   File "C:\Users\Lucas\Dropbox\Desarrollo\workspace\python\chipas-windows\src\reportlab\lib\utils.py",
  line 521, in _isPILImage
      return isinstance(im,Image.Image) AttributeError: 'NoneType' object has no attribute 'Image' INFO     2012-02-29 19:54:37,276
  dev_appserver.py:4247] "GET
  /pdf?pedido=ahVkZXZ-Y2hpcGFzLWludGhlY2xvdWRyLwsSBlBlZGlkbyIjMjAxMi0wMi0yOSAxOTo1NDoxOHRlc3RAZXhhbXBsZS5jb20M
  HTTP/1.1" 500 -

What's the proper way to add an image file inside a pdf document generated with reportlab?
Many thanks in advance!

Body:
Try this simple function:
This Worked For me....

def PrintImage(request):
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,topMargin=2)

    doc.pagesize = landscape(A6)
    elements = []
    I = Image('http://demoschoolzen.educationzen.com/images/tia.png')
    I.drawHeight =  0.7*inch
    I.drawWidth = 0.7*inch
    elements.append(I)
    doc.build(elements)
    return response

and Call it from your URLs


问:
Gulp + BrowserSync, serve at path
I'm using Gulp and BrowserSync to serve my webapp at localhost:9000.

How can I serve the webapp at localhost:9000/some/multi/level/path instead?

答:
Seems the option isn't available.
startPath will only change which URL is opened by browsersync.

I finally came up with a simple solution :

Just create a symbolic link from some/multi/level/path directory to your app files. Then going to localhost:9000/some/multi/level/path will provide the same files as going to localhost:9000

Title: Gulp + BrowserSync, serve at path


问:
How to group days in a week, like a calendar?
I have table that has a column of schedule, I would like to pivot on the Day_Name column so that the dates are displayed as columns like Monday, Tuesday etc.
this is my query:

```<code>SELECT
     Month_Name,Day_Name, Year, Week_Number, Day_Number
    , isnull((Select (CONVERT(varchar(5), empschedfrom, 108) + '-' + convert(varchar(5), empschedto, 108)) from empdayscheds where empno = '0030' and empday_no = DayNumber_of_Month and empday_month = Month_Number and empday_year = Year), 'OFF') as emp_sched
    from dtRule where DATE between '05/28/2017' and '07/08/2017'
</code>```

output:

```<code>   Month_Name | Day_Name | Year | Week_Number |Day_number| emp_sched
   May        |Sunday    | 2017 | 4           | 28       | 11:45-20:45
   May        | Tuesday  | 2017 | 5           | 29       | 14:15-23:15
   May        | Wednesday| 2017 | 5           | 30       | 13:45-22:45
   June       | Thursday | 2017 | 1           |  1       |10:00-19:00
   June       | Friday   | 2017 | 1           |  2       |10:00-19:00
   June       | Saturday | 2017 | 1           |  3       |10:00-19:00
</code>```

I would like it to come out like this:

```<code>Week_Number | Month_Name | Year | Monday | Tuesday | Wednesday | Thursday  | Friday    | Saturday
1           | June       | 2017 |        |         |           |10:00-19:00|10:00-19:00|10:00-19:00
</code>```

答:
```<code> drop table if exists dbo.Schedule;

create table dbo.Schedule (
Month_Name varchar(100)
, Day_Name varchar(100)
, Year int
, Week_Number int
, Day_Number int
, emp_sched varchar(100)
);

insert into dbo.Schedule (Month_Name, Day_Name, Year, Week_Number, Day_Number, emp_sched)
values ('May', 'Sunday', 2017, 4           ,  28       ,  '11:45-20:45')
 , ('May'        ,  'Tuesday'  ,  2017 ,  5           ,  29       ,  '14:15-23:15')
 , ('May'        ,  'Wednesday',  2017 ,  5           ,  30       ,  '13:45-22:45')
 , ('June'       ,  'Thursday' ,  2017 ,  1           ,   1       , '10:00-19:00')
 , ('June'       ,  'Friday'   ,  2017 ,  1           ,   2       , '10:00-19:00')
 , ('June'       ,  'Saturday' ,  2017 ,  1           ,   3       , '10:00-19:00');

select
s.Week_Number, s.Month_Name, s.Year
, max(case when s.Day_Name = 'Monday' then s.emp_sched else '' end) as Monday
, max(case when s.Day_Name = 'Tuesday' then s.emp_sched else '' end) as Tuesday
, max(case when s.Day_Name = 'Wednesday' then s.emp_sched else '' end) as Wednesday
, max(case when s.Day_Name = 'Thursday' then s.emp_sched else '' end) as Thursday
, max(case when s.Day_Name = 'Friday' then s.emp_sched else '' end) as Friday
, max(case when s.Day_Name = 'Saturday' then s.emp_sched else '' end) as Saturday
from dbo.Schedule s
group by s.Week_Number, s.Month_Name, s.Year;
</code>```

Body:
I have table that has a column of schedule, I would like to pivot on the Day_Name column so that the dates are displayed as columns like Monday, Tuesday etc.
this is my query:

SELECT
     Month_Name,Day_Name, Year, Week_Number, Day_Number
    , isnull((Select (CONVERT(varchar(5), empschedfrom, 108) + '-' + convert(varchar(5), empschedto, 108)) from empdayscheds where empno = '0030' and empday_no = DayNumber_of_Month and empday_month = Month_Number and empday_year = Year), 'OFF') as emp_sched
    from dtRule where DATE between '05/28/2017' and '07/08/2017'

output:

   Month_Name | Day_Name | Year | Week_Number |Day_number| emp_sched
   May        |Sunday    | 2017 | 4           | 28       | 11:45-20:45
   May        | Tuesday  | 2017 | 5           | 29       | 14:15-23:15
   May        | Wednesday| 2017 | 5           | 30       | 13:45-22:45
   June       | Thursday | 2017 | 1           |  1       |10:00-19:00
   June       | Friday   | 2017 | 1           |  2       |10:00-19:00
   June       | Saturday | 2017 | 1           |  3       |10:00-19:00

I would like it to come out like this:

Week_Number | Month_Name | Year | Monday | Tuesday | Wednesday | Thursday  | Friday    | Saturday
1           | June       | 2017 |        |         |           |10:00-19:00|10:00-19:00|10:00-19:00


问:
forms as html and pdf
I would create many forms with different outputs but i wish to design the form only once.

First - HTML:

the form must be displayed in
Internet Explorer

the values (the user fills out the
form) must be saved in a database

the form must be displayed with
the previus saved values in Internet
Explorer

Second - PDF:

the form must be exported as pdf
with the previus saved values

Requirements:

desing the form only once

display+edit as html

display as pdf

Optional:

support for javascript on client-side
for validation

I'm not sure whats the best way.

I could use libarys/tools like wkhtmltopdf or dompdf but i'm not sure if whether this also supports filled out html-form.
Imo XSL, XSLT and XSL:FO isn't an option because, if i understand that right i must create an XSL:FO for HTML-Output and one for PDF-Output.

What does you think?

答: I don't know if it could be useful for all your points, but Crystal Reports files (.rpt) can be filled then exported quite well to Pdf, html or Word. It can take some time to get it working though (at work we use the version integrated in VS2008)...</p>

Title: forms as html and pdf


问:
Open IPython notebooks (*.ipynb) in read-only view (like a HTML file)
Nowadays with more and more IPython notebook files (*.ipynb) around, it is very disturbing every time when I want to peek at some notebook I have to open a server for it, and cannot do it in read-only mode. Due to auto-save I can accidentally change the file when reading it if not in read-only mode.

I hope something like this: ipython notebook mynb.ipynb --read-only would work, but sadly it doesn't (although still it creates a server which I don't really want in read-only view). What I really want is to open an ipynb file like a HTML file for reading; currently it seems a missing view of ipynb file, and now the notebook is more like a black-box or near-binary file alone.

(P.S. I am using Linux/Ubuntu.)

答:
You may also want to try nteract app (https://nteract.io)

nteract is a desktop application that allows you to develop rich documents that contain prose, executable code (in almost any language!), and images.

Here you can find more detailed review of the app.

It is completely free and very convenient tool by itself and I use it quite often to see other ipynb files if needed and for quick development.


问:
Javascript Array - adding a value to a particular key
```<code>var all_area = [];
$.each(data,function(i,v){
    $.each(v.areas,function(a,b){
        all_area[i]['id'] = b.id;
        all_area[i]['name'] = b.name;
    });
});
</code>```

I want an array that has these data:

```<code>all_area[0]['id'] = 1;
all_area[0]['name'] = "test";
all_area[1]['id'] = 2;
all_area[1]['name'] = "test123";
</code>```

My code is not working. I am getting this error:
Uncaught TypeError: Cannot set property 'id' of undefined

This is the sample data that i am getting from my ajax call:

```<code>[
  {
    "name": "Dubai",
    "id": "1",
    "areas": [
      {
        "name": "Deira",
        "id": 1,
        "extra_fee": 0,
        "extra_time": 0,
        "min_order": 0
      },
      {
        "name": "Bur Dubai",
        "id": 2,
        "extra_fee": 5,
        "extra_time": 10,
        "min_order": 100
      }
    ]
  },
  {
    "name": "Abu Dhabi",
    "id": "2",
    "areas": [
      {
        "name": "Shahama",
        "id": 3,
        "extra_fee": 0,
        "extra_time": 0,
        "min_order": 0
      },
      {
        "name": "City Center",
        "id": 4,
        "extra_fee": 5,
        "extra_time": 10,
        "min_order": 100
      }
    ]
  }
]
</code>```

Thanks.

答:
Initialize the object

```<code>$.each(v.areas,function(a,b){
    all_area[i] = {};
    all_area[i]['id'] = b.id;
    all_area[i]['name'] = b.name;
});
</code>```

OR,

```<code>$.each(v.areas,function(a,b){
    all_area[i] = {
      id : b.id,
      name : b.name
    };
});
</code>```

Body:
var all_area = [];
$.each(data,function(i,v){
    $.each(v.areas,function(a,b){
        all_area[i]['id'] = b.id;
        all_area[i]['name'] = b.name;
    });
});

I want an array that has these data:

all_area[0]['id'] = 1;
all_area[0]['name'] = "test";
all_area[1]['id'] = 2;
all_area[1]['name'] = "test123";

My code is not working. I am getting this error:
Uncaught TypeError: Cannot set property 'id' of undefined

This is the sample data that i am getting from my ajax call:

[
  {
    "name": "Dubai",
    "id": "1",
    "areas": [
      {
        "name": "Deira",
        "id": 1,
        "extra_fee": 0,
        "extra_time": 0,
        "min_order": 0
      },
      {
        "name": "Bur Dubai",
        "id": 2,
        "extra_fee": 5,
        "extra_time": 10,
        "min_order": 100
      }
    ]
  },
  {
    "name": "Abu Dhabi",
    "id": "2",
    "areas": [
      {
        "name": "Shahama",
        "id": 3,
        "extra_fee": 0,
        "extra_time": 0,
        "min_order": 0
      },
      {
        "name": "City Center",
        "id": 4,
        "extra_fee": 5,
        "extra_time": 10,
        "min_order": 100
      }
    ]
  }
]

Thanks.

Body:
Initialize the object

$.each(v.areas,function(a,b){
    all_area[i] = {};
    all_area[i]['id'] = b.id;
    all_area[i]['name'] = b.name;
});

OR,

$.each(v.areas,function(a,b){
    all_area[i] = {
      id : b.id,
      name : b.name
    };
});


问:
python "shell" not print return value 0 after each successfully executed line
when i run (for example)

```<code>print("Hello")
</code>```

the interpreter shows

```<code>Hello
</code>```

thats perfect, but...

```<code>from subprocess import call
ls = 'ls'
call(ls)
</code>```

prints

```<code>file1 file2 file3
0
</code>```

im guessing that the 0 is the return value saying it was successfull (still very new to programming :)   )

soooo..... my question is how to get rid of the 0 so that i only get the output from it, with this example and others as well?

lol im probably over looking something simple here

any help is greatly apreciated!!! :)

EDIT: something like

```<code>@echo off
</code>```

in windows batch scripts would be prefered(so i can use it once and ignore it)

答:
If you are using python 2x:
You can use the commands module for getting the output of the command.

```<code>import commands
commands.getoutput("ls")
</code>```

if you are using python 3x:

```<code>import subprocess
subprocess.getoutput("ls")
</code>```

Body:
when i run (for example)

print("Hello")

the interpreter shows

Hello

thats perfect, but...

from subprocess import call
ls = 'ls'
call(ls)

prints

file1 file2 file3
0

im guessing that the 0 is the return value saying it was successfull (still very new to programming :)   )

soooo..... my question is how to get rid of the 0 so that i only get the output from it, with this example and others as well?

lol im probably over looking something simple here

any help is greatly apreciated!!! :)

EDIT: something like

@echo off

in windows batch scripts would be prefered(so i can use it once and ignore it)

Body:
If you are using python 2x:
You can use the commands module for getting the output of the command.

import commands
commands.getoutput("ls")

if you are using python 3x:

import subprocess
subprocess.getoutput("ls")


问:
Functions inside "for" iteration, Python
I am a beginner and kinda lost with the code i have written. I am writing an add-on for some software, trying to extract some data from its classes.

There is a list of statements that i am going through using operator for. I am interested in two types of statements called VC_STATEMENT_LINMOTION and VC_STATEMENT_PTPMOTION (there are many other types as well).
First in my code i see which of these two types of statements go first. If it is LinMotion, then, i get some extract values for this LinMotion statement (by going to that function (def get_initalvalues())) till code "meets" PtpMotion statement. After it does it goes to def get_conf() function where data for PtpMotion is extracted. Also, in get_conf() if later LinMotion is met, data is taken from PtpMotion of last iteration.

But it doesnt work.

I know it sounds heavy ))). Maybe i myself made it too complicated and solution is simpler.

```<code>for statement in main_routine.Statements:
    if statement.Type == VC_STATEMENT_LINMOTION or statement.Type == VC_STATEMENT_PTPMOTION:

        def get_conf(*args):
            global output
            if statement.Type == VC_STATEMENT_PTPMOTION:
                ptp_motion_conf = ""
                Extracted string data is assigned to ptp_motion_conf which is later added to overall output

                output += ptp_motion_conf
            elif statement.Type == VC_STATEMENT_LINMOTION:
                output += ptp_motion_conf #using data of VC_STATEMENT_PTPMOTION from last iteration

        def get_initialconf(*args):
            global output
            if statement.Type == VC_STATEMENT_LINMOTION:
                ...

            elif statement.Type == VC_STATEMENT_PTPMOTION:
                get_conf()

        statements = [] # getting list of statements to know which of LinMotion or PtpMotion goes first
        for statement in main_routine.Statements:
            statements.append(statement.Type)

        if statements.index("LinMotion") < statements.index("PtpMotion"): #statement LinMotion goes first
            get_initialconf()
        elif statements.index("LinMotion") > statements.index("PtpMotion"):#statement PtpMotion goes first
            get_conf()
</code>```

i will try to show in sample:

If LinMotions statement goes first, before PtpMotion then:

LinMotion (some special initial data)
LinMotion (still initial data)
...
in all other LinMotion statements prog still uses initial data until PtpMotion statement appears:

PtpMotion (its own PtpMotion  data)

if LinMotion appears again, data from last PtpMotion statement is used

If PtpMotion statement goes first, before LinMotion, then
PtpMotion (its own PtpMotion  data)

If Linmotion appears, data from last PtpMotion statement is used

答:
(Edit: I've updated the code to reflect new information in your post.)

If I understand your problem corrrectly, a simple description of what you're trying to achieve is this: you have a list of Statement instances in main_routine.Statements and you want to perform different code based on statement.Type. Here is the natural structure this usually (read: almost always) takes in Python code.

```<code># no idea what this is in your code, but since you want to save it
# to a file, I'll blindy assume it is a string.
output = ""

# current stream of statements. accumulate as long as type is compatible.
stream = []

# process each statement.
for statement in main_routine.Statements:

    if statement.Type == VC_STATEMENT_LINMOTION:
        stream.append(statement)

    elif statement.Type == VC_STATEMENT_PTPMOTION:
        if (len(stream) > 0) and (stream[-1].Type == VC_STATEMENT_LINMOTION):
            output += process_linmotion_stream(stream)
            stream = []
            continue
        stream.append(statement)

    # ignore other types of statements.

# after loop, make sure leftover statements are processed.
output += process_linmotion_stream(stream)
</code>```

Honestly, I think everybody, not just yourself, is confused with you've written. Switch to a simple control flow that models your data and you should be fine.

Body:
I am a beginner and kinda lost with the code i have written. I am writing an add-on for some software, trying to extract some data from its classes.

There is a list of statements that i am going through using operator for. I am interested in two types of statements called VC_STATEMENT_LINMOTION and VC_STATEMENT_PTPMOTION (there are many other types as well).
First in my code i see which of these two types of statements go first. If it is LinMotion, then, i get some extract values for this LinMotion statement (by going to that function (def get_initalvalues())) till code "meets" PtpMotion statement. After it does it goes to def get_conf() function where data for PtpMotion is extracted. Also, in get_conf() if later LinMotion is met, data is taken from PtpMotion of last iteration.

But it doesnt work.

I know it sounds heavy ))). Maybe i myself made it too complicated and solution is simpler.

for statement in main_routine.Statements:
    if statement.Type == VC_STATEMENT_LINMOTION or statement.Type == VC_STATEMENT_PTPMOTION:

        def get_conf(*args):
            global output
            if statement.Type == VC_STATEMENT_PTPMOTION:
                ptp_motion_conf = ""
                Extracted string data is assigned to ptp_motion_conf which is later added to overall output

                output += ptp_motion_conf
            elif statement.Type == VC_STATEMENT_LINMOTION:
                output += ptp_motion_conf #using data of VC_STATEMENT_PTPMOTION from last iteration

        def get_initialconf(*args):
            global output
            if statement.Type == VC_STATEMENT_LINMOTION:
                ...

            elif statement.Type == VC_STATEMENT_PTPMOTION:
                get_conf()

        statements = [] # getting list of statements to know which of LinMotion or PtpMotion goes first
        for statement in main_routine.Statements:
            statements.append(statement.Type)

        if statements.index("LinMotion") < statements.index("PtpMotion"): #statement LinMotion goes first
            get_initialconf()
        elif statements.index("LinMotion") > statements.index("PtpMotion"):#statement PtpMotion goes first
            get_conf()

i will try to show in sample:

If LinMotions statement goes first, before PtpMotion then:

LinMotion (some special initial data)
LinMotion (still initial data)
...
in all other LinMotion statements prog still uses initial data until PtpMotion statement appears:

PtpMotion (its own PtpMotion  data)

if LinMotion appears again, data from last PtpMotion statement is used

If PtpMotion statement goes first, before LinMotion, then
PtpMotion (its own PtpMotion  data)

If Linmotion appears, data from last PtpMotion statement is used

Body:
(Edit: I've updated the code to reflect new information in your post.)

If I understand your problem corrrectly, a simple description of what you're trying to achieve is this: you have a list of Statement instances in main_routine.Statements and you want to perform different code based on statement.Type. Here is the natural structure this usually (read: almost always) takes in Python code.

# no idea what this is in your code, but since you want to save it
# to a file, I'll blindy assume it is a string.
output = ""

# current stream of statements. accumulate as long as type is compatible.
stream = []

# process each statement.
for statement in main_routine.Statements:

    if statement.Type == VC_STATEMENT_LINMOTION:
        stream.append(statement)

    elif statement.Type == VC_STATEMENT_PTPMOTION:
        if (len(stream) > 0) and (stream[-1].Type == VC_STATEMENT_LINMOTION):
            output += process_linmotion_stream(stream)
            stream = []
            continue
        stream.append(statement)

    # ignore other types of statements.

# after loop, make sure leftover statements are processed.
output += process_linmotion_stream(stream)

Honestly, I think everybody, not just yourself, is confused with you've written. Switch to a simple control flow that models your data and you should be fine.


问:
Angular 2- Parent with multiple children
I have a situation where at first seemed fairly straight forward to myself but after a couple of days changing my solution structure it has become so convoluted!
Well I have a got a parent/child component relationship as following:

Parent

Child 1

Grandchild 1

Grandchild 2

Grandchild 3

Child 2

Grandchild 1

Grandchild 2

Grandchild 3

Each of these components (parent, child and grand child) has a property as "isValid" and a "validate()" method. All I want to achieve is a solution in which each component validity state depends on its own validate logic PLUS validity of all children component.
Here is a simple validation rules for each component:

Parent isValid = true if all children and grandchildren are valid

Child isValid = true if number of its children neither more than 3 and nor less than 1 Plus all children are valid

grandchild isValid = true if the textbox within it has a value

I have already read this https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-on-changes and tried all possible ways it describes but neither fits my requirements of having the parent level component valid if ALL its children are valid!

thanks for your advice in advance :)

答:
You didn't specify why the official documentation didn't help you..

Basically you need to follow the master/detail  guide.

I guess I would have done it with couple of Boolean array's...

Last say 'parent' has an array of 2, representing it's two children.

So

```<code>parentValid:boolean[]=[false,false];
</code>```

Every child has the same concept for it's children (Mark as grandchildren)

```<code>childValid:boolean[]=[false,false,false];
</code>```

The grandchild should only have an emitter witch notify it's parent on valid change. On every event like that, update childValid and do your logic there (More then 3 nor less then 1...) and emit the result to it's parent.

Body:
You didn't specify why the official documentation didn't help you..

Basically you need to follow the master/detail  guide.

I guess I would have done it with couple of Boolean array's...

Last say 'parent' has an array of 2, representing it's two children.

So

parentValid:boolean[]=[false,false];

Every child has the same concept for it's children (Mark as grandchildren)

childValid:boolean[]=[false,false,false];

The grandchild should only have an emitter witch notify it's parent on valid change. On every event like that, update childValid and do your logic there (More then 3 nor less then 1...) and emit the result to it's parent.


问:
Method to return username and Id
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

```<code> ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password
</code>```

This is my method:

```<code> public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }
</code>```

This is my User class:

```<code> public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
</code>```

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

答:
```<code>using (SqlConnection con = new SqlConnection(conexion))
        {
            SqlCommand comObj = new SqlCommand("spLogin", con);
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
            comObj.Parameters.Add(new SqlParameter("@password", User.Password));
            con.Open();
            var dr = comObj.ExecuteReader();
            while(dr.Read())
            {
              var userId = dr["Id"];
              var username = dr["Username"];
              // do something with your data....
            }
            con.Close();
        }
</code>```

You could also use output parameters. Google it: https://www.google.no/search?q=stored+procedures+output+parameters&oq=stored+procedures+output+parameters

You are putting passwords as clear text in your database. Don't do that. Please read my article on Codeproject: https://www.codeproject.com/Articles/425150/Beginners-guide-to-a-secure-way-of-storing-passwor

Title: Method to return username and Id

Body:
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

 ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password

This is my method:

 public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }

This is my User class:

 public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

Body:
using (SqlConnection con = new SqlConnection(conexion))
        {
            SqlCommand comObj = new SqlCommand("spLogin", con);
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
            comObj.Parameters.Add(new SqlParameter("@password", User.Password));
            con.Open();
            var dr = comObj.ExecuteReader();
            while(dr.Read())
            {
              var userId = dr["Id"];
              var username = dr["Username"];
              // do something with your data....
            }
            con.Close();
        }

You could also use output parameters. Google it: https://www.google.no/search?q=stored+procedures+output+parameters&oq=stored+procedures+output+parameters

You are putting passwords as clear text in your database. Don't do that. Please read my article on Codeproject: https://www.codeproject.com/Articles/425150/Beginners-guide-to-a-secure-way-of-storing-passwor