问:
npm install doesn't create node_modules directory
I am trying to do a homework for a mongodb uni course. They gave us some files, instructions are:

run npm install mongodb then node app.js

for some reason npm install does not create a node_modules directory but I don't see any build errors:

```<code>mongo-uni/hw1-2$ npm install mongodb
npm WARN package.json path@0.4.9 path is also the name of a node core module.
npm http GET https://registry.npmjs.org/mongodb
npm http 304 https://registry.npmjs.org/mongodb
npm http GET https://registry.npmjs.org/bson/0.2.5
npm http GET https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/bson/0.2.5

> kerberos@0.0.3 install /home/jasonshark/node_modules/mongodb/node_modules/kerberos
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'
  SOLINK_MODULE(target) Release/obj.target/kerberos.node
  SOLINK_MODULE(target) Release/obj.target/kerberos.node: Finished
  COPY Release/kerberos.node
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'

> bson@0.2.5 install /home/jasonshark/node_modules/mongodb/node_modules/bson
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
  CXX(target) Release/obj.target/bson/ext/bson.o
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
mongodb@1.3.23 ../../../node_modules/mongodb
├── kerberos@0.0.3
└── bson@0.2.5
mongo-uni/hw1-2$ node app.js
Failed to load c++ bson extension, using pure JS version
'No document found'
</code>```

答:
As soon as you have run npm init and you start installing npm packages it'll create the node_moduals folder after that first install

e.g

npm init

(Asks you to set up your package.json file)

npm install <package name here> --save-dev

installs package & creates the node modules directory

Body:
I am trying to do a homework for a mongodb uni course. They gave us some files, instructions are:

run npm install mongodb then node app.js

for some reason npm install does not create a node_modules directory but I don't see any build errors:

mongo-uni/hw1-2$ npm install mongodb
npm WARN package.json path@0.4.9 path is also the name of a node core module.
npm http GET https://registry.npmjs.org/mongodb
npm http 304 https://registry.npmjs.org/mongodb
npm http GET https://registry.npmjs.org/bson/0.2.5
npm http GET https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/bson/0.2.5

> kerberos@0.0.3 install /home/jasonshark/node_modules/mongodb/node_modules/kerberos
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'
  SOLINK_MODULE(target) Release/obj.target/kerberos.node
  SOLINK_MODULE(target) Release/obj.target/kerberos.node: Finished
  COPY Release/kerberos.node
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'

> bson@0.2.5 install /home/jasonshark/node_modules/mongodb/node_modules/bson
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
  CXX(target) Release/obj.target/bson/ext/bson.o
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
mongodb@1.3.23 ../../../node_modules/mongodb
├── kerberos@0.0.3
└── bson@0.2.5
mongo-uni/hw1-2$ node app.js
Failed to load c++ bson extension, using pure JS version
'No document found'


来源: stackexchange

问:
How do I pull from within a nested tag with javascript?
Obviously, I'm new to Javascript, and I'm sure that my time with it will be shortlived; this is just for a small project at work. I would really appreciate it if someone would help me figure this out.

I'm trying to set up a page that displays data from an external .xml file, of which I have absolutely no control. It is set up just like this:

```<code><lab id="1" name="A" inUse="14" offline="1" available="16">
</lab>
<lab id="2" name="B" inUse="11" offline="9" available="7">
   <client id="x" status="available" mac="#" ip="#" name="COMPUTER1" />
   <client id="y" status="available" mac="#" ip="#" name="COMPUTER2" />
</lab>
</code>```

I am displaying the data with a table using the following code:

```<code><%
    try
    {
        URL url = new URL("http://clstats.cc.nd.edu/public/xml-client.jsp");
        InputStream input = url.openStream();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document XMLInfo = builder.parse(input);

        NodeList labs = XMLInfo.getElementsByTagName("lab");

        int length = labs.getLength();
        int i;
        for (i = 0; i < length; i++)
        {

           Node current = labs.item(i);
           String labName = current.getAttributes().getNamedItem("name").getTextContent();
           String available = current.getAttributes().getNamedItem("available").getTextContent();
           String offline = current.getAttributes().getNamedItem("offline").getTextContent();
           String inUse = current.getAttributes().getNamedItem("inUse").getTextContent();
            //Alternate the row colors
            if( (i % 2) == 0)
            {
                  %>
                      <tr style="background:url(#);">
                  <%
             }
             else
             {
                 %>
                 <tr style="background:url(#);">
                 <%
              }
              %>
              <td><%= labName %></td>
              <td><%= available %></td>
                          <td><%= offline %></td>
              <td><%= inUse %></td>
              </tr>
              </td>
               <%
        }
    }
    catch(Exception e){
    }

%>
</code>```

I am having no trouble displaying information from the "lab" tag, but I'd like to only display data from within a particular lab, let's say lab id=2. Is there a way to display attributes from the "client" tags from under a single, particular "lab" tag?

Thanks, I hope I explained the problem well enough. As you can see, I'm pretty much a noob, and any help would be much appreciated.

Intended Result:

```<code><table>
<tr>
<td>Name</td>
<td>Status</td>
</tr>
<tr>
<td>COMPUTER1</td>
<td>Available</td>
</tr>
<tr>
<td>COMPUTER2</td>
<td>AVAILABLE</td>
</tr>
</table>
</code>```

答: You are using getElementsByTagName on the XMLInfo to get labs. I think you can also use  Nodelist clients = current.getElementsByTagName("client"); then iterate through those nodes.

ContentLicense: CC BY-SA 2.5

Body:
Obviously, I'm new to Javascript, and I'm sure that my time with it will be shortlived; this is just for a small project at work. I would really appreciate it if someone would help me figure this out.

I'm trying to set up a page that displays data from an external .xml file, of which I have absolutely no control. It is set up just like this:

<lab id="1" name="A" inUse="14" offline="1" available="16">
</lab>
<lab id="2" name="B" inUse="11" offline="9" available="7">
   <client id="x" status="available" mac="#" ip="#" name="COMPUTER1" />
   <client id="y" status="available" mac="#" ip="#" name="COMPUTER2" />
</lab>

I am displaying the data with a table using the following code:

<%
    try
    {
        URL url = new URL("http://clstats.cc.nd.edu/public/xml-client.jsp");
        InputStream input = url.openStream();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document XMLInfo = builder.parse(input);

        NodeList labs = XMLInfo.getElementsByTagName("lab");

        int length = labs.getLength();
        int i;
        for (i = 0; i < length; i++)
        {

           Node current = labs.item(i);
           String labName = current.getAttributes().getNamedItem("name").getTextContent();
           String available = current.getAttributes().getNamedItem("available").getTextContent();
           String offline = current.getAttributes().getNamedItem("offline").getTextContent();
           String inUse = current.getAttributes().getNamedItem("inUse").getTextContent();
            //Alternate the row colors
            if( (i % 2) == 0)
            {
                  %>

                  <%
             }
             else
             {
                 %>

                 <%
              }
              %>
              <%= labName %>
              <%= available %>
                          <%= offline %>
              <%= inUse %>

               <%
        }
    }
    catch(Exception e){
    }

%>

I am having no trouble displaying information from the "lab" tag, but I'd like to only display data from within a particular lab, let's say lab id=2. Is there a way to display attributes from the "client" tags from under a single, particular "lab" tag?

Thanks, I hope I explained the problem well enough. As you can see, I'm pretty much a noob, and any help would be much appreciated.

Intended Result:

Name
Status

COMPUTER1
Available

COMPUTER2
AVAILABLE


问:
Docusign change recipient for notification events
If this has already been posted, I apologize, I couldn't find an answer.
I am using the c# API.
We would like to specify, on a document by document base, who will receive the notification events.

As a for example:
We have our business segmented into regions.
Documents signed in any given region should send their notifications to the regional rep.  Currently, all notifications go to one person, and they have to forward the notifications.  It would be nice if I could set this up when I create the envelope, so the notification events go to the regional rep right away.

答: Whoever is the sender of an envelope will receive the notifications, you cannot explicitly tell DocuSign to whom to send the notifications. If you want PersonA of RegionA to get notification then you need to send envelope on behalf of PersonA, then that user will become the owner of the envelope. Also it depends which type of notifications you are interested in, if you want to have notification like, Completed, Void, Expired then you can add your Regional Rep as CC recipient type as 1st in routing order then if any activity will happen on that envelope then CC recipient will get Completed, Void, Expired types of notification. The notification they will not get is, if someone has viewed an envelope.</p>

ContentLicense: CC BY-SA 3.0


问:
Pass SSRS parameters into Drill through report VIA url
Im having trouble passing multiple parameters to my drill though report using an url.

I have got a single one working however when i try to add the next one it doesn't like what i have put.

```<code> ="http://rpt.Test.local/ReportServer/Pages/ReportViewer.aspx?%2f%5bQuote+Tool%5d%2fChange%20Elec%20Split&PC="&Parameters!PC.Value
</code>```

Above is the working one parameter and im now trying to add
        MTC = Parameters!MTC.Value.

Just think im imputting wrong.

Cheers

答:
Try this one.. almost there but just a small tweek:</p>

```<code>="http://rpt.Test.local/ReportServer/Pages/ReportViewer.aspx?%2f%5bQuote+Tool%5d%2fChange%20Elec%20Split&"&PC=" &Parameters!PC.Value &"&MTC=" & Parameters!MTC.Value & "&rs:Command=Render"
</code>```

Body:
Im having trouble passing multiple parameters to my drill though report using an url.

I have got a single one working however when i try to add the next one it doesn't like what i have put.

 ="http://rpt.Test.local/ReportServer/Pages/ReportViewer.aspx?%2f%5bQuote+Tool%5d%2fChange%20Elec%20Split&PC="&Parameters!PC.Value

Above is the working one parameter and im now trying to add
        MTC = Parameters!MTC.Value.

Just think im imputting wrong.

Cheers

Body:
Try this one.. almost there but just a small tweek:

="http://rpt.Test.local/ReportServer/Pages/ReportViewer.aspx?%2f%5bQuote+Tool%5d%2fChange%20Elec%20Split&"&PC=" &Parameters!PC.Value &"&MTC=" & Parameters!MTC.Value & "&rs:Command=Render"


问:
Call a word SynonymInfo object variable from Excel VBA
There might be something fairly simple I am missing here, but I can't quite figure out why I am getting an "Object variable or Object With block not set" error. I am trying to take a string from Excel, and use VBA to call a Word function that yields synonyms. Here is some reproducible simple code that will cause the error I am running into:

```<code>Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub
</code>```

I made sure I went to Tools→References and selected the Microsoft Word Object Library, and I also entered the following code into a Word Application without error:

```<code>Public Sub Tester()
    Dim Syn As SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = SynonymInfo(wrd)
End Sub
</code>```

I am wondering if there is some reference I am not calling? I am trying to replicate from Excel the example seen here and wondering declaration I am missing from within Excel VBA to call this. Thanks much for your help!

答:
You must first set WD =something before you can say WD.something.

For example, set WD = CreateObject ("Word.Application") (to open a new instance of Word behind the scenes). Don't forget to call WD.Quit when the instance of Word is no longer needed.

Body:
There might be something fairly simple I am missing here, but I can't quite figure out why I am getting an "Object variable or Object With block not set" error. I am trying to take a string from Excel, and use VBA to call a Word function that yields synonyms. Here is some reproducible simple code that will cause the error I am running into:

Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub

I made sure I went to Tools→References and selected the Microsoft Word Object Library, and I also entered the following code into a Word Application without error:

Public Sub Tester()
    Dim Syn As SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = SynonymInfo(wrd)
End Sub

I am wondering if there is some reference I am not calling? I am trying to replicate from Excel the example seen here and wondering declaration I am missing from within Excel VBA to call this. Thanks much for your help!


问:
Text input with IF statements
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

```<code><!DOCTYPE HTML>
<html>

<head>
<script type="text/javascript" src="gamescript.js"></script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

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

<script>
function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1", "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2", "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

</script>

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

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

答:
Your syntax on your if statements is wrong. Change your if statements to use proper "or" syntax:

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

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

</body></code>```

Title: Text input with IF statements

Body:
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

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

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

Body:
Your syntax on your if statements is wrong. Change your if statements to use proper "or" syntax:

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

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

</body>


问:
My program, when run, only returns with '[ ]' and I need it to return data from an info table from a website
Im trying to create a web scraping program that scrapes a web-page that has an information table on every 5mins or so. If the web-page is different/ been updated it should create the new one as original and send an email to notify an update. Heres my code so far:</p>

```<code>import urllib
import urllib.request as request
import re

totalurl = "https://www.icc-ccs.org/index.php/piracy-reporting-centre/live-piracy-report"
htmlfile = urllib.request.urlopen(totalurl)
htmltext = htmlfile.read()
regex = '<div class="fabrikDataContainer">...</div>'
pattern = re.compile(regex)
with urllib.request.urlopen(totalurl) as response:
    html = htmltext.decode()

num = re.findall(pattern, html)
print(num)
</code>```

答:
Regex is not actually an option in web-scraping. You can use, for example, lxml as below:

```<code>import urllib
import urllib.request as request
from lxml import html

totalurl = "https://www.icc-ccs.org/index.php/piracy-reporting-centre/live-piracy-report"
htmlfile = urllib.request.urlopen(totalurl)
htmltext = htmlfile.read()
source = html.fromstring(htmltext.decode())
num = source.xpath('//div[@class="fabrikDataContainer"]')
print(num[0].text_content())
</code>```

The output is complete text content of table. You can implement more complex selector to get specific data

Body:
Im trying to create a web scraping program that scrapes a web-page that has an information table on every 5mins or so. If the web-page is different/ been updated it should create the new one as original and send an email to notify an update. Heres my code so far:

import urllib
import urllib.request as request
import re

totalurl = "https://www.icc-ccs.org/index.php/piracy-reporting-centre/live-piracy-report"
htmlfile = urllib.request.urlopen(totalurl)
htmltext = htmlfile.read()
regex = '
...
'
pattern = re.compile(regex)
with urllib.request.urlopen(totalurl) as response:
    html = htmltext.decode()

num = re.findall(pattern, html)
print(num)

Body:
Regex is not actually an option in web-scraping. You can use, for example, lxml as below:

import urllib
import urllib.request as request
from lxml import html

totalurl = "https://www.icc-ccs.org/index.php/piracy-reporting-centre/live-piracy-report"
htmlfile = urllib.request.urlopen(totalurl)
htmltext = htmlfile.read()
source = html.fromstring(htmltext.decode())
num = source.xpath('//div[@class="fabrikDataContainer"]')
print(num[0].text_content())

The output is complete text content of table. You can implement more complex selector to get specific data


问:
How to have conditional elements and keep DRY with Facebook React's JSX?
How do I optionally include an element in JSX?  Here is an example using a banner that should be in the component if it has been passed in.  What I want to avoid is having to duplicate HTML tags in the if statement.</p>

```<code>render: function () {
    var banner;
    if (this.state.banner) {
        banner = <div id="banner">{this.state.banner}</div>;
    } else {
        banner = ?????
    }
    return (
        <div id="page">
            {banner}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}
</code>```

答:
There is also a technique using render props to conditional render a component. It's benefit is that the render wouldn't evaluate until the condition is met, resulting in no worries for null and undefined values.

```<code>const Conditional = ({ condition, render }) => {
  if (condition) {
    return render();
  }
  return null;
};

class App extends React.Component {
  constructor() {
    super();
    this.state = { items: null }
  }

  componentWillMount() {
    setTimeout(() => { this.setState({ items: [1,2] }) }, 2000);
  }

  render() {
    return (
      <Conditional
        condition={!!this.state.items}
        render={() => (
          <div>
            {this.state.items.map(value => <p>{value}</p>)}
          </div>
        )}
      />
    )
  }
}
</code>```

Body:
How do I optionally include an element in JSX?  Here is an example using a banner that should be in the component if it has been passed in.  What I want to avoid is having to duplicate HTML tags in the if statement.

render: function () {
    var banner;
    if (this.state.banner) {
        banner =
{this.state.banner}
;
    } else {
        banner = ?????
    }
    return (

            {banner}

                blah blah blah...

    );
}

Body:
There is also a technique using render props to conditional render a component. It's benefit is that the render wouldn't evaluate until the condition is met, resulting in no worries for null and undefined values.

const Conditional = ({ condition, render }) => {
  if (condition) {
    return render();
  }
  return null;
};

class App extends React.Component {
  constructor() {
    super();
    this.state = { items: null }
  }

  componentWillMount() {
    setTimeout(() => { this.setState({ items: [1,2] }) }, 2000);
  }

  render() {
    return (
      <Conditional
        condition={!!this.state.items}
        render={() => (
          <div>
            {this.state.items.map(value => <p>{value}</p>)}
          </div>
        )}
      />
    )
  }
}


问:
How to print a dict with some deviations added to its values?
I'm having a bit of trouble figuring out how can I append my dictionary values so that every time I print them, they will be slightly different e.i ±10% deviation.

Example code:

```<code>shop = {
 'Milk': 1.24,
 'Coffee': 8.68,
 'Bread': 1.99,
 'Apples': 0.96,
 'Cakes': 12.96,

}
</code>```

Something to make the shop.values change ±10%:

```<code> random_keys = random.choices(population=list(stock.keys()), k=random.randrange(2, 5))
 print({k: stock[k] for k in random_keys})
</code>```

End result:

```<code>{'Milk': 1.35, 'Cakes' : 12.82}
</code>```

答:
```<code>import random

for key in shop:

   print ( key, '%.2f' %(shop[key]*random.uniform(0.9,1.1)))
</code>```

if u need a percentage deviation of 10% --> you have to multiply between 0.9 and 1.1

ContentLicense: CC BY-SA 4.0

Body:
I'm having a bit of trouble figuring out how can I append my dictionary values so that every time I print them, they will be slightly different e.i ±10% deviation.

Example code:

shop = {
 'Milk': 1.24,
 'Coffee': 8.68,
 'Bread': 1.99,
 'Apples': 0.96,
 'Cakes': 12.96,

}

Something to make the shop.values change ±10%:

 random_keys = random.choices(population=list(stock.keys()), k=random.randrange(2, 5))
 print({k: stock[k] for k in random_keys})

End result:

{'Milk': 1.35, 'Cakes' : 12.82}

Body:
import random

for key in shop:

   print ( key, '%.2f' %(shop[key]*random.uniform(0.9,1.1)))

if u need a percentage deviation of 10% --> you have to multiply between 0.9 and 1.1


问:
Firebase - Deploy Your Site - Deletes Cloud Functions

Question

How can I deploy my Firebase site without erasing Cloud Functions.

Maybe, include both site and cloud-functions in one deploy? What does that look like?

Maybe, deploy the site without erasing cloud-functions? I don't find a firebase deploy --only site or similar

Context

I have a Firebase project that uses Cloud Functions. The code is in two folders:

```<code>-site-code
-cloud_function-code
</code>```

When I want to deploy the project, I use firebase CLI tools, in two steps:

Step 1

from -site-code I run:

```<code>firebase deploy
</code>```

Step 2

then from cloud_functions-code I run:

```<code>firebase deploy --only functions
</code>```

Issue

When I run firebase deploy from -site-code, my Firebase Cloud Functions are deleted, so I must follow up with firebase deploy --only functions from -cloud_functions-code.

I did not find an --only directive for deploying just the site code from -site-code

答:
To only deploy your web site, use</p>

```<code>firebase deploy --only hosting
</code>```

Body:
Question

How can I deploy my Firebase site without erasing Cloud Functions.

Maybe, include both site and cloud-functions in one deploy? What does that look like?

Maybe, deploy the site without erasing cloud-functions? I don't find a firebase deploy --only site or similar

Context

I have a Firebase project that uses Cloud Functions. The code is in two folders:

-site-code
-cloud_function-code

When I want to deploy the project, I use firebase CLI tools, in two steps:

Step 1

from -site-code I run:

firebase deploy

Step 2

then from cloud_functions-code I run:

firebase deploy --only functions

Issue

When I run firebase deploy from -site-code, my Firebase Cloud Functions are deleted, so I must follow up with firebase deploy --only functions from -cloud_functions-code.

I did not find an --only directive for deploying just the site code from -site-code

Body:
To only deploy your web site, use

firebase deploy --only hosting


问:
SOAP Proxy with Spring Integration
I'm trying to wrap my head around spring integration and would preferably like to stay away from XML-based configuration.

What I would like to do is the following:

Accept a SOAP request on a certain endpoint

Forward this request to a downstream SOAP service, without any modification (for now I just want the basics to work)

Return the result to the client

This seems like it should be pretty simple, but I don't have the faintest idea of where to start. Is this even possible with SI? As I understand it, and please correct me if I'm wrong, SI is mainly used for async data flows.

I did check out the integration sample repository, which includes example inbound WS requests, but these are all configured in XML, which, as I said, I'd preferably like to stay far away from.

Any pointers would be much appreciated; I've been reading through documentation for the past two days and I'm none the wiser!

答:
Here is an example using the SimpleWebServiceInboundGateway.  In this example we also set the "ExtractPayload" to false so that it sends the RAW soap message.  But agree with above, possibly the HTTPInboundRequest is better for your use case.  I also didn't find many examples using DSL for the SoapInboundGateway so wanted to share and hope it helps someone else.</p>
```<code>@Configuration
@EnableIntegration
public class SoapGatewayConfiguration {

    /**
     * URL mappings used by WS endpoints
     */
    public static final String[] WS_URL_MAPPINGS = {"/services/*", "*.wsdl", "*.xsd"};
    public static final String GATEWAY_INBOUND_CHANNEL_NAME  = "wsGatewayInboundChannel";
    public static final String GATEWAY_OUTBOUND_CHANNEL_NAME = "wsGatewayOutboundChannel";

    /**
     * Register the servlet mapper, note that it uses MessageDispatcher
     */
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        servlet.setTransformSchemaLocations(true);
        servlet.setPublishEvents(true);
        ServletRegistrationBean servletDef = new ServletRegistrationBean(servlet, WS_URL_MAPPINGS);
        servletDef.setLoadOnStartup(1);
        return servletDef;
    }

    /**
     * Create a new Direct channels to handle the messages
     */
    @Bean
    public MessageChannel wsGatewayInboundChannel() {
        return MessageChannels.direct(GATEWAY_INBOUND_CHANNEL_NAME).get();
    }
    @Bean
    public MessageChannel wsGatewayOutboundChannel() {
        return MessageChannels.direct(GATEWAY_OUTBOUND_CHANNEL_NAME).get();
    }

    /**
     * Startup the WebServiceInboundGateway Endpoint, this will handle the incoming SOAP requests
     *  and place them onto the request channel
     */
    @Bean
    public SimpleWebServiceInboundGateway webServiceInboundGateway(
            @Value("${spring.ws.request.timeout:1000}") long requestTimeout,
            @Value("${spring.ws.reply.timeout:1000}") long replyTimeout,
            @Value("${spring.ws.should.track:true}") boolean shouldTrack
    ) {
        SimpleWebServiceInboundGateway wsg = new SimpleWebServiceInboundGateway();
        wsg.setRequestChannel(wsGatewayInboundChannel());
        wsg.setReplyChannel(wsGatewayOutboundChannel());
        wsg.setExtractPayload(false);  // Send the full RAW SOAPMessage and not just payload
        wsg.setLoggingEnabled(true);
        wsg.setShouldTrack(shouldTrack);
        wsg.setReplyTimeout(replyTimeout); // Do not believe this prop supported currently
        wsg.setRequestTimeout(requestTimeout); // Do not believe this prop is supported currently
        wsg.setCountsEnabled(true);
        return wsg;
    }

    /**
     * You must enable debug logging on org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor
     *  to see the logs from this interceptor
     */
    @Bean
    public EndpointInterceptor soapMessageLoggingInterceptor() {
        SoapEnvelopeLoggingInterceptor li = new SoapEnvelopeLoggingInterceptor();
        li.setLogRequest(true);
        li.setLogResponse(true);
        li.setLogFault(true);
        return li;
    }

    /**
     * Validate the incoming web service against the schema
     */
    @Bean
    public EndpointInterceptor payloadValidatingInterceptor(XsdSchema xsdSchema
            , @Value("${spring.ws.soap.validate.request:true}") boolean soapValidateRequest
            , @Value("${spring.ws.soap.validate.reply:true}") boolean soapValidateResponse
            , @Value("${spring.ws.soap.validate.addErrorDetail:true}") boolean soapAddValidationErrorDetail

    ) {
        PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor();
        interceptor.setXsdSchema(xsdSchema);
        interceptor.setValidateRequest(soapValidateRequest);
        interceptor.setValidateResponse(soapValidateResponse);
        interceptor.setAddValidationErrorDetail(soapAddValidationErrorDetail);
        return interceptor;
    }

    /**
     * Map the allowable service Uri's.
     */
    @Bean
    public EndpointMapping uriEndpointMapping(
             PayloadValidatingInterceptor payloadValidatingInterceptor
            , SimpleWebServiceInboundGateway webServiceInboundGateway
            , SoapEnvelopeLoggingInterceptor loggingInterceptor) {
        UriEndpointMapping mapping = new UriEndpointMapping();
        mapping.setUsePath(true);
        mapping.setDefaultEndpoint(webServiceInboundGateway);
        mapping.setInterceptors(new EndpointInterceptor[]{loggingInterceptor, payloadValidatingInterceptor});
        return mapping;
    }

    /**
     * Expose the wsdl at http://localhost:8080/services/myService.wsdl
     **/
    @Bean
    public Wsdl11Definition myService() {
        SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
        wsdl11Definition.setWsdl(new ClassPathResource("META-INF/myService.wsdl"));
        return wsdl11Definition;
    }

    /**
     * Expose the xsd at http://localhost:8080/services/mySchema.xsd
     **/
    @Bean
    public XsdSchema mySchema() {
        return new SimpleXsdSchema(new ClassPathResource("META-INF/mySchema.xsd"));
    }

    @Bean
    public IntegrationFlow itemLookupFlow() {
        return IntegrationFlows.from("wsGatewayInboundChannel")
                .log(LoggingHandler.Level.INFO)
                .handle(myBeanName, "execute")
                .log(LoggingHandler.Level.TRACE, "afterExecute")
                .get();
    }

}
</code>```

Title: SOAP Proxy with Spring Integration

Body:
Here is an example using the SimpleWebServiceInboundGateway.  In this example we also set the "ExtractPayload" to false so that it sends the RAW soap message.  But agree with above, possibly the HTTPInboundRequest is better for your use case.  I also didn't find many examples using DSL for the SoapInboundGateway so wanted to share and hope it helps someone else.

@Configuration
@EnableIntegration
public class SoapGatewayConfiguration {

    /**
     * URL mappings used by WS endpoints
     */
    public static final String[] WS_URL_MAPPINGS = {"/services/*", "*.wsdl", "*.xsd"};
    public static final String GATEWAY_INBOUND_CHANNEL_NAME  = "wsGatewayInboundChannel";
    public static final String GATEWAY_OUTBOUND_CHANNEL_NAME = "wsGatewayOutboundChannel";

    /**
     * Register the servlet mapper, note that it uses MessageDispatcher
     */
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        servlet.setTransformSchemaLocations(true);
        servlet.setPublishEvents(true);
        ServletRegistrationBean servletDef = new ServletRegistrationBean(servlet, WS_URL_MAPPINGS);
        servletDef.setLoadOnStartup(1);
        return servletDef;
    }

    /**
     * Create a new Direct channels to handle the messages
     */
    @Bean
    public MessageChannel wsGatewayInboundChannel() {
        return MessageChannels.direct(GATEWAY_INBOUND_CHANNEL_NAME).get();
    }
    @Bean
    public MessageChannel wsGatewayOutboundChannel() {
        return MessageChannels.direct(GATEWAY_OUTBOUND_CHANNEL_NAME).get();
    }

    /**
     * Startup the WebServiceInboundGateway Endpoint, this will handle the incoming SOAP requests
     *  and place them onto the request channel
     */
    @Bean
    public SimpleWebServiceInboundGateway webServiceInboundGateway(
            @Value("${spring.ws.request.timeout:1000}") long requestTimeout,
            @Value("${spring.ws.reply.timeout:1000}") long replyTimeout,
            @Value("${spring.ws.should.track:true}") boolean shouldTrack
    ) {
        SimpleWebServiceInboundGateway wsg = new SimpleWebServiceInboundGateway();
        wsg.setRequestChannel(wsGatewayInboundChannel());
        wsg.setReplyChannel(wsGatewayOutboundChannel());
        wsg.setExtractPayload(false);  // Send the full RAW SOAPMessage and not just payload
        wsg.setLoggingEnabled(true);
        wsg.setShouldTrack(shouldTrack);
        wsg.setReplyTimeout(replyTimeout); // Do not believe this prop supported currently
        wsg.setRequestTimeout(requestTimeout); // Do not believe this prop is supported currently
        wsg.setCountsEnabled(true);
        return wsg;
    }

    /**
     * You must enable debug logging on org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor
     *  to see the logs from this interceptor
     */
    @Bean
    public EndpointInterceptor soapMessageLoggingInterceptor() {
        SoapEnvelopeLoggingInterceptor li = new SoapEnvelopeLoggingInterceptor();
        li.setLogRequest(true);
        li.setLogResponse(true);
        li.setLogFault(true);
        return li;
    }

    /**
     * Validate the incoming web service against the schema
     */
    @Bean
    public EndpointInterceptor payloadValidatingInterceptor(XsdSchema xsdSchema
            , @Value("${spring.ws.soap.validate.request:true}") boolean soapValidateRequest
            , @Value("${spring.ws.soap.validate.reply:true}") boolean soapValidateResponse
            , @Value("${spring.ws.soap.validate.addErrorDetail:true}") boolean soapAddValidationErrorDetail

    ) {
        PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor();
        interceptor.setXsdSchema(xsdSchema);
        interceptor.setValidateRequest(soapValidateRequest);
        interceptor.setValidateResponse(soapValidateResponse);
        interceptor.setAddValidationErrorDetail(soapAddValidationErrorDetail);
        return interceptor;
    }

    /**
     * Map the allowable service Uri's.
     */
    @Bean
    public EndpointMapping uriEndpointMapping(
             PayloadValidatingInterceptor payloadValidatingInterceptor
            , SimpleWebServiceInboundGateway webServiceInboundGateway
            , SoapEnvelopeLoggingInterceptor loggingInterceptor) {
        UriEndpointMapping mapping = new UriEndpointMapping();
        mapping.setUsePath(true);
        mapping.setDefaultEndpoint(webServiceInboundGateway);
        mapping.setInterceptors(new EndpointInterceptor[]{loggingInterceptor, payloadValidatingInterceptor});
        return mapping;
    }

    /**
     * Expose the wsdl at http://localhost:8080/services/myService.wsdl
     **/
    @Bean
    public Wsdl11Definition myService() {
        SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
        wsdl11Definition.setWsdl(new ClassPathResource("META-INF/myService.wsdl"));
        return wsdl11Definition;
    }

    /**
     * Expose the xsd at http://localhost:8080/services/mySchema.xsd
     **/
    @Bean
    public XsdSchema mySchema() {
        return new SimpleXsdSchema(new ClassPathResource("META-INF/mySchema.xsd"));
    }

    @Bean
    public IntegrationFlow itemLookupFlow() {
        return IntegrationFlows.from("wsGatewayInboundChannel")
                .log(LoggingHandler.Level.INFO)
                .handle(myBeanName, "execute")
                .log(LoggingHandler.Level.TRACE, "afterExecute")
                .get();
    }

}


问:
When zooming in, why does the footer overlap its preceding content
here is the sample html:

```<code><div id = "mainWrapperDiv">
    <div id = "mainDiv">
        <div> testing </div>
    </div>
 </div>
 <div id = "footerDiv">
 </div>
</code>```

its css:

```<code>*
{
    padding:            0px;
    margin:             0px;
}

body, html
{
    height:             100%
}

div
{
    border:             none;
}

#mainWrapperDiv
{
    min-height:         100%;
    height:             100%;
    margin-bottom:      -200px;
}

#mainDiv
{

    margin:             0px auto 0px auto;
    width:              1000px;
    min-height:         500px;
    background:         lightgreen;
}

#footerDiv
{
    height:             200px;
    width:              100%;
    position:           relative;
    clear:              both;
    background:         lightblue;
}
</code>```

答: Because the position is set to relative. and also the margin-bottom:      -200px;

Body:
here is the sample html:

 testing

its css:

*
{
    padding:            0px;
    margin:             0px;
}

body, html
{
    height:             100%
}

div
{
    border:             none;
}

#mainWrapperDiv
{
    min-height:         100%;
    height:             100%;
    margin-bottom:      -200px;
}

#mainDiv
{

    margin:             0px auto 0px auto;
    width:              1000px;
    min-height:         500px;
    background:         lightgreen;
}

#footerDiv
{
    height:             200px;
    width:              100%;
    position:           relative;
    clear:              both;
    background:         lightblue;
}


问:
$_SESSION not working in a login form
The code is suppose to set a variable if the password and username are inserted. But $_SESSION variable is never set and I don't know why and it just keeps redirecting me to the login page.

loginform.php:

```<code><?php
    $server = 'hiddenforthispost';
    $username = 'hiddenforthispost';
    $password = 'hiddenforthispost';
    $schema = 'hiddenforthispost';
    $pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password,
    [ PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);

                if (isset($_POST['Submit'])) {
                    if(empty($_POST['Username']) || empty($_POST['Password'])) {

                            echo '<p> You must insert all of the fields! </p>';
                        }
                        else {
                            $stmt = $pdo->prepare('SELECT * FROM logins
                                WHERE login_name = :username');
                            $criteria = [
                                        'username' => $_POST['Username']
                                        ];
                            $stmt->execute($criteria);
                            $user = $stmt->fetchColumn(1);
                            echo $user;
                            if (password_verify($_POST['Password'], $user)) {
                                session_start();
                                $_SESSION['loggedin'];
                                header('location: adminpage.php');
                                }
                                else {
                                    echo '<p> Wrong password </p>';
                                }
                            }
                        }
        ?>
</code>```

The page where I want only logged in users to access:
adminpage.php:

```<code><?php
 session_start();
 if(!isset($_SESSION['loggedin'])){
  header('location: loginpage.php');
 }
 else {
 }
?>
</code>```

答:
You're never putting anything in the session variable. Writing a variable by itself on a line doesn't assign anything to it.

In loginform.php, the line:

```<code>$_SESSION['loggedin'];
</code>```

should be something like:

```<code>$_SESSION['loggedin'] = true;
</code>```

Title: $_SESSION not working in a login form

Body:
The code is suppose to set a variable if the password and username are inserted. But $_SESSION variable is never set and I don't know why and it just keeps redirecting me to the login page.

loginform.php:

<?php
    $server = 'hiddenforthispost';
    $username = 'hiddenforthispost';
    $password = 'hiddenforthispost';
    $schema = 'hiddenforthispost';
    $pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password,
    [ PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);

                if (isset($_POST['Submit'])) {
                    if(empty($_POST['Username']) || empty($_POST['Password'])) {

                            echo '
 You must insert all of the fields!
';
                        }
                        else {
                            $stmt = $pdo->prepare('SELECT * FROM logins
                                WHERE login_name = :username');
                            $criteria = [
                                        'username' => $_POST['Username']
                                        ];
                            $stmt->execute($criteria);
                            $user = $stmt->fetchColumn(1);
                            echo $user;
                            if (password_verify($_POST['Password'], $user)) {
                                session_start();
                                $_SESSION['loggedin'];
                                header('location: adminpage.php');
                                }
                                else {
                                    echo '
 Wrong password
';
                                }
                            }
                        }
        ?>

The page where I want only logged in users to access:
adminpage.php:

<?php
 session_start();
 if(!isset($_SESSION['loggedin'])){
  header('location: loginpage.php');
 }
 else {
 }
?>

Body:
You're never putting anything in the session variable. Writing a variable by itself on a line doesn't assign anything to it.

In loginform.php, the line:

$_SESSION['loggedin'];

should be something like:

$_SESSION['loggedin'] = true;


问:
Partial specialization for pointers, c++
How to make partial specialization of the class GList so that it is possible to store pointers of I (i.e I*) ?</p>

```<code>template <class I>
struct TIList
{
    typedef std::vector <I> Type;
};

template <class I>
class GList
{
      private:
            typename TIList <I>::Type objects;
};
</code>```

答:
You don't need to specialise to allow that. It can store pointers already.

```<code>GList<int*> ints;
</code>```

Anyway, if you wanted to specialise GList for pointers, use the following syntax.

```<code>template <class I>
class GList<I*>
{
    ...
};
</code>```

Then just use I as you would in any normal template. In the example above with GList<int*>, the pointer specialisation would be used, and I would be int.

Body:
How to make partial specialization of the class GList so that it is possible to store pointers of I (i.e I*) ?

template <class I>
struct TIList
{
    typedef std::vector  Type;
};

template <class I>
class GList
{
      private:
            typename TIList ::Type objects;
};

Body:
You don't need to specialise to allow that. It can store pointers already.

GList<int*> ints;

Anyway, if you wanted to specialise GList for pointers, use the following syntax.

template <class I>
class GList<I*>
{
    ...
};

Then just use I as you would in any normal template. In the example above with GList<int*>, the pointer specialisation would be used, and I would be int.


问:
SQL join on columns of same table with MAX on another column
Have this table (top row is column names):

```<code>security    quote_type      price     round
sec_1       bid             3.4       1
sec_1       ask             3.6       1
sec_1       bid             3.5       2
sec_1       ask             3.7       2
sec_2       bid             5.2       1
sec_2       ask             5.4       1
sec_3       bid             2.3       1
sec_4       ask             7.8       1
sec_4       ask             7.9       2
</code>```

Need to achieve these results:

```<code>security    bid     ask      round
sec_1       3.5     3.7      2
sec_2       5.2     5.4      1
sec_3       2.3     null     1
sec_4       null    7.9      2
</code>```

Have this much working, which does not yet take into account the "round" column:

```<code>select security,
   max(case when quote_type = 'bid' then price end) as bid,
   max(case when quote_type = 'ask' then price end) as ask
from t
group by security;
</code>```

There will always be at most one bid and one ask price per security, per round.

Using SQL Server.

Thanks for any help!

答:
Create table and insert data:

```<code>CREATE TABLE [security] (security VARCHAR(10),quote_type VARCHAR(10),price NUMERIC(3,1),round INT)

INSERT INTO [security]
SELECT 'sec_1','bid','3.4','1'
UNION SELECT 'sec_1','ask','3.6','1'
UNION SELECT 'sec_1','bid','3.5','2'
UNION SELECT 'sec_1','ask','3.7','2'
UNION SELECT 'sec_2','bid','5.2','1'
UNION SELECT 'sec_2','ask','5.4','1'
UNION SELECT 'sec_3','bid','2.3','1'
UNION SELECT 'sec_4','ask','7.8','1'
UNION SELECT 'sec_4','ask','7.9','2'

select * From [security]
</code>```

Requested resulset:

```<code>  ;with cte_max_round as (
        SELECT security,MAX(Round) R FROM [security]
        group by security
        )

    SELECT B.security,BID.price,ASK.price,r Round
    FROM cte_max_round B
    LEFT JOIN [security] ASK
        ON B.security = ASK.security AND B.R = ASK.[round] AND ASK.quote_type = 'ask'
    LEFT JOIN [security] BID
        ON B.security = BID.security AND B.R = BID.[round] AND BID.quote_type = 'bid'
</code>```

Body:
Have this table (top row is column names):

security    quote_type      price     round
sec_1       bid             3.4       1
sec_1       ask             3.6       1
sec_1       bid             3.5       2
sec_1       ask             3.7       2
sec_2       bid             5.2       1
sec_2       ask             5.4       1
sec_3       bid             2.3       1
sec_4       ask             7.8       1
sec_4       ask             7.9       2

Need to achieve these results:

security    bid     ask      round
sec_1       3.5     3.7      2
sec_2       5.2     5.4      1
sec_3       2.3     null     1
sec_4       null    7.9      2

Have this much working, which does not yet take into account the "round" column:

select security,
   max(case when quote_type = 'bid' then price end) as bid,
   max(case when quote_type = 'ask' then price end) as ask
from t
group by security;

There will always be at most one bid and one ask price per security, per round.

Using SQL Server.

Thanks for any help!

Body:
Create table and insert data:

CREATE TABLE [security] (security VARCHAR(10),quote_type VARCHAR(10),price NUMERIC(3,1),round INT)

INSERT INTO [security]
SELECT 'sec_1','bid','3.4','1'
UNION SELECT 'sec_1','ask','3.6','1'
UNION SELECT 'sec_1','bid','3.5','2'
UNION SELECT 'sec_1','ask','3.7','2'
UNION SELECT 'sec_2','bid','5.2','1'
UNION SELECT 'sec_2','ask','5.4','1'
UNION SELECT 'sec_3','bid','2.3','1'
UNION SELECT 'sec_4','ask','7.8','1'
UNION SELECT 'sec_4','ask','7.9','2'

select * From [security]

Requested resulset:

  ;with cte_max_round as (
        SELECT security,MAX(Round) R FROM [security]
        group by security
        )

    SELECT B.security,BID.price,ASK.price,r Round
    FROM cte_max_round B
    LEFT JOIN [security] ASK
        ON B.security = ASK.security AND B.R = ASK.[round] AND ASK.quote_type = 'ask'
    LEFT JOIN [security] BID
        ON B.security = BID.security AND B.R = BID.[round] AND BID.quote_type = 'bid'


问:
what's wrong with string contains match
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

```<code> If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If
</code>```

but that's not working in my condition

```<code>dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"
</code>```

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?

答:
It has to be an exact part of the string, in your case the field does not contain “Cook Steve” like you’re asking, it contains (“Steve” and “Cook”) or (“Steve Cook”)

You need to split on the spaces and check each word. But you could find some cases where you’ll get false positives.

Title: what's wrong with string contains match

Body:
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

 If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If

but that's not working in my condition

dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?


问:
Select unique records and insert into another table avoiding duplicates in it
i have two table(userfrom and userto).

i want to insert data from "userfrom" table to "userto" and want to implement condition on two column i.e "username" and "date".

Basically i am pasting my data from "userfrom" to table "userto".

Condition before insertion is.

Same "username" with same "date" should not get inserted.
There can be same username but date shold be different.

Only username is identical in between both the tables

Please Note:(On re-run of insert query i dont want same data to be duplicated. This insert query runs for 5 time in 30 min bracket)
Table userfrom:

```<code>1 sampleusername  2017-12-04
2 sampleusername  2017-12-04
3 sampleusername2 2017-12-04
4 sampleusername  2017-12-05
</code>```

Table usertto:

```<code>1 sampleusername  2017-12-04
2 sampleusername2 2017-12-04
3 sampleusername  2017-12-05
</code>```

答:
You can LEFT JOIN the two tables, and then only insert the values from userfrom that don't exist in userto table like this:

```<code>INSERT INTO userTo
    (
        username
        ,userDate
    )
SELECT DISTINCT f.username
      ,f.userDate
FROM usertrom f
LEFT JOIN userto t ON f.username = t.username AND f.userDate = t.userDate
WHERE t.id IS NULL
</code>```

Body:
i have two table(userfrom and userto).

i want to insert data from "userfrom" table to "userto" and want to implement condition on two column i.e "username" and "date".

Basically i am pasting my data from "userfrom" to table "userto".

Condition before insertion is.

Same "username" with same "date" should not get inserted.
There can be same username but date shold be different.

Only username is identical in between both the tables

Please Note:(On re-run of insert query i dont want same data to be duplicated. This insert query runs for 5 time in 30 min bracket)
Table userfrom:

1 sampleusername  2017-12-04
2 sampleusername  2017-12-04
3 sampleusername2 2017-12-04
4 sampleusername  2017-12-05

Table usertto:

1 sampleusername  2017-12-04
2 sampleusername2 2017-12-04
3 sampleusername  2017-12-05

Body:
You can LEFT JOIN the two tables, and then only insert the values from userfrom that don't exist in userto table like this:

INSERT INTO userTo
    (
        username
        ,userDate
    )
SELECT DISTINCT f.username
      ,f.userDate
FROM usertrom f
LEFT JOIN userto t ON f.username = t.username AND f.userDate = t.userDate
WHERE t.id IS NULL


问:
What's the difference between this and super keywords in java?
Check my coolMethod, babes:

```<code>package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}
</code>```

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

```<code>package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

And my main, that calls my Moo class functionalities.

```<code>package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}
</code>```

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

答:
You are not overriding the coolMethod and you are inheriting it.

As a result it calls the same method.

Override coolMethod and see what happens.

super will call the method of base.

this will call method in this object

Body:
Check my coolMethod, babes:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities.

package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?


问:
How to improve my team creation logic?
I had one day to create a program that, when given a .csv file with the columns: [Name] | [Elo Rating], would output another .csv file with balanced teams.  The user can choose how many players they want per team.

This is probably the programming project I enjoyed the most, but it is highly inefficient given the rushed time frame and my limited knowledge of how best to implement such a task.  It is similar to this question, but I would prefer not to simplify the process into just placing the players into teams based on the rating order (faster, but less accurate than what I already have).  Can you give suggestions on how I could make this run faster without sacrificing accuracy?

The logic I went with is this:

Find all the possible team combinations.

Find the average rating of all the team combinations & find the closest team rating to that average

Select the first team that has the average rating from step 2.

Remove all the teams that have any of these players in them.

Repeat #2, #3, and #4 until all the teams are made.

Step 1 was accomplished by this answer and works excellently.

Step 2 might be more of a math question.  I'm not sure if the average of the player's ratings is equal to the average ratings of all the teams.  I'm using  a slightly modified version of this answer because I am using a dictionary to hold the name & rating.  I wouldn't need this dictionary if just averaging the player's ratings was just as accurate.

```<code>float average = teamScoreDict.Average(s => s.Value);

var closestScoreToAvg = teamScoreDict.Values.Aggregate((x, y) =>
Math.Abs(x - average) < Math.Abs(y - average) ? x : y);
</code>```

Step 3

```<code>static Team FindTeam(float targetScore)
    {
        var selectedTeam = new Team();

        //grabbing the first team with the proper score and adding it to final teams (not perfect since there could be multiple teams with the same score)
        for (int i = 0; i < teams.Count; i++)
        {
            if (teams[i].TeamRating == targetScore)
            {
                selectedTeam = teams[i];

                //add these players to the list of players who have already been selected
                foreach (var player in teams[i].Player)
                    if (!usedPlayers.Contains(player.Key))
                        usedPlayers.Add(player.Key);

                //remove the score and team then break
                teamScoreDict.Remove(teams[i].Id);
                teams.Remove(teams[i]);
                break;
            }
        }

        return selectedTeam;
    }
</code>```

Step 4 is what I believe to be the slowest part of this task.  I thought removing the teams each iteration would make the subsequent team searches faster, which it does, but the removal process is slow.

```<code>static void RemoveTeamsWithUsedPlayers()
    {
        for (int i = teams.Count - 1; i >= 0; i--)
        {
            if (teams[i].Player.Any(kvp => usedPlayers.Contains(kvp.Key)))
            {
                teamScoreDict.Remove(teams[i].Id);
                teams.Remove(teams[i]);
            }
        }
    }
</code>```

The results are excellent (My last run with 40 players into 5 man teams with elo ratings from 1300-2200 gave me 8 teams with only 19 point difference between the highest and lowest team's total score [8498 vs 8517]).

My problem is that it is extremely slow for larger team sizes.  12 players with 3 man teams is instant.  32 players in 4 man teams takes a few seconds.  40 players in 5 man teams takes many minutes because the possible K-combinations grow drastically and I'm looping through them so many times.

I hope this question is not too broad, and thank you for any suggestions.

EDIT: I went ahead and used the stopwatch class to get the times for each step as suggested.  For 12 players with 3 per team (220 k-combinations).

00:00:00.0014493

00:00:00.0083637

00:00:00.0015608

00:00:00.0015930

There is also another step that I forgot.  Between step 1 and step 2 I take the IEnumerable of all possible team combinations and put it into a class that I made, and calculate the total team score.  This step takes 00:00:00.0042700

```<code>foreach (var team in teamList)
        {
            Team teamClass = new Team();
            teamScore = 0.0F;

            foreach (var player in team)
            {
                if (participants.TryGetValue(player, out tempInt))
                {
                    teamScore += tempInt;
                    teamClass.Player.Add(player, tempInt);
                }
            }

            teamClass.TeamRating = teamScore;
            teamClass.Id = count;
            teamScoreDict.Add(count, teamScore);
            teams.Add(teamClass);
            count++;
        }
</code>```

EDIT 2 (Improved Logic): I'm certain I could still improve this a lot, but based on the answer I marked and the comments I was able to drastically speed things up while still maintaining accuracy.  The 3 person teams with 12 players take about the same time, but 4 person teams with 32 players went from 4.5229176s to 0.4067160s.  Here are the adjustments I made:

I use the average of just the players.  It is the same as the average of all team combinations

I remove the highest rated player and then find the combinations with one less player than I normally would.

While I am placing all these teams into the class I will use, I simultaneously check for the (closest team rating + highest player rating) to the (overall average * players per team)

Then I add the highest player back to that team and remove all the players from the list

Repeat step 2 & 3 until everyone is used up

答:
For your average of averages side question, the answer is that you don't need your dictionary.

As for the algorithm, the easiest speedup is to say that the person with the highest rating will have to be on SOME team.  So build only teams with that person, take the best.  Then build teams again with some other person.  And repeat.  The result will be different than what you are doing currently because the person with the highest rating is not always on the team with closest to average rating, but the result is no less accurate.  This will make your current O(n^m) algorithm for building a list of all possible teams into a O(n^(m-1)) algorithm.

But for a real speedup, what you need to do is follow the strategy in https://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution and use dynamic programming to eliminate looking at teams whose scores will come out to be the same.  That is, you build a data structure by number of players on the partial team so far, by total rating, the last player added.  Now the second time you find, for instance, a combined score of 3500 for 3 players, you know that the teams that it leads to will have duplicate scores with what you already did, so you throw it out.

Throwing away all of those duplicates in the team generation process will reduce finding the next team from O(n^m) to O(n*m*k) where k is the range between the lowest and highest rating.  And doing that n/m times will therefore take time O(n^2*k).  Which should be acceptable with 5 person teams up to several hundred people.

So you build up this data structure, then sort the scores for a full team, and take the best one.  Now walk the data structure backwards and you can find the selected team.  Then throw it away and do this again.

Title: How to improve my team creation logic?

Body:
I had one day to create a program that, when given a .csv file with the columns: [Name] | [Elo Rating], would output another .csv file with balanced teams.  The user can choose how many players they want per team.

This is probably the programming project I enjoyed the most, but it is highly inefficient given the rushed time frame and my limited knowledge of how best to implement such a task.  It is similar to this question, but I would prefer not to simplify the process into just placing the players into teams based on the rating order (faster, but less accurate than what I already have).  Can you give suggestions on how I could make this run faster without sacrificing accuracy?

The logic I went with is this:

Find all the possible team combinations.

Find the average rating of all the team combinations & find the closest team rating to that average

Select the first team that has the average rating from step 2.

Remove all the teams that have any of these players in them.

Repeat #2, #3, and #4 until all the teams are made.

Step 1 was accomplished by this answer and works excellently.

Step 2 might be more of a math question.  I'm not sure if the average of the player's ratings is equal to the average ratings of all the teams.  I'm using  a slightly modified version of this answer because I am using a dictionary to hold the name & rating.  I wouldn't need this dictionary if just averaging the player's ratings was just as accurate.

float average = teamScoreDict.Average(s => s.Value);

var closestScoreToAvg = teamScoreDict.Values.Aggregate((x, y) =>
Math.Abs(x - average) < Math.Abs(y - average) ? x : y);

Step 3

static Team FindTeam(float targetScore)
    {
        var selectedTeam = new Team();

        //grabbing the first team with the proper score and adding it to final teams (not perfect since there could be multiple teams with the same score)
        for (int i = 0; i < teams.Count; i++)
        {
            if (teams[i].TeamRating == targetScore)
            {
                selectedTeam = teams[i];

                //add these players to the list of players who have already been selected
                foreach (var player in teams[i].Player)
                    if (!usedPlayers.Contains(player.Key))
                        usedPlayers.Add(player.Key);

                //remove the score and team then break
                teamScoreDict.Remove(teams[i].Id);
                teams.Remove(teams[i]);
                break;
            }
        }

        return selectedTeam;
    }

Step 4 is what I believe to be the slowest part of this task.  I thought removing the teams each iteration would make the subsequent team searches faster, which it does, but the removal process is slow.

static void RemoveTeamsWithUsedPlayers()
    {
        for (int i = teams.Count - 1; i >= 0; i--)
        {
            if (teams[i].Player.Any(kvp => usedPlayers.Contains(kvp.Key)))
            {
                teamScoreDict.Remove(teams[i].Id);
                teams.Remove(teams[i]);
            }
        }
    }

The results are excellent (My last run with 40 players into 5 man teams with elo ratings from 1300-2200 gave me 8 teams with only 19 point difference between the highest and lowest team's total score [8498 vs 8517]).

My problem is that it is extremely slow for larger team sizes.  12 players with 3 man teams is instant.  32 players in 4 man teams takes a few seconds.  40 players in 5 man teams takes many minutes because the possible K-combinations grow drastically and I'm looping through them so many times.

I hope this question is not too broad, and thank you for any suggestions.

EDIT: I went ahead and used the stopwatch class to get the times for each step as suggested.  For 12 players with 3 per team (220 k-combinations).

00:00:00.0014493

00:00:00.0083637

00:00:00.0015608

00:00:00.0015930

There is also another step that I forgot.  Between step 1 and step 2 I take the IEnumerable of all possible team combinations and put it into a class that I made, and calculate the total team score.  This step takes 00:00:00.0042700

foreach (var team in teamList)
        {
            Team teamClass = new Team();
            teamScore = 0.0F;

            foreach (var player in team)
            {
                if (participants.TryGetValue(player, out tempInt))
                {
                    teamScore += tempInt;
                    teamClass.Player.Add(player, tempInt);
                }
            }

            teamClass.TeamRating = teamScore;
            teamClass.Id = count;
            teamScoreDict.Add(count, teamScore);
            teams.Add(teamClass);
            count++;
        }

EDIT 2 (Improved Logic): I'm certain I could still improve this a lot, but based on the answer I marked and the comments I was able to drastically speed things up while still maintaining accuracy.  The 3 person teams with 12 players take about the same time, but 4 person teams with 32 players went from 4.5229176s to 0.4067160s.  Here are the adjustments I made:

I use the average of just the players.  It is the same as the average of all team combinations

I remove the highest rated player and then find the combinations with one less player than I normally would.

While I am placing all these teams into the class I will use, I simultaneously check for the (closest team rating + highest player rating) to the (overall average * players per team)

Then I add the highest player back to that team and remove all the players from the list

Repeat step 2 & 3 until everyone is used up


问:
$ionicModal not updating the content when changes made in the controller when it is open
I have an $ionicModal like this:

```<code><ion-modal-view>
 <ion-content>
  <ion-slide-box>
    <ion-slide ng-repeat="display in VideoCtrl.display track by $index" >
      <div class="card">
        <div class="item item-divider">
         {{display.start}}-{{display.end}}
        </div>
        <div ng-style='{ "background" : "#" + display.css.color }'>
        </div>
      </div>
    </ion-slide>
  </ion-slide-box>
 </ion-content>
</ion-modal-view>
</code>```

And VideoCtrl is the parent controller of the modal. I am changing the value of 'display' obj in the VideoCtrl and the modal is kept open. But the changes are not reflected on the modal.

How can I bind the changes? I am thinking of ng-model but not getting where to use it and which variable to write.

答:
In your parent controller, when changing a variable, you should wrap it inside $apply fn.

for example:

```<code>$scope.$apply(function(){
    $scope.display++; // or if display is an object (which I assume from you example), it is still the same.

});
</code>```

Body:
I have an $ionicModal like this:

<ion-modal-view>
 <ion-content>
  <ion-slide-box>
    <ion-slide ng-repeat="display in VideoCtrl.display track by $index" >

         {{display.start}}-{{display.end}}

    </ion-slide>
  </ion-slide-box>
 </ion-content>
</ion-modal-view>

And VideoCtrl is the parent controller of the modal. I am changing the value of 'display' obj in the VideoCtrl and the modal is kept open. But the changes are not reflected on the modal.

How can I bind the changes? I am thinking of ng-model but not getting where to use it and which variable to write.

Body:
In your parent controller, when changing a variable, you should wrap it inside $apply fn.

for example:

$scope.$apply(function(){
    $scope.display++; // or if display is an object (which I assume from you example), it is still the same.

});


问:
Clojure Even List within even counts
Currently I am trying to partition my lists in clojure into even splits of even values.
To explain.

I have

```<code>(def a '(1 2 3 4 5 6 7 8 9 10))
</code>```

What I want to do is give it a partition function and create even lists that are even in count.
so if I were to split my list by 2 I would want it to look like

```<code>((1 2 3 4 5 6) (7 8 9 10)) or
((1 2 3 4)(5 6 7 8 9 10)) producing 2 lists with even counts.
</code>```

or if I want to split by 4 into even lists it would look something like

```<code>((1 2)(3 4)(5 6)(7 8 9 10))
</code>```

I will always be splitting by even (ex. 2,4,8,16,32). but I want every return list to have even counts without remainders.

I am at a lost and have created numerous parition functions all which don't work. Any help is appreciated.

答:
Marking the one above as the correct answer. I was able to use this method to further break it down to separate into even lists.

```<code>(defn trunc-to-even
"Truncates a value the largest int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn split-2 [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(defn split-4 [x]
  (apply concat (pmap split-2(concat (split-2 x)))))
</code>```

Doing this I can keep building on to split at 8-16-32.

Title: Clojure Even List within even counts

Body:
Currently I am trying to partition my lists in clojure into even splits of even values.
To explain.

I have

(def a '(1 2 3 4 5 6 7 8 9 10))

What I want to do is give it a partition function and create even lists that are even in count.
so if I were to split my list by 2 I would want it to look like

((1 2 3 4 5 6) (7 8 9 10)) or
((1 2 3 4)(5 6 7 8 9 10)) producing 2 lists with even counts.

or if I want to split by 4 into even lists it would look something like

((1 2)(3 4)(5 6)(7 8 9 10))

I will always be splitting by even (ex. 2,4,8,16,32). but I want every return list to have even counts without remainders.

I am at a lost and have created numerous parition functions all which don't work. Any help is appreciated.

Body:
Marking the one above as the correct answer. I was able to use this method to further break it down to separate into even lists.

(defn trunc-to-even
"Truncates a value the largest int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn split-2 [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(defn split-4 [x]
  (apply concat (pmap split-2(concat (split-2 x)))))

Doing this I can keep building on to split at 8-16-32.


问:
Python Cryptography Error cannot import name certificate_transparency
trying to run a pymodbus tcp server and im getting this stack trace... at a total loss here so any help is appreciated. Thanks!</p>

```<code>Traceback (most recent call last):
File "Worrking_ModbusJ1939Bridge.py", line 12, in <module>
from pymodbus.server.async import StartTcpServer
File "build/bdist.linux-armv7l/egg/pymodbus/server/async.py", line 18, in <module>
File "build/bdist.linux-armv7l/egg/pymodbus/internal/ptwisted.py", line 5, in <module>
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/manhole_ssh.py", line 14, in <module>
from twisted.conch.ssh import factory, session
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/factory.py", line 18, in <module>
from twisted.conch.ssh import (_kex, transport, userauth, connection)
File "/usr/local/lib/python2.7/dist packages/twisted/conch/ssh/transport.py", line 345, in <module>
class SSHTransportBase(protocol.Protocol):
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py", line 469, in SSHTransportBase
supportedCiphers = _getSupportedCiphers()
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py", line 335, in _getSupportedCiphers
backend=default_backend(),
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 15, in default_backend
from cryptography.hazmat.backends.openssl.backend import backend
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/__init__.py", line 7, in <module>
from cryptography.hazmat.backends.openssl.backend import backend
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 16, in <module>
from cryptography import utils, x509
File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/__init__.py", line 7, in <module>
from cryptography.x509 import certificate_transparency
ImportError: cannot import name certificate_transparency
</code>```

答:
I was using pip 7 and got the same problem. Upgrading to pip 9 solved it. I'm not sure about the cause.

Via: https://github.com/micheloosterhof/cowrie/issues/618

Body:
trying to run a pymodbus tcp server and im getting this stack trace... at a total loss here so any help is appreciated. Thanks!

Traceback (most recent call last):
File "Worrking_ModbusJ1939Bridge.py", line 12, in <module>
from pymodbus.server.async import StartTcpServer
File "build/bdist.linux-armv7l/egg/pymodbus/server/async.py", line 18, in <module>
File "build/bdist.linux-armv7l/egg/pymodbus/internal/ptwisted.py", line 5, in <module>
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/manhole_ssh.py", line 14, in <module>
from twisted.conch.ssh import factory, session
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/factory.py", line 18, in <module>
from twisted.conch.ssh import (_kex, transport, userauth, connection)
File "/usr/local/lib/python2.7/dist packages/twisted/conch/ssh/transport.py", line 345, in <module>
class SSHTransportBase(protocol.Protocol):
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py", line 469, in SSHTransportBase
supportedCiphers = _getSupportedCiphers()
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py", line 335, in _getSupportedCiphers
backend=default_backend(),
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 15, in default_backend
from cryptography.hazmat.backends.openssl.backend import backend
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/__init__.py", line 7, in <module>
from cryptography.hazmat.backends.openssl.backend import backend
File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 16, in <module>
from cryptography import utils, x509
File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/__init__.py", line 7, in <module>
from cryptography.x509 import certificate_transparency
ImportError: cannot import name certificate_transparency


问:
BLE 5 data rates supported by iOS and Android

What are the different BLE 5 data rates supported by latest version of iOS and Android?

Also, what are the different connection parameters supported by
these two platforms?

Is there a publicly available documentation which specifies this information ?

答:
The new PHYs are supported as long as the Bluetooth chip in the phone/tablet supports them. You can initiate an update of the symbol rate to 2 MBit/s from the remote device as a workaround if you use an old Android version which doesn't have an API to update the PHY. The connection parameters are not affected by the PHY selection (I think?) so all old restrictions should still apply.

Android API level 26 has added new methods which you can find in the documentation at https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html and https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html.


问:
How to make two left navbars with bootstrap?
I am trying to make a simple design including two left columns each including a navbar and one right column with the content.
I have tried a lot of things but each time I have a problem :

my columns don't stay on the left of my page (I want the two columns left fixed size, and the content column fluid taking the rest of the
page)

my columns overlap

the content overlaps with the content

I can't figure out what is wrong. This is what I desire to obtain :

And this is a sample of my actual code

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        BRAND

Tralalala1

SubMenu

RSubMenue

BSubMenut

SSubMenu

Tralalala1

SubsubMenu

SubSubMenu

SubSubMenut

SubSubMenu

SubSub Menu4

SubSub Menu5

```

答:
OFFICIAL BOOTSTRAP GRID DOCUMENTATION- Please go through this documentation to get better idea how to use the following classes.

container/container-fluid

row

col-sm/col-md/col-lg....and others

You don't necessarily need to use the offset in your case, as they all are in the same row.

Better to use all of them in same class i.e. row

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        BRAND

Tralalala1

SubMenu

RSubMenue

BSubMenut

SSubMenu

Tralalala1

SubsubMenu

SubSubMenu

SubSubMenut

SubSubMenu

SubSub Menu4

SubSub Menu5

```

Body:
OFFICIAL BOOTSTRAP GRID DOCUMENTATION- Please go through this documentation to get better idea how to use the following classes.

container/container-fluid

row

col-sm/col-md/col-lg....and others

You don't necessarily need to use the offset in your case, as they all are in the same row.

Better to use all of them in same class i.e. row

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-2">

      <div class="navbar navbar-inverse navbar-fixed-left">
        <a class="navbar-brand" href="#">BRAND  </a>

        <ul class="nav navbar-nav">

          <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Tralalala1<span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="#">SubMenu</a></li>
              <li><a href="#">RSubMenue</a></li>
              <li><a href="#">BSubMenut</a></li>
              <li><a href="#">SSubMenu</a></li>
            </ul>
          </li>

        </ul>
      </div>
    </div>
    <div class="col-md-2">
      <ul class="nav navbar-nav">

        <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Tralalala1<span class="caret"></span></a>
          <ul class="dropdown-menu" role="menu">
            <li><a href="#">SubsubMenu</a></li>
            <li><a href="#">SubSubMenu</a></li>
            <li><a href="#">SubSubMenut</a></li>
            <li><a href="#">SubSubMenu</a></li>
            <li class="divider"></li>
            <li><a href="#">SubSub Menu4</a></li>
            <li><a href="#">SubSub Menu5</a></li>

          </ul>

    </div>
    <div class="col-md-8">
      <div>
        <div style="text-align: center;">
          <img id="TimeLine" src="http://img.playbuzz.com/image/upload/f_auto,fl_lossy,q_auto/cdn/a123d728-dd6e-46b1-85c2-5907d9fbb488/5b3da9cf-d8b7-41cd-ae02-a414dbde71fc.jpg" orgwidth="1008" orgheight="709" usemap="#image-maps-2017-11-27-071035" alt="TimeLine Demande de Ticketing Generale"
            align="centre" border="0" height="709" width="1008">
        </div>
      </div>
    </div>

  </div>
</div>


问:
javascript escape problem with unicode characters
I use the following jquery code to load some date on a specific event from external file:

```<code>$("#container").load("/include/data.php?name=" + escape(name));
</code>```

if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1

How can I deal with this encoded symbols? I need to convert them back to readable one.

When I remove the escape function and leave just "name" variable the code doesn't work any more...

Can anyone please help?

答:
If you want to do this manually, then you should be using encodeURIComponent, not escape (which is deprecated)

The jQuery way, however, would be:

```<code>$("#container").load("/include/data.php", { "name": name });
</code>```

Either way PHP should decode it automatically when it populates $_GET.

Body:
I use the following jquery code to load some date on a specific event from external file:

$("#container").load("/include/data.php?name=" + escape(name));

if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1

How can I deal with this encoded symbols? I need to convert them back to readable one.

When I remove the escape function and leave just "name" variable the code doesn't work any more...

Can anyone please help?

Body:
If you want to do this manually, then you should be using encodeURIComponent, not escape (which is deprecated)

The jQuery way, however, would be:

$("#container").load("/include/data.php", { "name": name });

Either way PHP should decode it automatically when it populates $_GET.


问:
Downloaded file is corrupted
I am trying to download an image using Dropbox URL in elixir with the following code:

```<code>%HTTPoison.Response{body: body} = HTTPoison.get!("https://www.dropbox.com/s/fxot6tgw21mthg8/WeVnWhite-1.JPG")
File.write!("image.jpg", body)
</code>```

The file is created successfully with File.write!/2. But when I try to open it, it says the file is corrupted and the size of the file is also different from the original size.

答:
You are downloading Dropbox's HTML presentation page and saving it as a jpeg:

```<code>https://www.dropbox.com/s/fxot6tgw21mthg8/WeVnWhite-1.JPG
</code>```

When you open the file it is not encoded as a JPEG properly because the contents are probably HTML.

The actual image file link you want is here:

```<code>https://photos-3.dropbox.com/t/2/AAAVbXWztTiaGBvbN9xqj45gyFxFW5mWFPViVRMhUliZNQ/12/182502757/jpeg/32x32/3/1512439200/0/2/WeVnWhite-1.JPG/ELW71YoBGOvEAiAHKAc/9MJyVOom1Qyql6ewIOrAZsfC6JAzz2BaPAdgIgJvS7o
</code>```

Your code will work if you use the correct link.

Title: Downloaded file is corrupted

Body:
I am trying to download an image using Dropbox URL in elixir with the following code:

%HTTPoison.Response{body: body} = HTTPoison.get!("https://www.dropbox.com/s/fxot6tgw21mthg8/WeVnWhite-1.JPG")
File.write!("image.jpg", body)

The file is created successfully with File.write!/2. But when I try to open it, it says the file is corrupted and the size of the file is also different from the original size.

Body:
You are downloading Dropbox's HTML presentation page and saving it as a jpeg:

https://www.dropbox.com/s/fxot6tgw21mthg8/WeVnWhite-1.JPG

When you open the file it is not encoded as a JPEG properly because the contents are probably HTML.

The actual image file link you want is here:

https://photos-3.dropbox.com/t/2/AAAVbXWztTiaGBvbN9xqj45gyFxFW5mWFPViVRMhUliZNQ/12/182502757/jpeg/32x32/3/1512439200/0/2/WeVnWhite-1.JPG/ELW71YoBGOvEAiAHKAc/9MJyVOom1Qyql6ewIOrAZsfC6JAzz2BaPAdgIgJvS7o

Your code will work if you use the correct link.


问:
Cannot find module '@angular/compiler'
I run the command npm install -g @angular/cli and after i tried to run my app it says, Cannot find module '@angular/compiler' in the terminal. How can i install the compiler in my package.json in order to compile my application </p>

```<code>//package
{
  "name": "Restaurant",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~2.4.9",
    "@angular/compiler": "~2.4.9",
    "@angular/core": "~2.4.9",
    "@angular/forms": "~2.4.9",
    "@angular/http": "~2.4.9",
    "@angular/platform-browser": "~2.4.9",
    "@angular/platform-browser-dynamic": "~2.4.9",
    "@angular/router": "~3.4.9",
    "@types/lodash": "^4.14.50",
    "angular-2-data-table": "^0.1.2",
    "angular2-datatable": "^0.5.2",
    "core-js": "^2.4.1",
    "lodash": "^4.17.4",
    "ng2-date-picker": "^0.2.1",
    "ng2-file-upload": "^1.1.2",
    "ng2-modal": "0.0.25",
    "ng2-pagination": "^2.0.1",
    "ng2-table": "^1.3.2",
    "primeng": "^2.0.1",
    "rxjs": "5.2.0",
    "tinymce": "^4.5.2",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.7"
  },
  "devDependencies": {
    "@angular/cli": "^1.0.0-rc.1",
    "@types/jasmine": "2.2.30",
    "@types/node": "^7.0.5",
    "angular/cli": "1.0.0-beta.28.3",
    "codelyzer": "3.0.0-beta.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.6.0",
    "protractor": "5.1.1",
    "ts-node": "2.1.0",
    "tslint": "4.5.1",
    "typescript": "~2.2.1"
  }
}
</code>```

答: I just run npm install and then ok.

Title: Cannot find module '@angular/compiler'

Body:
I run the command npm install -g @angular/cli and after i tried to run my app it says, Cannot find module '@angular/compiler' in the terminal. How can i install the compiler in my package.json in order to compile my application

//package
{
  "name": "Restaurant",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~2.4.9",
    "@angular/compiler": "~2.4.9",
    "@angular/core": "~2.4.9",
    "@angular/forms": "~2.4.9",
    "@angular/http": "~2.4.9",
    "@angular/platform-browser": "~2.4.9",
    "@angular/platform-browser-dynamic": "~2.4.9",
    "@angular/router": "~3.4.9",
    "@types/lodash": "^4.14.50",
    "angular-2-data-table": "^0.1.2",
    "angular2-datatable": "^0.5.2",
    "core-js": "^2.4.1",
    "lodash": "^4.17.4",
    "ng2-date-picker": "^0.2.1",
    "ng2-file-upload": "^1.1.2",
    "ng2-modal": "0.0.25",
    "ng2-pagination": "^2.0.1",
    "ng2-table": "^1.3.2",
    "primeng": "^2.0.1",
    "rxjs": "5.2.0",
    "tinymce": "^4.5.2",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.7"
  },
  "devDependencies": {
    "@angular/cli": "^1.0.0-rc.1",
    "@types/jasmine": "2.2.30",
    "@types/node": "^7.0.5",
    "angular/cli": "1.0.0-beta.28.3",
    "codelyzer": "3.0.0-beta.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.6.0",
    "protractor": "5.1.1",
    "ts-node": "2.1.0",
    "tslint": "4.5.1",
    "typescript": "~2.2.1"
  }
}

Body: I just run npm install and then ok.


问:
Reshaping 2 numpy dimensions into one with zipping?
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

```<code>[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]
</code>```

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

```<code>[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]
</code>```

Unlike the array we get with reshape:

```<code>[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]
</code>```

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

```<code>import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])
</code>```

And again, I want my output to look like this instead:

```<code>[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]
</code>```

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps

答:
There is a simple answer here on the documentation of numpy

np.reshape(a,(3,9), order='F')

Body:
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]

Unlike the array we get with reshape:

[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])

And again, I want my output to look like this instead:

[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps