问:
Array of Integers to Arrays of Ranges
My Task:
I need to divide the Array into several Arrays of Arrays with the following properties:

every subarray is a range of continuous integer. As example [1,2,3,4,5] will be [[1,5]].

When there are no contiguous integer create a new subarray. As example [1,2,4,5] will be [[1,2], [4,5]]

Example:

If I have this Array of Integers - [0, 1, 5, 6, 3, 7]

Expected Result - [[0, 1], [3], [5, 7]]

I already tried this:

```<code>let array: [Int] = [0, 1, 3, 4, 5, 6, 7]

var group: [[Int]] = []
var temp: [Int] = [Int]()

for (index, element) in array.enumerated() {
    if index + 1 < array.count {
        let nextElement = array[index + 1]
        let step = nextElement - element

//        temp.append(element)

        if(step) == 1 { // Until it's in range
            temp.append(element)
        } else { // One-by-one
            temp.append(element)
            group.append(temp)

            temp = [Int]()
            group.append([nextElement])
        }
    } else {
        print(index)
    }
}

print(group)
</code>```

From my code, I get this result - [[0, 1], [3]]

答:
Here is my solution. Rather than manually managing indexes, I use two iterators. One which advances along denoting the "start" of runs, and one which races ahead to find the "ends" of runs.

I've gentrified my code to work over any Sequence (not just Array), and any Strideable type (any type that defines distance(to:), not necessarily just Int).

```<code>extension Sequence where Element: Strideable {
    func splitConsequtiveRuns() -> [[Element]] {
        var runs = [[Element]]()

        var runStartIterator = self.makeIterator()

        while let startElement = runStartIterator.next() {
            var runEndIterator = runStartIterator
            var prevElement = startElement

            var run = [startElement]
            while let nextElement = runEndIterator.next(),
                prevElement.distance(to: nextElement) == 1 {
                _ = runStartIterator.next() // advance the "start" iterator, to keep pace

                prevElement = nextElement // update this, for use in then next loop's comparison
                run.append(nextElement)
            }

            runs.append(run)
        }

        return runs
    }
}

let array: [Int] = [0...3, 8...8, 10...15].flatMap { $0 }
print(array.splitConsequtiveRuns()) // => [[0, 1, 2, 3], [8], [10, 11, 12, 13, 14, 15]]
</code>```

Title: Array of Integers to Arrays of Ranges

Body:
My Task:
I need to divide the Array into several Arrays of Arrays with the following properties:

every subarray is a range of continuous integer. As example [1,2,3,4,5] will be [[1,5]].

When there are no contiguous integer create a new subarray. As example [1,2,4,5] will be [[1,2], [4,5]]

Example:

If I have this Array of Integers - [0, 1, 5, 6, 3, 7]

Expected Result - [[0, 1], [3], [5, 7]]

I already tried this:

let array: [Int] = [0, 1, 3, 4, 5, 6, 7]

var group: [[Int]] = []
var temp: [Int] = [Int]()

for (index, element) in array.enumerated() {
    if index + 1 < array.count {
        let nextElement = array[index + 1]
        let step = nextElement - element

//        temp.append(element)

        if(step) == 1 { // Until it's in range
            temp.append(element)
        } else { // One-by-one
            temp.append(element)
            group.append(temp)

            temp = [Int]()
            group.append([nextElement])
        }
    } else {
        print(index)
    }
}

print(group)

From my code, I get this result - [[0, 1], [3]]

Body:
Here is my solution. Rather than manually managing indexes, I use two iterators. One which advances along denoting the "start" of runs, and one which races ahead to find the "ends" of runs.

I've gentrified my code to work over any Sequence (not just Array), and any Strideable type (any type that defines distance(to:), not necessarily just Int).

extension Sequence where Element: Strideable {
    func splitConsequtiveRuns() -> [[Element]] {
        var runs = [[Element]]()

        var runStartIterator = self.makeIterator()

        while let startElement = runStartIterator.next() {
            var runEndIterator = runStartIterator
            var prevElement = startElement

            var run = [startElement]
            while let nextElement = runEndIterator.next(),
                prevElement.distance(to: nextElement) == 1 {
                _ = runStartIterator.next() // advance the "start" iterator, to keep pace

                prevElement = nextElement // update this, for use in then next loop's comparison
                run.append(nextElement)
            }

            runs.append(run)
        }

        return runs
    }
}

let array: [Int] = [0...3, 8...8, 10...15].flatMap { $0 }
print(array.splitConsequtiveRuns()) // => [[0, 1, 2, 3], [8], [10, 11, 12, 13, 14, 15]]


来源: stackexchange

问:
bash looping through file to find beginning of string
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

```<code>789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...
</code>```

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

```<code>KGOX P0002
KMNO P0001
</code>```

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

```<code> while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done
</code>```

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

ContentLicense: CC BY-SA 4.0

Body:
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

KGOX P0002
KMNO P0001

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

 while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

Body:
With GNU sed:

sed -En 's/^[^ ]+ ([^ ]+).*( P00[^ ]*).*/\1\2/p' file

Output:

KGOX P0002
KMNO P0001


问:
React Native - Global screen outside React-Navigation
In my React Native application, I am using Redux to manage the global state of the app. This is what the render of my App.js looks like:

```<code>render() {
   return (
     <Provider store={store}>
       <MainNavigator />
     </Provider>
   );
}
</code>```

where <MainNavigator /> exports createAppContainer(createBottomTabNavigator({ ...my panel names })) and <Provider ... /> is imported from react-redux.

Everything works just fine. However, I would like to have a "global" screen which is independent of my navigator. I would like to have it mounted all the time immediately after the app has been launched and display it over the main navigator or hide it using Redux.

As an example, I am aiming to achieve something like the music screen on Spotify and SoundCloud which is always mounted while browsing through the whole app. Or as another example, the video screen on YouTube which serves the same purpose as the previous examples.

I have tried the following in my App.js:

```<code>render() {
   return (
     <Provider store={store}>
       <GlobalScreen />
       <MainNavigator />
     </Provider>
   );
}
</code>```

However, this would split my application into two halves where the upper half of the screen displays the <GlobalScreen /> component and the lower half displays the <MainNavigator /> component.

How can I achieve a "global" screen, independent of React Navigation, which can overlay it or hide itself using Redux?

P.S. I am not sure if this can be achieved by having the screen outside React Navigation. But I am open to any suggestions which could help me achieve my desired goal.

答:
You can use a conditional to render either the GlobalScreen or the MainNavigator.

```<code>{someConditionBasedOnDataFromStore ? (
  <GlobalScreen/>
):(
  <MainNavigator/>
)
</code>```

You probably want this logic inside a component which connects to the store to get the data for your conditional.

Body:
In my React Native application, I am using Redux to manage the global state of the app. This is what the render of my App.js looks like:

render() {
   return (
     <Provider store={store}>
       <MainNavigator />
     </Provider>
   );
}

where <MainNavigator /> exports createAppContainer(createBottomTabNavigator({ ...my panel names })) and <Provider ... /> is imported from react-redux.

Everything works just fine. However, I would like to have a "global" screen which is independent of my navigator. I would like to have it mounted all the time immediately after the app has been launched and display it over the main navigator or hide it using Redux.

As an example, I am aiming to achieve something like the music screen on Spotify and SoundCloud which is always mounted while browsing through the whole app. Or as another example, the video screen on YouTube which serves the same purpose as the previous examples.

I have tried the following in my App.js:

render() {
   return (
     <Provider store={store}>
       <GlobalScreen />
       <MainNavigator />
     </Provider>
   );
}

However, this would split my application into two halves where the upper half of the screen displays the <GlobalScreen /> component and the lower half displays the <MainNavigator /> component.

How can I achieve a "global" screen, independent of React Navigation, which can overlay it or hide itself using Redux?

P.S. I am not sure if this can be achieved by having the screen outside React Navigation. But I am open to any suggestions which could help me achieve my desired goal.

Body:
You can use a conditional to render either the GlobalScreen or the MainNavigator.

{someConditionBasedOnDataFromStore ? (
  <GlobalScreen/>
):(
  <MainNavigator/>
)

You probably want this logic inside a component which connects to the store to get the data for your conditional.


问:
How to open a new default browser window in Python when the default is Chrome
I have been looking for a way to open a new default browser window from inside Python code.

According to the documentation webbrowser.open_new(url)
Should do that. Unfortunately in case Chrome is the default browser it only opens a new tab.
Is there any way to open the default browser (without knowing what that browser is)?

答:
```<code>import subprocess

def open(url):
    cmd = "open " + url
    print(cmd)
    subprocess.Popen(cmd, shell=True)
</code>```

ContentLicense: CC BY-SA 3.0


问:
Usefulness of GraphQL
I am relatively new to learning Graphql. I am working with another developer who is designing the front end in ReactJS and backend in Django. His opinion regarding Graphql is that it is not necessary and can use MySql and Django ORM instead. I am not sure what benefit then Graphql brings if entire development can be done using only ReactJS, DjangoORM and MySql.</p>

答:
ReactJS is a frontend framework.

DjangoORM is an ORM, MySQL is a database.

GraphQL is an API architecture.

None of which can be compared to another one.

You can't use DjangoORM and MySQL instead of GraphQL, at best you can use GraphQL instead of REST, which both are architectural types for API's.

The difference, as simple as I can put it:

GraphQL architectured APIs give you exactly what you want from the server. (roughly)
REST architectured APIs give you standard schemes for the given objects. (roughly)

Title: Usefulness of GraphQL


答:
Looking at your input, maybe you could just go with:</p>

```<code>grep 'P00.' | cut -d' ' -f2
</code>```

Title: bash looping through file to find beginning of string

Body:
Looking at your input, maybe you could just go with:

grep 'P00.' | cut -d' ' -f2


问:
Serialize child collections with interfaces
I have an interface like so

```<code>public interface IA{
    IEnumerable<IB> Items {get;set;}
}

public interface IB{
    int ID {get;set;}
}
</code>```

If I try to serialize the interface I get an error

```<code>Cannot serialize interface
</code>```

If I create a concrete version of the interface, I can't create a concrete version of the collection.

```<code>public class classA:IA{
   public IEnumerable<B> Items {get;set;}  //this doesn't match the interface
}
</code>```

but if I do the below we still have the serialization problem

```<code>public class classA:IA{
   public IEnumerable<IB> Items {get;set;}
}
</code>```

答:
You cannot serialize an interface --- the computer isn't lying, you know ;-)

Try using concrete types.  Instead of IEnumerable<IB> try List<object> or an array.

HTH

Body:
I have an interface like so

public interface IA{
    IEnumerable<IB> Items {get;set;}
}

public interface IB{
    int ID {get;set;}
}

If I try to serialize the interface I get an error

Cannot serialize interface

If I create a concrete version of the interface, I can't create a concrete version of the collection.

public class classA:IA{
   public IEnumerable Items {get;set;}  //this doesn't match the interface
}

but if I do the below we still have the serialization problem

public class classA:IA{
   public IEnumerable<IB> Items {get;set;}
}


问:
How do I load optional css tags using ejs?
I'm trying to load optional, page-specific stylesheets using Node.js/ Express.js routing, but am having trouble with the ejs portion:

Express:

```<code>res.render('index', { title: 'Home', css: 'index'}); // some pages won't have the 'css' parameter.
</code>```

EJS loading:

```<code><link rel='stylesheet' href='/static/stylesheets/shared.css' />
<% if (css) { %>
  <link rel='stylesheet' href='/static/stylesheets/<%- css %>.css' />
<% } %>
</code>```

Looking at the official EJS documentation, my if statement follows their logic:

```<code><% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>
</code>```

I am receiving the error css is not defined. By that logic, wouldn't the example given on the ejs website also result in an error, if user was not defined?

What am I doing wrong here?

答:
Try sending all your data in a sub-object like this:

Express:

```<code>res.render('index', {data:{title:'Home',css:'index'}});
</code>```

or

```<code>res.render('index', {data:{title:'Home'}});
</code>```

EJS:

```<code><link rel='stylesheet' href='/static/stylesheets/shared.css' />
<% if (data.css) { %>
  <link rel='stylesheet' href='/static/stylesheets/<%- data.css %>.css' />
<% } %>
</code>```

If you just send in, optionally on object like this: {title:'Home',css:'index'} or {title:'Home'} then the variable css may or may not be defined.

You could change your check to if (typeof css !== 'undefined') but I find it easier and smaller to just use a sub-object.

Body:
I'm trying to load optional, page-specific stylesheets using Node.js/ Express.js routing, but am having trouble with the ejs portion:

Express:

res.render('index', { title: 'Home', css: 'index'}); // some pages won't have the 'css' parameter.

EJS loading:

<link rel='stylesheet' href='/static/stylesheets/shared.css' />
<% if (css) { %>
  <link rel='stylesheet' href='/static/stylesheets/<%- css %>.css' />
<% } %>

Looking at the official EJS documentation, my if statement follows their logic:

<% if (user) { %>

<%= user.name %>

<% } %>

I am receiving the error css is not defined. By that logic, wouldn't the example given on the ejs website also result in an error, if user was not defined?

What am I doing wrong here?

Body:
Try sending all your data in a sub-object like this:

Express:

res.render('index', {data:{title:'Home',css:'index'}});

or

res.render('index', {data:{title:'Home'}});

EJS:

<link rel='stylesheet' href='/static/stylesheets/shared.css' />
<% if (data.css) { %>
  <link rel='stylesheet' href='/static/stylesheets/<%- data.css %>.css' />
<% } %>

If you just send in, optionally on object like this: {title:'Home',css:'index'} or {title:'Home'} then the variable css may or may not be defined.

You could change your check to if (typeof css !== 'undefined') but I find it easier and smaller to just use a sub-object.


问:
Email Database Results
I have a firebase database where onCreate Google Cloud Functions calls nodemailer and sends me an email.  It all works fine but now I am trying to also include the data that was added to the database in the email.  I can't get it to work, seemingly because it is not in a text format and I've tried converting to text and that doesn't seem to do it.  What am I doing wrong?</p>

```<code>const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
 // TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

exports.sendWelcomeEmail =      functions.database.ref('/PickupRequests/{pushId}')
.onCreate(async(snapshot, context) => {

  const val = snapshot.data;

  const mailOptions = {
    from: '<noreply@firebase.com>',
    to: "mike@puravidalaundry.com",
    subject: "New Pickup Request",
    text: val //How do i convert this to a text format?
  };

  try {
    await mailTransport.sendMail(mailOptions);
    console.log('email sent');
  } catch(error) {
    console.error('There was an error while sending the email:',     error);
  }
  return null;
});
</code>```

答:
To get the value from the snapshot, use snapshot.val(). So:

```<code>const val = snapshot.val();
</code>```

Note that this is shown in an example in the documentation on handling event data for Realtime Database triggered Cloud Functions.

Title: Email Database Results

Body:
I have a firebase database where onCreate Google Cloud Functions calls nodemailer and sends me an email.  It all works fine but now I am trying to also include the data that was added to the database in the email.  I can't get it to work, seemingly because it is not in a text format and I've tried converting to text and that doesn't seem to do it.  What am I doing wrong?

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
 // TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

exports.sendWelcomeEmail =      functions.database.ref('/PickupRequests/{pushId}')
.onCreate(async(snapshot, context) => {

  const val = snapshot.data;

  const mailOptions = {
    from: '<noreply@firebase.com>',
    to: "mike@puravidalaundry.com",
    subject: "New Pickup Request",
    text: val //How do i convert this to a text format?
  };

  try {
    await mailTransport.sendMail(mailOptions);
    console.log('email sent');
  } catch(error) {
    console.error('There was an error while sending the email:',     error);
  }
  return null;
});

Body:
To get the value from the snapshot, use snapshot.val(). So:

const val = snapshot.val();

Note that this is shown in an example in the documentation on handling event data for Realtime Database triggered Cloud Functions.


问:
Import ansible facts into servicenow cmdb
I'm trying to determine if it's possible to populate our servicenow CMDB with Ansible facts gathered from our Ansible Tower instance. I can find a lot of documentation on pulling inventory FROM CMDB, or for using Ansible to create incidents, but nothing on updating CI objects based on gathered facts. Is this possible?</p>

答:
check out this repo, https://github.com/michaelford85/ansible-servicenow-exercises

especially the Ansible Playbook-> snow-table-fields.yml

```<code>  - name: Retrieve fields for a table {{ snow_table }}
    snow_record:
      state: present
      table: "{{ snow_table }}"
      data:
        name: delete_this_record
      username: "{{ SN_USERNAME }}"
      password: "{{ SN_PASSWORD }}"
      instance: "{{ SN_INSTANCE }}"
    register: table_output
</code>```

where {{snow_table}} can be something like cmdb_ci_linux_server

Body:
check out this repo, https://github.com/michaelford85/ansible-servicenow-exercises

especially the Ansible Playbook-> snow-table-fields.yml

  - name: Retrieve fields for a table {{ snow_table }}
    snow_record:
      state: present
      table: "{{ snow_table }}"
      data:
        name: delete_this_record
      username: "{{ SN_USERNAME }}"
      password: "{{ SN_PASSWORD }}"
      instance: "{{ SN_INSTANCE }}"
    register: table_output

where {{snow_table}} can be something like cmdb_ci_linux_server


问:
Invalid Element Type upon import of custom React component
I'm trying to render a custom nav bar in my React application and I get an Invalid Type error.

I'm aware that there are default and named imports/exports in React, however I am exporting the CustomNavBar class as default and importing it as default in App.jsx. Other posters have mentioned that it might be an issue with package versions but I don't know where to start fixing that.

App.jsx:

```<code>import Button from 'react-bootstrap/Button';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Resume from './components/Resume';
import CustomNavBar from './components/CustomNavBar';
import './App.css';

function App() {
  return (
    <div className="App">
      <Router>
        <div>
          <CustomNavBar />
          <Route exact path = "/" component={Home} />
          <Route path = "/about" component={About} />
          <Route path = "/resume" component={Resume} />
        </div>
      </Router>

    </div>
  );
}

export default App;
</code>```

Code runs as normal when the CustomNavBar component is omitted.

CustomNavBar.jsx:

```<code>import React, { Component } from 'react'
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';

export default class CustomNavBar extends Component {
    render() {
        return (
            <Navbar default collapseOnSelect>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Link to="/">Home</Link>
                    </Navbar.Brand>
                    <Navbar.Toggle />
                </Navbar.Header>
                <Navbar.Collapse>
                    <Nav pullRight>
                        <NavItem eventKey={1} componentClass={Link} to="/">
                            Home
                        </NavItem>
                        <NavItem eventKey={2} componentClass={Link} to="/about">
                            About
                        </NavItem>
                        <NavItem eventKey={3} componentClass={Link} to="/resume">
                            Resume
                        </NavItem>
                    </Nav>
                </Navbar.Collapse>
            </Navbar>
        );
    }
}
</code>```

package.json:

```<code>{
  "name": "my_site",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^16.8.6",
    "react-bootstrap": "^1.0.0-beta.8",
    "react-dom": "^16.8.6",
    "react-router": "^5.0.0",
    "react-router-dom": "^4.4.0-beta.8",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

The error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of CustomNavBar.

/****SOLVED****/
Header is no longer exported from bootstrap, brand and toggle should not be contained in a div in bootstrap 4.

答:
Seems like the Navbar.Header was removed in v1:

Navbar removed Navbar.Header removed Navbar.Form removed fluid, use
  your own Container component in. inverse removed and replaced with
  variant="dark" positioning props have been consolidated into
  fixed={top|bottom} and sticky={top|bottom}, staticTop has been removed

Body:
I'm trying to render a custom nav bar in my React application and I get an Invalid Type error.

I'm aware that there are default and named imports/exports in React, however I am exporting the CustomNavBar class as default and importing it as default in App.jsx. Other posters have mentioned that it might be an issue with package versions but I don't know where to start fixing that.

App.jsx:

import Button from 'react-bootstrap/Button';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Resume from './components/Resume';
import CustomNavBar from './components/CustomNavBar';
import './App.css';

function App() {
  return (

      <Router>

          <CustomNavBar />
          <Route exact path = "/" component={Home} />
          <Route path = "/about" component={About} />
          <Route path = "/resume" component={Resume} />

      </Router>

  );
}

export default App;

Code runs as normal when the CustomNavBar component is omitted.

CustomNavBar.jsx:

import React, { Component } from 'react'
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';

export default class CustomNavBar extends Component {
    render() {
        return (
            <Navbar default collapseOnSelect>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Link to="/">Home</Link>
                    </Navbar.Brand>
                    <Navbar.Toggle />
                </Navbar.Header>
                <Navbar.Collapse>

                        <NavItem eventKey={1} componentClass={Link} to="/">
                            Home
                        </NavItem>
                        <NavItem eventKey={2} componentClass={Link} to="/about">
                            About
                        </NavItem>
                        <NavItem eventKey={3} componentClass={Link} to="/resume">
                            Resume
                        </NavItem>

                </Navbar.Collapse>
            </Navbar>
        );
    }
}

package.json:

{
  "name": "my_site",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^16.8.6",
    "react-bootstrap": "^1.0.0-beta.8",
    "react-dom": "^16.8.6",
    "react-router": "^5.0.0",
    "react-router-dom": "^4.4.0-beta.8",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

The error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of CustomNavBar.

/****SOLVED****/
Header is no longer exported from bootstrap, brand and toggle should not be contained in a div in bootstrap 4.


问:
accordion with expandable sections
I would like to create an accordion box with Javascipt and CSS. The expanded section should include a link that, when clicked, would enable this section already expanded to expand even more without any vertical scroll bar. Is it possible? Thanks

答:
Of course it is possible. The get the thing done quicker there are a lot of resources available for you out there.

Have a look at http://jquery.com/ and look at the demos of flowplayer, they are actually pretty impressive : http://flowplayer.org/tools/demos/tabs/accordion.html

Title: accordion with expandable sections


问:
Difference between activites and the new callback-pattern feature in AWS Step Functions
AWS released a new feature for AWS Step Functions (Callback Pattern):

https://aws.amazon.com/about-aws/whats-new/2019/05/aws-step-functions-support-callback-patterns/

I wonder now, what's actually the difference to the already existing activities.

Let me sum that up for you:

a step function can wait for an activity and deliver certain input values to it

any service (e.g. CLI, EC2, lambda, etc.) can poll for a job on activity; do something and report back with an activity task success or failure.

the step functions then receives the error or the success

What is the difference to the newly announced callback pattern? In my eyes, it is actually totally the same - do I miss something?

答:
Activities are poll-based and the callback pattern is push-based. Both let you manage asynchronous tasks.

In an activity task, Step Functions waits for a worker to poll using GetActivityTask. When a match is made, Step Functions returns the state payload and a task token to the worker that made the request. This is useful, for example, when your workers reside in a datacenter. You have less network configuration to poll from the datacenter instead of opening VPN access.

In the callback pattern, Step Functions pushes the payload and task token to a supported AWS service integration (Lambda, Fargate, ECS, SNS, and SQS). This is useful in serverless architectures, which tend to favor ephemeral compute and event-driven data flows. The task token may be delegated to other services before returning to Step Functions, too.

Both require a worker to eventually return a result payload and the task token to Step Functions to advance the state machine to the next step.


问:
JavaScript querySelector versions of Jquery
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

```<code><div class="paperlist" data-role='listview' data-inset='true' data-split-icon='delete' id='clientProfiles'></div>
</code>```

my application will fill the 'div' with buttons like so.

```<code>function getClientHtml(device) {

                var html = "";
                html += '<div data-name="' + device.Name + '" data-id="' + device.Id + '"data-app="' + device.AppName + '" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">';
                html += '<img style="float-left; width:3%;" src="' + deviceNameImage(device.Name) + '"/>';
                html += '<div class="listItemBody">';
                html += '<h3 class="listItemBodyText">' + device.Name + ' - ' + device.AppName + '</h3>';
                html += '</div>';
                html += '<i class="md-icon btnDeleteProfile" data-index="0">close</i>';
                html += '</div>';
                html += '<br />';
                return html;
            };
</code>```

The html after a button has been added by a user looks like this:

```<code><div class="paperlist" data-role="listview" data-inset="true" data-split-icon="delete" id="clientProfiles">
<div data-name="Xbox One" data-id="mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s" data-app="Theater" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">
<img style="float-left; width:3%;" src="../images/devices/xboxone.png"><div class="listItemBody"><h3 class="listItemBodyText">XBLAHBLAHNAME</h3>
</div>
<i class="md-icon btnDeleteProfile" data-index="0">close</i>
</div>
<br>
</div>
</code>```

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

```<code> $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});
</code>```

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

答:
Okay, if you're just wanting to get that code to work, gaetanoM's answer is great.

However, it seems like the heart of your question is how to target all of the delete buttons in order to attach the function. So for future reference you can use querySelectorAll and a forEach like MDN shows here:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll#Accessing_the_matches

```<code>// use querySelectorAll to get a node list of the elements, similar to how you would get a jQuery object in jQuery
var deleteButtons = document.querySelectorAll(".btnDeleteProfile");

// iterate over the node list just like you would in jQuery with .each()
deleteButtons.forEach(function(button) {
  // do something with the individual element
  console.log(button);
});

</code>```

Body:
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

my application will fill the 'div' with buttons like so.

function getClientHtml(device) {

                var html = "";
                html += '
';
                html += '';
                html += '
';
                html += '
' + device.Name + ' - ' + device.AppName + '
';
                html += '
';
                html += 'close';
                html += '
';
                html += '
';
                return html;
            };

The html after a button has been added by a user looks like this:

XBLAHBLAHNAME

close

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

 $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

Body:
Okay, if you're just wanting to get that code to work, gaetanoM's answer is great.

However, it seems like the heart of your question is how to target all of the delete buttons in order to attach the function. So for future reference you can use querySelectorAll and a forEach like MDN shows here:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll#Accessing_the_matches

// use querySelectorAll to get a node list of the elements, similar to how you would get a jQuery object in jQuery
var deleteButtons = document.querySelectorAll(".btnDeleteProfile");

// iterate over the node list just like you would in jQuery with .each()
deleteButtons.forEach(function(button) {
  // do something with the individual element
  console.log(button);
});


问:
django formset not saving
EDIT: Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.

I am trying to manually render formset fields in a template, but the fields are not being saved when I submit.

My method works for a different formset based on another model, and as far as I can tell I haven't done anything differently. I tried a number of changes, but the issue seems to be {{ form.id }} in the template; when I change it to {{ form }}, I am able to save some of the fields.

As mentioned, this same set up works for another model/formset; when I make changes to a field and save, the page is refreshed and the model shows as updated. The code below is for the model/formset that is not working.

```<code>models.py

class Call(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    customer_number = models.CharField(max_length=200, null=True, blank=True)
    tracking_source = models.CharField(max_length=200, null=True, blank=True)
    tracking_number = models.CharField(max_length=200, null=True,
    qualified_offer = models.BooleanField(default=False)
    recorded_date = models.DateTimeField(default=timezone.now)

    def publish(self):
        self.recorded_date = timezone.now()
        self.save()

    def t_number(self):
        return self.tracking_number[-4:]

    def __str__(self):
        return str(self.name)

forms.py

class CallForm(forms.ModelForm):

    class Meta:
        model = Call
        fields = ('name', 'customer_number', 'tracking_source', 'qualified_offer', 'recorded_date')

CallFormSet = modelformset_factory(Call, fields=('name', 'customer_number', 'tracking_source', 'recorded_date', 'qualified_offer'))

view.py

def call_list(request):

    if request.method == 'GET':
        formset = CallFormSet(queryset=Call.objects.all())
    elif request.method == "POST":
        formset = CallFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                if form.cleaned_data.get('name'):
                    form.save()
        return redirect('call_list')

    return render(request, 'webapp/call_list.html', {'formset': formset})

call_list.html

{% extends 'webapp/base.html' %}

{% block content %}

<form class="form-horizontal" method="POST" action="">
<table style="width:100%" border="1">
    <tr>
      <th>Name</th>
      <th>Qualified Offer</th>
    </tr>
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
    {{ form.id }}
    <tr>
        <td>
            <label>{{form.name}}</label></td>
        <td>
            <label>{{form.qualified_offer}}</label>
            {% if form.qualified_offer.value %}
                <label>True</label>
            {% else %}
                <label>False</label>
            {% endif %}
        </td>
    </tr>
{% endfor %}

</table>
<div class="row spacer">
    <div class="col-4 offset-2">
        <button type="submit" class="btn btn-block btn-primary">Save</button>
    </div>
</div>

</form>
{% endblock %}
</code>```

With the code above, the page refreshes but the model is unchanged. Again, if I render the formset with {{ form }} instead of {{ form.id }} it does save, but then I am unable to manually render the fields.

答: Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.</p>

Title: django formset not saving

Body:
EDIT: Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.

I am trying to manually render formset fields in a template, but the fields are not being saved when I submit.

My method works for a different formset based on another model, and as far as I can tell I haven't done anything differently. I tried a number of changes, but the issue seems to be {{ form.id }} in the template; when I change it to {{ form }}, I am able to save some of the fields.

As mentioned, this same set up works for another model/formset; when I make changes to a field and save, the page is refreshed and the model shows as updated. The code below is for the model/formset that is not working.

models.py

class Call(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    customer_number = models.CharField(max_length=200, null=True, blank=True)
    tracking_source = models.CharField(max_length=200, null=True, blank=True)
    tracking_number = models.CharField(max_length=200, null=True,
    qualified_offer = models.BooleanField(default=False)
    recorded_date = models.DateTimeField(default=timezone.now)

    def publish(self):
        self.recorded_date = timezone.now()
        self.save()

    def t_number(self):
        return self.tracking_number[-4:]

    def __str__(self):
        return str(self.name)

forms.py

class CallForm(forms.ModelForm):

    class Meta:
        model = Call
        fields = ('name', 'customer_number', 'tracking_source', 'qualified_offer', 'recorded_date')

CallFormSet = modelformset_factory(Call, fields=('name', 'customer_number', 'tracking_source', 'recorded_date', 'qualified_offer'))

view.py

def call_list(request):

    if request.method == 'GET':
        formset = CallFormSet(queryset=Call.objects.all())
    elif request.method == "POST":
        formset = CallFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                if form.cleaned_data.get('name'):
                    form.save()
        return redirect('call_list')

    return render(request, 'webapp/call_list.html', {'formset': formset})

call_list.html

{% extends 'webapp/base.html' %}

{% block content %}

<form class="form-horizontal" method="POST" action="">

      Name
      Qualified Offer

{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
    {{ form.id }}

            {{form.name}}

            {{form.qualified_offer}}
            {% if form.qualified_offer.value %}
                True
            {% else %}
                False
            {% endif %}

{% endfor %}

        <button type="submit" class="btn btn-block btn-primary">Save</button>

</form>
{% endblock %}

With the code above, the page refreshes but the model is unchanged. Again, if I render the formset with {{ form }} instead of {{ form.id }} it does save, but then I am unable to manually render the fields.


问:
Retrieving a row when specific text strings occur in SQL
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

```<code>    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine
</code>```

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

```<code>SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'
</code>```

But this returns rows that contain text strings that I do not want.

答:
Use rlike:

```<code>with your_data as (
select stack (8,
1,'calcium potassium iodine fluoride',
2,'potassium calcium',
3,'hydrochloride\\; calcium',
4,'iodine, calcium, fluoride',
5,'iodine calcium phosphate',
6,'calcium phosphate' ,
7,'IODINE',
8,'calcium PHOSPHATE iodine') as (med_code,med_name)
)

select * from your_data
 where med_name rlike '(?i)calcium phosphate' --(?i) means case insensitive
    or med_name rlike '^(?i)iodine$'          --with string begin(`^`) and end(`$`) anchors
;
</code>```

Returns:

```<code>your_data.med_code  your_data.med_name
5   iodine calcium phosphate
6   calcium phosphate
7   IODINE
8   calcium PHOSPHATE iodine
</code>```

This works in Hive

Body:
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'

But this returns rows that contain text strings that I do not want.

Body:
Use rlike:

with your_data as (
select stack (8,
1,'calcium potassium iodine fluoride',
2,'potassium calcium',
3,'hydrochloride\\; calcium',
4,'iodine, calcium, fluoride',
5,'iodine calcium phosphate',
6,'calcium phosphate' ,
7,'IODINE',
8,'calcium PHOSPHATE iodine') as (med_code,med_name)
)

select * from your_data
 where med_name rlike '(?i)calcium phosphate' --(?i) means case insensitive
    or med_name rlike '^(?i)iodine$'          --with string begin(`^`) and end(`$`) anchors
;

Returns:

your_data.med_code  your_data.med_name
5   iodine calcium phosphate
6   calcium phosphate
7   IODINE
8   calcium PHOSPHATE iodine

This works in Hive


问:
How to add object values to viewmodel with List<object>
I have a view model and trying to return a linq object, I'm not sure how to add a list object in the linq return query.
I have attached the sample code for better understanding.

View model:

```<code>public class BusinessAnalysisViewModel
{
    public Guid UserGuid { get; set; }
    public List<BAQandR> QuestionResponseIds { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime UpdateDate { get; set; }
}
public class BAQandR
{
    public int BAQuestionId { get; set; }
    public string BAResponse { get; set; }
    public int? BAFinPreviousYr { get; set; }
    public int? BAFinCurrentYr { get; set; }
}
</code>```

Linq query:

```<code>public BusinessAnalysisViewModel GetBusinessAnalysisInfo(Guid userID)
    {
        using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
        {
            var model = (from ba in ctxAdmin.Business_Analysis
                         where ba.User_Guid == userID
                         select new BusinessAnalysisViewModel
                         {
                             UserGuid = ba.User_Guid,
                             CreateDate = ba.CreateDate,
                             UpdateDate = ba.UpdateDate,

                             QuestionResponseIds =
                         });
            return model;
        }
    }
</code>```

[![enter image description here][2]][2]

[![enter image description here][2]][2]

I'm expecting the below kind of json result from my logic.

{
  "UserGuid": "000000000-4D3B-4598-A1FC-6B7B1D6D99D2",
  "CreateDate": "2019-05-22T18:52:14.458Z",
  "UpdateDate": "2019-05-22T18:52:14.458Z",
  "QuestionResponseIds": [
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    }
  ]
}
```

<p>I have changed the model as shown below,</p>

```public class UserBusinessAnalysis
{
    public Guid UserGuid { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public int BAQuestionId { get; set; }
    public string BAResponse { get; set; }
    public int? BAFinPreviousYr { get; set; }
    public int? BAFinCurrentYr { get; set; }
}
```

<p>Linq as shown below,</p>

```public List<UserBusinessAnalysis> GetBusinessAnalysisInfoByUserId(Guid userID)
    {
        using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
        {
            var model = (from ba in ctxAdmin.Business_Analysis
                         where ba.User_Guid == userID
                         select new UserBusinessAnalysis
                         {
                             UserGuid = ba.User_Guid,
                             CreateDate = ba.CreateDate,
                             UpdateDate = ba.UpdateDate,
                             BAQuestionId = ba.B_Analysis_Question_id,
                             BAResponse = ba.B_Analysis_Response,
                             BAFinPreviousYr = ba.Fin_Review_Previous_Year,
                             BAFinCurrentYr = ba.Fin_Review_Current_Year
                         }).ToList();
            return model;
        }
    }
```

答:
You should be able to simply add your list property to the result

```<code>using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
{
    var model = (from ba in ctxAdmin.Business_Analysis
                 where ba.User_Guid == userID
                 select new BusinessAnalysisViewModel
                 {
                     UserGuid = ba.User_Guid,
                     CreateDate = ba.CreateDate,
                     UpdateDate = ba.UpdateDate,

                     QuestionResponseIds = ba.QuestionResponseIds
                 });
    return model;
}
</code>```

If your types don't match, you will need to do another projection

```<code>using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
{
    var model = (from ba in ctxAdmin.Business_Analysis
                 where ba.User_Guid == userID
                 select new BusinessAnalysisViewModel
                 {
                     UserGuid = ba.User_Guid,
                     CreateDate = ba.CreateDate,
                     UpdateDate = ba.UpdateDate,

                     QuestionResponseIds = ba.QuestionResponseIds.Select(r => new BAQandR { /* copy fields here */ }).ToList()
                 });
    return model;
}
</code>```

Body:
I have a view model and trying to return a linq object, I'm not sure how to add a list object in the linq return query.
I have attached the sample code for better understanding.

View model:

public class BusinessAnalysisViewModel
{
    public Guid UserGuid { get; set; }
    public List<BAQandR> QuestionResponseIds { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime UpdateDate { get; set; }
}
public class BAQandR
{
    public int BAQuestionId { get; set; }
    public string BAResponse { get; set; }
    public int? BAFinPreviousYr { get; set; }
    public int? BAFinCurrentYr { get; set; }
}

Linq query:

public BusinessAnalysisViewModel GetBusinessAnalysisInfo(Guid userID)
    {
        using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
        {
            var model = (from ba in ctxAdmin.Business_Analysis
                         where ba.User_Guid == userID
                         select new BusinessAnalysisViewModel
                         {
                             UserGuid = ba.User_Guid,
                             CreateDate = ba.CreateDate,
                             UpdateDate = ba.UpdateDate,

                             QuestionResponseIds =
                         });
            return model;
        }
    }

[![enter image description here][2]][2]

[![enter image description here][2]][2]

I'm expecting the below kind of json result from my logic.

{
  "UserGuid": "000000000-4D3B-4598-A1FC-6B7B1D6D99D2",
  "CreateDate": "2019-05-22T18:52:14.458Z",
  "UpdateDate": "2019-05-22T18:52:14.458Z",
  "QuestionResponseIds": [
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    },
    {
      "BAQuestionId": 1,
      "BAResponse": 1,
      "BAFinPreviousYr": "",
      "BAFinPreviousYr": ""
    }
  ]
}

I have changed the model as shown below,

public class UserBusinessAnalysis
{
    public Guid UserGuid { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public int BAQuestionId { get; set; }
    public string BAResponse { get; set; }
    public int? BAFinPreviousYr { get; set; }
    public int? BAFinCurrentYr { get; set; }
}

Linq as shown below,

public List<UserBusinessAnalysis> GetBusinessAnalysisInfoByUserId(Guid userID)
    {
        using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
        {
            var model = (from ba in ctxAdmin.Business_Analysis
                         where ba.User_Guid == userID
                         select new UserBusinessAnalysis
                         {
                             UserGuid = ba.User_Guid,
                             CreateDate = ba.CreateDate,
                             UpdateDate = ba.UpdateDate,
                             BAQuestionId = ba.B_Analysis_Question_id,
                             BAResponse = ba.B_Analysis_Response,
                             BAFinPreviousYr = ba.Fin_Review_Previous_Year,
                             BAFinCurrentYr = ba.Fin_Review_Current_Year
                         }).ToList();
            return model;
        }
    }

Body:
You should be able to simply add your list property to the result

using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
{
    var model = (from ba in ctxAdmin.Business_Analysis
                 where ba.User_Guid == userID
                 select new BusinessAnalysisViewModel
                 {
                     UserGuid = ba.User_Guid,
                     CreateDate = ba.CreateDate,
                     UpdateDate = ba.UpdateDate,

                     QuestionResponseIds = ba.QuestionResponseIds
                 });
    return model;
}

If your types don't match, you will need to do another projection

using (var ctxAdmin = new MemberDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_MEMBER_CONNECTION_STRING].ToString()))
{
    var model = (from ba in ctxAdmin.Business_Analysis
                 where ba.User_Guid == userID
                 select new BusinessAnalysisViewModel
                 {
                     UserGuid = ba.User_Guid,
                     CreateDate = ba.CreateDate,
                     UpdateDate = ba.UpdateDate,

                     QuestionResponseIds = ba.QuestionResponseIds.Select(r => new BAQandR { /* copy fields here */ }).ToList()
                 });
    return model;
}


问:
Divide numbers in SQL
I have a database with orders of products and i need to divide the orders for men with the all orders for every year.

I successfully printed the all orders for every year and the mens orders for every year but I don't have an idea how to show a number that divide the numbers.

```<code>SELECT
    YEAR(o.Order_Date) AS year,
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE
    p.Product_ID = o.Product_ID
GROUP BY
    YEAR(o.Order_Date);
</code>```

Output =

```<code>   year    number_of_orders
   -------------------------
   2012        540
   2013        512
   2014        180

SELECT DISTCINT
    YEAR(o.Order_Date) AS year,
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE
    p.Product_ID = o.Product_ID
    AND p.Product_Name LIKE '%men%'
GROUP BY
    YEAR(o.Order_Date);
</code>```

Output

```<code>year  number_of_orders
----------------------
2012       50
2013      146
2014      138
</code>```

Desired output

```<code>year   number_of_men_orders_of_all_orders
----------------------------------------
2012        0.0925
2013        0.285
2014        0.766
</code>```

答:
What flavor of SQL are you using? It looks like MS Sql Server.

You will have to join your two result sets on their year so you can compare the count of each. Try something like this:

```<code>WITH all_orders AS (
    SELECT YEAR(Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders]
    GROUP BY YEAR(Order_Date)
), men_orders AS (
    SELECT YEAR(o.Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders] o
    JOIN [targil 2].[dbo].[exc2 - product] p
        ON p.Product_ID = o.Product_ID
    WHERE p.Product_Name LIKE '%men%'
    GROUP BY YEAR(o.Order_Date)
)
SELECT
    COALESCE(a.Year, m.Year) 'Year',
    a.Count 'All Count',
    m.Count 'Men Count',
    CAST(ISNULL(m.Count, 0) AS DECIMAL) / CAST(a.Count AS DECIMAL) 'Ratio'
FROM all_orders a
LEFT JOIN men_orders m ON m.Year = a.Year
</code>```

Title: Divide numbers in SQL

Body:
I have a database with orders of products and i need to divide the orders for men with the all orders for every year.

I successfully printed the all orders for every year and the mens orders for every year but I don't have an idea how to show a number that divide the numbers.

SELECT
    YEAR(o.Order_Date) AS year,
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE
    p.Product_ID = o.Product_ID
GROUP BY
    YEAR(o.Order_Date);

Output =

   year    number_of_orders
   -------------------------
   2012        540
   2013        512
   2014        180

SELECT DISTCINT
    YEAR(o.Order_Date) AS year,
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE
    p.Product_ID = o.Product_ID
    AND p.Product_Name LIKE '%men%'
GROUP BY
    YEAR(o.Order_Date);

Output

year  number_of_orders
----------------------
2012       50
2013      146
2014      138

Desired output

year   number_of_men_orders_of_all_orders
----------------------------------------
2012        0.0925
2013        0.285
2014        0.766

Body:
What flavor of SQL are you using? It looks like MS Sql Server.

You will have to join your two result sets on their year so you can compare the count of each. Try something like this:

WITH all_orders AS (
    SELECT YEAR(Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders]
    GROUP BY YEAR(Order_Date)
), men_orders AS (
    SELECT YEAR(o.Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders] o
    JOIN [targil 2].[dbo].[exc2 - product] p
        ON p.Product_ID = o.Product_ID
    WHERE p.Product_Name LIKE '%men%'
    GROUP BY YEAR(o.Order_Date)
)
SELECT
    COALESCE(a.Year, m.Year) 'Year',
    a.Count 'All Count',
    m.Count 'Men Count',
    CAST(ISNULL(m.Count, 0) AS DECIMAL) / CAST(a.Count AS DECIMAL) 'Ratio'
FROM all_orders a
LEFT JOIN men_orders m ON m.Year = a.Year


问:
Jar in executable Jar: jorg.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I) org.apache.poi.ooxml.POIXMLTypeLoader.<clinit>
I am successfully using a Java command line program that I wrote
that uses the Apache POI  file to read a Microsoft
Word (.docx) file and mail it.  I wish to package it  as an executable jar.

I am creating this
by taking each jar that my application needs and expanding with jar -xvf.

Stackoverflow question 183292 describes the techniques that one can use when
one needs to put a library "jar in a jar."

Unfortunately, I am getting the error below when I run it.

```<code>DEBUG: setDebug: JavaMail version 1.4ea
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    at org.apache.poi.ooxml.POIXMLTypeLoader.<clinit>(POIXMLTypeLoader.java:43)
    at org.apache.poi.xwpf.usermodel.XWPFDocument.onDocumentRead(XWPFDocument.java:178)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:184)
    at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:145)
    at m4.main(m4.java:273)
</code>```

The last thing I did before creating the jar fille was to expand
(with jar -xvf) xmlbeans-5.1.3.jar.
I then rejarred everything (my application and the results of jaring all
the other files.)

Question 20799326 on StackOverflow.com explains that this
symptom is caused by multiple xml beans jar files on the class path.

However, since the executable jar should only see expanded versions,
I do not believe that could be a problem.

Question 183292 further said that expanding one jar to create another could
lead to issues with package name conflicts.

(But this "should not happen if people use proper
packages, ..."  However, I certainly believe that Apache does use the standard
package convention...

I expanded 5.1 version last.

That should replace any old version that might have
been lying around in the directory.
(Just in case, I tried removing the old org/apache/xmlbeans
directory and then redoing the jar.  Did not help.)

After I expanded the jar's, I did a ls -R

I take the liberty of attaching the list, on the offchance, someone might
see something there.  I did abbreviate those parts that seem least relevant
with ellipsis.

```<code>m4:
com
Debug
javax
LICENSE.txt
m4$1.class
m4$AddressMap.class
m4.class
m4$CmdLineConst.class
Manifest.txt
META-INF
NOTICE.txt
org
resolver.jar
schemaorg_apache_xmlbeans

m4/com:
microsoft
sun

m4/com/microsoft:
schemas

m4/com/microsoft/schemas:
compatibility
office
vml

...
m4/com/microsoft/schemas/office:
excel
office
visio
x2006

m4/com/microsoft/schemas/office/excel:
    ...
m4/com/microsoft/schemas/office/x2006:
digsig
encryption
keyEncryptor

m4/com/microsoft/schemas/office/x2006/digsig:
CTSignatureInfoV1.class
CTSignatureInfoV1$Factory.class
....

m4/com/microsoft/schemas/office/x2006/digsig/impl:
...

m4/com/microsoft/schemas/office/x2006/encryption:
CTDataIntegrity.class

....
m4/com/sun:
mail

m4/com/sun/mail:
handlers
iap
imap
pop3
smtp
util

m4/com/sun/mail/handlers:
image_gif.class
image_jpeg.class
message_rfc822.class
multipart_mixed.class
text_html.class
text_plain.class
text_xml.class

m4/com/sun/mail/iap:
Argument.class
AString.class
Atom.class
....

m4/com/sun/mail/imap:
ACL.class
AppendUID.class
DefaultFolder$1.class
...

m4/com/sun/mail/imap/protocol:
BASE64MailboxDecoder.class
BASE64MailboxEncoder.class
BODY.class
...

....

m4/com/sun/mail/smtp:
DigestMD5.class
SMTPAddressFailedException.class
....

m4/com/sun/mail/util:
ASCIIUtility.class
BASE64DecoderStream.class
...

m4/Debug:  (This is my class)
Debug.class
Debug.java

m4/javax:
mail

m4/javax/mail:
Address.class
AuthenticationFailedException.class
Authenticator.class
BodyPart.class
....

m4/javax/mail/event:
ConnectionAdapter.class
ConnectionEvent.class
....

m4/javax/mail/internet:
AddressException.class
AsciiOutputStream.class
CachedDataHandler.class
....

m4/javax/mail/search:
AddressStringTerm.class
AddressTerm.class
AndTerm.class
....

m4/javax/mail/util:
...

m4/META-INF:
INDEX.LIST
javamail.charset.map
javamail.default.address.map
javamail.default.providers
LICENSE
LICENSE.txt
mailcap
MANIFEST.MF
maven
NOTICE
NOTICE.txt
services
SUN_MICR.RSA
SUN_MICR.SF
xmlbeans.bnd

m4/META-INF/maven:
org.apache.commons
org.ow2.jonas.osgi

m4/META-INF/maven/org.apache.commons:
commons-collections4
commons-compress

....

m4/org:
apache
etsi
openxmlformats
w3
w3c

m4/org/apache:
commons
env
poi
xml
xmlbeans

m4/org/apache/commons:
collections4
compress

m4/org/apache/commons/collections4:
ArrayStack.class
ArrayUtils.class
bag
Bag.class
BagUtils.class
bidimap
...

m4/org/apache/commons/collections4/bag:
AbstractBagDecorator.class
AbstractMapBag$BagIterator.class
AbstractMapBag.class

.....

m4/org/apache/commons/compress:
archivers
changes
....

m4/org/apache/commons/compress/archivers:
ar
ArchiveEntry.class
ArchiveException.class
ArchiveInputStream.class
....
tar
zip

...

m4/org/apache/env:
WhichFactory.properties
WhichJar.properties

m4/org/apache/poi:
common
ddf
EmptyFileException.class
....

m4/org/apache/poi/common:
usermodel

m4/org/apache/poi/common/usermodel:
fonts
Hyperlink.class
HyperlinkType.class

m4/org/apache/poi/common/usermodel/fonts:
FontCharset.class
FontFamily.class
....

m4/org/apache/poi/ddf:
AbstractEscherOptRecord$1.class
AbstractEscherOptRecord.class
DefaultEscherRecordFactory.class
....

m4/org/apache/poi/extractor:
ole2
OLE2ExtractorFactory.class
POIOLE2TextExtractor.class
POITextExtractor.class

m4/org/apache/poi/extractor/ole2:
OLE2ScratchpadExtractorFactory.class

....

m4/org/apache/poi/ooxml:
extractor
POIXMLDocument.class
...

m4/org/apache/poi/ooxml/extractor:
CommandLineTextExtractor.class
....

m4/org/apache/poi/ooxml/util:
DocumentHelper$1.class
DocumentHelper.class
....

m4/org/apache/poi/openxml4j:
exceptions
opc
util

.....

m4/org/apache/poi/sl/usermodel:
AbstractColorStyle.class
AutoNumberingScheme$1.class
AutoNumberingScheme.class
...
TextShape$TextPlaceholder.class
VerticalAlignment.class

m4/org/apache/poi/ss:
excelant
extractor
format
formula
SpreadsheetVersion.class
usermodel
util

m4/org/apache/poi/ss/excelant:
antlib.xml
ExcelAntEvaluateCell.class
ExcelAntHandlerTask.class
ExcelAntPrecision.class
....

m4/org/apache/poi/ss/excelant/util:
ExcelAntEvaluationResult.class
ExcelAntWorkbookUtil.class
ExcelAntWorkbookUtilFactory.class

m4/org/apache/poi/ss/extractor:
EmbeddedData.class
EmbeddedExtractor$BiffExtractor.class
...

m4/org/apache/poi/ss/format:
CellDateFormatter$1.class
CellDateFormatter.class
CellDateFormatter$DatePartHandler.class
CellElapsedFormatter$1.class
...

m4/org/apache/poi/ss/formula:
atp
BaseFormulaEvaluator$1.class
BaseFormulaEvaluator.class
...
WorkbookDependentFormula.class
WorkbookEvaluator$1.class
WorkbookEvaluator.class
WorkbookEvaluatorProvider.class

...

....

m4/org/apache/poi/xddf:
usermodel

m4/org/apache/poi/xddf/usermodel:
BlackWhiteMode.class
chart
CompoundLine.class
...
XDDFRadarChartData.class
XDDFRadarChartData$Series.class
XDDFScatterChartData.class
XDDFScatterChartData$Series.class
XDDFSeriesAxis.class
XDDFValueAxis.class

....

....

m4/org/apache/poi/xwpf:
extractor
model
usermodel

m4/org/apache/poi/xwpf/extractor:
XWPFWordExtractor.class

m4/org/apache/poi/xwpf/model:
WMLHelper.class
XWPFCommentsDecorator.class
XWPFHeaderFooterPolicy.class
XWPFParagraphDecorator.class

m4/org/apache/poi/xwpf/usermodel:
BodyElementType.class
BodyType.class
Borders.class
BreakClear.class
...
XWPFTable$1.class
XWPFTable$Border.class
...

m4/org/apache/xml:
resolver

m4/org/apache/xml/resolver:
apps
Catalog.class
CatalogEntry.class
...
Resolver.class
tools
Version.class

m4/org/apache/xml/resolver/apps:
resolver.class
xparse.class
XParseError.class
xread.class

m4/org/apache/xml/resolver/etc:
catalog.dtd
catalog.rng
catalog.xsd

...

m4/org/apache/xmlbeans:
BindingConfig.class
CDataBookmark.class
DelegateXmlObject.class
...
XmlUnsignedShort$Factory.class
XmlValidationError.class

m4/org/apache/xmlbeans/impl:
common
config
inst2xsd
jam
piccolo
regex
richParser
schema
soap
store
tool
util
validator
values
xb
xpathgen
xsd2inst

m4/org/apache/xmlbeans/impl/common:
ConcurrentReaderHashMap$1.class
ConcurrentReaderHashMap$BarrierLock.class
ConcurrentReaderHashMap.class
ConcurrentReaderHashMap$Entry.class
...
XPath.class
XPath$CompilationContext.class
XPath$ExecutionContext.class
XPath$ExecutionContext$PathContext.class
XPath$Selector.class
XPath$Step.class
XPath$XPathCompileException.class

...

m4/org/etsi:
uri

m4/org/etsi/uri:
x01903

m4/org/etsi/uri/x01903:
v13

m4/org/etsi/uri/x01903/v13:
AnyType.class
AnyType$Factory.class
CertIDListType.class
CertIDListType$Factory.class
CertIDType.class
CertIDType$Factory.class
...
XAdESTimeStampType.class
XAdESTimeStampType$Factory.class

m4/org/etsi/uri/x01903/v13/impl:
AnyTypeImpl.class
CertIDListTypeImpl.class
CertIDTypeImpl.class
CertificateValuesTypeImpl.class
...
UnsignedPropertiesTypeImpl.class
UnsignedSignaturePropertiesTypeImpl.class
XAdESTimeStampTypeImpl.class

m4/org/openxmlformats:
schemas

m4/org/openxmlformats/schemas:
drawingml
officeDocument
presentationml
spreadsheetml
wordprocessingml
xpackage

....
...

m4/org/openxmlformats/schemas/officeDocument:
x2006

m4/org/openxmlformats/schemas/officeDocument/x2006:
customProperties
docPropsVTypes
extendedProperties
relationships

...

m4/org/openxmlformats/schemas/spreadsheetml/x2006/main:
CalcChainDocument.class
CalcChainDocument$Factory.class
ChartsheetDocument.class
ChartsheetDocument$Factory.class
CommentsDocument.class
...
StylesDocument.class
StylesDocument$Factory.class
STZoom$Enum.class

....
m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans:
impl

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl:
xb

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl/xb:
ltgfmt
substwsdl
xmlconfig
xmlschema
xsdownload
xsdschema

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl/xb/ltgfmt:
Code.xsb
FileDesc
FileDesc.xsb
TestCase
   ... (rest is all schemaorg stuff)
</code>```

答:
Same error here but loading an excel file, just upgrade my XMLBeans from 2.3.0 to 3.1.0 and all work really nice.

download here:

```<code>https://www.apache.org/dyn/closer.lua/poi/xmlbeans/release/bin/xmlbeans-bin-3.1.0.zip
</code>```

Body:
I am successfully using a Java command line program that I wrote
that uses the Apache POI  file to read a Microsoft
Word (.docx) file and mail it.  I wish to package it  as an executable jar.

I am creating this
by taking each jar that my application needs and expanding with jar -xvf.

Stackoverflow question 183292 describes the techniques that one can use when
one needs to put a library "jar in a jar."

Unfortunately, I am getting the error below when I run it.

DEBUG: setDebug: JavaMail version 1.4ea
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    at org.apache.poi.ooxml.POIXMLTypeLoader.<clinit>(POIXMLTypeLoader.java:43)
    at org.apache.poi.xwpf.usermodel.XWPFDocument.onDocumentRead(XWPFDocument.java:178)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:184)
    at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:145)
    at m4.main(m4.java:273)

The last thing I did before creating the jar fille was to expand
(with jar -xvf) xmlbeans-5.1.3.jar.
I then rejarred everything (my application and the results of jaring all
the other files.)

Question 20799326 on StackOverflow.com explains that this
symptom is caused by multiple xml beans jar files on the class path.

However, since the executable jar should only see expanded versions,
I do not believe that could be a problem.

Question 183292 further said that expanding one jar to create another could
lead to issues with package name conflicts.

(But this "should not happen if people use proper
packages, ..."  However, I certainly believe that Apache does use the standard
package convention...

I expanded 5.1 version last.

That should replace any old version that might have
been lying around in the directory.
(Just in case, I tried removing the old org/apache/xmlbeans
directory and then redoing the jar.  Did not help.)

After I expanded the jar's, I did a ls -R

I take the liberty of attaching the list, on the offchance, someone might
see something there.  I did abbreviate those parts that seem least relevant
with ellipsis.

m4:
com
Debug
javax
LICENSE.txt
m4$1.class
m4$AddressMap.class
m4.class
m4$CmdLineConst.class
Manifest.txt
META-INF
NOTICE.txt
org
resolver.jar
schemaorg_apache_xmlbeans

m4/com:
microsoft
sun

m4/com/microsoft:
schemas

m4/com/microsoft/schemas:
compatibility
office
vml

...
m4/com/microsoft/schemas/office:
excel
office
visio
x2006

m4/com/microsoft/schemas/office/excel:
    ...
m4/com/microsoft/schemas/office/x2006:
digsig
encryption
keyEncryptor

m4/com/microsoft/schemas/office/x2006/digsig:
CTSignatureInfoV1.class
CTSignatureInfoV1$Factory.class
....

m4/com/microsoft/schemas/office/x2006/digsig/impl:
...

m4/com/microsoft/schemas/office/x2006/encryption:
CTDataIntegrity.class

....
m4/com/sun:
mail

m4/com/sun/mail:
handlers
iap
imap
pop3
smtp
util

m4/com/sun/mail/handlers:
image_gif.class
image_jpeg.class
message_rfc822.class
multipart_mixed.class
text_html.class
text_plain.class
text_xml.class

m4/com/sun/mail/iap:
Argument.class
AString.class
Atom.class
....

m4/com/sun/mail/imap:
ACL.class
AppendUID.class
DefaultFolder$1.class
...

m4/com/sun/mail/imap/protocol:
BASE64MailboxDecoder.class
BASE64MailboxEncoder.class
BODY.class
...

....

m4/com/sun/mail/smtp:
DigestMD5.class
SMTPAddressFailedException.class
....

m4/com/sun/mail/util:
ASCIIUtility.class
BASE64DecoderStream.class
...

m4/Debug:  (This is my class)
Debug.class
Debug.java

m4/javax:
mail

m4/javax/mail:
Address.class
AuthenticationFailedException.class
Authenticator.class
BodyPart.class
....

m4/javax/mail/event:
ConnectionAdapter.class
ConnectionEvent.class
....

m4/javax/mail/internet:
AddressException.class
AsciiOutputStream.class
CachedDataHandler.class
....

m4/javax/mail/search:
AddressStringTerm.class
AddressTerm.class
AndTerm.class
....

m4/javax/mail/util:
...

m4/META-INF:
INDEX.LIST
javamail.charset.map
javamail.default.address.map
javamail.default.providers
LICENSE
LICENSE.txt
mailcap
MANIFEST.MF
maven
NOTICE
NOTICE.txt
services
SUN_MICR.RSA
SUN_MICR.SF
xmlbeans.bnd

m4/META-INF/maven:
org.apache.commons
org.ow2.jonas.osgi

m4/META-INF/maven/org.apache.commons:
commons-collections4
commons-compress

....

m4/org:
apache
etsi
openxmlformats
w3
w3c

m4/org/apache:
commons
env
poi
xml
xmlbeans

m4/org/apache/commons:
collections4
compress

m4/org/apache/commons/collections4:
ArrayStack.class
ArrayUtils.class
bag
Bag.class
BagUtils.class
bidimap
...

m4/org/apache/commons/collections4/bag:
AbstractBagDecorator.class
AbstractMapBag$BagIterator.class
AbstractMapBag.class

.....

m4/org/apache/commons/compress:
archivers
changes
....

m4/org/apache/commons/compress/archivers:
ar
ArchiveEntry.class
ArchiveException.class
ArchiveInputStream.class
....
tar
zip

...

m4/org/apache/env:
WhichFactory.properties
WhichJar.properties

m4/org/apache/poi:
common
ddf
EmptyFileException.class
....

m4/org/apache/poi/common:
usermodel

m4/org/apache/poi/common/usermodel:
fonts
Hyperlink.class
HyperlinkType.class

m4/org/apache/poi/common/usermodel/fonts:
FontCharset.class
FontFamily.class
....

m4/org/apache/poi/ddf:
AbstractEscherOptRecord$1.class
AbstractEscherOptRecord.class
DefaultEscherRecordFactory.class
....

m4/org/apache/poi/extractor:
ole2
OLE2ExtractorFactory.class
POIOLE2TextExtractor.class
POITextExtractor.class

m4/org/apache/poi/extractor/ole2:
OLE2ScratchpadExtractorFactory.class

....

m4/org/apache/poi/ooxml:
extractor
POIXMLDocument.class
...

m4/org/apache/poi/ooxml/extractor:
CommandLineTextExtractor.class
....

m4/org/apache/poi/ooxml/util:
DocumentHelper$1.class
DocumentHelper.class
....

m4/org/apache/poi/openxml4j:
exceptions
opc
util

.....

m4/org/apache/poi/sl/usermodel:
AbstractColorStyle.class
AutoNumberingScheme$1.class
AutoNumberingScheme.class
...
TextShape$TextPlaceholder.class
VerticalAlignment.class

m4/org/apache/poi/ss:
excelant
extractor
format
formula
SpreadsheetVersion.class
usermodel
util

m4/org/apache/poi/ss/excelant:
antlib.xml
ExcelAntEvaluateCell.class
ExcelAntHandlerTask.class
ExcelAntPrecision.class
....

m4/org/apache/poi/ss/excelant/util:
ExcelAntEvaluationResult.class
ExcelAntWorkbookUtil.class
ExcelAntWorkbookUtilFactory.class

m4/org/apache/poi/ss/extractor:
EmbeddedData.class
EmbeddedExtractor$BiffExtractor.class
...

m4/org/apache/poi/ss/format:
CellDateFormatter$1.class
CellDateFormatter.class
CellDateFormatter$DatePartHandler.class
CellElapsedFormatter$1.class
...

m4/org/apache/poi/ss/formula:
atp
BaseFormulaEvaluator$1.class
BaseFormulaEvaluator.class
...
WorkbookDependentFormula.class
WorkbookEvaluator$1.class
WorkbookEvaluator.class
WorkbookEvaluatorProvider.class

...

....

m4/org/apache/poi/xddf:
usermodel

m4/org/apache/poi/xddf/usermodel:
BlackWhiteMode.class
chart
CompoundLine.class
...
XDDFRadarChartData.class
XDDFRadarChartData$Series.class
XDDFScatterChartData.class
XDDFScatterChartData$Series.class
XDDFSeriesAxis.class
XDDFValueAxis.class

....

....

m4/org/apache/poi/xwpf:
extractor
model
usermodel

m4/org/apache/poi/xwpf/extractor:
XWPFWordExtractor.class

m4/org/apache/poi/xwpf/model:
WMLHelper.class
XWPFCommentsDecorator.class
XWPFHeaderFooterPolicy.class
XWPFParagraphDecorator.class

m4/org/apache/poi/xwpf/usermodel:
BodyElementType.class
BodyType.class
Borders.class
BreakClear.class
...
XWPFTable$1.class
XWPFTable$Border.class
...

m4/org/apache/xml:
resolver

m4/org/apache/xml/resolver:
apps
Catalog.class
CatalogEntry.class
...
Resolver.class
tools
Version.class

m4/org/apache/xml/resolver/apps:
resolver.class
xparse.class
XParseError.class
xread.class

m4/org/apache/xml/resolver/etc:
catalog.dtd
catalog.rng
catalog.xsd

...

m4/org/apache/xmlbeans:
BindingConfig.class
CDataBookmark.class
DelegateXmlObject.class
...
XmlUnsignedShort$Factory.class
XmlValidationError.class

m4/org/apache/xmlbeans/impl:
common
config
inst2xsd
jam
piccolo
regex
richParser
schema
soap
store
tool
util
validator
values
xb
xpathgen
xsd2inst

m4/org/apache/xmlbeans/impl/common:
ConcurrentReaderHashMap$1.class
ConcurrentReaderHashMap$BarrierLock.class
ConcurrentReaderHashMap.class
ConcurrentReaderHashMap$Entry.class
...
XPath.class
XPath$CompilationContext.class
XPath$ExecutionContext.class
XPath$ExecutionContext$PathContext.class
XPath$Selector.class
XPath$Step.class
XPath$XPathCompileException.class

...

m4/org/etsi:
uri

m4/org/etsi/uri:
x01903

m4/org/etsi/uri/x01903:
v13

m4/org/etsi/uri/x01903/v13:
AnyType.class
AnyType$Factory.class
CertIDListType.class
CertIDListType$Factory.class
CertIDType.class
CertIDType$Factory.class
...
XAdESTimeStampType.class
XAdESTimeStampType$Factory.class

m4/org/etsi/uri/x01903/v13/impl:
AnyTypeImpl.class
CertIDListTypeImpl.class
CertIDTypeImpl.class
CertificateValuesTypeImpl.class
...
UnsignedPropertiesTypeImpl.class
UnsignedSignaturePropertiesTypeImpl.class
XAdESTimeStampTypeImpl.class

m4/org/openxmlformats:
schemas

m4/org/openxmlformats/schemas:
drawingml
officeDocument
presentationml
spreadsheetml
wordprocessingml
xpackage

....
...

m4/org/openxmlformats/schemas/officeDocument:
x2006

m4/org/openxmlformats/schemas/officeDocument/x2006:
customProperties
docPropsVTypes
extendedProperties
relationships

...

m4/org/openxmlformats/schemas/spreadsheetml/x2006/main:
CalcChainDocument.class
CalcChainDocument$Factory.class
ChartsheetDocument.class
ChartsheetDocument$Factory.class
CommentsDocument.class
...
StylesDocument.class
StylesDocument$Factory.class
STZoom$Enum.class

....
m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans:
impl

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl:
xb

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl/xb:
ltgfmt
substwsdl
xmlconfig
xmlschema
xsdownload
xsdschema

m4/schemaorg_apache_xmlbeans/javaname/org/apache/xmlbeans/impl/xb/ltgfmt:
Code.xsb
FileDesc
FileDesc.xsb
TestCase
   ... (rest is all schemaorg stuff)

Body:
Same error here but loading an excel file, just upgrade my XMLBeans from 2.3.0 to 3.1.0 and all work really nice.

download here:

https://www.apache.org/dyn/closer.lua/poi/xmlbeans/release/bin/xmlbeans-bin-3.1.0.zip


问:
How to provide custom comparator for `std::multiset` without overloading `operator()`, `std::less`, `std::greater`?
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

```<code>#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}
</code>```

Edit: With lambdas

```<code>class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};
</code>```

Error:

```<code>'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}
</code>```

答:
You can use a function pointer of a comparison function in the constructor:

main.cpp

```<code>#include <iostream>
#include <set>

using compType=bool(*)(int lhs, int rhs);

bool custom_compare_function(int lhs, int rhs)
{
    return lhs>rhs;
}

using list = std::multiset<int,compType>;
int main() {
    list l(&custom_compare_function);
    l.insert(1);
    l.insert(4);
    l.insert(2);
    for (auto& item: l) std::cout<<item<<std::endl;
}
</code>```

produces the output

```<code>$ g++ main.cpp
$ ./a.out
4
2
1
</code>```

Body:
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}

Edit: With lambdas

class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};

Error:

'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}

Body:
You can use a function pointer of a comparison function in the constructor:

main.cpp

#include <iostream>
#include <set>

using compType=bool(*)(int lhs, int rhs);

bool custom_compare_function(int lhs, int rhs)
{
    return lhs>rhs;
}

using list = std::multiset<int,compType>;
int main() {
    list l(&custom_compare_function);
    l.insert(1);
    l.insert(4);
    l.insert(2);
    for (auto& item: l) std::cout<<item<<std::endl;
}

produces the output

$ g++ main.cpp
$ ./a.out
4
2
1


问:
word2vec: negative sampling (in layman term)?
I'm reading the paper below and I have some trouble , understanding the concept of negative sampling.

http://arxiv.org/pdf/1402.3722v1.pdf

Can anyone help , please?

答:
I wrote an tutorial article about negative sampling here.

Why do we use negative sampling? -> to reduce computational cost

The cost function for vanilla Skip-Gram (SG) and Skip-Gram negative sampling (SGNS) looks like this:

Note that T is the number of all vocabs. It is equivalent to V. In the other words, T = V.

The probability distribution p(w_t+j|w_t) in SG is computed for all V vocabs in the corpus with:

V can easily exceed tens of thousand when training Skip-Gram model. The probability needs to be computed V times, making it computationally expensive. Furthermore, the normalization factor in the denominator requires extra V computations.

On the other hand, the probability distribution in SGNS is computed with:

c_pos is a word vector for positive word, and W_neg is word vectors for all K negative samples in the output weight matrix. With SGNS, the probability needs to be computed only K + 1 times, where K is typically between 5 ~ 20. Furthermore, no extra iterations are necessary to compute the normalization factor in the denominator.

With SGNS, only a fraction of weights are updated for each training sample, whereas SG updates all millions of weights for each training sample.

How does SGNS achieve this? -> by transforming multi-classification task into binary classification task.

With SGNS, word vectors are no longer learned by predicting context words of a center word. It learns to differentiate the actual context words (positive) from randomly drawn words (negative) from the noise distribution.

In real life, you don't usually observe regression with random words like Gangnam-Style, or pimples. The idea is that if the model can distinguish between the likely (positive) pairs vs unlikely (negative) pairs, good word vectors will be learned.

In the above figure, current positive word-context pair is (drilling, engineer). K=5 negative samples are randomly drawn from the noise distribution: minimized, primary, concerns, led, page. As the model iterates through the training samples, weights are optimized so that the probability for positive pair will output p(D=1|w,c_pos)≈1, and probability for negative pairs will output p(D=1|w,c_neg)≈0.


问:
How to show output for K-means clustering on multi-dimensional data?
I'm developing a code to create clusters of products based on their movement in 2018 (Jan-2018, Fev-2018, ...)

The instances will be the movements per month, so the data will have 12 dimensions. Example: The product x were consumed 3 times in january, 2 in february, 4 in march, 2 in april, 3 may, 4 june, 7 july, 10 august, 3 october , 8 november and 10 times in december. So that point will be (3, 2, 4, 2, 3, 4, 7, 10, 3, 8, 10). The problem is: in my code, i don't know how to use more than 2 variables:

```<code>    from scipy.cluster.vq import kmeans, vq
        from matplotlib import pyplot as plt
        import seaborn as sns
        import pandas as pnd

        import random
        random.seed ((1000,2000))

#the movement data will be inserted below
        m1 = []
        m2 = []
        m3 = []
        m4 = []
        m5 = []
        m6 = []
        m7 = []
        m8 = []
        m9 = []
        m10 = []
        m11 = []
        m12 = []

        df = pd.Dataframe({'january': m1, 'february': m2, 'march': m3, 'april': m4, 'may': m5, 'june': m6, 'july': m7, 'august': m8, 'september': m9, 'october': m10, 'november': m11, 'december': m12})

        centroids,_ = Kmeans(df, 3)
        df['cluster_labels'],_= vq(df, centroids)

        sns.scatterplot(m1 = 'january', m2 = 'february', m3 = 'march', m4 = 'april', m5 = 'may', m6 = 'june', m7 = 'july', m8 = 'august', m9 = 'september', m10 = 'october', m11 = 'november', m12 = 'december', hue
    = 'cluster_labels', data = df)

        plt.show()
</code>```

Theres some way that i can use the 12 dimensions in this code? If not, what i have to do? HELP ME, FRIENDS

答:
Well, how would you usually visualize this data?

Probably with a line chart with 12 columns.

You can do the same with k-means cluster centers.

Body:
I'm developing a code to create clusters of products based on their movement in 2018 (Jan-2018, Fev-2018, ...)

The instances will be the movements per month, so the data will have 12 dimensions. Example: The product x were consumed 3 times in january, 2 in february, 4 in march, 2 in april, 3 may, 4 june, 7 july, 10 august, 3 october , 8 november and 10 times in december. So that point will be (3, 2, 4, 2, 3, 4, 7, 10, 3, 8, 10). The problem is: in my code, i don't know how to use more than 2 variables:

    from scipy.cluster.vq import kmeans, vq
        from matplotlib import pyplot as plt
        import seaborn as sns
        import pandas as pnd

        import random
        random.seed ((1000,2000))

#the movement data will be inserted below
        m1 = []
        m2 = []
        m3 = []
        m4 = []
        m5 = []
        m6 = []
        m7 = []
        m8 = []
        m9 = []
        m10 = []
        m11 = []
        m12 = []

        df = pd.Dataframe({'january': m1, 'february': m2, 'march': m3, 'april': m4, 'may': m5, 'june': m6, 'july': m7, 'august': m8, 'september': m9, 'october': m10, 'november': m11, 'december': m12})

        centroids,_ = Kmeans(df, 3)
        df['cluster_labels'],_= vq(df, centroids)

        sns.scatterplot(m1 = 'january', m2 = 'february', m3 = 'march', m4 = 'april', m5 = 'may', m6 = 'june', m7 = 'july', m8 = 'august', m9 = 'september', m10 = 'october', m11 = 'november', m12 = 'december', hue
    = 'cluster_labels', data = df)

        plt.show()

Theres some way that i can use the 12 dimensions in this code? If not, what i have to do? HELP ME, FRIENDS


问:
MQTT topic names for request/response
I'm designing a system with many devices using MQTT to connect to a central broker.

There are some masters that can send requests to certain devices that are slaves. The request from one master is usually directed to one slave.

The topic for requests could be: mysystem/slaveId/req, so the slaves can subscribe to this topic and master publishes to the same topic. Only the addressed slave will receive the request, as it should be.

My question is how to decide the topic for responses. I'm in doubt between: mysystem/slaveId/res/masterId or simply mysystem/slaveId/res.

In the first case, I should send masterId to the slave in the payload of request, so the slave will be able to construct the response topic name. The answer will be received only by the master that send the request.

In the second case, all the active masters will receive the response, because the topic doesn't contain the masterId. The master that send the request should detect its response by looking at a requestId in the payload (that was sent in the request payload too).

I think the first choice is better, however the Device Shadow service of AWS uses topic names similar to the second choice. For example the device that replies to a get request publishes a message to $aws/things/myLightBulb/shadow/get/accepted. So every devices will receive the message, not only the one that requested.

I think AWS makes good choices, so I am tempted to follow it... however I'm not sure if I understood what they do.

答:
"Good choices" depend on context, and here the contexts differ. A Device Shadow is meant to track and accurately reflect the state of the device. The page you linked does not discuss having multiple shadows for one device, and may not have been written with multiple receivers in mind. Still, its simple topic architecture would work in a system that had multiple shadows per device because a shadow should receive all responses from its device. Any of those responses could reveal a change in device state, and any shadow whose client does not receive the response will be out of date, and out of sync with the other shadows.

Your masters do not sound like shadows. Perhaps they independently report their results to a data store that functions as the shadow. Perhaps nothing in the responses represents a state change worth tracking beyond the request. Either way, the documentation does not sound relevant to your goal.

I support your preference for the first choice, especially as the number of nodes grows. The main drawback is the extra work keeping track of the requesting master ID. It's easy for the masters (each can just subscribe to mySystem/+/res/masterId, and in a system with topic access control you could even isolate them). If the request body is otherwise simple (not already multiple attributes to parse), you might consider having the masters post to mysystem/slaveId/req/masterId (slave could subscribe to mysystem/slaveId/req/+).

The biggest example to take from AWS might be the clear sense of hierarchy in the topics. If the parsing convenience of having the masterId at the end of the topic is not your top concern, it might make more sense to order as: mysystem/masterId/slaveId/req (or res). Very dependent on your system and goals.

Title: MQTT topic names for request/response