问:
QT reformat date time string
I've got a QString that contains a date in the following format:

2014-03-18 09:30:36

How can i format it to: HH:mm?

答:
```<code>function todayDate(){
    var months = [ "jan", "feb", "mar", "apr", "may", "jun",
       "jul", "aug", "sep", "oct", "nov", "dec" ];
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();

    var yyyy = today.getFullYear();
    if(dd<10){
        dd='0'+dd;
    }
    if(mm<10){
        mm='0'+mm;
    }
    var today = dd+months[mm]+yyyy;
    console.log("Date::::::::::::::::"+today)
}
</code>```

I hope this function of mine helps!!

Title: QT reformat date time string

Body:
function todayDate(){
    var months = [ "jan", "feb", "mar", "apr", "may", "jun",
       "jul", "aug", "sep", "oct", "nov", "dec" ];
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();

    var yyyy = today.getFullYear();
    if(dd<10){
        dd='0'+dd;
    }
    if(mm<10){
        mm='0'+mm;
    }
    var today = dd+months[mm]+yyyy;
    console.log("Date::::::::::::::::"+today)
}

I hope this function of mine helps!!


来源: stackexchange

问:
What is the correct SharePoint CAML query to retrieve all items from a list?
For some reason I am trying to query SharePoint 2007 using CAML and web services with the Python suds library. The call looks like:

```<code>listItems = client.service.GetListItems(
    listName, '', Raw('<Query />'), viewFields, 0,
    Raw("""<QueryOptions>
       <IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>
       </QueryOptions>"""),
    None)
</code>```

For some reason, I get 0 results or an error with <Query/> or <Query><Where/></Query> but get all items with a simple tautology WHERE x = 1 OR x != 1.

What is the correct way to just get all list items?

答:
there is a silly thing about it, you have to wrap your Query within a query element. The resulting SOAP envelope looks like

```<code><soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
 <soapenv:Body>
  <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
     <listName>TestQuery</listName>
     <query><Query><Where><Eq><FieldRef Name='Title'/>
      <Value Type='Text'>One</Value></Eq></Where></Query>
     </query>
     <viewFields><ViewFields><FieldRefName='Title'/>
  </ViewFields></viewFields><RowLimit>1</RowLimit>
 </GetListItems></soapenv:Body></soapenv:Envelope>
</code>```

As a result, the GetListItems web service decides that your query is wrong and returns no items.

See also this post: GetListItems Webservice ignores my query filter

ContentLicense: CC BY-SA 2.5

Body:
For some reason I am trying to query SharePoint 2007 using CAML and web services with the Python suds library. The call looks like:

listItems = client.service.GetListItems(
    listName, '', Raw('<Query />'), viewFields, 0,
    Raw("""<QueryOptions>
       <IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>
       </QueryOptions>"""),
    None)

For some reason, I get 0 results or an error with <Query/> or <Query><Where/></Query> but get all items with a simple tautology WHERE x = 1 OR x != 1.

What is the correct way to just get all list items?

Body:
there is a silly thing about it, you have to wrap your Query within a query element. The resulting SOAP envelope looks like

<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
 <soapenv:Body>
  <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
     <listName>TestQuery</listName>
     <query><Query><Where><Eq><FieldRef Name='Title'/>
      <Value Type='Text'>One</Value></Eq></Where></Query>
     </query>
     <viewFields><ViewFields><FieldRefName='Title'/>
  </ViewFields></viewFields><RowLimit>1</RowLimit>
 </GetListItems></soapenv:Body></soapenv:Envelope>

As a result, the GetListItems web service decides that your query is wrong and returns no items.

See also this post: GetListItems Webservice ignores my query filter


问:
Is global objects (e.g. Array) are part of Javascript programming Language?
I read  the ECMAScript Doc and MDN Documents

In browser or node environment, Javascript provides some global objects like Array and they have functions like filter and map.

The question is: are these objects/functions part of the "Javascript Language" or are there just provided by the "environment"?

答:
Functions like filter and map are described in standards. This means that all browsers that follow those standards should implement them in the same way, making them act the same way, without exception.

For example, for filter, there is this page: here which explains the function, and at the bottom you can see links to the document which explains exactly how the function should behave, what parameters it should have, what it should return, etc.

ContentLicense: CC BY-SA 3.0


问:
Data Frame Mapping in spark scala?
I have a data set like below

```<code>INo,Sc,Desc,Quan,IDate,UPice,CID,Country
1,2,"H,H",6,12-1-2010 8:26,2.55,c1,United Kingdom
2,3,"WE,RN",6,12-1-2010 8:26,3.39,c2,United Kingdom
3,3,CREAM ,8,12-1-2010 8:26,2.75,c3,United Kingdom
4,4,KLE,6,12-1-2010 8:26,3.39,c4,United Kingdom
5,5,"DI,AMR,ROR, ",2,1-7-2011 13:55,11.02,c5,United Kingdom
6,6,SU"asasa,1,12-9-2010 16:26,11.02,c6,United Kingdom
</code>```

I have created Data frame by executing below code:

```<code>case class Rating(CID: String, SC: String, rating: Double)
def parseRating(str: String): Rating = {
val fields = str.split(",")
Rating(fields(6), fields(1), 1.0D)
}
val ratings = spark.read.textFile("C:/Users/test/Desktop/test123.txt").map(parseRating).toDF().dropDuplicates("CID", "SC")
ratings.collect().map(t => println(t))
ratings.show()
</code>```

I am getting output like below

```<code>+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|12-9-2010 16:26|  6|   1.0|
|             c3|  3|   1.0|
|            CID| Sc|   1.0|
|             c4|  4|   1.0|
|           3.39|  3|   1.0|
|              2|  5|   1.0|
|           2.55|  2|   1.0|
+---------------+---+------+
</code>```

Here I came to because of field=str.split(",").input data is
6,6,"SET,CO,SU",1,12-9-2010 16:26,11.02,c6,United Kingdom

But my expected output is

```<code>+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|             c6|  6|   1.0|
|             c3|  3|   1.0|
|             c2|  3|   1.0|
|             c4|  4|   1.0|
|             c5|  5|   1.0|
|             c1|  2|   1.0|
+---------------+---+------+
</code>```

Please help me on this.

Title: Data Frame Mapping in spark scala?

Body:
I have a data set like below

INo,Sc,Desc,Quan,IDate,UPice,CID,Country
1,2,"H,H",6,12-1-2010 8:26,2.55,c1,United Kingdom
2,3,"WE,RN",6,12-1-2010 8:26,3.39,c2,United Kingdom
3,3,CREAM ,8,12-1-2010 8:26,2.75,c3,United Kingdom
4,4,KLE,6,12-1-2010 8:26,3.39,c4,United Kingdom
5,5,"DI,AMR,ROR, ",2,1-7-2011 13:55,11.02,c5,United Kingdom
6,6,SU"asasa,1,12-9-2010 16:26,11.02,c6,United Kingdom

I have created Data frame by executing below code:

case class Rating(CID: String, SC: String, rating: Double)
def parseRating(str: String): Rating = {
val fields = str.split(",")
Rating(fields(6), fields(1), 1.0D)
}
val ratings = spark.read.textFile("C:/Users/test/Desktop/test123.txt").map(parseRating).toDF().dropDuplicates("CID", "SC")
ratings.collect().map(t => println(t))
ratings.show()

I am getting output like below

+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|12-9-2010 16:26|  6|   1.0|
|             c3|  3|   1.0|
|            CID| Sc|   1.0|
|             c4|  4|   1.0|
|           3.39|  3|   1.0|
|              2|  5|   1.0|
|           2.55|  2|   1.0|
+---------------+---+------+

Here I came to because of field=str.split(",").input data is
6,6,"SET,CO,SU",1,12-9-2010 16:26,11.02,c6,United Kingdom

But my expected output is

+---------------+---+------+
|            CID| SC|rating|
+---------------+---+------+
|             c6|  6|   1.0|
|             c3|  3|   1.0|
|             c2|  3|   1.0|
|             c4|  4|   1.0|
|             c5|  5|   1.0|
|             c1|  2|   1.0|
+---------------+---+------+

Please help me on this.

Body:
If you are using Spark 2, you can do it like below:

val data = spark.read.option("header", true).csv("test123.txt")
data.select("CID", "Sc").withColumn("rating", lit(1.0)).show
+---+---+------+
|CID| Sc|rating|
+---+---+------+
| c1|  2|   1.0|
| c2|  3|   1.0|
| c3|  3|   1.0|
| c4|  4|   1.0|
| c5|  5|   1.0|
| c6|  6|   1.0|
+---+---+------+


问:
NERDTree command automatically change directory and root directory
Is it possible that whenever I select a directory and enter that directory from the NERDTree it should become the root directory? That is, every time I select a new directory the following two commands will be triggered: cd and :NERDTreeCWD?

Thanks!

答: set in your vimrc: let g:NERDTreeChDirMode = 2


问:
To show only a part of the v-model data based on a condition
Here is my fiddle : DEMO

```<code>methods: {
  create() {
    console.log(JSON.stringify(this.modules, null, 4))
  }
}
</code>```

I have modules, their actions and its permissions.

```<code><div v-for="(module, moduleIndex) in modules"><b>{{ module.moduleName }}</b>
    <div v-for="(action, actionIndex) in module.actions">{{ action.actionName }}
      <div v-for="(permission, permIndex) in action.permissions">
        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}
      </div>
    </div>
</code>```

On choice of the checkboxes, the associated v-model gets updated. Is there a way I show only permissions for which the value in "true" in v-model or the displayed content.

Any help would be much appreciated. Thank you!

答:
Since your view is already updating based on the values from the model with v-if I think what you want is that your JSON.stringify(modules) is updating accordingly.

You can do that by creating a computed property that deletes the permissions if their value is false.

An example could be this:

```<code>computed: {
    updated_modules: function() {
      var updated = JSON.parse(JSON.stringify(this.modules));
      for(i = 0; i < updated.length; i++) {
        for(k = 0; k < updated[i].actions.length; k++) {
          for (j = 0; j < updated[i].actions[k].permissions.length; j++) {
            if(updated[i].actions[k].permissions[j].value == false) {
              updated[i].actions[k].permissions.splice(j, 1);
            }
          }
        }
      }
      return updated;
    }
},
</code>```

And then of course you wouldn't stringify the modules but updated_modules, see the updated fiddle:
https://jsfiddle.net/c7amyx6o/2/

Body:
Here is my fiddle : DEMO

methods: {
  create() {
    console.log(JSON.stringify(this.modules, null, 4))
  }
}

I have modules, their actions and its permissions.

{{ module.moduleName }}

{{ action.actionName }}

        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}

On choice of the checkboxes, the associated v-model gets updated. Is there a way I show only permissions for which the value in "true" in v-model or the displayed content.

Any help would be much appreciated. Thank you!

Body:
Since your view is already updating based on the values from the model with v-if I think what you want is that your JSON.stringify(modules) is updating accordingly.

You can do that by creating a computed property that deletes the permissions if their value is false.

An example could be this:

computed: {
    updated_modules: function() {
      var updated = JSON.parse(JSON.stringify(this.modules));
      for(i = 0; i < updated.length; i++) {
        for(k = 0; k < updated[i].actions.length; k++) {
          for (j = 0; j < updated[i].actions[k].permissions.length; j++) {
            if(updated[i].actions[k].permissions[j].value == false) {
              updated[i].actions[k].permissions.splice(j, 1);
            }
          }
        }
      }
      return updated;
    }
},

And then of course you wouldn't stringify the modules but updated_modules, see the updated fiddle:
https://jsfiddle.net/c7amyx6o/2/


问:
How can I add a missing PyQt5 modules on Raspberry Pi
I am using PyQt5 version 5.7, python 3.5.3 and raspbian. My problem is that in my code some modules of PyQt5 get recognized and produce no error and some do.

The error I get: ImportError: cannot import name 'QMultimedia'

So why does QtCore/Widgets/Gui get reconized but not QMultimedia? Do I need to install some extra packages? Do I need to reinstall and do something special? This might be a trivial question but please help me.

Note: I also tried: from PyQt5 import QtMultimedia

```<code>import numpy as np
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QMultimedia
from PyQt5 import QCameraInfo
from PyQt5 import QVideoWidget
from PyQt5 import QMediaObject
from PyQt5.QtCore import pyqtSignal

class Camera():
    def iniCamera():
        cam = QCamera()
        caminfo = QCameraInfo(cam)
        print (caminfo.description)

        if caminfo.isNull() != True:
           cam = QCamera(caminfo.deviceName())
           print (caminfo.description)

if __name__ == '__main__':

    iniCamera()
</code>```

答:
Check your site-packages folder to see if this package actually exists.

If you are working behind a virtualenv (which you should), make sure it's activated. Using pip3 freeze, see if PyQt5 is correctly installed.

Then, install a pylint extension, this can help you in future missing packages and other stuff.

Body:
I am using PyQt5 version 5.7, python 3.5.3 and raspbian. My problem is that in my code some modules of PyQt5 get recognized and produce no error and some do.

The error I get: ImportError: cannot import name 'QMultimedia'

So why does QtCore/Widgets/Gui get reconized but not QMultimedia? Do I need to install some extra packages? Do I need to reinstall and do something special? This might be a trivial question but please help me.

Note: I also tried: from PyQt5 import QtMultimedia

import numpy as np
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QMultimedia
from PyQt5 import QCameraInfo
from PyQt5 import QVideoWidget
from PyQt5 import QMediaObject
from PyQt5.QtCore import pyqtSignal

class Camera():
    def iniCamera():
        cam = QCamera()
        caminfo = QCameraInfo(cam)
        print (caminfo.description)

        if caminfo.isNull() != True:
           cam = QCamera(caminfo.deviceName())
           print (caminfo.description)

if __name__ == '__main__':

    iniCamera()


问:
Page object covers fixed navigationbar
Im creating a simple website where I want the navigation bar to always stay on the top of the page and I want it to always be visible.

I achieved this, but when scrolling past some elements, the navigationbar is covered up by said elements.

I have googled around for a bit, and everyone says to add "z-index: 1", but the navbar (which I did not make myself) uses z-index: 2 and -1, and if I change it to 1, the navbar just gets wonky. I'm probably just changing the z-index of the wrong object or something stupid, but I feel like I have tried everything here..

I may or may not have copy-pasted a lot :P

HTML:

```<code><a relatively normal list> things in the list</a relatively normal list>
</code>```

CSS:

```<code>#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
line-height: 1;
display: block;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#cssmenu {
width: 100%;
border-bottom: 3px solid #a24fef;
font-family: Raleway, sans-serif;
line-height: 1;
}
#cssmenu ul {
background: rgb(220, 220, 0);
background: rgba(220, 220, 0, 0);
}
#cssmenu > ul > li {
float: left;
}
#cssmenu.align-center > ul {
font-size: 0;
text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right > ul > li > a {
  margin-right: 0;
  margin-left: -4px;
}
#cssmenu > ul > li > a {
  z-index: 2;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
#cssmenu > ul > li.active > a:after,
#cssmenu > ul > li:hover > a:after,
#cssmenu > ul > li > a:hover:after {
  background: #a24fef;
}
</code>```

EDIT:  Here is a jsfiddle with more code and it shows what happens. WARNING: THIS INCLUDES A GIVEAWAY WHICH PROMOTES STUFF. (couldn't figure out how to use an example giveaway so I used my friend's one.)

https://jsfiddle.net/vvqLLb1x/

答:
There's really not enough code here to do much, but z-index is most likely what you will need to address to fix this issue.

In your code you have the following:

```<code>z-index: 2;
</code>```

Think of a z-index of 0 as sea level. Whatever we stack above that line will have a positive z axis (thinking in 3 dimensions). When you are looking at a web page, you are looking down at it (helicopter view). The items with the highest z index will be visible and the items with a lower z-index (assuming they are on top of each other) will not be visible.

Somewhere on your page must be an element that has a higher z-index than the elements in your navbar. You can raise the z-index even higher than single digits.

```<code>#cssmenu > ul > li > a {
  z-index: 99;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 97;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
</code>```

Without seeing the rest of your code, I can't be sure. Try this and let me know if it helps. If not, you will probably need to give us a little more code to look at. I hope this helps.

Edit: Try this:

```<code>html body .e-widget-preloader, html body iframe.e-embed-frame {
    z-index: -1 !important;
}
</code>```

add that to your css file

Title: Page object covers fixed navigationbar

Body:
Im creating a simple website where I want the navigation bar to always stay on the top of the page and I want it to always be visible.

I achieved this, but when scrolling past some elements, the navigationbar is covered up by said elements.

I have googled around for a bit, and everyone says to add "z-index: 1", but the navbar (which I did not make myself) uses z-index: 2 and -1, and if I change it to 1, the navbar just gets wonky. I'm probably just changing the z-index of the wrong object or something stupid, but I feel like I have tried everything here..

I may or may not have copy-pasted a lot :P

HTML:

 things in the list

CSS:

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
line-height: 1;
display: block;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#cssmenu {
width: 100%;
border-bottom: 3px solid #a24fef;
font-family: Raleway, sans-serif;
line-height: 1;
}
#cssmenu ul {
background: rgb(220, 220, 0);
background: rgba(220, 220, 0, 0);
}
#cssmenu > ul > li {
float: left;
}
#cssmenu.align-center > ul {
font-size: 0;
text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right > ul > li > a {
  margin-right: 0;
  margin-left: -4px;
}
#cssmenu > ul > li > a {
  z-index: 2;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
#cssmenu > ul > li.active > a:after,
#cssmenu > ul > li:hover > a:after,
#cssmenu > ul > li > a:hover:after {
  background: #a24fef;
}

EDIT:  Here is a jsfiddle with more code and it shows what happens. WARNING: THIS INCLUDES A GIVEAWAY WHICH PROMOTES STUFF. (couldn't figure out how to use an example giveaway so I used my friend's one.)

https://jsfiddle.net/vvqLLb1x/

Body:
There's really not enough code here to do much, but z-index is most likely what you will need to address to fix this issue.

In your code you have the following:

z-index: 2;

Think of a z-index of 0 as sea level. Whatever we stack above that line will have a positive z axis (thinking in 3 dimensions). When you are looking at a web page, you are looking down at it (helicopter view). The items with the highest z index will be visible and the items with a lower z-index (assuming they are on top of each other) will not be visible.

Somewhere on your page must be an element that has a higher z-index than the elements in your navbar. You can raise the z-index even higher than single digits.

#cssmenu > ul > li > a {
  z-index: 99;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 97;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}

Without seeing the rest of your code, I can't be sure. Try this and let me know if it helps. If not, you will probably need to give us a little more code to look at. I hope this helps.

Edit: Try this:

html body .e-widget-preloader, html body iframe.e-embed-frame {
    z-index: -1 !important;
}

add that to your css file


问:
Linetype can not be changed with element_line
I want to create a plot with the following data as example:

```<code>library(data.table)
library(ggplot2)
library(plotly)

Data <- data.table(Datum = c("2017-11-01","2017-11-02","2017-11-03","2017-11-04","2017-11-05","2017-11-06","2017-11-07","2017-11-08","2017-11-09","2017-11-10"),Index = c(200,250,230,210,190,215,216,250,260,245), Long = c(c(250,220,225,215,240,255,256,266,223,222)))
Data$Datum <- as.Date(Data$Datum, format = "%Y-%m-%d")

startdate <- min(Data$Datum)
enddate <- max(Data$Datum)

plot <- ggplot(Data, aes(Datum)) +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) +
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) +
  theme(panel.background = element_rect(fill = "white")) +
  theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(size = 0.5, colour = "grey", linetype = "dotted")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks=seq(0,300,20)) +
  scale_x_date(breaks = seq(as.Date(startdate), as.Date(enddate), by="2 month"), date_labels = "%m %Y") +
  ylab("") +
  xlab("")

plot <- ggplotly(plot)
print(plot)
</code>```

But as you can see in the graph, the linetype of the x grid is still solid, even if set with linetype = "dotted"

How can I change the linetype or what is wrong with my approach?

答:
From your code, it can be seen that the plot comes out as desired within ggplot, but loses the dashed lines once converted into plotly. As mentioned within the comments, this appears to be a limitation of plotly. However, this is a workaround you can use.

As the ggplotly function can handle aesthetics from the geom_line function, an easy way to fix this is to remove the Y lines and just add some manually specified horizontal lines, as below using the geom_hline function:

```<code>plot <- ggplot(Data, aes(Datum)) +
  geom_hline(yintercept =c(200, 220, 240, 260), size = 0.5, colour = "grey", linetype = "dotted") +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) +
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) +
  scale_y_continuous(breaks=seq(0,300,20)) +
  ylab("") +
  xlab("") +
  theme(panel.background = element_rect(fill = "white"),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank())

plot <- ggplotly(plot)
print(plot)
</code>```

Check out here for more documentation on the geom_line functions.

Instead of manually specifying the steps, you can add to automatically determine the line spacing by finding the maximum and minimum y values then creating a sequence:

```<code>min.plot <- roundUP(min(Data$Index,Data$Long),10) - 20
max.plot <- max(Data$Index,Data$Long) + 20
y.axis <- seq(from = min.plot, to = max.plot, by = 10)
</code>```

and edit the geom_hline argument to:

```<code>geom_hline(yintercept = y.axis, size = 0.5, colour = "grey", linetype = "dotted")
</code>```

Body:
I want to create a plot with the following data as example:

library(data.table)
library(ggplot2)
library(plotly)

Data <- data.table(Datum = c("2017-11-01","2017-11-02","2017-11-03","2017-11-04","2017-11-05","2017-11-06","2017-11-07","2017-11-08","2017-11-09","2017-11-10"),Index = c(200,250,230,210,190,215,216,250,260,245), Long = c(c(250,220,225,215,240,255,256,266,223,222)))
Data$Datum <- as.Date(Data$Datum, format = "%Y-%m-%d")

startdate <- min(Data$Datum)
enddate <- max(Data$Datum)

plot <- ggplot(Data, aes(Datum)) +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) +
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) +
  theme(panel.background = element_rect(fill = "white")) +
  theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(size = 0.5, colour = "grey", linetype = "dotted")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks=seq(0,300,20)) +
  scale_x_date(breaks = seq(as.Date(startdate), as.Date(enddate), by="2 month"), date_labels = "%m %Y") +
  ylab("") +
  xlab("")

plot <- ggplotly(plot)
print(plot)

But as you can see in the graph, the linetype of the x grid is still solid, even if set with linetype = "dotted"

How can I change the linetype or what is wrong with my approach?

Body:
From your code, it can be seen that the plot comes out as desired within ggplot, but loses the dashed lines once converted into plotly. As mentioned within the comments, this appears to be a limitation of plotly. However, this is a workaround you can use.

As the ggplotly function can handle aesthetics from the geom_line function, an easy way to fix this is to remove the Y lines and just add some manually specified horizontal lines, as below using the geom_hline function:

plot <- ggplot(Data, aes(Datum)) +
  geom_hline(yintercept =c(200, 220, 240, 260), size = 0.5, colour = "grey", linetype = "dotted") +
  geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) +
  geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) +
  scale_y_continuous(breaks=seq(0,300,20)) +
  ylab("") +
  xlab("") +
  theme(panel.background = element_rect(fill = "white"),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank())

plot <- ggplotly(plot)
print(plot)

Check out here for more documentation on the geom_line functions.

Instead of manually specifying the steps, you can add to automatically determine the line spacing by finding the maximum and minimum y values then creating a sequence:

min.plot <- roundUP(min(Data$Index,Data$Long),10) - 20
max.plot <- max(Data$Index,Data$Long) + 20
y.axis <- seq(from = min.plot, to = max.plot, by = 10)

and edit the geom_hline argument to:

geom_hline(yintercept = y.axis, size = 0.5, colour = "grey", linetype = "dotted")


问:
How do I calculate an condition based upon input answer in Python?
Need some help with this question. I did not find anything in the search, but that can be because I am not entirely sure on what to ask or define the problem.

I will try to do this here.

So I wanted to make a SAC Calculator for scuba diving. That is in lamens terms a calculator to calculate air consumption basically.

The formula for metric is VT x VC / T / P = SAC
More info here https://www.divein.com/guide/know-your-air-consumption/

I ran into some issues when calculating the air consumption as it seems I need to convert in somehow the input from the user into a value.

The user answers the question, how deep was your dive in meters(or feet)? Well this is pretty straight forward as the user would answer i.e. 30 meters / 100 feet.

However for the calculator to work correctly, I would need to calculate using the ATM model. As depth increases under water, the atmospheric pressure also increases as seen in this image:

So if the user enters a value of 30 meters, I need to know the ATM value for this answer.

I tried to make an if statement to fix this, but I do not belive this might be the better approach.

Here is the code so far

```<code>    #SAC Rate Calculator
#This program will calculate your air consumption rate for scuba diving
#Made by Tom Knudsen - post@tknudsen.com
#License is open source

import os
import time

os.system('clear')
print('***********************************')
print('***********************************')
print('**********SAC Calculator***********')
print('****************by*****************')
print('************Tom Knudsen************')
print('***********************************')
print('***********************************')
print('')
print('')
print('Welcome to the SAC calculator')
time.sleep(1)

# This code is to first determain the air consumption in bar)
print('First we need to calculate your air consumption in bar')
tankVolum = input('How large is your tank in litres? :')
startBar = input('Please enter your start pressure in BAR: ') #starting pressure with full cooled tank
endBar = input('Please enter your end pressure in BAR: ') #ending pressure with cooled tank
totalBar = startBar - endBar
time.sleep(2)
print('Thank you, your total pressure used is: ') #feedback to the user
print(totalBar)
time.sleep(3)
os.system('clear')
# Input to calculate air consumption in litres
print("Let's now see how much Surface Air Concumption in litre you used!")
time.sleep(2)
print('First we need to know a little bit about your dive :')
time.sleep(2)
depth = input('How deep was your dive in meter? :')
time.sleep(2)
diveTime = input('How long was your dive in minutes? :')
time.sleep(2)
print('Let me calculate, please wait...')

#this is my test, I do not know how to get "depthTotal" as this calue equals ATM pressure and P in the equation formula above.
if depth <= 10:
    a = 2
elif depth >10 and <= 20:
    b = 3
elif depath >20 and <= 30:
    c = 4
    else:
        print('You need to enter a depth between 0 and 40 meter')

sacResults = tankVolum x totalBar / diveTime / depthTotal

 # Example =  12 Liter x 150 bar used / 46 minutes dive time / 30 meter depth
 # sacResults = 12 * 150 / 46 / 3
</code>```

答:
The easiest way to fix your problem would be to do something like this:

```<code>#this is my test, I do not know how to get "depthTotal" as this calue equals ATM pressure and P in the equation formula above.

depth_total = None
if depth <= 10:
    depth_total  = 2
elif depth >10 and <= 20:
    depth_total  = 3
elif depath >20 and <= 30:
    depth_total  = 4
    else:
        print('You need to enter a depth between 0 and 40 meter')

sacResults = tankVolum x totalBar / diveTime / depthTotal
</code>```

You can do it in a simpler way since it seems that the ATM are proportional to the depth (1 bar of pressure for every 33 feets), you could create a simple function converting depth into ATM:

```<code>def depth_to_atm(depth_in_meters):
    (depth_in_meters*3.2808)/ 33 # apparently 1 bar equals 33 feet of water
                                 # (3.2808 is how many feet there are in a meter)
</code>```

And use that function in your formula.

Body:
Need some help with this question. I did not find anything in the search, but that can be because I am not entirely sure on what to ask or define the problem.

I will try to do this here.

So I wanted to make a SAC Calculator for scuba diving. That is in lamens terms a calculator to calculate air consumption basically.

The formula for metric is VT x VC / T / P = SAC
More info here https://www.divein.com/guide/know-your-air-consumption/

I ran into some issues when calculating the air consumption as it seems I need to convert in somehow the input from the user into a value.

The user answers the question, how deep was your dive in meters(or feet)? Well this is pretty straight forward as the user would answer i.e. 30 meters / 100 feet.

However for the calculator to work correctly, I would need to calculate using the ATM model. As depth increases under water, the atmospheric pressure also increases as seen in this image:

So if the user enters a value of 30 meters, I need to know the ATM value for this answer.

I tried to make an if statement to fix this, but I do not belive this might be the better approach.

Here is the code so far

    #SAC Rate Calculator
#This program will calculate your air consumption rate for scuba diving
#Made by Tom Knudsen - post@tknudsen.com
#License is open source

import os
import time

os.system('clear')
print('***********************************')
print('***********************************')
print('**********SAC Calculator***********')
print('****************by*****************')
print('************Tom Knudsen************')
print('***********************************')
print('***********************************')
print('')
print('')
print('Welcome to the SAC calculator')
time.sleep(1)

# This code is to first determain the air consumption in bar)
print('First we need to calculate your air consumption in bar')
tankVolum = input('How large is your tank in litres? :')
startBar = input('Please enter your start pressure in BAR: ') #starting pressure with full cooled tank
endBar = input('Please enter your end pressure in BAR: ') #ending pressure with cooled tank
totalBar = startBar - endBar
time.sleep(2)
print('Thank you, your total pressure used is: ') #feedback to the user
print(totalBar)
time.sleep(3)
os.system('clear')
# Input to calculate air consumption in litres
print("Let's now see how much Surface Air Concumption in litre you used!")
time.sleep(2)
print('First we need to know a little bit about your dive :')
time.sleep(2)
depth = input('How deep was your dive in meter? :')
time.sleep(2)
diveTime = input('How long was your dive in minutes? :')
time.sleep(2)
print('Let me calculate, please wait...')

#this is my test, I do not know how to get "depthTotal" as this calue equals ATM pressure and P in the equation formula above.
if depth <= 10:
    a = 2
elif depth >10 and <= 20:
    b = 3
elif depath >20 and <= 30:
    c = 4
    else:
        print('You need to enter a depth between 0 and 40 meter')

sacResults = tankVolum x totalBar / diveTime / depthTotal

 # Example =  12 Liter x 150 bar used / 46 minutes dive time / 30 meter depth
 # sacResults = 12 * 150 / 46 / 3

Body:
The easiest way to fix your problem would be to do something like this:

#this is my test, I do not know how to get "depthTotal" as this calue equals ATM pressure and P in the equation formula above.

depth_total = None
if depth <= 10:
    depth_total  = 2
elif depth >10 and <= 20:
    depth_total  = 3
elif depath >20 and <= 30:
    depth_total  = 4
    else:
        print('You need to enter a depth between 0 and 40 meter')

sacResults = tankVolum x totalBar / diveTime / depthTotal

You can do it in a simpler way since it seems that the ATM are proportional to the depth (1 bar of pressure for every 33 feets), you could create a simple function converting depth into ATM:

def depth_to_atm(depth_in_meters):
    (depth_in_meters*3.2808)/ 33 # apparently 1 bar equals 33 feet of water
                                 # (3.2808 is how many feet there are in a meter)

And use that function in your formula.


问:
Displaying String values on Y-axis using d3.js
I am new to D3.js and got one issue.
I tried to create bar using some sample data.

```<code> var data = [{"date":"Chennai","value":"53"},
            {"date":"Banglore","value":"165"},
            {"date":"Pune","value":"269"},
            {"date":"Ban","value":"344"},
            {"date":"Hyderabad","value":"376"},
            {"date":"HYd","value":"410"},
            {"date":"Gurugram","value":"421"},
            {"date":"Che","value":"376"}];
</code>```

Able to display Strings(Ex: "Bangalore" on X-axis and values on Y-axis but I need to display Strings on Y-axis and values on X-axis.

```<code>var margin = {top: 20, right: 20, bottom: 70, left: 60},
    width = 600 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var y = d3.scale.ordinal().rangeRoundBands([height,0]);

var x = d3.scale.linear().range([0, width]);

var data = [{"date":"Chennai","value":"53"},
            {"date":"Banglore","value":"165"},
            {"date":"Pune","value":"269"},
            {"date":"Ban","value":"344"},
            {"date":"Hyderabad","value":"376"},
            {"date":"HYd","value":"410"},
            {"date":"Gurugram","value":"421"},
            {"date":"Kadapa","value":"405"},
            {"date":"Che","value":"376"}]

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(12);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

    data.forEach(function(d) {
        d.value = +d.value;
    });

  y.domain(data.map(function(d) { return d.date; }));
  x.domain([0, d3.max(data, function(d) { return d.value; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" );

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

  svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.value); })
      .attr("width", function(d) { return width - x(d.value); })
      .attr("y", function(d) { return y(d.date); })
      .attr("height", y.rangeBand())
      .attr("title",function(d) { return y(d.value); });

      svg.selectAll("bar")
      .data(data)
      .enter()
      .append("text")
      .attr("class","label")
      .attr("y", (function(d) { return y(d.date) + y.rangeBand()/2 ; }  ))
      .attr("x", function(d) { return x(d.value) + 1; })
      .attr("dx", ".75em")
      .text(function(d) { return d.date; });
</code>```

When I tried with the above code bars are coming as Horizontal but need as vertical.

Please help me on this.

Thanks in Advance.

答:
You should be more accurate with your "height/x/y" manipulations :)

D3 uses coordinate space where x=0 and y=0 coordinates fall on the bottom left.

I've changed some of your code:
svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x",function(d) { return x(d.value); })
      .attr("width", y.rangeBand())
      .attr("y", function(d) { return height - y(d.date); })
      .attr("height", function(d) { return y(d.date); })
      .attr("title",function(d) { return y(d.value); });
and I've got the result

Bars are in the right places.
I believe you can figure out with titles by your own, if no - you  know what to do

ps: http://jsfiddle.net/om42ts61/

Body:
I am new to D3.js and got one issue.
I tried to create bar using some sample data.

 var data = [{"date":"Chennai","value":"53"},
            {"date":"Banglore","value":"165"},
            {"date":"Pune","value":"269"},
            {"date":"Ban","value":"344"},
            {"date":"Hyderabad","value":"376"},
            {"date":"HYd","value":"410"},
            {"date":"Gurugram","value":"421"},
            {"date":"Che","value":"376"}];

Able to display Strings(Ex: "Bangalore" on X-axis and values on Y-axis but I need to display Strings on Y-axis and values on X-axis.

var margin = {top: 20, right: 20, bottom: 70, left: 60},
    width = 600 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var y = d3.scale.ordinal().rangeRoundBands([height,0]);

var x = d3.scale.linear().range([0, width]);

var data = [{"date":"Chennai","value":"53"},
            {"date":"Banglore","value":"165"},
            {"date":"Pune","value":"269"},
            {"date":"Ban","value":"344"},
            {"date":"Hyderabad","value":"376"},
            {"date":"HYd","value":"410"},
            {"date":"Gurugram","value":"421"},
            {"date":"Kadapa","value":"405"},
            {"date":"Che","value":"376"}]

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(12);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

    data.forEach(function(d) {
        d.value = +d.value;
    });

  y.domain(data.map(function(d) { return d.date; }));
  x.domain([0, d3.max(data, function(d) { return d.value; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" );

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

  svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.value); })
      .attr("width", function(d) { return width - x(d.value); })
      .attr("y", function(d) { return y(d.date); })
      .attr("height", y.rangeBand())
      .attr("title",function(d) { return y(d.value); });

      svg.selectAll("bar")
      .data(data)
      .enter()
      .append("text")
      .attr("class","label")
      .attr("y", (function(d) { return y(d.date) + y.rangeBand()/2 ; }  ))
      .attr("x", function(d) { return x(d.value) + 1; })
      .attr("dx", ".75em")
      .text(function(d) { return d.date; });

When I tried with the above code bars are coming as Horizontal but need as vertical.

Please help me on this.

Thanks in Advance.


问:
how to accept part of variable(string) as dynamic value in cobol?
I have a field in working storage section WS_CONTRACT_NUM , this has few hard-coded values of leght 15 characters.But first 5 characters could be anything, my question is how can i declare this variable in that case.

```<code>WORKING STORAGE
 01 WS_CONTRACT_NUM PIC X(15) VALUE '?????9999999999' --- > instead of '?' what can i give so that dynamic value can be substituted in my query.
</code>```

And i am performing select query like this :

```<code>EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM = :WS_CONTRACT_NUM
END-EXEC
</code>```

Thanks in advance!

答:
PIC X is the any character symbol.  So PIC X(5)9(10).

Unless you need to do arithmetic, you could get away with PIC X(15).    Just because something is called "Number" doesn't mean it has to be stored as computational. It is more often than not more efficient to store fields called "Number" as character data. For instance Social Insurance Number - rarely do you have to add 1 or divide by 2, so you can get away with treating the field as PIC X.

Or to add clarity in this case:

```<code>01 ws-contract-value.
   05 first-part pic x(5).
   05 contract-number pic 9(10).   *> or x(10) unless you need to do math
</code>```

If you need to verify that the character data is all digits, you can use IF field IS NUMERIC ... for validation of PIC X fields.

Body:
I have a field in working storage section WS_CONTRACT_NUM , this has few hard-coded values of leght 15 characters.But first 5 characters could be anything, my question is how can i declare this variable in that case.

WORKING STORAGE
 01 WS_CONTRACT_NUM PIC X(15) VALUE '?????9999999999' --- > instead of '?' what can i give so that dynamic value can be substituted in my query.

And i am performing select query like this :

EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM = :WS_CONTRACT_NUM
END-EXEC

Thanks in advance!

Body:
PIC X is the any character symbol.  So PIC X(5)9(10).

Unless you need to do arithmetic, you could get away with PIC X(15).    Just because something is called "Number" doesn't mean it has to be stored as computational. It is more often than not more efficient to store fields called "Number" as character data. For instance Social Insurance Number - rarely do you have to add 1 or divide by 2, so you can get away with treating the field as PIC X.

Or to add clarity in this case:

01 ws-contract-value.
   05 first-part pic x(5).
   05 contract-number pic 9(10).   *> or x(10) unless you need to do math

If you need to verify that the character data is all digits, you can use IF field IS NUMERIC ... for validation of PIC X fields.


问:
Triangles algorithm
I have this problem to solve:

The input is a number and a triangle, for example:

```<code>5
#-##----#
 -----#-
  ---#-
   -#-
    -
</code>```

The number is count of rows of the triangle.

And I have to print the largest "triangle area" - the largest triangle made of -. For this one the answer is 9.

The triangle can also be upside down:

```<code>4
#-#-#--
 #---#
  ##-
   -
</code>```

For this, the output is 4.

I need some help with the algorithm. Please give me just a little help, not the whole algorithm, because I want to try to solve it by myself, I just need a direction.

答:
Hint

I assume that all triangles are of the form:

```<code>---
 -
</code>```

And not like:

```<code> -    or  -    or    -
---       --        --
          -          -
</code>```

Remark that a 2-units triangles is made up of three 1-unit triangles. A 3-unit triangles is made up of 3 overlapping 2-unit triangles, and so on.

The next figure is an example of a 3-unit triangles made up of three 2-units triangles, themselves made up of three 1-unit triangles

```<code>  - -+ -+* +* *            --- +++ ***
     -  +  *      ==>       -   +   *
        o                       o
</code>```

Spoiler: full algorithm follow, don't read it

```<code> /!\ spoiler alert /!\

 /!\ spoiler alert /!\

 /!\ spoiler alert /!\
</code>```

The main algorithm

You can do a first pass to compute all unit sized triangles (having exactly 1 - inside). Maintain a table where T[x,y] is the size of the triangle (length of its sides). In this pass you initialize every cell with a - to 1.

Then you can go from top to bottom and try to build more complex triangles.

When at position [x,y], you should consider the triangles whose down head is at:

[x-1,y-1]

[x  ,y-1]

[x+1,y-1]

The size of the new triangles will be 1 plus the minimum size of any of the 3 above triangles. Then you update the table T[x,y]

```<code>T[x,y+1] = 1 + min(T[x-1,y], T[x,y], T[x+1,y])
</code>```

At the end, just find the biggest sized triangles in your table T and compute the corresponding triangle area. (formula left as an exercise to the reader)

Complexity is O(n²).

Title: Triangles algorithm

Body:
I have this problem to solve:

The input is a number and a triangle, for example:

5
#-##----#
 -----#-
  ---#-
   -#-
    -

The number is count of rows of the triangle.

And I have to print the largest "triangle area" - the largest triangle made of -. For this one the answer is 9.

The triangle can also be upside down:

4
#-#-#--
 #---#
  ##-
   -

For this, the output is 4.

I need some help with the algorithm. Please give me just a little help, not the whole algorithm, because I want to try to solve it by myself, I just need a direction.

Body:
Hint

I assume that all triangles are of the form:

---
 -

And not like:

 -    or  -    or    -
---       --        --
          -          -

Remark that a 2-units triangles is made up of three 1-unit triangles. A 3-unit triangles is made up of 3 overlapping 2-unit triangles, and so on.

The next figure is an example of a 3-unit triangles made up of three 2-units triangles, themselves made up of three 1-unit triangles

  - -+ -+* +* *            --- +++ ***
     -  +  *      ==>       -   +   *
        o                       o

Spoiler: full algorithm follow, don't read it

 /!\ spoiler alert /!\

 /!\ spoiler alert /!\

 /!\ spoiler alert /!\

The main algorithm

You can do a first pass to compute all unit sized triangles (having exactly 1 - inside). Maintain a table where T[x,y] is the size of the triangle (length of its sides). In this pass you initialize every cell with a - to 1.

Then you can go from top to bottom and try to build more complex triangles.

When at position [x,y], you should consider the triangles whose down head is at:

[x-1,y-1]

[x  ,y-1]

[x+1,y-1]

The size of the new triangles will be 1 plus the minimum size of any of the 3 above triangles. Then you update the table T[x,y]

T[x,y+1] = 1 + min(T[x-1,y], T[x,y], T[x+1,y])

At the end, just find the biggest sized triangles in your table T and compute the corresponding triangle area. (formula left as an exercise to the reader)

Complexity is O(n²).


问:
How to correctly use .NET2.0 serial port .BaseStream for async operation
I am attempting to use the .BaseStream property of the .NET2.0 SerialPort to do asynchronous reads and writes (BeginWrite/EndWrite, BeginRead/EndRead).

I am having some success in this, but after a time, I notice (using Process Explorer) a very gradual increase in the Handles the app is using, and occasionally an extra thread, which also increases the Handle count.

The context switch rate also increases each time a new thread appears.

The app constantly sends 3 bytes to a PLC device, and gets 800 or so bytes in return, and does so at a baud rate of 57600.

The initial CSwitch Delta (again, from Process Explorer) is around 2500, which seems very high anyway. Each time a new thread appears, this value increases, and the CPU load increases accordingly.

I'm hoping that somebody might have done something similar, and can help me out, or even say 'In God's name, don't do it that way.'

In the code below, 'this._stream' is obtained from SerialPort.BaseStream, and CommsResponse is a class I use as the IAsyncresult state object.

This code is common to a TCP connection I make as an alternative to using the serial port, (I have a CommsChannel base class, with a serial and TCP channel derived from it) and it has none of these problems so I'm reasonably hopeful that there is nothing wrong with the CommsResponse class.

Any comments gratefully received.

```<code>    /// <summary>
    /// Write byte data to the channel.
    /// </summary>
    /// <param name="bytes">The byte array to write.</param>
    private void Write(byte[] bytes)
    {
        try
        {
            // Write the data to the port asynchronously.
            this._stream.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(this.WriteCallback), null);
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }

    /// <summary>
    /// Asynchronous write callback operation.
    /// </summary>
    private void WriteCallback(IAsyncResult ar)
    {
        bool writeSuccess = false;

        try
        {
            this._stream.EndWrite(ar);
            writeSuccess = true;
        }
        catch (IOException ex)
        {
            // Do stuff.
        }

        // If the write operation completed sucessfully, start the read process.
        if (writeSuccess) { this.Read(); }
    }

    /// <summary>
    /// Read byte data from the channel.
    /// </summary>
    private void Read()
    {
        try
        {
            // Create new comms response state object.
            CommsResponse response = new CommsResponse();

            // Begin the asynchronous read process to get response.
            this._stream.BeginRead(this._readBuffer, 0, this._readBuffer.Length, new AsyncCallback(this.ReadCallback), response);
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }

    /// <summary>
    /// Asynchronous read callback operation.
    /// </summary>
    private void ReadCallback(IAsyncResult ar)
    {
        // Retrieve the comms response object.
        CommsResponse response = (CommsResponse)ar.AsyncState;

        try
        {
            // Call EndRead to complete call made by BeginRead.
            // At this point, new data will be in this._readbuffer.
            int numBytesRead = this._stream.EndRead(ar);

            if (numBytesRead > 0)
            {
                // Create byte array to hold newly received bytes.
                byte[] rcvdBytes = new byte[numBytesRead];

                // Copy received bytes from read buffer to temp byte array
                Buffer.BlockCopy(this._readBuffer, 0, rcvdBytes, 0, numBytesRead);

                // Append received bytes to the response data byte list.
                response.AppendBytes(rcvdBytes);

                // Check received bytes for a correct response.
                CheckResult result = response.CheckBytes();

                switch (result)
                {
                    case CheckResult.Incomplete: // Correct response not yet received.
                        if (!this._cancelComm)
                        {
                            this._stream.BeginRead(this._readBuffer, 0, this._readBuffer.Length,
                                new AsyncCallback(this.ReadCallback), response);
                        }
                        break;

                    case CheckResult.Correct:  // Raise event if complete response received.
                        this.OnCommResponseEvent(response);
                        break;

                    case CheckResult.Invalid: // Incorrect response
                        // Do stuff.
                        break;

                    default: // Unknown response
                        // Do stuff.
                        break;
                }
            }
            else
            {
                // Do stuff.
            }
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }
</code>```

答:
Some suggestions:

Since you are only sending 3 bytes, you could have a synchronous Write Operation. The delay wouldn't be much of an issue.

Also don't create a new AsyncCallback all the time. Create one Read and one Write AsyncCallback and use that in every begin call.

OwnerDisplayName: Andy

Body:
I am attempting to use the .BaseStream property of the .NET2.0 SerialPort to do asynchronous reads and writes (BeginWrite/EndWrite, BeginRead/EndRead).

I am having some success in this, but after a time, I notice (using Process Explorer) a very gradual increase in the Handles the app is using, and occasionally an extra thread, which also increases the Handle count.

The context switch rate also increases each time a new thread appears.

The app constantly sends 3 bytes to a PLC device, and gets 800 or so bytes in return, and does so at a baud rate of 57600.

The initial CSwitch Delta (again, from Process Explorer) is around 2500, which seems very high anyway. Each time a new thread appears, this value increases, and the CPU load increases accordingly.

I'm hoping that somebody might have done something similar, and can help me out, or even say 'In God's name, don't do it that way.'

In the code below, 'this._stream' is obtained from SerialPort.BaseStream, and CommsResponse is a class I use as the IAsyncresult state object.

This code is common to a TCP connection I make as an alternative to using the serial port, (I have a CommsChannel base class, with a serial and TCP channel derived from it) and it has none of these problems so I'm reasonably hopeful that there is nothing wrong with the CommsResponse class.

Any comments gratefully received.

    ///
    /// Write byte data to the channel.
    ///
    /// <param name="bytes">The byte array to write.</param>
    private void Write(byte[] bytes)
    {
        try
        {
            // Write the data to the port asynchronously.
            this._stream.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(this.WriteCallback), null);
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }

    ///
    /// Asynchronous write callback operation.
    ///
    private void WriteCallback(IAsyncResult ar)
    {
        bool writeSuccess = false;

        try
        {
            this._stream.EndWrite(ar);
            writeSuccess = true;
        }
        catch (IOException ex)
        {
            // Do stuff.
        }

        // If the write operation completed sucessfully, start the read process.
        if (writeSuccess) { this.Read(); }
    }

    ///
    /// Read byte data from the channel.
    ///
    private void Read()
    {
        try
        {
            // Create new comms response state object.
            CommsResponse response = new CommsResponse();

            // Begin the asynchronous read process to get response.
            this._stream.BeginRead(this._readBuffer, 0, this._readBuffer.Length, new AsyncCallback(this.ReadCallback), response);
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }

    ///
    /// Asynchronous read callback operation.
    ///
    private void ReadCallback(IAsyncResult ar)
    {
        // Retrieve the comms response object.
        CommsResponse response = (CommsResponse)ar.AsyncState;

        try
        {
            // Call EndRead to complete call made by BeginRead.
            // At this point, new data will be in this._readbuffer.
            int numBytesRead = this._stream.EndRead(ar);

            if (numBytesRead > 0)
            {
                // Create byte array to hold newly received bytes.
                byte[] rcvdBytes = new byte[numBytesRead];

                // Copy received bytes from read buffer to temp byte array
                Buffer.BlockCopy(this._readBuffer, 0, rcvdBytes, 0, numBytesRead);

                // Append received bytes to the response data byte list.
                response.AppendBytes(rcvdBytes);

                // Check received bytes for a correct response.
                CheckResult result = response.CheckBytes();

                switch (result)
                {
                    case CheckResult.Incomplete: // Correct response not yet received.
                        if (!this._cancelComm)
                        {
                            this._stream.BeginRead(this._readBuffer, 0, this._readBuffer.Length,
                                new AsyncCallback(this.ReadCallback), response);
                        }
                        break;

                    case CheckResult.Correct:  // Raise event if complete response received.
                        this.OnCommResponseEvent(response);
                        break;

                    case CheckResult.Invalid: // Incorrect response
                        // Do stuff.
                        break;

                    default: // Unknown response
                        // Do stuff.
                        break;
                }
            }
            else
            {
                // Do stuff.
            }
        }
        catch (IOException ex)
        {
            // Do stuff.
        }
        catch (ObjectDisposedException ex)
        {
            // Do stuff.
        }
    }

OwnerDisplayName: kgiannakakis


问:
IE7 CSS Compatibility
Let me start off by saying I'm not a web developer and I don't know much at all about comparability.

I've been asked if I can fix a problem with a website in IE7. It loads completely fine in all modern browsers, but they want to make sure it works perfectly in IE7 as well. It technically works fine, but it appears to load the initial content on one pass and then the style on a second pass. I guess I can't be positive if this is what it's doing.

Does anyone who has experience with browser compatibility have any idea if this can be remedied? The website is extremely basic, just HTML, CSS, and a little bit of JS.

If this is the case, is there an easy way to set everything to invisible until the page is done loading? I know you can do this with javascript and individual elements.

答:
Include jQuery, put in,  block:

```<code><script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"></script>
</code>```

Hide the body in your HTML:

```<code><body style='display:none'>
</code>```

Unhide the body when the DOM is ready:

```<code><script type='text/javascript'>
$(document).ready(function() { $(body).show() })
</script>
</code>```

The danger is: if it's slow to load is people will leave before seeing the page.

Title: IE7 CSS Compatibility

Body:
Include jQuery, put in, <HEAD> block:

<script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"></script>

Hide the body in your HTML:

<body style='display:none'>

Unhide the body when the DOM is ready:

<script type='text/javascript'>
$(document).ready(function() { $(body).show() })
</script>

The danger is: if it's slow to load is people will leave before seeing the page.


问:
Select current element from getElementsbyClassName
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
  <button onclick="myFunction()">Click</button>
</div>
<div class="myClass">
  <button onclick="myFunction()">Click</button>
</div></code>```

答:
Similar to David Thomas' answer, but mine checks if the button itself was clicked, rather than the div:

HTML

```<code><div class="myClass">
  <button>Click</button>
</div>
</code>```

JS

```<code>var buttons = document.querySelectorAll('.myClass button');

buttons.forEach(button => {
  button.addEventListener('click', myFunction, false);
});

function myFunction() {
  this.parentNode.style.display = "none";
}
</code>```

DEMO

Body:
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}

  <button onclick="myFunction()">Click</button>

  <button onclick="myFunction()">Click</button>

Body:
Similar to David Thomas' answer, but mine checks if the button itself was clicked, rather than the div:

HTML

<div class="myClass">
  <button>Click</button>
</div>

JS

var buttons = document.querySelectorAll('.myClass button');

buttons.forEach(button => {
  button.addEventListener('click', myFunction, false);
});

function myFunction() {
  this.parentNode.style.display = "none";
}

DEMO


问:
Determine which scatter points are within a filled area in highcharts
I'm running an experiment to determine if geometric borders influence agents to coordinate in certain economic games.

I have made a graph of a unit square randomly partitioned into two parts using the following method:

In python (not super relevant)...

Create a self-avoiding random walk and store the lattice-points visited

Jitter the lattice points a bit

Format the jittered points as a highcharts series

with Highcharts (more relevant)...

Render the jittered points as type "areaspline"

I also add in some uniformly scattered points (appearing as circles, i.e. the players).

All of which yields a chart like this:

Which is exactly what I want.

My question is, how can I identify which scatter points are in which partition? My intuition is that HighCharts must identify the set of points to fill in when I call areaspline and that I should be able find the intersection of that set and my set of scatter points. Supposing that is correct, I can't find a way to return the set of filled in points. If incorrect, then I'm really lost! Please advise.

答:
Refer to this live demo (click and drag to create area): http://jsfiddle.net/vsbrwgso/

It uses ray casting algorithm (https://en.wikipedia.org/wiki/Point_in_polygon) to find the point within the path.

```<code>var pointInPolygon = function(point, vs) {
  // ray-casting algorithm based on
  // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

  var x = point[0],
    y = point[1];

  var inside = false;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i][0],
      yi = vs[i][1];
    var xj = vs[j][0],
      yj = vs[j][1];

    var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }

  return inside;
};
</code>```

You should adjust this example to your needs (remove interactivity, use areaspline/polygon series instead of user selection etc.)

Body:
Refer to this live demo (click and drag to create area): http://jsfiddle.net/vsbrwgso/

It uses ray casting algorithm (https://en.wikipedia.org/wiki/Point_in_polygon) to find the point within the path.

var pointInPolygon = function(point, vs) {
  // ray-casting algorithm based on
  // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

  var x = point[0],
    y = point[1];

  var inside = false;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i][0],
      yi = vs[i][1];
    var xj = vs[j][0],
      yj = vs[j][1];

    var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }

  return inside;
};

You should adjust this example to your needs (remove interactivity, use areaspline/polygon series instead of user selection etc.)


问:
update between three tables using left join in mysql
I have three tables, and want to update some fields in these tables but the query doesn't work

This is my Query:

```<code>UPDATE
customers cust
    left JOIN
contract cont ON cust.Customer_id = cont.Customers_Customer_id
    left JOIN
payments pay ON cust.Customer_id = pay.Customers_Customer_id
SET
cust.Customer_Name = 'Sara',
cust.Customer_id = '1201941718',
cust.Customer_Mobile1 = '01258863956',
cust.Customer_Phone = '0224598755',
cust.Customer_Mail = 'sara@gmail.com',
cont.Customers_Customer_id = '1201941718',
pay.Customers_Customer_id = '1201941718'
where cust.Customer_id = '2';
</code>```

The error:

Error Code: 1451. Cannot delete or update a parent row: a foreign key
  constraint fails (alhawel.payments, CONSTRAINT
  fk_Payments_Customers1 FOREIGN KEY (Customers_Customer_id)
  REFERENCES customers (Customer_id) ON DELETE NO ACTION ON UPDATE
  NO ACTION)

答:
I believe it isn't working because of the ON UPDATE NO ACTION in the foreign key. When you are updating the Customer_id in the Customer table, the foreign keys pointing to that will no longer be valid.

This answer deals with ON DELETE NO ACTION but it applies to update as well. I think you will need to modify the constraint to fix this error (which may not be the right thing to do for other reasons, knowing more about the schema may get a better answer).

Body:
I have three tables, and want to update some fields in these tables but the query doesn't work

This is my Query:

UPDATE
customers cust
    left JOIN
contract cont ON cust.Customer_id = cont.Customers_Customer_id
    left JOIN
payments pay ON cust.Customer_id = pay.Customers_Customer_id
SET
cust.Customer_Name = 'Sara',
cust.Customer_id = '1201941718',
cust.Customer_Mobile1 = '01258863956',
cust.Customer_Phone = '0224598755',
cust.Customer_Mail = 'sara@gmail.com',
cont.Customers_Customer_id = '1201941718',
pay.Customers_Customer_id = '1201941718'
where cust.Customer_id = '2';

The error:

Error Code: 1451. Cannot delete or update a parent row: a foreign key
  constraint fails (alhawel.payments, CONSTRAINT
  fk_Payments_Customers1 FOREIGN KEY (Customers_Customer_id)
  REFERENCES customers (Customer_id) ON DELETE NO ACTION ON UPDATE
  NO ACTION)


问:
Interface builder doesn't allow adding Table View Cell
For an alert dialog, I added a UITableView, then while I try to Table View Cell the Interface Builders doesn't accept dropping Table View Cell "on" table view, please check screenshot, I should mention the root is UIView, not UIViewController:

答:
I'm sorry, but prototype cells are available only in storyboard-based projects.

Cannot add a PrototypeCell to UITableView inside xib file

You have to create custom UITableViewCell For UITableView


问:
MySQL - ORDER BY values within IN()
I'm hoping to sort the items returned in the following query by the order they're entered into the IN() function.

INPUT:

```<code>SELECT id, name FROM mytable WHERE name IN ('B', 'A', 'D', 'E', 'C');
</code>```

OUTPUT:

```<code>|   id   |   name  |
^--------^---------^
|   5    |   B     |
|   6    |   B     |
|   1    |   D     |
|   15   |   E     |
|   17   |   E     |
|   9    |   C     |
|   18   |   C     |
</code>```

Any ideas?

答:
just use

```<code>order by INSTR( ',B,C,D,A,' ,  concat(',' , `field`, ',' ) )
</code>```

avoid the situation like

```<code> INSTR('1,2,3,11' ,`field`)
</code>```

will end with unordered result row : 1 and 11 alternant

Title: MySQL - ORDER BY values within IN()

Body:
I'm hoping to sort the items returned in the following query by the order they're entered into the IN() function.

INPUT:

SELECT id, name FROM mytable WHERE name IN ('B', 'A', 'D', 'E', 'C');

OUTPUT:

|   id   |   name  |
^--------^---------^
|   5    |   B     |
|   6    |   B     |
|   1    |   D     |
|   15   |   E     |
|   17   |   E     |
|   9    |   C     |
|   18   |   C     |

Any ideas?

Body:
just use

order by INSTR( ',B,C,D,A,' ,  concat(',' , `field`, ',' ) )

avoid the situation like

 INSTR('1,2,3,11' ,`field`)

will end with unordered result row : 1 and 11 alternant


问:
How to access nested JSON data with dynamic variables
I am stuck on a issue where i need to access a nested JSON with dynamic variables. This is my JSON:

```<code>{
    "Account2": [{
        "accountId": "17467****",
        "containerId": "7454***",
        "path": "accounts\/17467*****\/containers\/7454***",
    }, {
        "accountId": "17467****",
        "containerId": "7519***",
        "path": "accounts\/17467****\/containers\/7519***",
    }],
    "Account 1": [{
        "accountId": "17661****",
        "containerId": "7483***",
        "path": "accounts\/17661****\/containers\/7483***",
    }]
}
</code>```

Using AngluarJS on front-end i use this to print a table, here i can use the "path" variable to use a href and then make second API call based on url parameters like this:

```<code><td><a href="/gui/tags/{{v1.path}}">View Container</a></td>
</code>```

v1.path = accounts/17467*****/containers/7454***

Now to my problem, i want to send this call before clicking on table to show some data. The problem is that when accessing the JSON that has dynamic variable as you can see: "Account2", "Account1". I cannot use: `$scope.GTMcontainersAccount = response.data.ACCOUNT1;

because "account1" is dynamic and changes from user to user.

Someone has an idea? regEx?

UPDATED:

when i use:

```<code> $scope.GTMcontainersAccount = response.data;
                    $scope.keys = Object.keys(response.data);
                    for(n in $scope.keys)
                    {
                       $scope.asim = $scope.keys[n];
                       console.log($scope.asim);
                       console.log(response.data[$scope.asim]);
                    }
</code>```

This gives me this result:

So i have to write like:

```<code>console.log(response.data[$scope.asim][0].accountId);
</code>```

But this gives me only row of "account2" not "account1"

答:
You need to use Object.keys() to get the keys of your object, then for each key get the relevant array and loop over its items:

```<code>Object.keys(data).forEach(function(key) {
  let accounts = data[key];
  if (accounts && accounts.length) {
    accounts.forEach(function(account) {
      console.log(account);
    });
  }
});
</code>```

Demo:

let data = {
  "Account2": [{
    "accountId": "17467****",
    "containerId": "7454***",
    "path": "accounts\/17467*****\/containers\/7454***",
  }, {
    "accountId": "17467****",
    "containerId": "7519***",
    "path": "accounts\/17467****\/containers\/7519***",
  }],
  "Account 1": [{
    "accountId": "17661****",
    "containerId": "7483***",
    "path": "accounts\/17661****\/containers\/7483***",
  }]
};

Object.keys(data).forEach(function(key) {
  let accounts = data[key];
  if (accounts && accounts.length) {
    console.log(key+": ");
    accounts.forEach(function(account) {
      console.log(account);
    });
  }
});```

Body:
I am stuck on a issue where i need to access a nested JSON with dynamic variables. This is my JSON:

{
    "Account2": [{
        "accountId": "17467****",
        "containerId": "7454***",
        "path": "accounts\/17467*****\/containers\/7454***",
    }, {
        "accountId": "17467****",
        "containerId": "7519***",
        "path": "accounts\/17467****\/containers\/7519***",
    }],
    "Account 1": [{
        "accountId": "17661****",
        "containerId": "7483***",
        "path": "accounts\/17661****\/containers\/7483***",
    }]
}

Using AngluarJS on front-end i use this to print a table, here i can use the "path" variable to use a href and then make second API call based on url parameters like this:

View Container

v1.path = accounts/17467*****/containers/7454***

Now to my problem, i want to send this call before clicking on table to show some data. The problem is that when accessing the JSON that has dynamic variable as you can see: "Account2", "Account1". I cannot use: `$scope.GTMcontainersAccount = response.data.ACCOUNT1;

because "account1" is dynamic and changes from user to user.

Someone has an idea? regEx?

UPDATED:

when i use:

 $scope.GTMcontainersAccount = response.data;
                    $scope.keys = Object.keys(response.data);
                    for(n in $scope.keys)
                    {
                       $scope.asim = $scope.keys[n];
                       console.log($scope.asim);
                       console.log(response.data[$scope.asim]);
                    }

This gives me this result:

So i have to write like:

console.log(response.data[$scope.asim][0].accountId);

But this gives me only row of "account2" not "account1"

Body:
You need to use Object.keys() to get the keys of your object, then for each key get the relevant array and loop over its items:

Object.keys(data).forEach(function(key) {
  let accounts = data[key];
  if (accounts && accounts.length) {
    accounts.forEach(function(account) {
      console.log(account);
    });
  }
});

Demo:

let data = {
  "Account2": [{
    "accountId": "17467****",
    "containerId": "7454***",
    "path": "accounts\/17467*****\/containers\/7454***",
  }, {
    "accountId": "17467****",
    "containerId": "7519***",
    "path": "accounts\/17467****\/containers\/7519***",
  }],
  "Account 1": [{
    "accountId": "17661****",
    "containerId": "7483***",
    "path": "accounts\/17661****\/containers\/7483***",
  }]
};

Object.keys(data).forEach(function(key) {
  let accounts = data[key];
  if (accounts && accounts.length) {
    console.log(key+": ");
    accounts.forEach(function(account) {
      console.log(account);
    });
  }
});


问:
How do I find duplicates across multiple columns?
So I want to do something like this sql code below:

```<code>select s.id, s.name,s.city
from stuff s
group by s.name having count(where city and name are identical) > 1
</code>```

To produce the following, (but ignore where only name or only city match, it has to be on  both columns):

```<code>id      name  city
904834  jim   London
904835  jim   London
90145   Fred  Paris
90132   Fred  Paris
90133   Fred  Paris
</code>```

答:
Given a staging table with 70 columns and only 4 representing duplicates,
this code will return the offending columns:

```<code>SELECT
    COUNT(*)
    ,LTRIM(RTRIM(S.TransactionDate))
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber))
    ,LTRIM(RTRIM(GrossCost))
FROM Staging.dbo.Stage S
GROUP BY
    LTRIM(RTRIM(S.TransactionDate))
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber))
    ,LTRIM(RTRIM(GrossCost))
HAVING COUNT(*) > 1
</code>```

.

Body:
So I want to do something like this sql code below:

select s.id, s.name,s.city
from stuff s
group by s.name having count(where city and name are identical) > 1

To produce the following, (but ignore where only name or only city match, it has to be on  both columns):

id      name  city
904834  jim   London
904835  jim   London
90145   Fred  Paris
90132   Fred  Paris
90133   Fred  Paris

Body:
Given a staging table with 70 columns and only 4 representing duplicates,
this code will return the offending columns:

SELECT
    COUNT(*)
    ,LTRIM(RTRIM(S.TransactionDate))
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber))
    ,LTRIM(RTRIM(GrossCost))
FROM Staging.dbo.Stage S
GROUP BY
    LTRIM(RTRIM(S.TransactionDate))
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber))
    ,LTRIM(RTRIM(GrossCost))
HAVING COUNT(*) > 1

.


问:
Create a python dictionary from a list
I'm trying to create a dictionary from a list in python. I'm creating  alist from a .txt fril in the same directory as the .py file. But I don't understand how I create a dictionary without manually assigning a key to every value?

```<code>l = open ("Luther_King.txt").read()
words = l.split( )
print (words)
</code>```

The print statement is just to check if it did in fact split the string into a list. Am I going to need to manually assign a key for every word or can I generate one somehow?

答:
Unfortunately you have to have key and value. You can try this, send two list and merge them in a dictionary. You can just send a very basic list in order to have a key like : 1, 2, 3, 4, 5, ...</p>

```<code>def get_dic_from_two_lists(keys, values):
    return {keys[i]: values[i] for i in range(keys)}
</code>```

Title: Create a python dictionary from a list

Body:
I'm trying to create a dictionary from a list in python. I'm creating  alist from a .txt fril in the same directory as the .py file. But I don't understand how I create a dictionary without manually assigning a key to every value?

l = open ("Luther_King.txt").read()
words = l.split( )
print (words)

The print statement is just to check if it did in fact split the string into a list. Am I going to need to manually assign a key for every word or can I generate one somehow?

Body:
Unfortunately you have to have key and value. You can try this, send two list and merge them in a dictionary. You can just send a very basic list in order to have a key like : 1, 2, 3, 4, 5, ...

def get_dic_from_two_lists(keys, values):
    return {keys[i]: values[i] for i in range(keys)}


问:
Why is ProgressEvent.lengthComputable false?
I am loading a JSON file using XMLHttpRequest in Google Chrome, Safari and Firefox. In all three browsers I am receiving ProgressEvents which correctly show the .loaded property. However the .lengthComputable property is false and the .total property is zero. I have checked that the Content-Length HTTP header is being sent and is correct - it is. The response is being gzip-encoded, but the Content-length correctly shows the encoded length (before decompression).

Why would the total length not be available in my ProgressEvents?

Here are the headers:

```<code>HTTP/1.1 200 OK
ETag: "hKXdZA"
Date: Wed, 20 Jun 2012 20:17:17 GMT
Expires: Wed, 20 Jun 2012 20:17:17 GMT
Cache-Control: private, max-age=3600
X-AppEngine-Estimated-CPM-US-Dollars: $0.000108
X-AppEngine-Resource-Usage: ms=2 cpu_ms=0 api_cpu_ms=0
Content-Type: application/json
Content-Encoding: gzip
Server: Google Frontend
Content-Length: 621606
</code>```

Note: the file is being served via Google App Engine.

Here is the JavaScript:

```<code>var req;
if (window.XMLHttpRequest){
    req = new XMLHttpRequest();
    if(req.overrideMimeType){
        req.overrideMimeType( "text/json" );
    }
}else{
    req = new ActiveXObject('Microsoft.XMLHTTP');
}

// Listen for progress events
req.addEventListener("progress", function (event) {
    console.log(event, event.lengthComputable, event.total);
    if (event.lengthComputable) {
        self.progress = event.loaded / event.total;
    } else if (this.explicitTotal) {
        self.progress = Math.min(1, event.loaded / self.explicitTotal);
    } else {
        self.progress = 0;
    }
    self.dispatchEvent(Breel.Asset.ON_PROGRESS);
}, false);

req.open('GET', this.url);
</code>```

Note: The console.log in that code is showing hundreds of events with up to date .loadeds but .lengthComputable is always false and .total is always zero. self refers to the object responsible for this XMLHttpRequest.

答:
Meanwhile 2017, things are fine in Firefox, but Chrome does not show the progress for gzip'd content.

This seems to be caused by the specifications once being unclear if loaded and total refer to the compressed or uncompressed content. Since Jun 26, 2014 the XMLHttpRequest specifications make clear they should refer to the transmitted (compressed) content:

6.1. Firing events using the ProgressEvent interface

[...] given transmitted and length [...]  fire an event [...] ProgressEvent, with the loaded attribute initialized to transmitted, and if length is not 0, with the lengthComputable attribute initialized to true and the total attribute initialized to length.

However, the 2015 Chromium bug report "XHR's progress events should handle gzipped content" explains that things were different, and states:

when encoded, total stays to be 0 and lengthComputable is not set

The event itself is still fired, and event.loaded is still populated. But Chrome is decompressing gzip'd content on the fly and (today) sets loaded to the resulting decompressed length, not to the transmitted length. This cannot be compared to the value of the Content-Length header, as that's the length of the compressed content, so loaded will become larger than the content length.

At best one could assume some compression factor to compare loaded against Content-Length, or make the server add some custom header to provide the original length or the true compression factor, assuming Chrome's on-the-fly decompression will not change.

I've no idea what Chrome does for other values for Content-Encoding.

Body:
I am loading a JSON file using XMLHttpRequest in Google Chrome, Safari and Firefox. In all three browsers I am receiving ProgressEvents which correctly show the .loaded property. However the .lengthComputable property is false and the .total property is zero. I have checked that the Content-Length HTTP header is being sent and is correct - it is. The response is being gzip-encoded, but the Content-length correctly shows the encoded length (before decompression).

Why would the total length not be available in my ProgressEvents?

Here are the headers:

HTTP/1.1 200 OK
ETag: "hKXdZA"
Date: Wed, 20 Jun 2012 20:17:17 GMT
Expires: Wed, 20 Jun 2012 20:17:17 GMT
Cache-Control: private, max-age=3600
X-AppEngine-Estimated-CPM-US-Dollars: $0.000108
X-AppEngine-Resource-Usage: ms=2 cpu_ms=0 api_cpu_ms=0
Content-Type: application/json
Content-Encoding: gzip
Server: Google Frontend
Content-Length: 621606

Note: the file is being served via Google App Engine.

Here is the JavaScript:

var req;
if (window.XMLHttpRequest){
    req = new XMLHttpRequest();
    if(req.overrideMimeType){
        req.overrideMimeType( "text/json" );
    }
}else{
    req = new ActiveXObject('Microsoft.XMLHTTP');
}

// Listen for progress events
req.addEventListener("progress", function (event) {
    console.log(event, event.lengthComputable, event.total);
    if (event.lengthComputable) {
        self.progress = event.loaded / event.total;
    } else if (this.explicitTotal) {
        self.progress = Math.min(1, event.loaded / self.explicitTotal);
    } else {
        self.progress = 0;
    }
    self.dispatchEvent(Breel.Asset.ON_PROGRESS);
}, false);

req.open('GET', this.url);

Note: The console.log in that code is showing hundreds of events with up to date .loadeds but .lengthComputable is always false and .total is always zero. self refers to the object responsible for this XMLHttpRequest.


问:
Authenticate JWT with Guardian 1 and Phoenix 1.3
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

```<code>http://0.0.0.0:4000/api/login
</code>```

with the body:

```<code>{ "user": { "username": "kenneth", "password": "kenneth" } }
</code>```

That is a user that is in the database.
I get the response:

```<code>{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}
</code>```

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.

答:
you have this in your pipeline:

```<code>plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}, realm: :none
</code>```

which means your header needs to be:

```<code>Authorization: none: <token>
</code>```

because that is what is in Guardian.Plug.VerifyHeader:

```<code>def init(opts \\ %{}) do
  opts_map = Enum.into(opts, %{})
  realm = Map.get(opts_map, :realm)
  if realm do
    {:ok, reg} = Regex.compile("#{realm}\:?\s+(.*)$", "i")
    Map.put(opts_map, :realm_reg, reg)
  else
    opts_map
  end
end
</code>```

my guess you need to remove realm: :none setting so your token can be properly parsed.

Body:
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

http://0.0.0.0:4000/api/login

with the body:

{ "user": { "username": "kenneth", "password": "kenneth" } }

That is a user that is in the database.
I get the response:

{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.

Body:
you have this in your pipeline:

plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}, realm: :none

which means your header needs to be:

Authorization: none: <token>

because that is what is in Guardian.Plug.VerifyHeader:

def init(opts \\ %{}) do
  opts_map = Enum.into(opts, %{})
  realm = Map.get(opts_map, :realm)
  if realm do
    {:ok, reg} = Regex.compile("#{realm}\:?\s+(.*)$", "i")
    Map.put(opts_map, :realm_reg, reg)
  else
    opts_map
  end
end

my guess you need to remove realm: :none setting so your token can be properly parsed.


问:
Unable to convert json string to json object
```<code>let dictionaryToJsonObject: [String: Any]

let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo@sm.com", "Password": "john@123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
    let jsonText = String(data: jsonData,
                          encoding: .ascii)

    print("JSON string = \(jsonText!)")

    if JSONSerialization.isValidJSONObject(jsonText!) {
        print("Valid")
    } else {
        print("Not Valid")
    }

}catch {
    print(error.localizedDescription)
}
</code>```

Output Will be : -

```<code>JSON string = {
  "FirstName" : "John",
  "Email" : "Jo@sm.com",
  "Password" : "john@123",
  "LastName" : "Smith",
  "Organization" : {
    "Type" : 5,
    "Name" : "IT"
  }
}
</code>```

expected Result :

```<code>{
    FirstName:"John",
    Email:"Jo@sm.com",
    Password:"john@123",
    LastName:"Smith",
    Organization:{
        Type:5,
        Name:"IT"
        }
}
</code>```

答:
If you want to get it in json object form then your code should be like,

```<code>  let dictionaryToJsonObject: [String: Any]

    let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo@sm.com", "Password": "john@123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
        let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .init(rawValue: 0))

        print("JSON string = \(jsonObject)")

        if JSONSerialization.isValidJSONObject(jsonObject) {
            print("Valid")
        } else {
            print("Not Valid")
        }

    }catch {
        print(error.localizedDescription)
    }
</code>```

and your output will be,

```<code>JSON string = {
Email = "Jo@sm.com";
FirstName = John;
LastName = Smith;
Organization =     {
    Name = IT;
    Type = 5;
};
    Password = "john@123";
}
Valid
</code>```

Ultimately it is your declared dictionary itself I think!

Body:
let dictionaryToJsonObject: [String: Any]

let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo@sm.com", "Password": "john@123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
    let jsonText = String(data: jsonData,
                          encoding: .ascii)

    print("JSON string = \(jsonText!)")

    if JSONSerialization.isValidJSONObject(jsonText!) {
        print("Valid")
    } else {
        print("Not Valid")
    }

}catch {
    print(error.localizedDescription)
}

Output Will be : -

JSON string = {
  "FirstName" : "John",
  "Email" : "Jo@sm.com",
  "Password" : "john@123",
  "LastName" : "Smith",
  "Organization" : {
    "Type" : 5,
    "Name" : "IT"
  }
}

expected Result :

{
    FirstName:"John",
    Email:"Jo@sm.com",
    Password:"john@123",
    LastName:"Smith",
    Organization:{
        Type:5,
        Name:"IT"
        }
}

Body:
If you want to get it in json object form then your code should be like,

  let dictionaryToJsonObject: [String: Any]

    let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo@sm.com", "Password": "john@123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
        let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .init(rawValue: 0))

        print("JSON string = \(jsonObject)")

        if JSONSerialization.isValidJSONObject(jsonObject) {
            print("Valid")
        } else {
            print("Not Valid")
        }

    }catch {
        print(error.localizedDescription)
    }

and your output will be,

JSON string = {
Email = "Jo@sm.com";
FirstName = John;
LastName = Smith;
Organization =     {
    Name = IT;
    Type = 5;
};
    Password = "john@123";
}
Valid

Ultimately it is your declared dictionary itself I think!