问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答:
Have you never heard about prevalence frameworks ?

EDIT some clarifications on the term.

Like James Gosling now says, no SQL DB is as efficient as an in-memory storage. Prevalence frameworks (most known being prevayler and space4j) are built upon this idea of an in-memory, maybe storable on disk, storage. How do they work ? In fact, it's deceptively simple : a storage object contains all persistent entities. This storage can only be changed by serializable operations. As a consequence, putting an object in storage is a Put operation performed in isolated context. As this operation is serializable, it may (depending upon configuration) be also saved on disk for long-term persistence. However, the main data repository is the memory, which proides undoubtly fast access time, at the cost of a high memory usage.

Another advantage is that, because of their obvious simplicity, these frameworks hardly contain more than a tenth of classes

Considering your question, the use of Space4J immediatly came to my mind (as it provides support for "passivation" of rarely used objects, that's to say their index key is in memory, but the objects are kept on disk as long as they're not used).

Notice you can also find some infos at c2wiki.


来源: stackexchange

问:
How to off throttle in debug=true?
In Laravel in App/Http/Kernel exist such string:

```<code>protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];
</code>```

How to off throttle when debug mode in ENV set true?

答:
I'm afraid you cannot set this dynamically as of now in Laravel.'

However what you can do is to define your own throttling middleware and then you can assign the throttle values dynamically.

Note: You can fetch the debug config like so:

```<code>config('app.debug')
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to off throttle in debug=true?

Body:
In Laravel in App/Http/Kernel exist such string:

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

How to off throttle when debug mode in ENV set true?

Body:
I'm afraid you cannot set this dynamically as of now in Laravel.'

However what you can do is to define your own throttling middleware and then you can assign the throttle values dynamically.

Note: You can fetch the debug config like so:

config('app.debug')


问:
Generate a variable in Groovy JMeter
I have a Thread Group wherein I have three samplers. They are HTML Requests. The first one returns a person and gives me the name, age and address. The second one changes the attribute name of the person but has no response.
The third sampler is the same as the first.

The second sampler isn't working and doesn't change the name.

I want a failure message like: "The name of the person was $(name1) and should be changed to $(name2), but the name is $(name3)" or something like that.

I do the whole things with Groovy so is there any way to generate variables with the output of the first and third request and the input of the second?

答:
Most probably you're looking for Response Assertion, you can conditionally mark samplers as failed depending on various criteria. It might be the case that you won't even need scripting like.

Just add Response Assertion as a child of 3rd request and configure it to expect ${name3} variable to be present in the response (you can use Perl-5 style regular expressions for this as well) and if the name will not be present - the sampler will get failed and you will see the relevant failure message

More information: How to Use JMeter Assertions in Three Easy Steps

Title: Generate a variable in Groovy JMeter


问:
How to make a Python list based on another list
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?</p>

```<code>master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']
</code>```

答:
I came up with a solution for your problem, but it doesn't answer your question since I didn't link the different lists.

Nevertheless, I propose you this function:

```<code>def del_item(item, *args) :
    for lst in args :
        if item in lst :
            lst.remove(item)
</code>```

Then you just have to call this function with the item you want to pop out and the different lists that you want to check.

Hope this can be useful

Body:
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?

master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']

Body:
I came up with a solution for your problem, but it doesn't answer your question since I didn't link the different lists.

Nevertheless, I propose you this function:

def del_item(item, *args) :
    for lst in args :
        if item in lst :
            lst.remove(item)

Then you just have to call this function with the item you want to pop out and the different lists that you want to check.

Hope this can be useful


问:
How to mix const and let when using object or array destructuring assignment in ES6?
Example :

```<code>const foo = {a: "A", b: "B"}
const {a, b} = foo
</code>```

What if I want b to be a variable using let ?

答:
It seems like you can't differentiate variable's declaration in a one line. However, you could split it into two lines and use a different variable declaration, depends on which variable you want to get.</p>

```<code>const { a } = foo;
let { b } = foo;
</code>```

Body:
Example :

const foo = {a: "A", b: "B"}
const {a, b} = foo

What if I want b to be a variable using let ?

Body:
It seems like you can't differentiate variable's declaration in a one line. However, you could split it into two lines and use a different variable declaration, depends on which variable you want to get.

const { a } = foo;
let { b } = foo;


问:
Use JavaScript to prevent a later `<script>` tag from being evaluated?
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

```<code><script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</code>```

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

```<code><script type="text/javascript">
  function func() {
    window.meaningOfLife = 42;
    window.loadSecond();
  };
  setTimeout(func, 10);
</script>
</code>```

precedes the two script includes, and that second.js contains the line

```<code>if (window.meaningOfLife !== 42) {throw new Error();}
</code>```

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...

答:
In first.js, set var shouldILoad = true

Then, load second.js this way:

```<code><script>
    if (shouldILoad) {
        (function() {
            var myscript = document.createElement('script');
            myscript.type = 'text/javascript';
            myscript.src = ('second.js');
            var s = document.getElementById('myscript');
            s.parentNode.insertBefore(myscript, s);
        })();
    }
</script>
</code>```

(where 'myscript' is the ID of some element before which you'd like to insert the new Script element)

ContentLicense: CC BY-SA 2.5

Body:
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

precedes the two script includes, and that second.js contains the line

if (window.meaningOfLife !== 42) {throw new Error();}

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...

Body:
In first.js, set var shouldILoad = true

Then, load second.js this way:

<script>
    if (shouldILoad) {
        (function() {
            var myscript = document.createElement('script');
            myscript.type = 'text/javascript';
            myscript.src = ('second.js');
            var s = document.getElementById('myscript');
            s.parentNode.insertBefore(myscript, s);
        })();
    }
</script>

(where 'myscript' is the ID of some element before which you'd like to insert the new Script element)


问:
Elements in common for each two elements in first column dataframes
I'm new with Pandas. I have the following dataframe.

Group           type

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1```
</div>
</div>
</p>

<p>And I would like to obtain for each couple of groups how many "types" they have in common. Something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Group           type  count

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

count: (G1, G2, 2) (Elements in common: a1,a2)
count: (G1, G3, 1) (Elements in common: a1)
count: (G1, G4, 1) (Elements in common: a1)
...</code>```

Do you have any idea how could I implement this? Is there any function from the pandas library that could guide me into the right direction.

答:
I think you need numpy.intersect1d:

```<code>import itertools

#get all combinations of Group values
c = list(itertools.combinations(list(set(df['Group'])), 2))

df = df.set_index('Group')

#create list of tuples of intersections and lengths
L = []
for a, b in c:
    d = np.intersect1d(df.loc[a], df.loc[b]).tolist()
    L.append((a,b, len(d), d))

#new DataFrame
df = pd.DataFrame(L, columns=['a','b','lens','common'])
print (df)
    a   b  lens    common
0  G2  G4     1      [a1]
1  G2  G1     2  [a1, a2]
2  G2  G3     1      [a1]
3  G2  G5     1      [a1]
4  G4  G1     1      [a1]
5  G4  G3     1      [a1]
6  G4  G5     1      [a1]
7  G1  G3     1      [a1]
8  G1  G5     1      [a1]
9  G3  G5     1      [a1]
</code>```

Body:
I'm new with Pandas. I have the following dataframe.

Group           type

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

And I would like to obtain for each couple of groups how many "types" they have in common. Something like this:

Group           type  count

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

count: (G1, G2, 2) (Elements in common: a1,a2)
count: (G1, G3, 1) (Elements in common: a1)
count: (G1, G4, 1) (Elements in common: a1)
...

Do you have any idea how could I implement this? Is there any function from the pandas library that could guide me into the right direction.

Body:
I think you need numpy.intersect1d:

import itertools

#get all combinations of Group values
c = list(itertools.combinations(list(set(df['Group'])), 2))

df = df.set_index('Group')

#create list of tuples of intersections and lengths
L = []
for a, b in c:
    d = np.intersect1d(df.loc[a], df.loc[b]).tolist()
    L.append((a,b, len(d), d))

#new DataFrame
df = pd.DataFrame(L, columns=['a','b','lens','common'])
print (df)
    a   b  lens    common
0  G2  G4     1      [a1]
1  G2  G1     2  [a1, a2]
2  G2  G3     1      [a1]
3  G2  G5     1      [a1]
4  G4  G1     1      [a1]
5  G4  G3     1      [a1]
6  G4  G5     1      [a1]
7  G1  G3     1      [a1]
8  G1  G5     1      [a1]
9  G3  G5     1      [a1]


问:
React functional components vs classical components
I'm trying to understand when to use React functional components vs. classes and reading from the docs they don't really go into detail. Can you give me some primary examples of the below of when you would want a specific feature of a class to make a component?

A functional component is less powerful but is simpler, and acts like
  a class component with just a single render() method. Unless you need
  features available only in a class, we encourage you to use functional
  components instead.

答:
Functional Component

Used for presenting static data.

Can't handle fetching data.

Easy to write.

Example :

```<code>const Foo =()=>
{
   return <Text>Hi there!</Text>
}
</code>```

Class Component

Used for the dynamic source of data.

Handles any data that might change(fetching data, user events, etc).

More code to write.

Example :

```<code>class Foo extends Component {

render(){
return <Text>Hi There!</Text>
  }
}
</code>```

Body:
Functional Component

Used for presenting static data.

Can't handle fetching data.

Easy to write.

Example :

const Foo =()=>
{
   return <Text>Hi there!</Text>
}

Class Component

Used for the dynamic source of data.

Handles any data that might change(fetching data, user events, etc).

More code to write.

Example :

class Foo extends Component {

render(){
return <Text>Hi There!</Text>
  }
}

ContentLicense: CC BY-SA 4.0


问:
How to POST in ReactJS
I am new to ReactJs. I am working with ASP.net and reactjs to create a crud application. I have displayed the table. Now I am trying to insert values into table from forms. Please let me know how to do the same. I have shared the controller and reactjs code.

EmployeeController:

```<code>[RoutePrefix("api/Employee")]
public class EmployeeController : ApiController
{
    EmployeeEntities db = new EmployeeEntities();

    [Route("GetEmployeeList")]
    public IQueryable<EmployeeTable> GetEmployeeList()
    {
        return db.EmployeeTables.AsQueryable();
    }

    [Route("InputEmployee")]
    public void InputEmployee()
    {

    }
}
</code>```

EmployeeJSX.jsx:

```<code>    var EmployeeRow = React.createClass({

      render: function () {
          return(
              <tr>
                  <td>{this.props.item.EmployeeID}</td>
                  <td>{this.props.item.FirstName}</td>
                  <td>{this.props.item.LastName}</td>
                  <td>{this.props.item.Gender}</td>
                  <td>{this.props.item.Designation}</td>
                  <td>{this.props.item.Salary}</td>
                  <td>{this.props.item.City}</td>
                  <td>{this.props.item.Country}</td>
              </tr>

              );
      }
  });

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
      });
  return (<table className="table">
     <thead>
         <tr>
            <th>EmployeeID</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Gender</th>
            <th>Designation</th>
            <th>Salary</th>
            <th>City</th>
            <th>Country</th>
         </tr>
     </thead>

      <tbody>
          {rows}
      </tbody>

  </table>);
  }

  });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid'))
</code>```

input form component:

```<code>var InputValues=React.createClass({
  handleClick:function(){
      this.props.onUserInput(this.refs.firstName.value,this.refs.lastName.value,this.refs.gender.value,this.refs.designation.value,this.refs.salary.value,this.refs.city.value,this.refs.country.value);
  },
  render:function(){
    return(
      <div>
        <form>
          <label id="firstname">First Name </label><br/>
          <input type="text"  placeholder="Enter First Name" ref="firstName"   />
          <br/><br/><label id="lastname">Last Name: </label><br/>
          <input type="text"  placeholder="Enter Last Name"  ref="lastName"   />
          <br/><br/><label id="gender">Gender: </label><br/>
          <input type="text"  placeholder="Gender"  ref="gender"   />
          <br/><br/><label id="designation">Designation: </label><br/>
          <input type="text"  placeholder="Enter Designation"  ref="designation"   />
          <br/><br/><label id="salary">Salary: </label><br/>
          <input type="number"  placeholder="Enter Salary"  ref="salary"   />
          <br/><br/><label id="city">City: </label><br/>
          <input type="text"  placeholder="Enter City"  ref="city"   />
          <br/><br/><label id="country">City: </label><br/>
          <input type="text"  placeholder="Enter Country"  ref="country"   />
          <p>
            <button type="button" onClick={this.handleClick}>Submit</button>
          </p>
        </form>
      </div>
    );
  }
});
</code>```

答:
Well the great thing about React is that it's just Javascript.

So all you need is something to do a POST do your server!

You can use the native fetch function or a full-on library like axios

Examples using both could be:

```<code>// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();
</code>```

```<code>// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };
</code>```

```<code>// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

Title: How to POST in ReactJS

Body:
I am new to ReactJs. I am working with ASP.net and reactjs to create a crud application. I have displayed the table. Now I am trying to insert values into table from forms. Please let me know how to do the same. I have shared the controller and reactjs code.

EmployeeController:

[RoutePrefix("api/Employee")]
public class EmployeeController : ApiController
{
    EmployeeEntities db = new EmployeeEntities();

    [Route("GetEmployeeList")]
    public IQueryable<EmployeeTable> GetEmployeeList()
    {
        return db.EmployeeTables.AsQueryable();
    }

    [Route("InputEmployee")]
    public void InputEmployee()
    {

    }
}

EmployeeJSX.jsx:

    var EmployeeRow = React.createClass({

      render: function () {
          return(

                  {this.props.item.EmployeeID}
                  {this.props.item.FirstName}
                  {this.props.item.LastName}
                  {this.props.item.Gender}
                  {this.props.item.Designation}
                  {this.props.item.Salary}
                  {this.props.item.City}
                  {this.props.item.Country}

              );
      }
  });

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
      });
  return (

            EmployeeID
            FirstName
            LastName
            Gender
            Designation
            Salary
            City
            Country

          {rows}

);
  }

  });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid'))

input form component:

var InputValues=React.createClass({
  handleClick:function(){
      this.props.onUserInput(this.refs.firstName.value,this.refs.lastName.value,this.refs.gender.value,this.refs.designation.value,this.refs.salary.value,this.refs.city.value,this.refs.country.value);
  },
  render:function(){
    return(

        <form>
          First Name

          <input type="text"  placeholder="Enter First Name" ref="firstName"   />

Last Name:

          <input type="text"  placeholder="Enter Last Name"  ref="lastName"   />

Gender:

          <input type="text"  placeholder="Gender"  ref="gender"   />

Designation:

          <input type="text"  placeholder="Enter Designation"  ref="designation"   />

Salary:

          <input type="number"  placeholder="Enter Salary"  ref="salary"   />

City:

          <input type="text"  placeholder="Enter City"  ref="city"   />

City:

          <input type="text"  placeholder="Enter Country"  ref="country"   />

            <button type="button" onClick={this.handleClick}>Submit</button>

        </form>

    );
  }
});

Body:
Well the great thing about React is that it's just Javascript.

So all you need is something to do a POST do your server!

You can use the native fetch function or a full-on library like axios

Examples using both could be:

// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();

// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };

// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


问:
How to make custom route with custom action in sonata admin using Symfony
I am new in Symfony as well as sonata admin, I want to make a custom route with custom action in sonata admin.any one know how to make a custom route with custom action and how to call that custom route from twing file ?.</p>

答:
Example of route in your AdminBundle:

```<code><route id="get_driver_location" path="/driver-location">
    <default key="_controller">MyAdminBundle:Core:getlocation</default>
</route>
</code>```

Then you must create a controller called CoreController in the controller directory of your bundle

```<code>    namespace My\AdminBundle\Controller;

    use Symfony\Component\Config\Definition\Exception\Exception;
    use Symfony\Component\HttpFoundation\Response;
    use Sonata\AdminBundle\Controller\CoreController as BaseController;

    class CoreController extends BaseController {

    public function getlocationAction() {
        //your logic here
       ......
       return $this->render($this->getAdminPool()->getTemplate('driver'), array(
                    'base_template' => $this->getBaseTemplate());
    }

    }
</code>```

Edit: Add Twig:

```<code>-Resources

  -views

    -Core

      -driver.html.twig
</code>```

in the file driver.html.twig you make a route

```<code><div>
                <a class="btn btn-default" href="{{ path('get_driver_location') }}" role="button">
                    {{ "example"|trans({}, "MyAdminBundle") }}
                </a>
            </div>
</code>```

Body:
Example of route in your AdminBundle:

<route id="get_driver_location" path="/driver-location">
    <default key="_controller">MyAdminBundle:Core:getlocation</default>
</route>

Then you must create a controller called CoreController in the controller directory of your bundle

    namespace My\AdminBundle\Controller;

    use Symfony\Component\Config\Definition\Exception\Exception;
    use Symfony\Component\HttpFoundation\Response;
    use Sonata\AdminBundle\Controller\CoreController as BaseController;

    class CoreController extends BaseController {

    public function getlocationAction() {
        //your logic here
       ......
       return $this->render($this->getAdminPool()->getTemplate('driver'), array(
                    'base_template' => $this->getBaseTemplate());
    }

    }

Edit: Add Twig:

-Resources

  -views

    -Core

      -driver.html.twig

in the file driver.html.twig you make a route

<div>
                <a class="btn btn-default" href="{{ path('get_driver_location') }}" role="button">
                    {{ "example"|trans({}, "MyAdminBundle") }}
                </a>
            </div>


问:
Loading local libaries in jekyll (Liquid template library + ruby bundler)
My question is: How do I load local libaries in ruby and with bundler + jekyll?

I'm trying to load a bunch of local libraries.
For example: project_root/_plugins/fileexists.rb

I've tried following https://jekyllrb.com/docs/plugins/ but that solution assumes you have a library that can be installed from the global Gem repository.

The plugins I'm trying to load are here https://github.com/nicnocquee/appolo/tree/master/_plugins

The error I'm getting when  doing 'bundle exec jekyll serve':

```<code>Dependency Error: Yikes! It looks like you don't have fileexists or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: 'cannot load such file -- fileexists' If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/!
</code>```

To complicate the matter, I'm using the Liquid template library. (Though this shouldnt be a Liquid problem because I get the error when doing bundle exec jekyll serve. I think..)

```<code>{% file_exists {{ fb_img_default }} %}
</code>```

The code for the template is here:
https://github.com/nicnocquee/appolo/blob/master/_includes/head.html#L25

My _config.yml file for jekyll: https://pastebin.com/SphuLcVt
The Gemfile: https://pastebin.com/3ptcBx5m

Thanks in advance for ideas about how to proceed!

Library version

bundle  --version
Bundler version 1.16.0

ruby --version
ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

gem --version
2.5.2

答:
Ok, I figured this out.

I removed:

```<code>plugins:
 - fileexists
</code>```

From _config.yml

And removed:

```<code>gem 'fileexists', :path => '/home/test/xxx.github.io/_plugins/fileexists'
gem 'github-pages'
</code>```

from Gemfile

The clue that github-pages packet was the problem: https://github.com/jekyll/jekyll/issues/5990#issuecomment-308231021

Short answer:
"No custom plugins will load when using github-pages because of their whitelist."

Body:
My question is: How do I load local libaries in ruby and with bundler + jekyll?

I'm trying to load a bunch of local libraries.
For example: project_root/_plugins/fileexists.rb

I've tried following https://jekyllrb.com/docs/plugins/ but that solution assumes you have a library that can be installed from the global Gem repository.

The plugins I'm trying to load are here https://github.com/nicnocquee/appolo/tree/master/_plugins

The error I'm getting when  doing 'bundle exec jekyll serve':

Dependency Error: Yikes! It looks like you don't have fileexists or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: 'cannot load such file -- fileexists' If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/!

To complicate the matter, I'm using the Liquid template library. (Though this shouldnt be a Liquid problem because I get the error when doing bundle exec jekyll serve. I think..)

{% file_exists {{ fb_img_default }} %}

The code for the template is here:
https://github.com/nicnocquee/appolo/blob/master/_includes/head.html#L25

My _config.yml file for jekyll: https://pastebin.com/SphuLcVt
The Gemfile: https://pastebin.com/3ptcBx5m

Thanks in advance for ideas about how to proceed!

Library version

bundle  --version
Bundler version 1.16.0

ruby --version
ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

gem --version
2.5.2

Body:
Ok, I figured this out.

I removed:

plugins:
 - fileexists

From _config.yml

And removed:

gem 'fileexists', :path => '/home/test/xxx.github.io/_plugins/fileexists'
gem 'github-pages'

from Gemfile

The clue that github-pages packet was the problem: https://github.com/jekyll/jekyll/issues/5990#issuecomment-308231021

Short answer:
"No custom plugins will load when using github-pages because of their whitelist."


问:
Hibernate enum casting and converter mapping
I' m working with enums and I want to store code from enum body in database. I' m using hibernate 5.2.11.. For the entity mapping I'm using .hbm.xml files. What I'm doing wrong? Why I can't store the enmus code. It keeps storing enum name or bytearray.

MyEntity.java

    public class MyEntity {

       private Long id;
       private MyEnums num;

       public Long getId() {
           return id;
       }

       public void setId(Long id) {
           this.id = id;
       }

       @Convert(converter = MyEnumConverter.class)
       public MyEnums getNum() {
           return num;
       }

       @Convert(converter = MyEnumConverter.class)
       public void setNum(MyEnums num) {
           this.num = num;
       }
    }
```

<p>Using this entity I'm setting enum and I want that hibernate store the code from the enum body.
<strong>MyEnums.java</strong></p>

<pre class="lang-java prettyprint-override"><code>    public enum MyEnums {

       FIRST("123", "first"),
       SECOND("456", "second");

       private final String code;
       private final String description;

       private MyEnums(String code, String description) {
           this.code = code;
           this.description = description;
       }

       public static MyEnums fromCode(String code) {
           if (code.equals(FIRST.code)) {
               return FIRST;
           } else if (code.equals(SECOND.code)) {
               return SECOND;
           } else {
               return null;
           }
       }

       public String getCode() {
           return code;
       }

       public String getDescription() {
           return description;
       }
    }
</code>```

Using MyEnums class logic I can get code or description from enum body. To store code into database I am using AttributeConverter<>.

MyEnumConverter.java

    @Converter(autoApply = true)
    public class MyEnumConverter implements AttributeConverter<MyEnums, String> {

       @Override
       public String convertToDatabaseColumn(MyEnums myEnums) {
           return (myEnums != null)? myEnums.getCode() : null;
       }

       @Override
       public MyEnums convertToEntityAttribute(String code) {
           return (code != null)? MyEnums.fromCode(code) : null;
       }
    }
```

<p>As I said I'm using .hbm.xml mapping. So I tried two different ways to map my enum type. When I'm using 1-ST annotation - database store <em>bytea</em> type value. And when I'm using 2-nd annotation - database stores enum name or possition number in enum class.</p>

<p><strong>MyEntity.hbm.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code>    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
        <class name="main.test.main.MyEntity" table="test_enums">
            <id name="id" column="id">
                <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
                    <param name="optimizer">none</param>
                    <param name="increment_size">1</param>
                    <param name="sequence_name">seq_enums</param>
                </generator>
            </id>

       <!-- 1-ST ANNOTATION -->
            <property name="num" column="enum_code"/>

       <!-- 2-ND ANNOTATION -->
            <!--<property name="num" column="enum_code">
                <type name="org.hibernate.type.EnumType">
                    <param name="enumClass">main.test.main.MyEnums</param>
                </type>
            </property>-->
        </class>
    </hibernate-mapping>
</code>```

When I' m using 1-st annotation database table looks like this:

```<code>----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | 81B 00000000 AC ED 00 ... |
----------------------------------
</code>```

When I' m using 2-nd annotation table looks like this:

```<code>----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | SECOND                    |
----------------------------------
</code>```

Or like this:

```<code>----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | 1                         |
----------------------------------
</code>```

So seems that my enum converter does not work. Is someone encountered with this type of problem? I really need some help...

答:
After long time of Internet browsing finally I found the solution. Thanks for Gabriel Axel. He is offering to create your own value type class which converts enum to his body value.

More information (example): http://www.gabiaxel.com/2011/01/better-enum-mapping-with-hibernate.html

Body:
I' m working with enums and I want to store code from enum body in database. I' m using hibernate 5.2.11.. For the entity mapping I'm using .hbm.xml files. What I'm doing wrong? Why I can't store the enmus code. It keeps storing enum name or bytearray.

MyEntity.java

    public class MyEntity {

       private Long id;
       private MyEnums num;

       public Long getId() {
           return id;
       }

       public void setId(Long id) {
           this.id = id;
       }

       @Convert(converter = MyEnumConverter.class)
       public MyEnums getNum() {
           return num;
       }

       @Convert(converter = MyEnumConverter.class)
       public void setNum(MyEnums num) {
           this.num = num;
       }
    }

Using this entity I'm setting enum and I want that hibernate store the code from the enum body.
MyEnums.java

    public enum MyEnums {

       FIRST("123", "first"),
       SECOND("456", "second");

       private final String code;
       private final String description;

       private MyEnums(String code, String description) {
           this.code = code;
           this.description = description;
       }

       public static MyEnums fromCode(String code) {
           if (code.equals(FIRST.code)) {
               return FIRST;
           } else if (code.equals(SECOND.code)) {
               return SECOND;
           } else {
               return null;
           }
       }

       public String getCode() {
           return code;
       }

       public String getDescription() {
           return description;
       }
    }

Using MyEnums class logic I can get code or description from enum body. To store code into database I am using AttributeConverter<>.

MyEnumConverter.java

    @Converter(autoApply = true)
    public class MyEnumConverter implements AttributeConverter<MyEnums, String> {

       @Override
       public String convertToDatabaseColumn(MyEnums myEnums) {
           return (myEnums != null)? myEnums.getCode() : null;
       }

       @Override
       public MyEnums convertToEntityAttribute(String code) {
           return (code != null)? MyEnums.fromCode(code) : null;
       }
    }

As I said I'm using .hbm.xml mapping. So I tried two different ways to map my enum type. When I'm using 1-ST annotation - database store bytea type value. And when I'm using 2-nd annotation - database stores enum name or possition number in enum class.

MyEntity.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
        <class name="main.test.main.MyEntity" table="test_enums">
            <id name="id" column="id">
                <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
                    <param name="optimizer">none</param>
                    <param name="increment_size">1</param>
                    <param name="sequence_name">seq_enums</param>
                </generator>
            </id>

            <property name="num" column="enum_code"/>

        </class>
    </hibernate-mapping>

When I' m using 1-st annotation database table looks like this:

----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | 81B 00000000 AC ED 00 ... |
----------------------------------

When I' m using 2-nd annotation table looks like this:

----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | SECOND                    |
----------------------------------

Or like this:

----------------------------------
| id | enum_code                 |
----------------------------------
| 1  | 1                         |
----------------------------------

So seems that my enum converter does not work. Is someone encountered with this type of problem? I really need some help...


问:
Lookup to column on site collection does not contain contents
I create a site collection column that itself has a lookup onto a list inside that site collection. I create this column using CSOM:

```<code>    string contextUrl = "http://company.example.com/sites/mysite/subsite";

    SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
    ClientContext clientContext = new ClientContext(contextUrl);
    Web web = clientContext.Web;
    clientContext.Load(web);
    clientContext.ExecuteQuery();

    Web rootWeb = clientContext.Site.RootWeb;
    clientContext.Load(rootWeb);

    // Add List containing target column
    ListCreationInformation targetListInfo = new ListCreationInformation();
    targetListInfo.Title = "TargetListTitle";
    targetListInfo.TemplateType = (int)ListTemplateType.GenericList;

    List targetList = web.Lists.Add(targetListInfo);
    targetList.Update();
    clientContext.Load(targetList);
    clientContext.ExecuteQuery();

    // Update Title
    FieldCollection techListFields = targetList.Fields;
    clientContext.Load(techListFields);
    clientContext.ExecuteQuery();

    // Create Site Lookupcolumns
    var techListID = targetList.Id;

    FieldCollection colSCFields = rootWeb.Fields;
    clientContext.Load(colSCFields);
    clientContext.ExecuteQuery();

    var lookupSchema = "<Field Type='Lookup' DisplayName='Magic' Required='FALSE' List='" + techListID + "' ShowField='Title' StaticName='Magic' Name='Magic'/>";
    colSCFields.AddFieldAsXml(lookupSchema, false, AddFieldOptions.AddFieldInternalNameHint);

    clientContext.ExecuteQuery();
</code>```

(for complete information I added all lines, but the crucial part start below "// Create Site Lookupcolumns")

The site column is being created, but when I use a lookup onto that column on a list inside a sub site (manually or by program) the dropdown from that lookup field does not display any content. (The behavior looks like a lookup column being created before the target column exists)

答:
You need to specify WebId attribute value (set it to subsite ID) in the field xml definition, like this:</p>

```<code>var lookupSchema = "<Field Type='Lookup' DisplayName='Magic' Required='FALSE' WebId='" + web.Id + "' List='" + techListID + "' ShowField='Title' StaticName='Magic' Name='Magic'/>";
</code>```

Body:
I create a site collection column that itself has a lookup onto a list inside that site collection. I create this column using CSOM:

    string contextUrl = "http://company.example.com/sites/mysite/subsite";

    SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
    ClientContext clientContext = new ClientContext(contextUrl);
    Web web = clientContext.Web;
    clientContext.Load(web);
    clientContext.ExecuteQuery();

    Web rootWeb = clientContext.Site.RootWeb;
    clientContext.Load(rootWeb);

    // Add List containing target column
    ListCreationInformation targetListInfo = new ListCreationInformation();
    targetListInfo.Title = "TargetListTitle";
    targetListInfo.TemplateType = (int)ListTemplateType.GenericList;

    List targetList = web.Lists.Add(targetListInfo);
    targetList.Update();
    clientContext.Load(targetList);
    clientContext.ExecuteQuery();

    // Update Title
    FieldCollection techListFields = targetList.Fields;
    clientContext.Load(techListFields);
    clientContext.ExecuteQuery();

    // Create Site Lookupcolumns
    var techListID = targetList.Id;

    FieldCollection colSCFields = rootWeb.Fields;
    clientContext.Load(colSCFields);
    clientContext.ExecuteQuery();

    var lookupSchema = "<Field Type='Lookup' DisplayName='Magic' Required='FALSE' List='" + techListID + "' ShowField='Title' StaticName='Magic' Name='Magic'/>";
    colSCFields.AddFieldAsXml(lookupSchema, false, AddFieldOptions.AddFieldInternalNameHint);

    clientContext.ExecuteQuery();

(for complete information I added all lines, but the crucial part start below "// Create Site Lookupcolumns")

The site column is being created, but when I use a lookup onto that column on a list inside a sub site (manually or by program) the dropdown from that lookup field does not display any content. (The behavior looks like a lookup column being created before the target column exists)

Body:
You need to specify WebId attribute value (set it to subsite ID) in the field xml definition, like this:

var lookupSchema = "<Field Type='Lookup' DisplayName='Magic' Required='FALSE' WebId='" + web.Id + "' List='" + techListID + "' ShowField='Title' StaticName='Magic' Name='Magic'/>";


问:
How do I change text-color determined by the background color?
I'm looking for a way, with jQuery ideally, to determine the correct text color, based on the brightness of the background color?

E.g. white background, black text colour. I believe this could be done crudely with adding the HEX value and guesstimating but does anyone know a better way or jQuery way to do this?

答:
You can try inverting the hex value of the color. So #FFFFFF becomes #000000 and #AAAAAA becomes #555555. Of course, this method falls through when you have #888888 which when inverted, gives you #777777 (they don't contrast as much).

This blog post describes another way (they only use black or white for the foreground color, depending on the background color). I've translated it into Javascript:

```<code>function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";
}

function getRGBComponents(color) {

    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);

    return {
       R: parseInt(r, 16),
       G: parseInt(g, 16),
       B: parseInt(b, 16)
    };
}
</code>```

Body:
You can try inverting the hex value of the color. So #FFFFFF becomes #000000 and #AAAAAA becomes #555555. Of course, this method falls through when you have #888888 which when inverted, gives you #777777 (they don't contrast as much).

This blog post describes another way (they only use black or white for the foreground color, depending on the background color). I've translated it into Javascript:

function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";
}

function getRGBComponents(color) {

    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);

    return {
       R: parseInt(r, 16),
       G: parseInt(g, 16),
       B: parseInt(b, 16)
    };
}


问:
Mongo DB authentication not working in grails but from console
I want to use authentication in my mongodb. So I created a user. Which this user I can connect on command line and insert data without any problem.

But when I want to use this user in grails, I get this error:

```<code>{ "serverUsed" : "127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18 , "codeName" : "AuthenticationFailed"}
</code>```

When I connect from commandline, everything works:

```<code>mongo --port 27017 -u "mongouser" -p "pwd" mydb
</code>```

My code in Grails:

```<code> MongoCredential credential = MongoCredential.createMongoCRCredential("mongouser", "mydb", "pwd".toCharArray())
 def mongoClient = new MongoClient( new ServerAddress(host, port), [credential ] )
 gMongoCon = new GMongo(mongoClient)
</code>```

What is wrong here?

答:
Add your mongo credentials in Config.groovy or external config as follows,

```<code>grails
        {

                mongo
                {
                    host            =   "YOUR_HOST_NAME_OR_IP_ADDRESS" // e.g localhost
                    port            =   27017
                    username        =   "mongouser" //Username
                    password        =   "pwd"       //password
                    databaseName    =   "mydb" //Database name
                }
        }
</code>```

Note: change the bind_ip from /etc/mongod.conf if the application and
  mongo are on different server.

Body:
I want to use authentication in my mongodb. So I created a user. Which this user I can connect on command line and insert data without any problem.

But when I want to use this user in grails, I get this error:

{ "serverUsed" : "127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18 , "codeName" : "AuthenticationFailed"}

When I connect from commandline, everything works:

mongo --port 27017 -u "mongouser" -p "pwd" mydb

My code in Grails:

 MongoCredential credential = MongoCredential.createMongoCRCredential("mongouser", "mydb", "pwd".toCharArray())
 def mongoClient = new MongoClient( new ServerAddress(host, port), [credential ] )
 gMongoCon = new GMongo(mongoClient)

What is wrong here?

Body:
Add your mongo credentials in Config.groovy or external config as follows,

grails
        {

                mongo
                {
                    host            =   "YOUR_HOST_NAME_OR_IP_ADDRESS" // e.g localhost
                    port            =   27017
                    username        =   "mongouser" //Username
                    password        =   "pwd"       //password
                    databaseName    =   "mydb" //Database name
                }
        }

Note: change the bind_ip from /etc/mongod.conf if the application and
  mongo are on different server.


问:
What does m >>= return means?
Was reading tutorial about monads and stuck on following:

```<code>let m = return 2 :: IO Int
</code>```

That's understandable - we pack 2 in monadic variable(IO 2)
But what does the following mean?

```<code>m >>= return
</code>```

It outputs 2.

As I know from Monad definition, that return always accepts exactly one argument. However, here the argument absents. How it could be understood?

答:
(>>=) is the bind operator. It has signature:

```<code>(>>=) :: Monad m => m a -> (a -> m b) -> m b
</code>```

So it expects (on the left side) a monadic object (for instance IO Int), and on the right side a function a -> m b (for instance Int -> IO b) here.

The operator is used to chain operations in a monad together. For instance putStrLn :: String -> IO () can be used if we use it like:

```<code>return "foo" >>= putStrLn
</code>```

So now we return a string "foo". The bind operator will unwrap it out of the IO monad so to speak, and pass it to the putStrLn function that will print "foo" to the standard output channel, and return an IO (). We can then use that IO () for further processing.

Since return wraps data into a monad, writing >>= return is basically useless. Since for all x x >>= return should be equal to x.

The argument of return is not missing in the sense that >>= will call the return with an argument. You can also write:

```<code>m >>= (\x -> return x)
</code>```

but this is equivalent to m >>= return.

Title: What does m >>= return means?

Body:
Was reading tutorial about monads and stuck on following:

let m = return 2 :: IO Int

That's understandable - we pack 2 in monadic variable(IO 2)
But what does the following mean?

m >>= return

It outputs 2.

As I know from Monad definition, that return always accepts exactly one argument. However, here the argument absents. How it could be understood?

Body:
(>>=) is the bind operator. It has signature:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

So it expects (on the left side) a monadic object (for instance IO Int), and on the right side a function a -> m b (for instance Int -> IO b) here.

The operator is used to chain operations in a monad together. For instance putStrLn :: String -> IO () can be used if we use it like:

return "foo" >>= putStrLn

So now we return a string "foo". The bind operator will unwrap it out of the IO monad so to speak, and pass it to the putStrLn function that will print "foo" to the standard output channel, and return an IO (). We can then use that IO () for further processing.

Since return wraps data into a monad, writing >>= return is basically useless. Since for all x x >>= return should be equal to x.

The argument of return is not missing in the sense that >>= will call the return with an argument. You can also write:

m >>= (\x -> return x)

but this is equivalent to m >>= return.


问:
How do I Parse the google result to just get the names, latitudes and longitudes in a readable format?
Please help,

I am running a query to find all the bars within a radius of a particular location. The code works to produce this result.
However, this result is too difficult to actually get any information from.
I need the geometry (lat and long) for each result and preferably the name too. I'd like this information to be automatically populated in a new dataframe, but even printing it would be perfect right now.

```<code>import googlemaps
from datetime import datetime
from googlemaps import convert

gmaps = googlemaps.Client(key='my_api_key_is_here')

query = 'bar'
location = (54.584520, -5.935232)
radius = 500

local = gmaps.places('bar', location = location, radius = radius)

#This is what I attempted
#print local['local']['results'][0]['titleNoFormatting']

print local
.... {u'results': {u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....} }
</code>```

When I print it, it looks like the below image. How do I access the particular lat and long for each bar?

How do I access the following:

```<code>{u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....}
</code>```

I'm very new to python so any extremely obvious help is appreciated!

答:
You would need to iterate over the results.

You can access the geometry values by doing: bar["geometry"] and so forth.

```<code>local = gmaps.places('bar', location=location, radius=radius)
for bar in local['results']:
    loc = bar['geometry']['location']
    print(
        '{} ({}, {})'
        .format(bar['name'], loc['lon'], loc['lat'])
    )
</code>```

You can read more about python dictionaries here: https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Body:
Please help,

I am running a query to find all the bars within a radius of a particular location. The code works to produce this result.
However, this result is too difficult to actually get any information from.
I need the geometry (lat and long) for each result and preferably the name too. I'd like this information to be automatically populated in a new dataframe, but even printing it would be perfect right now.

import googlemaps
from datetime import datetime
from googlemaps import convert

gmaps = googlemaps.Client(key='my_api_key_is_here')

query = 'bar'
location = (54.584520, -5.935232)
radius = 500

local = gmaps.places('bar', location = location, radius = radius)

#This is what I attempted
#print local['local']['results'][0]['titleNoFormatting']

print local
.... {u'results': {u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....} }

When I print it, it looks like the below image. How do I access the particular lat and long for each bar?

How do I access the following:

{u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....}

I'm very new to python so any extremely obvious help is appreciated!

Body:
You would need to iterate over the results.

You can access the geometry values by doing: bar["geometry"] and so forth.

local = gmaps.places('bar', location=location, radius=radius)
for bar in local['results']:
    loc = bar['geometry']['location']
    print(
        '{} ({}, {})'
        .format(bar['name'], loc['lon'], loc['lat'])
    )

You can read more about python dictionaries here: https://docs.python.org/2/tutorial/datastructures.html#dictionaries


问:
Firefox - Unnecessary x-scrollbar
An unwanted x-scrollbar appears in Firefox.

Even if disable it by overflow-x: hidden; the width is wrong (strings stay hidden).

```<code>.wrapper {
  position: absolute;
}
.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow: auto;
}
.left > div {
  white-space: nowrap;
  padding-left: 20px;
}
</code>```

Chrome:

Firefox:

Any suggestions why?

jsfiddle to play with code: https://jsfiddle.net/5yqkoujm/

答:
Try this code:

```<code>.wrapper {
    position: absolute;
}
.left {
    max-height: 250px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 20px;  //this fixes scrollbar covering content
}
.left > div {
    white-space: nowrap;
    padding-left: 20px;
}
</code>```

EDIT: For mozilla browser:

```<code>.wrapper {
    position: absolute;
}
.left {
    height: 150px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
}
@-moz-document url-prefix() {
.left {
    height: 150px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 20px;  //this fixes scrollbar covering content
}
}
.left > div {
    white-space: nowrap;
    padding-left: 20px;
}
</code>```

Title: Firefox - Unnecessary x-scrollbar

Body:
An unwanted x-scrollbar appears in Firefox.

Even if disable it by overflow-x: hidden; the width is wrong (strings stay hidden).

.wrapper {
  position: absolute;
}
.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow: auto;
}
.left > div {
  white-space: nowrap;
  padding-left: 20px;
}

Chrome:

Firefox:

Any suggestions why?

jsfiddle to play with code: https://jsfiddle.net/5yqkoujm/

Body:
Try this code:

.wrapper {
    position: absolute;
}
.left {
    max-height: 250px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 20px;  //this fixes scrollbar covering content
}
.left > div {
    white-space: nowrap;
    padding-left: 20px;
}

EDIT: For mozilla browser:

.wrapper {
    position: absolute;
}
.left {
    height: 150px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
}
@-moz-document url-prefix() {
.left {
    height: 150px;
    display: inline-block;
    position: relative;
    min-width: auto;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 20px;  //this fixes scrollbar covering content
}
}
.left > div {
    white-space: nowrap;
    padding-left: 20px;
}


问:
How to get the first numbers in a SQL string
I need to get the first number(s) in a string:

1-2-3 --> 1

45-6  --> 45

777 8 --> 777

9ab10 --> 9

How can I do that with SQL?

答:
You could also use of substring() with patindex() function in order to get first numeric values

```<code>SELECT SUBSTRING(DATA, 1, PATINDEX('%[^0-9]%', DATA)-1) FROM <table_name>
</code>```

Result :

```<code>1
45
777
9
</code>```

Body:
You could also use of substring() with patindex() function in order to get first numeric values

SELECT SUBSTRING(DATA, 1, PATINDEX('%[^0-9]%', DATA)-1) FROM <table_name>

Result :

1
45
777
9


问:
C# - List of Database connectionsStrings Provider
Im trying to develop a dotnet application with multiple database providers and i need to know the ConnectionString and Provider of the most used databases. Im i using System.DBCommon. This is my code:

```<code>public  class DBConnector
{

  public void ConectDatabase()
  {
      {
          string connectionString =
            "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" +
            "(HOST=MYHOST)(PORT=1527))(CONNECT_DATA=(SID=MYSERVICE)));" +
            "User Id=MYUSER;Password=MYPASS;"; //Connection String
          string provider =
            "Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess"; //I need this  for the most used databases (Mysql, PostgreSQL, SqlServer)

          using (DbConnection conn = (DbConnection)Activator.
            CreateInstance(Type.GetType(provider), connectionString))
          {
              conn.Open();
              string sql =
                "select distinct owner from sys.all_objects order by owner";
              using (DbCommand comm = conn.CreateCommand())
              {
                  comm.CommandText = sql;
                  using (DbDataReader rdr = comm.ExecuteReader())
                  {
                      while (rdr.Read())
                      {
                          string owner = rdr.GetString(0);
                          Console.WriteLine("{0}", owner);
                      }
                  }
              }
          }
      }
  }
</code>```

I found the connectionstrings in this site
https://www.connectionstrings.com/

But i need the provider too.
Thanks

答:
You can list the registered db providers like this:

```<code>using System;
using System.Data;
using System.Data.Common;

namespace StackOverflowExamples
{
    class AvailableDataProviders
    {
        public static void Main(string[] args)
        {
            using (DataTable providers = DbProviderFactories.GetFactoryClasses())
            {
                Console.WriteLine("Available Data Providers:");

                foreach (DataRow provider in providers.Rows)
                {
                    Console.WriteLine();
                    Console.WriteLine("Name: {0}", provider["Name"]);
                    Console.WriteLine("Description: {0}", provider["Description"]);
                    Console.WriteLine("Invariant Name: {0}", provider["InvariantName"]);
                    Console.WriteLine("AssemblyQualifiedName: {0}", provider["AssemblyQualifiedName"]);
                }
            }
        }
    }
}
</code>```

There can be provider classes in your application's assemblies that are not registered by your application (in app.config or web.config) or by your machine (in machine.config) or by framework.

Your application can only use the providers that are registered in system.data -> DbProviderFactories of your application config.

Body:
Im trying to develop a dotnet application with multiple database providers and i need to know the ConnectionString and Provider of the most used databases. Im i using System.DBCommon. This is my code:

public  class DBConnector
{

  public void ConectDatabase()
  {
      {
          string connectionString =
            "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" +
            "(HOST=MYHOST)(PORT=1527))(CONNECT_DATA=(SID=MYSERVICE)));" +
            "User Id=MYUSER;Password=MYPASS;"; //Connection String
          string provider =
            "Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess"; //I need this  for the most used databases (Mysql, PostgreSQL, SqlServer)

          using (DbConnection conn = (DbConnection)Activator.
            CreateInstance(Type.GetType(provider), connectionString))
          {
              conn.Open();
              string sql =
                "select distinct owner from sys.all_objects order by owner";
              using (DbCommand comm = conn.CreateCommand())
              {
                  comm.CommandText = sql;
                  using (DbDataReader rdr = comm.ExecuteReader())
                  {
                      while (rdr.Read())
                      {
                          string owner = rdr.GetString(0);
                          Console.WriteLine("{0}", owner);
                      }
                  }
              }
          }
      }
  }

I found the connectionstrings in this site
https://www.connectionstrings.com/

But i need the provider too.
Thanks

Body:
You can list the registered db providers like this:

using System;
using System.Data;
using System.Data.Common;

namespace StackOverflowExamples
{
    class AvailableDataProviders
    {
        public static void Main(string[] args)
        {
            using (DataTable providers = DbProviderFactories.GetFactoryClasses())
            {
                Console.WriteLine("Available Data Providers:");

                foreach (DataRow provider in providers.Rows)
                {
                    Console.WriteLine();
                    Console.WriteLine("Name: {0}", provider["Name"]);
                    Console.WriteLine("Description: {0}", provider["Description"]);
                    Console.WriteLine("Invariant Name: {0}", provider["InvariantName"]);
                    Console.WriteLine("AssemblyQualifiedName: {0}", provider["AssemblyQualifiedName"]);
                }
            }
        }
    }
}

There can be provider classes in your application's assemblies that are not registered by your application (in app.config or web.config) or by your machine (in machine.config) or by framework.

Your application can only use the providers that are registered in system.data -> DbProviderFactories of your application config.


问:
Checking if checkboxes are checked ornot, returns addEventListener is not a function
Hi I got the following code snippet where im trying to print a console.log dependent on if a checkbox has been checked or not.

```<code>var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');

checkbox.addEventListener("change", function() {

    var isChecked = checkbox.checked;
    if(isChecked){ //checked
        console.log('checked');
    }else{ //unchecked
        console.log('unchecked');
    }
});
</code>```

I keep getting the following error:

Uncaught TypeError: checkbox.addEventListener is not a function and a cant figure out why this is happening.

答:
You're getting the error since querySelectorAll() return a array of elements and you're trying to attach the event to this array, else you should loop through it to attach the change event to every element inside, like :

```<code>//Loop through the array elements and attach the event
for (var i = 0; i < checkbox.length; i++) {
  checkbox[i].addEventListener("change", checkedOrNot);
}

//Define separate function
function checkedOrNot() {
  var isChecked = this.checked;

  if (isChecked) { //checked
    console.log('checked');
  } else { //unchecked
    console.log('unchecked');
  }
}
</code>```

Hoep this helps.

var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');

for (var i = 0; i < checkbox.length; i++) {
  checkbox[i].addEventListener("change", checkedOrNot);
}

function checkedOrNot() {
  var isChecked = this.checked;

  if (isChecked) { //checked
    console.log('checked');
  } else { //unchecked
    console.log('unchecked');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="customer-club-widget__gender__categories">
  <input type="checkbox" class="form__input-checkbox" /> A
  <br>
  <input type="checkbox" class="form__input-checkbox" /> B
  <br>
  <input type="checkbox" class="form__input-checkbox" /> C
  <br>
  <input type="checkbox" class="form__input-checkbox" /> D
</div></code>```

Body:
Hi I got the following code snippet where im trying to print a console.log dependent on if a checkbox has been checked or not.

var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');

checkbox.addEventListener("change", function() {

    var isChecked = checkbox.checked;
    if(isChecked){ //checked
        console.log('checked');
    }else{ //unchecked
        console.log('unchecked');
    }
});

I keep getting the following error:

Uncaught TypeError: checkbox.addEventListener is not a function and a cant figure out why this is happening.

Body:
You're getting the error since querySelectorAll() return a array of elements and you're trying to attach the event to this array, else you should loop through it to attach the change event to every element inside, like :

//Loop through the array elements and attach the event
for (var i = 0; i < checkbox.length; i++) {
  checkbox[i].addEventListener("change", checkedOrNot);
}

//Define separate function
function checkedOrNot() {
  var isChecked = this.checked;

  if (isChecked) { //checked
    console.log('checked');
  } else { //unchecked
    console.log('unchecked');
  }
}

Hoep this helps.

var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');

for (var i = 0; i < checkbox.length; i++) {
  checkbox[i].addEventListener("change", checkedOrNot);
}

function checkedOrNot() {
  var isChecked = this.checked;

  if (isChecked) { //checked
    console.log('checked');
  } else { //unchecked
    console.log('unchecked');
  }
}

<div class="customer-club-widget__gender__categories">
  <input type="checkbox" class="form__input-checkbox" /> A
  <br>
  <input type="checkbox" class="form__input-checkbox" /> B
  <br>
  <input type="checkbox" class="form__input-checkbox" /> C
  <br>
  <input type="checkbox" class="form__input-checkbox" /> D
</div>


问:
How to launch MobileIron Docs@Work app from another iOS app?
I am trying to figure out the URL name for MobileIron Docsb@Work in order to launch it from another app. For most apps you can type in "appname://" and it will prompt to launch the application</p>

答: MobileIron iOS Docs@Work does not expose any URLScheme for third party apps to launch it.</p>


问:
blackberry java maps
my program didnt showing the map. when i invoke the Blackberry maps, then its showing a pin mark with white background. its not showing the map, its only showing the locations as pin points. how i get the map ?</p>

答:
I think the problem is in the connection,
also make sure the location is supported: http://devblog.blackberry.com/2010/11/blackberry-maps-revamped/</p>

Title: blackberry java maps


问:
How to count distinct values that all satisfy a condition in MySQL?
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

```<code>RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111
</code>```

Desired Result:

```<code>Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1
</code>```

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

答:
I assume you have 2 tables as below

```<code>CREATE TABLE table1 (RowId INT PRIMARY KEY, MemberIdentifier VARCHAR(255));
INSERT INTO table1 (RowId, MemberIdentifier)
VALUES
(1,'111111111'), (2, '123456789'), (3, '146782452'), (4, '111111111'),(5,'123456789'), (6,'146782452'), (7,'111111111');

CREATE TABLE table2 (RowId INT PRIMARY KEY, Status VARCHAR(255));
INSERT INTO table2 (RowId, Status)
VALUES
(1,'In Progress'), (2,'Complete'   ), (3,'Not Started'), (4,'Complete'   ), (5,'Complete'   ), (6,'Not Started'), (7,'Complete'   );
</code>```

Assuming you don't have millions of records in these tables, you can use the query below to achieve what you want.

```<code>SELECT CASE WHEN not_started.Status = 'Not Started'
            THEN 'Not Started'
            WHEN in_progress.Status = 'In Progress'
            THEN 'In Progress'
            WHEN complete.Status = 'Complete'
            THEN 'Complete'
       END AS over_all_status,
       COUNT(*) AS MemberIdentifierCount
  FROM  (SELECT DISTINCT t1.MemberIdentifier
          FROM table1 t1) main
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'In Progress') in_progress
            ON (main.MemberIdentifier = in_progress.MemberIdentifier)
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'Not Started') not_started
        ON (main.MemberIdentifier = not_started.MemberIdentifier)
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'Complete') complete
        ON (main.MemberIdentifier = complete.MemberIdentifier)
GROUP BY over_all_status;
</code>```

Basically the query creates one record per MemberIdentifier containing all three statuses possible. It then groups the result based on the overall status and outputs the count.

Output from the query is

Body:
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111

Desired Result:

Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

Body:
I assume you have 2 tables as below

CREATE TABLE table1 (RowId INT PRIMARY KEY, MemberIdentifier VARCHAR(255));
INSERT INTO table1 (RowId, MemberIdentifier)
VALUES
(1,'111111111'), (2, '123456789'), (3, '146782452'), (4, '111111111'),(5,'123456789'), (6,'146782452'), (7,'111111111');

CREATE TABLE table2 (RowId INT PRIMARY KEY, Status VARCHAR(255));
INSERT INTO table2 (RowId, Status)
VALUES
(1,'In Progress'), (2,'Complete'   ), (3,'Not Started'), (4,'Complete'   ), (5,'Complete'   ), (6,'Not Started'), (7,'Complete'   );

Assuming you don't have millions of records in these tables, you can use the query below to achieve what you want.

SELECT CASE WHEN not_started.Status = 'Not Started'
            THEN 'Not Started'
            WHEN in_progress.Status = 'In Progress'
            THEN 'In Progress'
            WHEN complete.Status = 'Complete'
            THEN 'Complete'
       END AS over_all_status,
       COUNT(*) AS MemberIdentifierCount
  FROM  (SELECT DISTINCT t1.MemberIdentifier
          FROM table1 t1) main
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'In Progress') in_progress
            ON (main.MemberIdentifier = in_progress.MemberIdentifier)
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'Not Started') not_started
        ON (main.MemberIdentifier = not_started.MemberIdentifier)
        LEFT OUTER JOIN
            (SELECT DISTINCT t1.MemberIdentifier, t2.Status
              FROM table1 t1,
                   table2 t2
             WHERE t1.RowId = t2.RowId
               AND t2.Status = 'Complete') complete
        ON (main.MemberIdentifier = complete.MemberIdentifier)
GROUP BY over_all_status;

Basically the query creates one record per MemberIdentifier containing all three statuses possible. It then groups the result based on the overall status and outputs the count.

Output from the query is


问:
Bootstrap : input-group and select height
Why input-group with select don't have simular render of input ?

I want select height relative of input-group.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

  <input type="text" class="form-control">

    <button type="submit" class="btn btn-info">

    </button>

  <select class="form-control">
    <option>
      Option 1
    </option>
  </select>

    <button type="submit" class="btn btn-info">

    </button>

```

Thanks you very much :)

答:
Just edit one line in your form stylesheet as below

select.form-control:not([size]):not([multiple]) {
    height: auto!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="input-group">
  <input type="text" class="form-control">
  <span class="input-group-addon">
    <button type="submit" class="btn btn-info">
      <i class="fa fa-3x fa-search" aria-hidden="true"></i>
    </button>
  </span>
</div>

<br>

<div class="input-group">
  <select class="form-control">
    <option>
      Option 1
    </option>
  </select>
  <span class="input-group-addon">
    <button type="submit" class="btn btn-info">
      <i class="fa fa-3x fa-search" aria-hidden="true"></i>
    </button>
  </span>
</div></code>```

Body:
Why input-group with select don't have simular render of input ?

I want select height relative of input-group.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

  <input type="text" class="form-control">

    <button type="submit" class="btn btn-info">

    </button>

  <select class="form-control">
    <option>
      Option 1
    </option>
  </select>

    <button type="submit" class="btn btn-info">

    </button>

Thanks you very much :)

Body:
Just edit one line in your form stylesheet as below

select.form-control:not([size]):not([multiple]) {
    height: auto!important;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="input-group">
  <input type="text" class="form-control">
  <span class="input-group-addon">
    <button type="submit" class="btn btn-info">
      <i class="fa fa-3x fa-search" aria-hidden="true"></i>
    </button>
  </span>
</div>

<br>

<div class="input-group">
  <select class="form-control">
    <option>
      Option 1
    </option>
  </select>
  <span class="input-group-addon">
    <button type="submit" class="btn btn-info">
      <i class="fa fa-3x fa-search" aria-hidden="true"></i>
    </button>
  </span>
</div>


问:
How to connect mysql2 to Ruby on Rails?
I am trying to work on a RoR project, I have created the project called tester to check my db connection, command which I had used is 'rails new tester -d mysql'
my gemfile has mysql2 gem included
I have installed mysql and workbench, and my database.yml looks like this:

```<code>default: &default
adapter: mysql2
encoding: utf8
pool: <%=ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: password
host: localhost
socket: MySQL

development:   <<: *default
database: tester_development

test:   <<:*default
database: tester_test

production:   <<: *default
database: tester_production
username: tester
password: <%=ENV['TESTER_DATABASE_PASSWORD'] %>
</code>```

And my cmd error is following:

```<code>C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2/mysql2.rb:2:in `require': cannot load such file -- mysql2/2.4/mysql2 (LoadError)
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2/mysql2.rb:2:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2.rb:31:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2.rb:31:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:in `block (2 levels) in require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in `each'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in `block in require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in `each'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler.rb:114:in `require'
        from C:/Users/donki/Desktop/testing/tester/config/application.rb:7:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `block in perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `tap'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'
</code>```

Sorry for the long post. I really do not understand what the error is. The error occurs when I try to run rails server.
Help would be appreciated.

答:
It's seems like you are using windows and ruby 2.4

but I think mysql2 library not support ruby 2.4 in windows till now,

So, It would be better to use ruby 2.3 instead of ruby2.4

Hope it will help you.

reference

Title: How to connect mysql2 to Ruby on Rails?

Body:
I am trying to work on a RoR project, I have created the project called tester to check my db connection, command which I had used is 'rails new tester -d mysql'
my gemfile has mysql2 gem included
I have installed mysql and workbench, and my database.yml looks like this:

default: &default
adapter: mysql2
encoding: utf8
pool: <%=ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: password
host: localhost
socket: MySQL

development:   <<: *default
database: tester_development

test:   <<:*default
database: tester_test

production:   <<: *default
database: tester_production
username: tester
password: <%=ENV['TESTER_DATABASE_PASSWORD'] %>

And my cmd error is following:

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2/mysql2.rb:2:in `require': cannot load such file -- mysql2/2.4/mysql2 (LoadError)
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2/mysql2.rb:2:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2.rb:31:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9-x64-mingw32/lib/mysql2.rb:31:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:in `block (2 levels) in require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in `each'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in `block in require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in `each'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/lib/bundler.rb:114:in `require'
        from C:/Users/donki/Desktop/testing/tester/config/application.rb:7:in `<top (required)>'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `require'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `block in perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `tap'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `'

Sorry for the long post. I really do not understand what the error is. The error occurs when I try to run rails server.
Help would be appreciated.


问:
Exceptions not showing when an error occurred laravel

Error are not showing in the app.following are my config/app.php settings

'env' => env('APP_ENV', 'development'),

'debug' => env('APP_DEBUG', true),

I have tried clearing config cache clear and optimize command
.env file

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Pq/tS8K9qPwxyqPUz+efLhxhteuH1sgUuA/rPcG0msc=
APP_DEBUG=false
APP_LOG_LEVEL=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lar_potal
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
</code>```

答:
You need to put APP_DEBUG=true and APP_LOG_LEVEL=debug in .env file at the root of laravel.

The .env file you should have :

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Pq/tS8K9qPwxyqPUz+efLhxhteuH1sgUuA/rPcG0msc=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lar_potal
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
</code>```

Body:
Error are not showing in the app.following are my config/app.php settings

'env' => env('APP_ENV', 'development'),

'debug' => env('APP_DEBUG', true),

I have tried clearing config cache clear and optimize command
.env file

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Pq/tS8K9qPwxyqPUz+efLhxhteuH1sgUuA/rPcG0msc=
APP_DEBUG=false
APP_LOG_LEVEL=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lar_potal
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

Body:
You need to put APP_DEBUG=true and APP_LOG_LEVEL=debug in .env file at the root of laravel.

The .env file you should have :

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Pq/tS8K9qPwxyqPUz+efLhxhteuH1sgUuA/rPcG0msc=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lar_potal
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=