问:
Create a method called filter that has two string parameters and returns a string
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

```<code>public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}
</code>```

Output of the code

```<code> CS221 is
 my is a nice
 b

 b
 at
 dar
 us
</code>```

Expected output

```<code> CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user
</code>```

答:
This works perfectly fine.</p>

```<code>     public static void main(String[] args){        // should filter out the
     System.out.println("method: filter");       // second string
     System.out.println(filter( "CS221 is terrible", "terrible"));
     System.out.println(filter( "my cat is a nice cat", "cat"));
     System.out.println(filter( "ababababa","ab"));
     System.out.println(filter( "not here", "a"));
     System.out.println(filter( "abababab","ab"));
     System.out.println(filter( "CATcatCAT","CAT"));
     System.out.println(filter( "dark","k"));
     System.out.println(filter("ususerer", "user"));
     }
  public static String filter ( String str, String filter)
  {
     String temp = "";
     int i = 0;
     if(str.indexOf(filter,i) == -1)
     {
        return temp;
     }
   else
   {
       return str.replace(filter,"");
    }

    }
</code>```

Body:
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}

Output of the code

 CS221 is
 my is a nice
 b

 b
 at
 dar
 us

Expected output

 CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user

Body:
This works perfectly fine.

     public static void main(String[] args){        // should filter out the
     System.out.println("method: filter");       // second string
     System.out.println(filter( "CS221 is terrible", "terrible"));
     System.out.println(filter( "my cat is a nice cat", "cat"));
     System.out.println(filter( "ababababa","ab"));
     System.out.println(filter( "not here", "a"));
     System.out.println(filter( "abababab","ab"));
     System.out.println(filter( "CATcatCAT","CAT"));
     System.out.println(filter( "dark","k"));
     System.out.println(filter("ususerer", "user"));
     }
  public static String filter ( String str, String filter)
  {
     String temp = "";
     int i = 0;
     if(str.indexOf(filter,i) == -1)
     {
        return temp;
     }
   else
   {
       return str.replace(filter,"");
    }

    }


来源: stackexchange

问:
Fetch array value - JQuery
Consider that i have the following html

```<code><input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
</code>```

To fetch the values i use

```<code>a = $('#other_floor_plans').val()
</code>```

It returns the following

```<code>"["Pool","Office","Sprinkler","Boiler"]"
</code>```

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?

答:
There you doing a wrong practice when you initialize value in input box you must contain a value in different quotation symbols.
there you take " for value assign and " also for array string, that truncate your string on the second " that's why this return only [ in your value.
Try to use like this:

HTML

```<code><input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
</code>```

JQuery

```<code>var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fetch array value - JQuery

Body:
Consider that i have the following html

<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">

To fetch the values i use

a = $('#other_floor_plans').val()

It returns the following

"["Pool","Office","Sprinkler","Boiler"]"

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?

Body:
There you doing a wrong practice when you initialize value in input box you must contain a value in different quotation symbols.
there you take " for value assign and " also for array string, that truncate your string on the second " that's why this return only [ in your value.
Try to use like this:

HTML

<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>

JQuery

var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
Simple approach:

```<code>print (name for name in ('bob', 'fred') if name == 'bob').next()
</code>```

If you really want an error when there is more than one value, then you need a function. The most simple I can think of is (EDITED to work with lists too):

```<code>def one(iterable):
    it = iter(iterable)
    val = it.next()
    try:
        it.next()
    except StopIteration:
        return val
    else:
        raise Exception('More than one value')
</code>```

OwnerDisplayName: GHZ

ContentLicense: CC BY-SA 2.5

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
Simple approach:

print (name for name in ('bob', 'fred') if name == 'bob').next()

If you really want an error when there is more than one value, then you need a function. The most simple I can think of is (EDITED to work with lists too):

def one(iterable):
    it = iter(iterable)
    val = it.next()
    try:
        it.next()
    except StopIteration:
        return val
    else:
        raise Exception('More than one value')

OwnerDisplayName: nosklo


问:
SSL Connections with ADODB
I have a project we are about to wrap up, but just got a request from the DBA to make all our connections SSL.  So I switched the driver to mysqli in the object that turns out ADODB instances, but I don't see any native method to create secure connections.

To make things more difficult, there is a different set of certs and keys per connection type (read and write).

Anyone have any ideas?

答:
I prefer the one with the Connect method, and clientFlags property.

```<code>$dbc = NewADOConnection('mysqli');
$dbc->clientFlags = CLIENT_SSL;
$this->dbc->Connect('dbhost', 'ssluser', 'sslpass', 'test');
</code>```

Either of them would work.

Title: SSL Connections with ADODB

Body:
I prefer the one with the Connect method, and clientFlags property.

$dbc = NewADOConnection('mysqli');
$dbc->clientFlags = CLIENT_SSL;
$this->dbc->Connect('dbhost', 'ssluser', 'sslpass', 'test');

Either of them would work.


问:
How to increase font size in Windows CE
I'm trying to develop a simple clock program for a Windows CE 5.0 device in my car, using Visual Studio 2008 professional and C#. I had to use .NET 2.0 since 3.5 doesn't work. The clock program was made as a Form application. It consists of a simple label and a timer, that's it. The clock program works on the device, but I only get a standard font and font-size, no matter what font and size I choose in the label properties in Visual Studio. On my computer the program works fine with several fonts and large font sizes. I can not add anything in the Windows/Font directory on my device since it will be erased after every shut down. It is clear the windows CE version is a totally simplified version with nearly no functions. I guess I have to add the font size in a different way in the program file. How can I do this?</p>

答:
You can call AddFontResource during your application startup to add additional fonts to the system ones:
https://msdn.microsoft.com/en-us/library/ee489896(v=winembedded.60).aspx
You can use pinvoke.net (http://www.pinvoke.net/) to find the right declaration to use to import this API in your managed code application.</p>

Title: How to increase font size in Windows CE


问:
ng test fail after adding 'ng2-dateime '
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

```<code>'Cannot find name 'jQuery'
'Cannot find name '$'
</code>```

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

```<code>declare var jQuery: any;
declare var $: any;
</code>```

this will start 'ng test' but it will throw error while making build using ng build --prod.

```<code>Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'
</code>```

TIA

答:
This issue appens when you use a plugin that requires jQuery without declaring the jQuery variable. You can fix it by adding this on top of your component:

```<code>declare jQuery: any;
</code>```

However, using jQuery to accessing your DOM isn't a good practice in Angular projects, and will be annoying when you'll want to implement things like angular universal on your project.

Try with the ngx-bootstrap plugin, which contains a cleaner datepicker :

https://valor-software.com/ngx-bootstrap/#/datepicker

Body:
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

'Cannot find name 'jQuery'
'Cannot find name '$'

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

declare var jQuery: any;
declare var $: any;

this will start 'ng test' but it will throw error while making build using ng build --prod.

Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'

TIA

Body:
This issue appens when you use a plugin that requires jQuery without declaring the jQuery variable. You can fix it by adding this on top of your component:

declare jQuery: any;

However, using jQuery to accessing your DOM isn't a good practice in Angular projects, and will be annoying when you'll want to implement things like angular universal on your project.

Try with the ngx-bootstrap plugin, which contains a cleaner datepicker :

https://valor-software.com/ngx-bootstrap/#/datepicker


问:
What is the exact algorithm for Objective-C's built-in rand() function?
If you have a client/server application and you want to duplicate the same series of random numbers that the rand() function produces on the client, but on a server, what is the algorithm/pseudo code?  The client and server would be given the same seed (srand() on the client).

Thank you!

Please note:

Is this not known?  If so, please state

Can it be reverse engineered?  If so, please post, unless any license agreements would prevent you from doing so.  In other words, don't do anything illegal

I am not interested in design suggestions for the client/server application

I understand that there are better and more recent ways to generate rand numbers

答: From Apple's Darwin source code, here is the Mac implementation of rand(), which should be the same as the one used on iOS.  Here also is the random() implementation.  They both appear to be drawn from FreeBSD.


问:
Can a timer goes faster than 1ms Android
I want to sample sound from an analog device and I use a timer. However, with Android API timer you can set the wait and delay in milliseconds. For example

```<code>schedule(TimerTask task, Date firstTime, long period)//period in milliseconds
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
</code>```

It means that I cannot go faster than 1ms (i.e., 1kHz).

Is that true?

答: It is True. It's a System defined time period.</p>

Body:
I want to sample sound from an analog device and I use a timer. However, with Android API timer you can set the wait and delay in milliseconds. For example

schedule(TimerTask task, Date firstTime, long period)//period in milliseconds
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

It means that I cannot go faster than 1ms (i.e., 1kHz).

Is that true?


问:
Kendo UI Jquery vs Kendo UI Angular
Require the comparison information about the KENDO UI JQUERY versus Kendo UI Angular? Currently using Kendo UI Jquery planning to migrate it on KENDO UI Angular.</p>

答:
You can use KENDO UI Angular because it has almost all jQuery components and in Angular you can easily integrate them.

I have used them in Angular 4 project. Easy to integrate and easy to use with good performance.

More Info : https://www.telerik.com/kendo-angular-ui/

Components : https://www.telerik.com/kendo-angular-ui/components/

Title: Kendo UI Jquery vs Kendo UI Angular


问:
Passing LocalStorage value to a drop down title
I'm trying to pass the localStorage value user_id as a title of Bootstrap drop down list, But not sure why its not working.

I'm trying to show user's name as a heading/title of drop down list items with the help of localStorage, whatever input user gives in 'user_id' should be used as heading/title of drop down list.

function validateLogin() {
  var profile_name = document.getElementById('user_id').value();
  localStorage.setItem("userID", profile_name);
  document.getElementById('profile-ddl').value = localStorage.getItem('userID');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div>
  <input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder="User Name" />
</div>

<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="Submit" onsubmit="return validateLogin()" />

<li class="dropdown">
   <span class="caret"></span>
  <ul class="dropdown-menu">
    <li>Profile</li>
    <li>Setting</li>
    <hr/>
    <li class="disabled">Manage Account</li>
    <li class="disabled">Ledger Account</li>
  </ul>
</li></code>```

答: You dont have value attribute on a tags, instead you can use element.innerHTML.</p>

Body:
I'm trying to pass the localStorage value user_id as a title of Bootstrap drop down list, But not sure why its not working.

I'm trying to show user's name as a heading/title of drop down list items with the help of localStorage, whatever input user gives in 'user_id' should be used as heading/title of drop down list.

function validateLogin() {
  var profile_name = document.getElementById('user_id').value();
  localStorage.setItem("userID", profile_name);
  document.getElementById('profile-ddl').value = localStorage.getItem('userID');
}

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

  <input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder="User Name" />

<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="Submit" onsubmit="return validateLogin()" />

Profile

Setting

Manage Account

Ledger Account


问:
Serving React build with Express shows nothing
I have this project structure:

app

server.js

frontend

build

index.html

build directory is the result after npm run build in my React app (created with create-react-app). There are more files but I omit them for the example.

I want to serve the React app as static files, so in server.js, I have this:

```<code>app.use(express.static(path.resolve(__dirname, 'frontend/build')));
app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'frontend/build', 'index.html'));
});
app.listen(9001);
</code>```

I navigate to http://localhost:9001 in my browser and there are no errors but the screen is blank. React app is not shown.

If I run the React app (from inside frontend directory) with npm start, it works properly (in default webpack port 3000).

This is the build/index.html file (pretty printed):

```<code><!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">

  <meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json">
  <link rel="shortcut icon" href="/favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"/>

  <title>React App</title><link href="/static/css/main.65027555.css" rel="stylesheet"></head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript" src="/static/js/main.a4d4d402.js"></script>
  </body>

</html>
</code>```

If I navigate to http://localhost:9001/static/js/main.a4d4d402.js, I can see the javascript file.

答: I found the error. There was an error in the bootstrap imports in index.html. I was closing a  tag twice. In my question looks well because I have pretty printed by hand and maybe I have corrected it somehow.

Body:
I have this project structure:

app

server.js

frontend

build

index.html

build directory is the result after npm run build in my React app (created with create-react-app). There are more files but I omit them for the example.

I want to serve the React app as static files, so in server.js, I have this:

app.use(express.static(path.resolve(__dirname, 'frontend/build')));
app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'frontend/build', 'index.html'));
});
app.listen(9001);

I navigate to http://localhost:9001 in my browser and there are no errors but the screen is blank. React app is not shown.

If I run the React app (from inside frontend directory) with npm start, it works properly (in default webpack port 3000).

This is the build/index.html file (pretty printed):

<!DOCTYPE html>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">

  <meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json">
  <link rel="shortcut icon" href="/favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

If I navigate to http://localhost:9001/static/js/main.a4d4d402.js, I can see the javascript file.


问:
JDK 8 javadoc @propertyGetter,@propertySetter and @propertyDescription warnings
JDK8 Javadoc give me lots of the following warning messages:

```<code>warning - Tags @propertyGetter, @propertySetter and @propertyDescription
can only be used in JavaFX properties getters and setters.
</code>```

source code does not use any of these tags.

Where do the messages come from?

JDK 7 works fine without these warnings.

答:
There is a closed OpenJDK bug report for that exact error message, stating that it arose on Linux using Java 8u131 when running javadoc for a class with a method like this:

```<code>public boolean isProperty() {
    return false;
}
</code>```

The user also reported (like you) that this was not an issue with Java 7. That bug was closed since the error could not be reproduced. I also tried to reproduce the problem using 8u152 on Windows 10, but everything worked fine.

However, an open and related bug report was then created by the user, suggesting that the issue was related to an Ubuntu build of 8u131.

I'm guessing that this is no longer an issue for you, but if it is:

If you still have the problem, can you reproduce it by running javadoc against the trivial class detailed in that original bug report?

What version of Java and what Operating System are you using?

Does your source have any methods named getProperty(), setProperty() or isProperty()?

Body:
JDK8 Javadoc give me lots of the following warning messages:

warning - Tags @propertyGetter, @propertySetter and @propertyDescription
can only be used in JavaFX properties getters and setters.

source code does not use any of these tags.

Where do the messages come from?

JDK 7 works fine without these warnings.

Body:
There is a closed OpenJDK bug report for that exact error message, stating that it arose on Linux using Java 8u131 when running javadoc for a class with a method like this:

public boolean isProperty() {
    return false;
}

The user also reported (like you) that this was not an issue with Java 7. That bug was closed since the error could not be reproduced. I also tried to reproduce the problem using 8u152 on Windows 10, but everything worked fine.

However, an open and related bug report was then created by the user, suggesting that the issue was related to an Ubuntu build of 8u131.

I'm guessing that this is no longer an issue for you, but if it is:

If you still have the problem, can you reproduce it by running javadoc against the trivial class detailed in that original bug report?

What version of Java and what Operating System are you using?

Does your source have any methods named getProperty(), setProperty() or isProperty()?


问:
Selectize not showing data from ajax call
I'm using selectize js to have a search functionality and lets the user select multiple items based on the search. My problem is that the data is being retrieved properly but the data is not being shown by the control. Here's how I'm doing it.

The control:

```<code><label>Skills Required</label>
<select id="skills-ddl"  class="form-control" placeholder="Search skills.." multiple ></select>
</code>```

Js:

```<code>$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});
</code>```

Here's a screenshot the data is there:

When I press backspace to make the search text box empty, the previous result is being displayed.

EDIT:

Here's how my response data looks like:

答:
have not yet worked with selectize, but having a look at the docu I see that the load function should get only the callback function as parameter, no query parameter. Is this the problem?

https://github.com/selectize/selectize.js/blob/master/docs/api.md#methods_other

Regards,
Jochen

Body:
I'm using selectize js to have a search functionality and lets the user select multiple items based on the search. My problem is that the data is being retrieved properly but the data is not being shown by the control. Here's how I'm doing it.

The control:

Skills Required
<select id="skills-ddl"  class="form-control" placeholder="Search skills.." multiple ></select>

Js:

$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});

Here's a screenshot the data is there:

When I press backspace to make the search text box empty, the previous result is being displayed.

EDIT:

Here's how my response data looks like:


问:
Installing pfx SSL certificate in tomcat 8.5 on windows
I have wild card pfx certificate with its Intermediate certificate in p7b/crt format. Those certificate are installed on IIS 8.0. How to install those certificates in tomcat 8.0? Tomcat is installed on windows</p>

答:
I could do it successfully. As I have mentioned that my certificate was installed on IIS web server on windows with intermediate certificate. So I follow below steps

Step 1: Create a Microsoft Management Console (MMC) Snap-in for managing certificates

Access the Search menu. In the search box, type mmc

From the Microsoft Management Console (MMC), click  File > Add/Remove Snap-in

From the list of snap-ins, select Certificates

Click Add

Select Computer Account

Click Next

Select Local Computer (the computer this console is running on)

Click Finish

In the Add/Remove Snap-in window, click OK

Save these console settings for future use

Step 2: Export/ Back Up the certificate

Open the Certificates (Local Computer) snap-in you added > select Personal > Certificates

Right-click certificate name > select All Tasks > Export.

The Certificate Export Wizard opens > click Next

Select Yes, export the private key > click Next

Select Personal Information Exchange

Ensure to check only Include all certificates in the certificate path if possible > click Next

Enter and confirm a password > click Next

Choose a file name and location for the export file > click Next

Click Finish

Step 3:  Configure PKCS12 (.pfx) file on Tomcat server

Open %TOMCAT_HOME/conf/server.xml in XML or text editor

Find the following lines: (In my case, I could not find below lines, So I directly jump to point 4 and add whole tag in my server.xml and change keystorefile and keystorePassword)

Delete the comment markers at the beginning of the code ()

Immediately after sslProtocol="TLS" and before />,  add the following attributes:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile=”/path/to/mycert.pfx” keystoreType=”PKCS12″ keystorePass="your_PKCS12_password" />

Save server.xml

Restart Tomcat

Hope it will help somebody :)

Body:
I could do it successfully. As I have mentioned that my certificate was installed on IIS web server on windows with intermediate certificate. So I follow below steps

Step 1: Create a Microsoft Management Console (MMC) Snap-in for managing certificates

Access the Search menu. In the search box, type mmc

From the Microsoft Management Console (MMC), click  File > Add/Remove Snap-in

From the list of snap-ins, select Certificates

Click Add

Select Computer Account

Click Next

Select Local Computer (the computer this console is running on)

Click Finish

In the Add/Remove Snap-in window, click OK

Save these console settings for future use

Step 2: Export/ Back Up the certificate

Open the Certificates (Local Computer) snap-in you added > select Personal > Certificates

Right-click certificate name > select All Tasks > Export.

The Certificate Export Wizard opens > click Next

Select Yes, export the private key > click Next

Select Personal Information Exchange

Ensure to check only Include all certificates in the certificate path if possible > click Next

Enter and confirm a password > click Next

Choose a file name and location for the export file > click Next

Click Finish

Step 3:  Configure PKCS12 (.pfx) file on Tomcat server

Open %TOMCAT_HOME/conf/server.xml in XML or text editor

Find the following lines: (In my case, I could not find below lines, So I directly jump to point 4 and add whole tag in my server.xml and change keystorefile and keystorePassword)

<!-- <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> -->

Delete the comment markers at the beginning of the code (<!--) and at the end of the code (-->)

Immediately after sslProtocol="TLS" and before />,  add the following attributes:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile=”/path/to/mycert.pfx” keystoreType=”PKCS12″ keystorePass="your_PKCS12_password" />

Save server.xml

Restart Tomcat

Hope it will help somebody :)

ContentLicense: CC BY-SA 4.0


问:
Bootstrap Navbar fixed on top, Container centered vertically
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <nav class="navbar transparent navbar-static-top">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container d-flex h-100">

    <div class="row justify-content-center align-self-center">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body></code>```

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.

答:
From what I notice, you want an element to be centered, but not using all 12 columns, so you can use mx-auto to center an element that has less than 12 columns. You also said

.noMX {
  background-color: red;
}
.withMX {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="noMX col-8">awts</div>
  </div>
</div>

<div class="container">
  <div class="row">
    <div class="withMX col-8 mx-auto">awts</div>
  </div>
</div></code>```

To center it vertically you can try this. First add height: 100% to the body and html, since I noticed you used h-100 meaning you want 100% height on the container. You also need to wrap the panels into another div so that the element that will be centered is the div wrapper rather than the panels. I also removed md in the columns so that you can the result in smaller viewport

html,
body {
  height: 100%;
}

.wrapper {
  background-color: Red;
}

#panel {
  background-color: blue;
}

#panel2 {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />

<nav class="navbar transparent navbar-static-top">
  <div class="navbar-header">
    <p>Welcome</p>
  </div>
</nav>

<div class="wrapper container h-100">
  <div class="row d-flex align-items-center h-100">
    <div class="col-12">
      <div class="row">
        <div class="col-4 mb-4" id="panel">
          <div class="panel panel-default1">
            <div class="panel-body">
              <p>Blablabla</p>
            </div>
          </div>
        </div>
        <div class="col-8" id="panel2">
          <div class="panel panel-default2">
            <div class="panel-body">
              <p>Blablabla</p>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</div></code>```

Body:
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

Welcome

Blablabla

Blablabla

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.

Body:
From what I notice, you want an element to be centered, but not using all 12 columns, so you can use mx-auto to center an element that has less than 12 columns. You also said

.noMX {
  background-color: red;
}
.withMX {
  background-color: green;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="noMX col-8">awts</div>
  </div>
</div>

<div class="container">
  <div class="row">
    <div class="withMX col-8 mx-auto">awts</div>
  </div>
</div>

To center it vertically you can try this. First add height: 100% to the body and html, since I noticed you used h-100 meaning you want 100% height on the container. You also need to wrap the panels into another div so that the element that will be centered is the div wrapper rather than the panels. I also removed md in the columns so that you can the result in smaller viewport

html,
body {
  height: 100%;
}

.wrapper {
  background-color: Red;
}

#panel {
  background-color: blue;
}

#panel2 {
  background-color: green;
}

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

<nav class="navbar transparent navbar-static-top">
  <div class="navbar-header">
    <p>Welcome</p>
  </div>
</nav>

<div class="wrapper container h-100">
  <div class="row d-flex align-items-center h-100">
    <div class="col-12">
      <div class="row">
        <div class="col-4 mb-4" id="panel">
          <div class="panel panel-default1">
            <div class="panel-body">
              <p>Blablabla</p>
            </div>
          </div>
        </div>
        <div class="col-8" id="panel2">
          <div class="panel panel-default2">
            <div class="panel-body">
              <p>Blablabla</p>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>


问:
Unable to use update npm or install any npm module on mac
```<code>npm ERR! Darwin 17.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "-g" "npm"
npm ERR! node v6.9.2
npm ERR! npm  v3.10.9
npm ERR! code MODULE_NOT_FOUND

npm ERR! Cannot find module 'realize-package-specifier'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
</code>```

When I try to update npm this the error I receive. I get similar errors while performing any npm install/update operation.

Any idea how to resolve this issue?

答: I installed node using nvm and my issue was resolved. This is what I followed to do so.

Body:
npm ERR! Darwin 17.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "-g" "npm"
npm ERR! node v6.9.2
npm ERR! npm  v3.10.9
npm ERR! code MODULE_NOT_FOUND

npm ERR! Cannot find module 'realize-package-specifier'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

When I try to update npm this the error I receive. I get similar errors while performing any npm install/update operation.

Any idea how to resolve this issue?


问:
Advance / Increment Sequence in sqlite3
I'm trying to increment a sequence in sqlite3.

Basically, I'm using the sequence as a key into another system, and I have multiple DB's which are generating conflicts.

i.e. I have 2 DB's both creating entries with the same sequence number.  They both create a 15, which I use as a key to another system.

I'd like to advance one of the DB's sequences by, say 10 000, so that I stop getting conflicts.

Disclaimer:  before you start jumping all over me, I know this is not a good design, and it's only being used for early prototyping.  I plan to 'upgrade' to using a UUID generated from the sequence and timestamp as my key in the future.  However, until I'm out of 'demo mode' I just want to fix my problem with a line of SQL if I can.

I've tried update sqlite_sequence set seq = 2000 where name = 'XXXX';  but it doesn't seem to do the trick.  I'm new to sqlite3, maybe it's something else?

答:
This issue seems to be getting a lot of attention, so I thought I would post the actual code I'm using with minimal scrubbing.  This is in my seeds.rb file.</p>

```<code>min_sequence = 1000

case ActiveRecord::Base.connection.adapter_name
when 'SQLite'
  select_current_sequence_number_sql = "select seq from sqlite_sequence where name = 'businesses';"
  set_min_sequence_to_ten_sql = "update sqlite_sequence set seq = #{min_sequence} where name = 'businesses';"
  result = ActiveRecord::Base.connection.execute(select_current_sequence_number_sql)
  result.nil? || result.empty? ? current_sequence_number = 0 : current_sequence_number = result[0]['seq'].to_i
  if current_sequence_number < min_sequence
    ActiveRecord::Base.connection.execute(set_min_sequence_to_ten_sql)
  end
when 'PostgreSQL'
...
else
  raise "Task not implemented for this DB adapter"
end
</code>```

Title: Advance / Increment Sequence in sqlite3

Body:
This issue seems to be getting a lot of attention, so I thought I would post the actual code I'm using with minimal scrubbing.  This is in my seeds.rb file.

min_sequence = 1000

case ActiveRecord::Base.connection.adapter_name
when 'SQLite'
  select_current_sequence_number_sql = "select seq from sqlite_sequence where name = 'businesses';"
  set_min_sequence_to_ten_sql = "update sqlite_sequence set seq = #{min_sequence} where name = 'businesses';"
  result = ActiveRecord::Base.connection.execute(select_current_sequence_number_sql)
  result.nil? || result.empty? ? current_sequence_number = 0 : current_sequence_number = result[0]['seq'].to_i
  if current_sequence_number < min_sequence
    ActiveRecord::Base.connection.execute(set_min_sequence_to_ten_sql)
  end
when 'PostgreSQL'
...
else
  raise "Task not implemented for this DB adapter"
end


问:
Split At @ in excel
BOS@TOR 11/10/2017 07:00PM ET

LA@TB 11/10/2017 07:00PM ET

Above is data I would like to Split at the @ and not get the @ to show up in my columns.
The First is Away and the Second is Home.

```<code>=LEFT(L2,FIND("@",L2)-1)
=RIGHT(L2,FIND("@",L2)*1)
</code>```

It Returns  Home: TOR, Away: BOS. Perfect! Same With LA AND TB. But If its BOS@LA
it will return HOME @LA and ROAD BOS. How can I just remove the @ regardless of the number of Characters?

答:
I think you are confusing what =RIGHT(L2,FIND("@",L2)-1) is doing (I'm assuming you typo-ed on this formula seeing as the one in your question cannot give you the results you mention). FIND("@",L2) gets the position of the first @ in the string, And RIGHT takes the nth characters from the right of the supplied string. You will notice your current formula will only work if the @ is at a position gives a number which is the same length plus one as the part you want to get. i.e. BOS@TOR has @ at 4th position, and TOR is 3 characters long, and LA@TB has @ at 3rd position, and TB is 2 characters long.

Proposed solutions:

Using Formula

```<code>=MID(L2,FIND("@",L2)+1,LEN(L2))
</code>```

MID is a formula similar to LEFT and RIGHT, except it has one additional parameter required; the length of the string. FIND("@",L2)+1 gets the position of the next character after the first @, and the length of the string can be anything at least equal to the length of the string you want to get (if it's larger, it's still fine).

The below is another option that uses SUBSTITUTE, assuming that M2 is where the HOME value is stored:

```<code>=SUBSTITUTE(L2,M2&"@","",1)
</code>```

This instead takes the original text and removes the home value at the accompanying @ sign with a blank. The last parameter indicates that it removes only the first instance of "Home+@" (if you know there can be only one, you can ignore the last parameter completely so that the formula becomes =SUBSTITUTE(L2,M2&"@",""))

Using Text to Column

Select the column, and click the option 'Text to Columns' in the Data tab, pick 'Delimited' and click next:

Uncheck everything, then check the last option 'Other', type @ in the box, then next:

Click on finish:

Note: this method overwrites the original texts, so if you want to keep them, make a copy of the text in a new column first, and split on that column.

Title: Split At @ in excel

Body:
BOS@TOR 11/10/2017 07:00PM ET

LA@TB 11/10/2017 07:00PM ET

Above is data I would like to Split at the @ and not get the @ to show up in my columns.
The First is Away and the Second is Home.

=LEFT(L2,FIND("@",L2)-1)
=RIGHT(L2,FIND("@",L2)*1)

It Returns  Home: TOR, Away: BOS. Perfect! Same With LA AND TB. But If its BOS@LA
it will return HOME @LA and ROAD BOS. How can I just remove the @ regardless of the number of Characters?

Body:
I think you are confusing what =RIGHT(L2,FIND("@",L2)-1) is doing (I'm assuming you typo-ed on this formula seeing as the one in your question cannot give you the results you mention). FIND("@",L2) gets the position of the first @ in the string, And RIGHT takes the nth characters from the right of the supplied string. You will notice your current formula will only work if the @ is at a position gives a number which is the same length plus one as the part you want to get. i.e. BOS@TOR has @ at 4th position, and TOR is 3 characters long, and LA@TB has @ at 3rd position, and TB is 2 characters long.

Proposed solutions:

Using Formula

=MID(L2,FIND("@",L2)+1,LEN(L2))

MID is a formula similar to LEFT and RIGHT, except it has one additional parameter required; the length of the string. FIND("@",L2)+1 gets the position of the next character after the first @, and the length of the string can be anything at least equal to the length of the string you want to get (if it's larger, it's still fine).

The below is another option that uses SUBSTITUTE, assuming that M2 is where the HOME value is stored:

=SUBSTITUTE(L2,M2&"@","",1)

This instead takes the original text and removes the home value at the accompanying @ sign with a blank. The last parameter indicates that it removes only the first instance of "Home+@" (if you know there can be only one, you can ignore the last parameter completely so that the formula becomes =SUBSTITUTE(L2,M2&"@",""))

Using Text to Column

Select the column, and click the option 'Text to Columns' in the Data tab, pick 'Delimited' and click next:

Uncheck everything, then check the last option 'Other', type @ in the box, then next:

Click on finish:

Note: this method overwrites the original texts, so if you want to keep them, make a copy of the text in a new column first, and split on that column.


问:
Action name mistaken as show id
I'm still new to Rails, and so I have this issue.

I have a controller name Client. In the routing I have:

```<code>resources :clients do
   get 'confirmation_import/:page', action: :confirmation_import, on: :collection, :defaults => {:page => 1}
   collection do
     get :autocomplete
     post :confirmation_import
     post :import
   end
end
</code>```

As you can see, I'm using pagination. When I go back to the first page though, the page param is not used, so the link becomes /clients/confirmation_import. From there I'm getting an error because a before_action for show action is being used, and it says my id param is confirmation_import. How do I fix this?

答:
Generally routes are matched from top to bottom and as the route for show action is defined before the route for confirmation_report action it is routing to show action with confirmation_report as id.

So, put your route for confirmation_report before show route as below:

```<code>get 'clients/confirmation_import/:page' => 'clients#confirmation_import, :defaults => {:page => 1}

resources :clients do
  collection do
    get :autocomplete
    post :confirmation_import
    post :import
  end
end
</code>```

Title: Action name mistaken as show id

Body:
I'm still new to Rails, and so I have this issue.

I have a controller name Client. In the routing I have:

resources :clients do
   get 'confirmation_import/:page', action: :confirmation_import, on: :collection, :defaults => {:page => 1}
   collection do
     get :autocomplete
     post :confirmation_import
     post :import
   end
end

As you can see, I'm using pagination. When I go back to the first page though, the page param is not used, so the link becomes /clients/confirmation_import. From there I'm getting an error because a before_action for show action is being used, and it says my id param is confirmation_import. How do I fix this?

Body:
Generally routes are matched from top to bottom and as the route for show action is defined before the route for confirmation_report action it is routing to show action with confirmation_report as id.

So, put your route for confirmation_report before show route as below:

get 'clients/confirmation_import/:page' => 'clients#confirmation_import, :defaults => {:page => 1}

resources :clients do
  collection do
    get :autocomplete
    post :confirmation_import
    post :import
  end
end


问:
Why is the hex value of a period in a DNS request not 0x2E, and why does it change?
Looking at a DNS request in wireshark for www.google.com and the hex for it is 03 77 77 77 06 67 6f 6f 67 6c 65 03 63 6f 6d 00

Little confused why the first period is 03 (and why it's there), the second is 06, and the last is 03

答:
The DNS protocol layer is defined in RFC 1035. To cite from "3.1. Name space definitions":

Domain names in messages are expressed in terms of a sequence of labels.
  Each label is represented as a one octet length field followed by that
  number of octets.  Since every domain name ends with the null label of
  the root, a domain name is terminated by a length byte of zero.

Thus www.google.com is encoded in the DNS packet as:

```<code>03 77 77 77                  length 3, "www"
06 67 6f 6f 67 6c 65         length 6, "google"
03 63 6f 6d                  length 3, "com"
00                           length 0 (end of label)
</code>```

Body:
The DNS protocol layer is defined in RFC 1035. To cite from "3.1. Name space definitions":

Domain names in messages are expressed in terms of a sequence of labels.
  Each label is represented as a one octet length field followed by that
  number of octets.  Since every domain name ends with the null label of
  the root, a domain name is terminated by a length byte of zero.

Thus www.google.com is encoded in the DNS packet as:

03 77 77 77                  length 3, "www"
06 67 6f 6f 67 6c 65         length 6, "google"
03 63 6f 6d                  length 3, "com"
00                           length 0 (end of label)


问:
Make a dictionary from csv columns in pandas in python
I have 3 column csv file, with column headings {id, ingredients, recipe}

Now, I want to create a dictionary in a way, id is the key and ingredients and recipe is the value.

When combining ingredients and recipe, I need to insert a fullstop and a whitespace as well.
e.g., <ingredient>. <recipe>

My current code is as follows.

```<code>input_data = pd.read_csv( input_file, header=0, delimiter="\t", quoting=3 )
L= input_data["ingredient"] + '. ' + input_data["recipe"]
my_d = input_data.set_index('id')[L].to_dict()
</code>```

Please help me!!

答:
Use zip with dict:

```<code>my_d = dict(zip(input_data['id'], input_data["ingredient"] + '. ' + input_data["recipe"]))
</code>```

Sample:

```<code>input_data = pd.DataFrame({'ingredient':list('abg'),
                           'id':[1,2,4],
                           'recipe':list('rth')})

print (input_data)
   id ingredient recipe
0   1          a      r
1   2          b      t
2   4          g      h

my_d = dict(zip(input_data['id'], input_data["ingredient"] + '. ' + input_data["recipe"]))
print (my_d)
{1: 'a. r', 2: 'b. t', 4: 'g. h'}
</code>```

Body:
I have 3 column csv file, with column headings {id, ingredients, recipe}

Now, I want to create a dictionary in a way, id is the key and ingredients and recipe is the value.

When combining ingredients and recipe, I need to insert a fullstop and a whitespace as well.
e.g., <ingredient>. <recipe>

My current code is as follows.

input_data = pd.read_csv( input_file, header=0, delimiter="\t", quoting=3 )
L= input_data["ingredient"] + '. ' + input_data["recipe"]
my_d = input_data.set_index('id')[L].to_dict()

Please help me!!

Body:
Use zip with dict:

my_d = dict(zip(input_data['id'], input_data["ingredient"] + '. ' + input_data["recipe"]))

Sample:

input_data = pd.DataFrame({'ingredient':list('abg'),
                           'id':[1,2,4],
                           'recipe':list('rth')})

print (input_data)
   id ingredient recipe
0   1          a      r
1   2          b      t
2   4          g      h

my_d = dict(zip(input_data['id'], input_data["ingredient"] + '. ' + input_data["recipe"]))
print (my_d)
{1: 'a. r', 2: 'b. t', 4: 'g. h'}


问:
Array highest value or create next value?
I have an array of names and id's.

```<code>Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)
</code>```

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

答:
Something like this:

```<code>//$my_array is your array of values
//$string = 'New York'; your search term
$id = false;
for($i = count($my_array) - 1; $i >= 0; $i++) {
    if($id === false) {
        if(strpos($my_array[$i]['name'], $string) !== false && $my_array[$i]['can'] == 1) {
            $id = $my_array[$i]['id'];
        }
    }
}
//Insert it if no id was found
if($id === false) {
    $id = 'something';
    $can = 1;
    array_push($my_array, array('name' => $string, 'id' => $id, 'can' => $can));
}
</code>```

Does that work?

edit
(In case it's not obvious, $string is whatever you are searching for)

Body:
I have an array of names and id's.

Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

Body:
Something like this:

//$my_array is your array of values
//$string = 'New York'; your search term
$id = false;
for($i = count($my_array) - 1; $i >= 0; $i++) {
    if($id === false) {
        if(strpos($my_array[$i]['name'], $string) !== false && $my_array[$i]['can'] == 1) {
            $id = $my_array[$i]['id'];
        }
    }
}
//Insert it if no id was found
if($id === false) {
    $id = 'something';
    $can = 1;
    array_push($my_array, array('name' => $string, 'id' => $id, 'can' => $can));
}

Does that work?

edit
(In case it's not obvious, $string is whatever you are searching for)


问:
How to choose the order of PivotItems?
I have a PivotItem added dynamically and another 2 PivotItems which are added from the designer. I would like to place the one added dynamically first (First from the left).

```<code> <Pivot Name="EntryPivot" Title="Gym Crew" Background="Azure">
        <Pivot.RightHeader>
            <CommandBar>
                <AppBarButton Icon="Import" Label="Import" Click="ImportCsv_Button"/>
                <AppBarSeparator/>
                <AppBarButton Icon="Edit" Label="Edit"/>
                <AppBarButton Icon="Delete" Label="Delete"/>
                <AppBarSeparator/>
                <AppBarButton Icon="Save" Label="Save"/>
            </CommandBar>
        </Pivot.RightHeader>
        <PivotItem Header="View Progress">

        </PivotItem>
        <PivotItem Header="Progress Charts">

        </PivotItem>
    </Pivot>
</code>```

Or at least, upon enetring the application, the dynamically added PivotItem is shown.

```<code>private void addElements()
{
    calendar = getTheBloodyCalendar();
    pivot = EntryPivot;

    Grid calendarGrid = new Grid()
    {
        HorizontalAlignment = HorizontalAlignment.Stretch,
        VerticalAlignment = VerticalAlignment.Stretch
    };
    calendarGrid.Children.Add(calendar);

    calendarItem = new PivotItem()
    {
        Header = "Calendar",
        Content = calendarGrid
    };

    pivot.Items.Add(calendarItem);
}
</code>```

答:
Try using Insert method for inserting at a particular index</p>

```<code>pivot.Items.Insert(0, calendarItem);
</code>```

Title: How to choose the order of PivotItems?

Body:
I have a PivotItem added dynamically and another 2 PivotItems which are added from the designer. I would like to place the one added dynamically first (First from the left).

 <Pivot Name="EntryPivot" Title="Gym Crew" Background="Azure">
        <Pivot.RightHeader>
            <CommandBar>
                <AppBarButton Icon="Import" Label="Import" Click="ImportCsv_Button"/>
                <AppBarSeparator/>
                <AppBarButton Icon="Edit" Label="Edit"/>
                <AppBarButton Icon="Delete" Label="Delete"/>
                <AppBarSeparator/>
                <AppBarButton Icon="Save" Label="Save"/>
            </CommandBar>
        </Pivot.RightHeader>
        <PivotItem Header="View Progress">

        </PivotItem>
        <PivotItem Header="Progress Charts">

        </PivotItem>
    </Pivot>

Or at least, upon enetring the application, the dynamically added PivotItem is shown.

private void addElements()
{
    calendar = getTheBloodyCalendar();
    pivot = EntryPivot;

    Grid calendarGrid = new Grid()
    {
        HorizontalAlignment = HorizontalAlignment.Stretch,
        VerticalAlignment = VerticalAlignment.Stretch
    };
    calendarGrid.Children.Add(calendar);

    calendarItem = new PivotItem()
    {
        Header = "Calendar",
        Content = calendarGrid
    };

    pivot.Items.Add(calendarItem);
}

Body:
Try using Insert method for inserting at a particular index

pivot.Items.Insert(0, calendarItem);


问:
Hide disabled time range in jquery timepicker
I am using jquery timepicker.

I want to hide particular time range :

following is the code i am using it disables but does not hide the time range

```<code>$(document).ready(function(){
         $('#durationExample').timepicker({
            'disableTimeRanges': [
                ['1am', '2am'],
                ['3am', '4:01am']
            ]
        });
    })
</code>```

How do i hide this time range please help me

答:
```<code>$('document').on('change','YourClassName',function(){
       $('.ui-timepicker-disabled').css('display','none');
   })
</code>```

Body:
I am using jquery timepicker.

I want to hide particular time range :

following is the code i am using it disables but does not hide the time range

$(document).ready(function(){
         $('#durationExample').timepicker({
            'disableTimeRanges': [
                ['1am', '2am'],
                ['3am', '4:01am']
            ]
        });
    })

How do i hide this time range please help me


问:
Do Statement that isn't working correctly
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!</p>

```<code>    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}
</code>```

答:
That is because you have used an assignment operator = in first while statement instead of relational operator ==.
The = assignment operator  sets your swapflag to true instead  of comparing.
Change it with
while(swapflag==true)
== is relational operator which will check if swapflag is true
or while (swapflag)</p>

Body:
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!

    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}


问:
Upgrade to VS 2015 - error when publishing to Azure
I have an asp.net web application deployed in Azure.
I have just migrated from VS 2013 to VS 2015 and have upgraded from framework 4.5 to framework 4.6.1

My application works fine in local, however when I publish it, I have access to the first login account and then get the following error:

An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

I have tried to go back to framework 4.6, but that did not change the problem.

Any idea what it could be?

答:
I assume that you may have some references(most likely Azure SDK references) that are not set to Copy local = true, and them are not deployed to Azure.

You could set customErrors = "Off" in the Web.config and reploy it to azure to get more detail error info.

```<code><system.web>
      <customErrors mode="Off" />
</code>```

Azure WebApp also allow us to remote debug it from Visual studio. You could troubleshoot a webApp in Azure following this Azure official document.

Body:
I assume that you may have some references(most likely Azure SDK references) that are not set to Copy local = true, and them are not deployed to Azure.

You could set customErrors = "Off" in the Web.config and reploy it to azure to get more detail error info.

<system.web>
      <customErrors mode="Off" />

Azure WebApp also allow us to remote debug it from Visual studio. You could troubleshoot a webApp in Azure following this Azure official document.


问:
DataGrid-Column widths not updating on ItemsSource change
XAML:

```<code><DataGrid.Columns>
    <DataGridTextColumn x:Name="colDisplayName" Width="Auto" IsReadOnly="True" Header="Name" Binding="{Binding ssn.SSN_DISPLAY_NAME}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colValue" Width="Auto" Header="Value" Binding="{Binding ssv.SSV_VALUE}" CellStyle="{StaticResource SingleClickEditing}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colDescription" Width="Auto" IsReadOnly="True" Header="Description" Binding="{Binding ssn.SSN_DESCRIPTION}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colUnit" Width="Auto" IsReadOnly="True" Header="Unit Abbreviation" Binding="{Binding ssn.UNIT_TYPE.UNIT_NAME.UN_ABBREVIATION}"></DataGridTextColumn>
    </DataGrid.Columns>
</code>```

CS:

```<code>private void tvSystemConfiguration_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
       {
           dgSystemSettings.ItemsSource =
               ((tvSystemConfiguration.SelectedItem as SYSTEM_SETTINGS_GROUP).SYSTEM_SETTINGS_NAMEs.Join
               (ssdc.SYSTEM_SETTINGS_VALUEs, x => x.SSN_ID, y => y.SSV_SSN_ID, (x, y) => new DataGridItem{ ssn = x, ssv = y })).ToList();
       }
</code>```

Column widths shrink to fit correctly when increasing in column size but do not properly shrink to fit when decreasing in column size. It will not decrase the size of the column on an ItemsSource update after it has increased. Hope that makes sense. Any help is appreciated. Thank you.

答:
did not make any sense for me, sorry.

I understand the code, but this part:

Column widths shrink to fit correctly when increasing in column size but do
  not properly shrink to fit when decreasing in column size. It will not
  decrase the size of the column on an ItemsSource update after it has increased

has me puzzled

I understood this like that:

if the width of a column's content increases, the column's width increases, but if the
  content's width decreases, the column's width does not.

Is that right ?

if so, this behaviour is normal: Wpf will just resize a datagrid's column width set to Auto if needed, i.e: the content cannot be displayed entirely. So when the content's width shrinks, the column does not resize as the content can still been seen entirely.

the only way I can see to force wpf to recalculate the columns' widths would be to force them all to 0 and then back to auto in the code behind, with one or two updateLayout() thrown in, but this is not very nice programming :-/

Edit:
basically, in your code behind:

```<code>foreach (DataGridColumn c in dg.Columns)
    c.Width = 0;

// Update your DG's source here

foreach (DataGridColumn c in dg.Columns)
    c.Width = DataGridLength.Auto;
</code>```

and you probably need a dg.UpdateLayout() or two somewhere in there (after the update and the setting back to auto probably)

Body:
XAML:

<DataGrid.Columns>
    <DataGridTextColumn x:Name="colDisplayName" Width="Auto" IsReadOnly="True" Header="Name" Binding="{Binding ssn.SSN_DISPLAY_NAME}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colValue" Width="Auto" Header="Value" Binding="{Binding ssv.SSV_VALUE}" CellStyle="{StaticResource SingleClickEditing}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colDescription" Width="Auto" IsReadOnly="True" Header="Description" Binding="{Binding ssn.SSN_DESCRIPTION}"></DataGridTextColumn>
    <DataGridTextColumn x:Name="colUnit" Width="Auto" IsReadOnly="True" Header="Unit Abbreviation" Binding="{Binding ssn.UNIT_TYPE.UNIT_NAME.UN_ABBREVIATION}"></DataGridTextColumn>
    </DataGrid.Columns>

CS:

private void tvSystemConfiguration_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
       {
           dgSystemSettings.ItemsSource =
               ((tvSystemConfiguration.SelectedItem as SYSTEM_SETTINGS_GROUP).SYSTEM_SETTINGS_NAMEs.Join
               (ssdc.SYSTEM_SETTINGS_VALUEs, x => x.SSN_ID, y => y.SSV_SSN_ID, (x, y) => new DataGridItem{ ssn = x, ssv = y })).ToList();
       }

Column widths shrink to fit correctly when increasing in column size but do not properly shrink to fit when decreasing in column size. It will not decrase the size of the column on an ItemsSource update after it has increased. Hope that makes sense. Any help is appreciated. Thank you.

Body:
did not make any sense for me, sorry.

I understand the code, but this part:

Column widths shrink to fit correctly when increasing in column size but do
  not properly shrink to fit when decreasing in column size. It will not
  decrase the size of the column on an ItemsSource update after it has increased

has me puzzled

I understood this like that:

if the width of a column's content increases, the column's width increases, but if the
  content's width decreases, the column's width does not.

Is that right ?

if so, this behaviour is normal: Wpf will just resize a datagrid's column width set to Auto if needed, i.e: the content cannot be displayed entirely. So when the content's width shrinks, the column does not resize as the content can still been seen entirely.

the only way I can see to force wpf to recalculate the columns' widths would be to force them all to 0 and then back to auto in the code behind, with one or two updateLayout() thrown in, but this is not very nice programming :-/

Edit:
basically, in your code behind:

foreach (DataGridColumn c in dg.Columns)
    c.Width = 0;

// Update your DG's source here

foreach (DataGridColumn c in dg.Columns)
    c.Width = DataGridLength.Auto;

and you probably need a dg.UpdateLayout() or two somewhere in there (after the update and the setting back to auto probably)


问:
How to display the workHr that comes as json data in table format using vue js?
My json data is

```<code>{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}
</code>```

Currently I am displaying data as

```<code> <p><i class="fa fa-map-marker" aria-hidden="true"></I>{{data.place}}, {{data.city}}, {{data.pincode}}</p><br>
</code>```

I need to display {{data.workHr}} in the form of a table

My table is as

```<code> <table class="table">
  <thead>
    <tr>
      <th>Sunday</th>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
      <th>Saturday</th>
    </tr>
  </thead>
  <tbody>
    <tr>

      <td></td>
       <td></td>
        <td></td>
         <td></td>
          <td></td>
           <td></td>
            <td></td>
    </tr>
  </tbody>
</table>
</code>```

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

答:
You can modify your workHr to array of object, so it will be easier to iterate over them. For example

const workHour = "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM".split(',').map((val) => {
  const obj = val.split(':');
  const time = val.replace(`${obj[0]}:`, '');
  return {
    day: obj[0],
    time,
  }
});
console.log(workHour);

/*  following is the output of the code above
    [
      { day: 'Monday', time: '9:00AM to 5:00PM'},
      ........
    ]
*/```
</div>
</div>
</p>

<p>Then, you can assign workHour to data</p>

```data.workHr = workHour;
```

<p>Then, it's easy to iterate over your table </p>

```

      {{item.day}}

      {{item.time}}

```

Body:
My json data is

{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}

Currently I am displaying data as

{{data.place}}, {{data.city}}, {{data.pincode}}

I need to display {{data.workHr}} in the form of a table

My table is as

      Sunday
      Monday
      Tuesday
      Wednesday
      Thursday
      Friday
      Saturday

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

Body:
You can modify your workHr to array of object, so it will be easier to iterate over them. For example

const workHour = "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM".split(',').map((val) => {
  const obj = val.split(':');
  const time = val.replace(`${obj[0]}:`, '');
  return {
    day: obj[0],
    time,
  }
});
console.log(workHour);

/*  following is the output of the code above
    [
      { day: 'Monday', time: '9:00AM to 5:00PM'},
      ........
    ]
*/

Then, you can assign workHour to data

data.workHr = workHour;

Then, it's easy to iterate over your table

<table class="table">
  <thead>
    <tr>
      <th v-for="(item,key) in data.workHr" :key="key">{{item.day}}</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td v-for="(item,key) in data.workHr" :key="key">{{item.time}}</td>
    </tr>
  </tbody>
</table>


问:
Get Keys with Multi Patterns in Redis
I want to get all keys start with 460  or 45412.

keys 460*  combine keys 45412*

I try the method in this Link: https://redis.io/commands/keys but Failed

答:
There is no combine option in Redis.

And keys command is not supposed to be used on application level, it is slow. Instead you can use appropriate type (hash or zset or its combination, depending on what you need)

Anyway, if you want to get keys by two patterns you can just call keys a couple times and combine results:

```<code>cat <(redis-cli -n 0 keys "460*") <(redis-cli -n 0 keys "45412*") > keys.txt
</code>```

Title: Get Keys with Multi Patterns in Redis

Body:
There is no combine option in Redis.

And keys command is not supposed to be used on application level, it is slow. Instead you can use appropriate type (hash or zset or its combination, depending on what you need)

Anyway, if you want to get keys by two patterns you can just call keys a couple times and combine results:

cat <(redis-cli -n 0 keys "460*") <(redis-cli -n 0 keys "45412*") > keys.txt


问:
Show more and less with respective height or content
Hi i was trying to create a dynamic table, it has to display only 2 item(rows) and other rows need to be hidden, on click showmore remaining rows has to display.

Thanks

```<code><table class="table borderless">
  <thead>
    <tr>
      <th></th>
      <th>Thead1</th>
      <th>Thead2</th>
    </tr>
  </thead>
  <tbody class="tbodySpace">
    <tr>
      <td>Row 1 - heading</td>
      <td>
        data1
      </td>
      <td>
        data2
      </td>
    </tr>
    <tr>
      <td>Row 2 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 3 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
  </tbody>
</table>
<button class="button">Show more</button>
</code>```

Jsfiddle is here

答:
Below is the snippet to show 2 rows when clicked on button:

$("table tr:gt(2)").hide();

$(".button").on('click', function() {
  var lastIndex = $("table tr:visible:last").index();
  $("table tr").show();
  $("table tr:gt(" + (lastIndex + 3) + ")").hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table>tbody>tr>td {
  padding: 15px!important;
}

.table>tbody>tr>td:not(:first-child) {
  border-left: 1px solid #eee !important;
  color: #07A4DD;
}</code>```

      Thead1
      Thead2

      Row 1 - heading

        data1

        data2

      Row 2 - heading

        data3

        data4

      Row 3 - heading

        data3

        data4

      Row 4 - heading

        data3

        data4

      Row 5 - heading

        data3

        data4

      Row 6 - heading

        data3

        data4

      Row 7 - heading

        data3

        data4

      Row 8 - heading

        data3

        data4

<button class="button">Show more</button>```

Body:
Hi i was trying to create a dynamic table, it has to display only 2 item(rows) and other rows need to be hidden, on click showmore remaining rows has to display.

Thanks

      Thead1
      Thead2

      Row 1 - heading

        data1

        data2

      Row 2 - heading

        data3

        data4

      Row 3 - heading

        data3

        data4

<button class="button">Show more</button>

Jsfiddle is here

Body:
Below is the snippet to show 2 rows when clicked on button:

$("table tr:gt(2)").hide();

$(".button").on('click', function() {
  var lastIndex = $("table tr:visible:last").index();
  $("table tr").show();
  $("table tr:gt(" + (lastIndex + 3) + ")").hide();
});

.table>tbody>tr>td {
  padding: 15px!important;
}

.table>tbody>tr>td:not(:first-child) {
  border-left: 1px solid #eee !important;
  color: #07A4DD;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table borderless">
  <thead>
    <tr>
      <th></th>
      <th>Thead1</th>
      <th>Thead2</th>
    </tr>
  </thead>
  <tbody class="tbodySpace">
    <tr>
      <td>Row 1 - heading</td>
      <td>
        data1
      </td>
      <td>
        data2
      </td>
    </tr>
    <tr>
      <td>Row 2 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 3 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 4 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 5 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 6 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 7 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 8 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>

  </tbody>
</table>
<button class="button">Show more</button>


问:
How can I search/index multiple geo-location positions for a aggregated search?
I am using $geoNear to search for a business location based of a users location. However when I perform the search, Mongo only allows me to index 1 geo-location some businesses have multiple location, and I would like to be able to turn the location index to find the closest result.

This is what I currently have:

```<code> location : {
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },
</code>```

And this is what I would like to have:

```<code> location : [{
            name: "Suburb 1",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },
    {
            name: "Suburb 2",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    }],
</code>```

Where the search would find the closest result. Is there an ideal way to do this?

Thanks

答:
If you would like to use $geoNear, you should consider redesigning your data model. $geoNear would return you the closest location (sorted), and it requires geospatial-index(es).

A suggestion would be to store a single document entry per business location.

You may also find Tutorial: Geospatial useful especially the examples.

Body:
I am using $geoNear to search for a business location based of a users location. However when I perform the search, Mongo only allows me to index 1 geo-location some businesses have multiple location, and I would like to be able to turn the location index to find the closest result.

This is what I currently have:

 location : {
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },

And this is what I would like to have:

 location : [{
            name: "Suburb 1",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },
    {
            name: "Suburb 2",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    }],

Where the search would find the closest result. Is there an ideal way to do this?

Thanks


问:
How does Data Encapsulation actually happen in OOP?
I'm learning C++.

Came across data encapsulation and data hiding at a website, check out the following piece of code:

```<code>#include<iostream.h>
#include<conio.h>

class sum {
private: int a, b, c;

public:
    void add() {
        clrscr();
        cout << "Enter any two numbers: ";
        cin >> a >> b;
        c = a + b;
        cout << "Sum: " << c;
    }
};
void main() {
    sum s;
    s.add();
    getch();
}
</code>```

NOW. As it says here that:

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

What happens underneath the code, what does the compiler do that makes it inaccessible to other classes? And in the given example what was the reason behind defining a,b and c as private.

What were they trying to achieve by hiding "just the declarations of the three variables"? Because anyone can see that inside public three numbers being used are a,b, and c - first two for input and third one for output.

答:
How is this possible that the data under private can't be accessed
  outside the class?

Compiler makes sure you don't. If you try to access say a outside class, your code will not compile.

And in the given example what was the reason behind defining a,b and c
  as private.

It could be anything! But as a result, a,b and c are not accessible outside members of class.

Basically you want to hide some variables in your class for the sake of consistency. So that you or your clients can not produce a code that makes unwanted and uncontrolled changes.

Updates:

What happens underneath the code, what does the compiler do that makes
  it unaccessible to other classes?

Compiler implementation check for access level while producing code. If there is something wrong, you will get a syntax error and no machine code will be generated from your file.

And in the given example what was the reason behind defining a,b and c
  as private; what were they trying to achieve by hiding "just the
  declarations of the three variables"? Because anyone can see that
  inside public three numbers being used are a,b, and c - first two for
  input and third one for output.

You don't hide variables in your class to make them invisible to others. Private variables that are not intended to be used from outside of the class can be marked as private to limit the potential for coding errors.

As an example consider following class:

```<code>class rectangle {
  public:
    int width;
    int height;
    int area;
};

void something_important(const rectangle& r) {
// ...
}
</code>```

What happens if I pass a rectangle of width -10, height 0 and area of -15? There could be a plane crash or a nuclear weapon launched to some wrong target... So I will make sure my rectangles are always valid:

```<code>class rectangle {
  public:
    void set_width(int w) {
      if(w) width = w;
      else width = 0;
      area = width*height;
    }
    int get_width() const {return width;}
    void set_height(int h) {
      if(w) height = h;
      else height = 0;
      area = width*height;
    }
    int get_height() const {return height;}
    int get_area() const {return area;}
  private:
    int width;
    int height;
    int area;
};
</code>```

So no one can make a rectangle of negative height or width, and no one can make a rectangle having a wrong area. (you can not actually change area directly)

I hope it makes sense for you now.

Body:
I'm learning C++.

Came across data encapsulation and data hiding at a website, check out the following piece of code:

#include<iostream.h>
#include<conio.h>

class sum {
private: int a, b, c;

public:
    void add() {
        clrscr();
        cout << "Enter any two numbers: ";
        cin >> a >> b;
        c = a + b;
        cout << "Sum: " << c;
    }
};
void main() {
    sum s;
    s.add();
    getch();
}

NOW. As it says here that:

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

What happens underneath the code, what does the compiler do that makes it inaccessible to other classes? And in the given example what was the reason behind defining a,b and c as private.

What were they trying to achieve by hiding "just the declarations of the three variables"? Because anyone can see that inside public three numbers being used are a,b, and c - first two for input and third one for output.

Body:
How is this possible that the data under private can't be accessed
  outside the class?

Compiler makes sure you don't. If you try to access say a outside class, your code will not compile.

And in the given example what was the reason behind defining a,b and c
  as private.

It could be anything! But as a result, a,b and c are not accessible outside members of class.

Basically you want to hide some variables in your class for the sake of consistency. So that you or your clients can not produce a code that makes unwanted and uncontrolled changes.

Updates:

What happens underneath the code, what does the compiler do that makes
  it unaccessible to other classes?

Compiler implementation check for access level while producing code. If there is something wrong, you will get a syntax error and no machine code will be generated from your file.

And in the given example what was the reason behind defining a,b and c
  as private; what were they trying to achieve by hiding "just the
  declarations of the three variables"? Because anyone can see that
  inside public three numbers being used are a,b, and c - first two for
  input and third one for output.

You don't hide variables in your class to make them invisible to others. Private variables that are not intended to be used from outside of the class can be marked as private to limit the potential for coding errors.

As an example consider following class:

class rectangle {
  public:
    int width;
    int height;
    int area;
};

void something_important(const rectangle& r) {
// ...
}

What happens if I pass a rectangle of width -10, height 0 and area of -15? There could be a plane crash or a nuclear weapon launched to some wrong target... So I will make sure my rectangles are always valid:

class rectangle {
  public:
    void set_width(int w) {
      if(w) width = w;
      else width = 0;
      area = width*height;
    }
    int get_width() const {return width;}
    void set_height(int h) {
      if(w) height = h;
      else height = 0;
      area = width*height;
    }
    int get_height() const {return height;}
    int get_area() const {return area;}
  private:
    int width;
    int height;
    int area;
};

So no one can make a rectangle of negative height or width, and no one can make a rectangle having a wrong area. (you can not actually change area directly)

I hope it makes sense for you now.


问:
How to let user decide the increment of a series bounded by a range?
I want to print a list of number which is bounded by the range -2 <= x <= 2 in an incremental value such that the list always start with -2 and ends with 2 or vice versa. I'm looking to let the user input an increment value i.e. 0.5 or 0.05. From the range given above it is evident that the largest increment would be 4.

I'm looking to prompt an error message whenever the user inputs an increment value that's > 4 and also when they input an increment value that doesn't allow the list to start printing from 2 and finishes at -2 i.e. when the increment value is 0.23.

The way I thought I could do would be to use the modulus operator where if (4%increment value) = str() i.e. a whole number means that the given increment value is valid for that range. However I'm slightly stuck since when I run my code I end up in a never ending loop. Below is what I've done so far, so hoping somebody can help me out here:

```<code>def IncCheck():
    while True:
        try:     #I first check if the user inputs me a string then an error message would come up
            c = float(input("For the range -2 <= x <= 2, please input the increment you wish to display: "))
            break
        except ValueError:
            print("Invalid input. The increment has to be a number.")
    while 4%c != int():    #Here I wanna check the validity of the increment value so ideally it'd be < 4 and be a value that prints a list that starts with -2 and ends with 2.
        print("Your selected increment is not valid for -2 <= x <= 2. It should be a divisible increment of 4(the range). Please try again.")
        if c > 4:
            print("Your increment is too high. The maximum increment for the given range is 4. Please try again.")
    return c

print(IncCheck())
</code>```

As you can see I've tried to create a function which checks the increment. In the end I'm looking to print the list using something like

```<code>import numpy as np
for i in np.arange(2, -2-c, -c): #c is the increment value the users input
    print i
</code>```

which I can use to do other things. I need to use these x values and plot them into an arctan(x) function that I've approximated using a Taylor Series with a N value i.e. the number of iterations in the Taylor Series and compare them side by side with a real arctan(x) function basically. And then graph them. Thanks in advance.

答:
This is how I would do it (without the user input routine)

```<code>def increment_(c, start = -2, end = 2):
    assert np.isclose((end - start) % c, 0), "Step does not evenly divide range"
    steps = (end - start) / c
    if np.signbit(steps):
        return np.linspace(end,   start, - int(steps) + 1)
    else:
        return np.linspace(start, end,     int(steps) + 1)
</code>```

The infinite loop in your user input is explained in this question which @wwii linked in the comments

Body:
I want to print a list of number which is bounded by the range -2 <= x <= 2 in an incremental value such that the list always start with -2 and ends with 2 or vice versa. I'm looking to let the user input an increment value i.e. 0.5 or 0.05. From the range given above it is evident that the largest increment would be 4.

I'm looking to prompt an error message whenever the user inputs an increment value that's > 4 and also when they input an increment value that doesn't allow the list to start printing from 2 and finishes at -2 i.e. when the increment value is 0.23.

The way I thought I could do would be to use the modulus operator where if (4%increment value) = str() i.e. a whole number means that the given increment value is valid for that range. However I'm slightly stuck since when I run my code I end up in a never ending loop. Below is what I've done so far, so hoping somebody can help me out here:

def IncCheck():
    while True:
        try:     #I first check if the user inputs me a string then an error message would come up
            c = float(input("For the range -2 <= x <= 2, please input the increment you wish to display: "))
            break
        except ValueError:
            print("Invalid input. The increment has to be a number.")
    while 4%c != int():    #Here I wanna check the validity of the increment value so ideally it'd be < 4 and be a value that prints a list that starts with -2 and ends with 2.
        print("Your selected increment is not valid for -2 <= x <= 2. It should be a divisible increment of 4(the range). Please try again.")
        if c > 4:
            print("Your increment is too high. The maximum increment for the given range is 4. Please try again.")
    return c

print(IncCheck())

As you can see I've tried to create a function which checks the increment. In the end I'm looking to print the list using something like

import numpy as np
for i in np.arange(2, -2-c, -c): #c is the increment value the users input
    print i

which I can use to do other things. I need to use these x values and plot them into an arctan(x) function that I've approximated using a Taylor Series with a N value i.e. the number of iterations in the Taylor Series and compare them side by side with a real arctan(x) function basically. And then graph them. Thanks in advance.

Body:
This is how I would do it (without the user input routine)

def increment_(c, start = -2, end = 2):
    assert np.isclose((end - start) % c, 0), "Step does not evenly divide range"
    steps = (end - start) / c
    if np.signbit(steps):
        return np.linspace(end,   start, - int(steps) + 1)
    else:
        return np.linspace(start, end,     int(steps) + 1)

The infinite loop in your user input is explained in this question which @wwii linked in the comments