问:
how to make a carousel in the center and fit 3/4 of the page
im working with HTML and right now i just added a carousel item to my html project, my question is how can you display the carousel in the middle of the page since it appears at the left side.

www.littlebossworld.com

答:
In this situation you have to use !important attribute because your carousel plugin is adding inline styles (maybe there is a setup where you can change this?).

"hard" css:

```<code>.fusion-carousel .fusion-carousel-wrapper {
    margin: 0 auto !important;
}
</code>```

Body:
In this situation you have to use !important attribute because your carousel plugin is adding inline styles (maybe there is a setup where you can change this?).

"hard" css:

.fusion-carousel .fusion-carousel-wrapper {
    margin: 0 auto !important;
}


来源: stackexchange

问:
Understanding a Complicated Type Signature
I need help understanding this type signature which is from the Thrist package.

```<code>import Prelude hiding ((.), id)
import Control.Category
import Data.Monoid
import Control.Arrow
import Control.Monad

foldlThirst :: (forall j k . (a +> j) -> (j ~> k) -> (a +> k))
               -> (a +> b)
               -> Thrist (~>) b c
               -> (a +> c)
</code>```

I am confused about several things.

First what are the +> and ~> symbols? Where are they documented and what are they called?

But my confusion does stop there. I realize that the quantification is describing the threading of types of the Thrist, but I am not sure if is describing a relationship that holds for the first argument, or the whole function, or who knows...

In othercases where I have seen existential quantification, the phrase ends with a period, but here it ends with ->, is that significant?

答:
First what are the +> and ~> symbols? Where are they documented and what are they called?

They're infix identifiers, just like if you used them as the name of a function. By the same token, being equivalent to lowercase identifiers (in contrast to operators beginning with : which are equivalent to upper-case alphanumeric identifiers), in a type signature they're simply type variables. In other words, it's equivalent to this:

```<code>(forall j k . (f a j) -> (g j k) -> (f a k))
  -> etc . . .
</code>```

But my confusion does stop there. I realize that the quantification is describing the threading of types of the Thrist, but I am not sure if is describing a relationship that holds for the first argument, or the whole function, or who knows...

Explicit quantifiers are scoped only within enclosing parentheses, or to the end of the expression. In this case, they describe only the first argument, because the type variables introduced are only in scope for that argument.

In this case, it just means that the function given as the first argument must be fully polymorphic in those types. As an example, a function whose type signature starts with (a -> a) -> ... could be given not as its first argument, unifying a with Bool. In contrast, if the type signature started with (forall a. a -> a) -> ... it would require a function that works for all possible types a, the only such function being id.

ContentLicense: CC BY-SA 2.5

Body:
I need help understanding this type signature which is from the Thrist package.

import Prelude hiding ((.), id)
import Control.Category
import Data.Monoid
import Control.Arrow
import Control.Monad

foldlThirst :: (forall j k . (a +> j) -> (j ~> k) -> (a +> k))
               -> (a +> b)
               -> Thrist (~>) b c
               -> (a +> c)

I am confused about several things.

First what are the +> and ~> symbols? Where are they documented and what are they called?

But my confusion does stop there. I realize that the quantification is describing the threading of types of the Thrist, but I am not sure if is describing a relationship that holds for the first argument, or the whole function, or who knows...

In othercases where I have seen existential quantification, the phrase ends with a period, but here it ends with ->, is that significant?

Body:
First what are the +> and ~> symbols? Where are they documented and what are they called?

They're infix identifiers, just like if you used them as the name of a function. By the same token, being equivalent to lowercase identifiers (in contrast to operators beginning with : which are equivalent to upper-case alphanumeric identifiers), in a type signature they're simply type variables. In other words, it's equivalent to this:

(forall j k . (f a j) -> (g j k) -> (f a k))
  -> etc . . .

But my confusion does stop there. I realize that the quantification is describing the threading of types of the Thrist, but I am not sure if is describing a relationship that holds for the first argument, or the whole function, or who knows...

Explicit quantifiers are scoped only within enclosing parentheses, or to the end of the expression. In this case, they describe only the first argument, because the type variables introduced are only in scope for that argument.

In this case, it just means that the function given as the first argument must be fully polymorphic in those types. As an example, a function whose type signature starts with (a -> a) -> ... could be given not as its first argument, unifying a with Bool. In contrast, if the type signature started with (forall a. a -> a) -> ... it would require a function that works for all possible types a, the only such function being id.


问:
R finding patterns in numbers/layouts
Consider a database with the following structure:

```<code><Age> <Gender> <Field1> <Field2> <Field3> <Field4> <Field#>
</code>```

Where for each row, some fields might be zero, others will not, representing the amount of times the individual used such field - multiple fields may be used for each row.

For instance, consider the DB as being:

```<code>10 M 10 0 5 0 1
5  M  7 1 6 0 2
10 M  6 1 4 1 0
....
</code>```

So one could say that the pattern for individuals of age 10 and male gender, would be the first and third fields as being the most representative.

I'm not sure if my explanation is making sense. Is this achievable? Is there any algorithm/R package for such problems?

答:
What comes to mind is to subset.  If I'm understanding your question correctly.
Look up subsetting, I'm not positive my code is correct...

df[which(df$Age=10 & df$Gender=M),]

ContentLicense: CC BY-SA 3.0

Title: R finding patterns in numbers/layouts

Body:
Consider a database with the following structure:

<Age> <Gender> <Field1> <Field2> <Field3> <Field4> <Field#>

Where for each row, some fields might be zero, others will not, representing the amount of times the individual used such field - multiple fields may be used for each row.

For instance, consider the DB as being:

10 M 10 0 5 0 1
5  M  7 1 6 0 2
10 M  6 1 4 1 0
....

So one could say that the pattern for individuals of age 10 and male gender, would be the first and third fields as being the most representative.

I'm not sure if my explanation is making sense. Is this achievable? Is there any algorithm/R package for such problems?


问:
Creating a folder with today's date using c++
I am new to c++ programing and working with visual Studio 2015. I want to create a Folder with  a Name of current date in a particular path. I searched on the Internet but I was not able to find the satisfactory solution. Moreover I tried by my own but unfortunately the result is not successful.
I used _mkdir() and CreateFolder().

For example, if i compile the program today (07.07.2017) then it should create a Folder with a Name: "07072017" and if i compile it again then it should Show the message: "Folder already exists".

Thanks in advance.

答:
As mentioned by @user8210143 you can use the c++ standard library experimental bits.

If the date format isn't critical for your purpose, you could just use the __DATE__ compiler define:

Live On Coliru

```<code>#include <experimental/filesystem>
#include <iostream>

namespace fs = std::experimental::filesystem;

int main() {
    auto dirname = fs::current_path() / __DATE__;

    std::cout << "creating directory " << dirname << "\n";
    if (create_directories(dirname)) {
        std::cout << "directory didn't exist yet\n";
    }
}
</code>```

Which prints something like

```<code>creating directory "/home/sehe/Projects/stackoverflow/Jul  7 2017"
directory didn't exist yet
</code>```

On my system

Body:
As mentioned by @user8210143 you can use the c++ standard library experimental bits.

If the date format isn't critical for your purpose, you could just use the __DATE__ compiler define:

Live On Coliru

#include <experimental/filesystem>
#include <iostream>

namespace fs = std::experimental::filesystem;

int main() {
    auto dirname = fs::current_path() / __DATE__;

    std::cout << "creating directory " << dirname << "\n";
    if (create_directories(dirname)) {
        std::cout << "directory didn't exist yet\n";
    }
}

Which prints something like

creating directory "/home/sehe/Projects/stackoverflow/Jul  7 2017"
directory didn't exist yet

On my system


问:
Python - Error with scikit learn Random Forest about values format
When I execute the command:

```<code>clf.fit(train_data, train_label)
</code>```

I'm obtaining the following error

ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

The problem is the array train_data with size (18000,20). I've tried to use this command:

```<code>clf.fit(np.float32(train_data), train_label)
</code>```

or

```<code>train_data = np.array([s[0].astype('float32') for s in train_data])
</code>```

Find the datasets train_data and train_label in the train file (python) in the following link:

https://www.dropbox.com/s/b3017gi18x6x325/train?dl=0

However, I cannot get that all the values from the array "train_data" being valid for the clf.fit function. Any help?

答:
Just found a solution to overcome this error. You need to scale the data:

Code:

```<code>from sklearn.ensemble import RandomForestClassifier
import pickle
import numpy as np
from sklearn.preprocessing import scale

with open('train', 'rb') as f:
    train_data, train_label = pickle.load(f)

#some diagnostic to see if there are NaNs. No NaN were found !
print(np.isnan(train_data))
print(np.where(np.isnan(train_data)))
print(np.nan_to_num(train_data))
print(np.isnan(train_label))
print(np.where(np.isnan(train_label)))

#so need to scale
train_data = scale(train_data)

clf = RandomForestClassifier()
clf.fit(train_data, train_label)
</code>```

Body:
When I execute the command:

clf.fit(train_data, train_label)

I'm obtaining the following error

ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

The problem is the array train_data with size (18000,20). I've tried to use this command:

clf.fit(np.float32(train_data), train_label)

or

train_data = np.array([s[0].astype('float32') for s in train_data])

Find the datasets train_data and train_label in the train file (python) in the following link:

https://www.dropbox.com/s/b3017gi18x6x325/train?dl=0

However, I cannot get that all the values from the array "train_data" being valid for the clf.fit function. Any help?

Body:
Just found a solution to overcome this error. You need to scale the data:

Code:

from sklearn.ensemble import RandomForestClassifier
import pickle
import numpy as np
from sklearn.preprocessing import scale

with open('train', 'rb') as f:
    train_data, train_label = pickle.load(f)

#some diagnostic to see if there are NaNs. No NaN were found !
print(np.isnan(train_data))
print(np.where(np.isnan(train_data)))
print(np.nan_to_num(train_data))
print(np.isnan(train_label))
print(np.where(np.isnan(train_label)))

#so need to scale
train_data = scale(train_data)

clf = RandomForestClassifier()
clf.fit(train_data, train_label)


问:
JS: Group array by values in nested array
I have an array:

```<code>[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]
</code>```

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

```<code>[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]
</code>```

答:
You can use forEach() loop and thisArg parameter to store each component and increment amount.

var data = [{"theme":"low battery","Number":"S-10","components":["hardware","battery"]},{"theme":"bad sync","Number":"S-11","components":["software"]},{"theme":"misc troubles","Number":"S-12","components":["hardware","software"]}]

var result = []

data.forEach(function(e) {
  var that = this;
  e.components.forEach(function(c) {
    if(!that[c]) {
      that[c] = {component: c, amount: 0}
      result.push(that[c])
    }
    that[c].amount += 1
  })
}, {})

console.log(result)```

Body:
I have an array:

[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]


问:
PHP query to sql server syntax, all i have is the ASP.NET connection string
I've got a project on my hands.

In our new hour-registration software, we want to make a query to a database that is located at an external company.

The external company has opened a connection that we've used for another application in ASP.NET.

I want to make a query from the hour-registration PHP project to this database, but I can't make the connection syntax work.

All I have at this moment is the ASP.NET connection string.
(the database is SQL server)

ASP.NET connection string:

```<code><connectionStrings>
  <add name="NAV_ODS_2016ConnectionString" connectionString="Data Source=AX1234SQL;Initial Catalog=NAV_ODS_2016;User ID=test;Password=test" providerName="System.Data.SqlClient"/>
    <add name="NAV_ODS_2016ConnectionString1" connectionString="Data Source=AX1234SQL;Initial Catalog=NAV_ODS_2016;User ID=test" providerName="System.Data.SqlClient"/>
    <add name="NAV2016Test" connectionString="metadata=res://*/Nav.csdl|res://*/Nav.ssdl|res://*/Nav.msl;provider=System.Data.SqlClient;provider connection string="data source=AX1234SQL;initial catalog=NAV_ODS_2016;persist security info=True;user id=test;password=test;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
</code>```

Any ideas how to do this, I've tried the official PHP user manual.

答:
Typed in this textbox here so...

```<code>$config = new DOMDocument();
$config->loadXML('path/to/web.config');

$connection = [];

foreach($config->selectNodes('//connectionStrings/add[@providerName="System.Data.SqlClient"]') as $element)
{
    $connectionString = $element->getAttribute('connectionString');
    $key = $element->getAttribute('name');
    $parts = explode(';', $connectionString);
    $cnData = [];
    foreach($parts as $part)
    {
        list($key, $value) = explode('=', $part);
        $cnData[$key] = $value;
    }
    // add error checking, seriously...
    $hostname = $cnData['Data Source'];
    $username = $cnData['User Id'];
    $database = $cnData['Initial Catalog'];
    $password = $cnData['Password'] ?: null;
    $port = $cnData['Port'] ?: 1433;

    $connection[$name] = new PDO("odbc:Driver={SQL Server};Server={$hostname};Database={$database}; Uid={$username};Pwd={$password}");
}
</code>```

You should end up with:

$connection['NAV_ODS_2016ConnectionString'] and $connection['NAV_ODS_2016ConnectionString1']

that you can use to communicate with the database.

Body:
I've got a project on my hands.

In our new hour-registration software, we want to make a query to a database that is located at an external company.

The external company has opened a connection that we've used for another application in ASP.NET.

I want to make a query from the hour-registration PHP project to this database, but I can't make the connection syntax work.

All I have at this moment is the ASP.NET connection string.
(the database is SQL server)

ASP.NET connection string:

<connectionStrings>
  <add name="NAV_ODS_2016ConnectionString" connectionString="Data Source=AX1234SQL;Initial Catalog=NAV_ODS_2016;User ID=test;Password=test" providerName="System.Data.SqlClient"/>
    <add name="NAV_ODS_2016ConnectionString1" connectionString="Data Source=AX1234SQL;Initial Catalog=NAV_ODS_2016;User ID=test" providerName="System.Data.SqlClient"/>
    <add name="NAV2016Test" connectionString="metadata=res://*/Nav.csdl|res://*/Nav.ssdl|res://*/Nav.msl;provider=System.Data.SqlClient;provider connection string="data source=AX1234SQL;initial catalog=NAV_ODS_2016;persist security info=True;user id=test;password=test;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>

Any ideas how to do this, I've tried the official PHP user manual.

Body:
Typed in this textbox here so...

$config = new DOMDocument();
$config->loadXML('path/to/web.config');

$connection = [];

foreach($config->selectNodes('//connectionStrings/add[@providerName="System.Data.SqlClient"]') as $element)
{
    $connectionString = $element->getAttribute('connectionString');
    $key = $element->getAttribute('name');
    $parts = explode(';', $connectionString);
    $cnData = [];
    foreach($parts as $part)
    {
        list($key, $value) = explode('=', $part);
        $cnData[$key] = $value;
    }
    // add error checking, seriously...
    $hostname = $cnData['Data Source'];
    $username = $cnData['User Id'];
    $database = $cnData['Initial Catalog'];
    $password = $cnData['Password'] ?: null;
    $port = $cnData['Port'] ?: 1433;

    $connection[$name] = new PDO("odbc:Driver={SQL Server};Server={$hostname};Database={$database}; Uid={$username};Pwd={$password}");
}

You should end up with:

$connection['NAV_ODS_2016ConnectionString'] and $connection['NAV_ODS_2016ConnectionString1']

that you can use to communicate with the database.


问:
FirebaseMessagingService delay happens after using for a while
Hello I am trying to write a chat application.

I am using Firebase Cloud messaging

The server side code:

```<code>    Sender sender = new NotificationService(serverKey);
    Message message = new Message.Builder()
            .collapseKey("message")
            .timeToLive(500)
            .delayWhileIdle(false)
            .priority(Message.Priority.HIGH)
            .addData("message"+currentSendingRequestTimeInMillis, typeOfMessage+" Time Request"+currentSendingRequestTimeInMillis)
            .build();
        MulticastResult result = sender.send(message, all, 1);
</code>```

Code on Android side:

```<code>@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
    try {
        boolean found=false;

        Set<String> keySet = remoteMessage.getData().keySet();
        for (Iterator<String> it = keySet.iterator(); it.hasNext(); ) {
            String keyValue = it.next();
            if (  keyValue.contains("message")){
                found=true;
                Log.e(TAG, "ChatLogicFunctionality starts "+keyValue);
                ChatLogicFunctionality();
            }
        }

        if(!found){
            Log.e(TAG, " unknown stuff ");
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception "+e.getMessage());
    }

}
</code>```

So the person sends for example every 2 seconds. It works for a while I see the logs in the onMessageReceived but then it just stops. Then it comes much later.

Does google block or something ?
For chat realtime purpose what should I use.

答:
I am doing testing so it maybe related to same .collapseKey("message")
I will continue on testing if it fixes I will accept as answer.</p>

Body:
Hello I am trying to write a chat application.

I am using Firebase Cloud messaging

The server side code:

    Sender sender = new NotificationService(serverKey);
    Message message = new Message.Builder()
            .collapseKey("message")
            .timeToLive(500)
            .delayWhileIdle(false)
            .priority(Message.Priority.HIGH)
            .addData("message"+currentSendingRequestTimeInMillis, typeOfMessage+" Time Request"+currentSendingRequestTimeInMillis)
            .build();
        MulticastResult result = sender.send(message, all, 1);

Code on Android side:

@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
    try {
        boolean found=false;

        Set<String> keySet = remoteMessage.getData().keySet();
        for (Iterator<String> it = keySet.iterator(); it.hasNext(); ) {
            String keyValue = it.next();
            if (  keyValue.contains("message")){
                found=true;
                Log.e(TAG, "ChatLogicFunctionality starts "+keyValue);
                ChatLogicFunctionality();
            }
        }

        if(!found){
            Log.e(TAG, " unknown stuff ");
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception "+e.getMessage());
    }

}

So the person sends for example every 2 seconds. It works for a while I see the logs in the onMessageReceived but then it just stops. Then it comes much later.

Does google block or something ?
For chat realtime purpose what should I use.


问:
making a directory and then cd'ing in it directly without a new command
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

```<code>#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep
</code>```

by the way this script is for ios

答:
As @edvin already said, this script runs on a different shell and have no effect on your current session PWD.

You could write this script in your user's .profile or shell-specific file as a function. This way calling the function will not create a new shell instance to execute your commands but will execute them in current shell:

```<code>mkcd() {
  mkdir $1 && cd $1
}
</code>```

You could use it like this:

```<code>now=$(date +"%Y-%m-%d-%S")
mkcd $now
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep

by the way this script is for ios

Body:
As @edvin already said, this script runs on a different shell and have no effect on your current session PWD.

You could write this script in your user's .profile or shell-specific file as a function. This way calling the function will not create a new shell instance to execute your commands but will execute them in current shell:

mkcd() {
  mkdir $1 && cd $1
}

You could use it like this:

now=$(date +"%Y-%m-%d-%S")
mkcd $now


问:
How to make the shape return back to its default value in jquery?
```<code>$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
});
</code>```

I would like to know how to return the shape back to the original form after expanding it.

答:
you need to know the width and the height of your form first and replace the value by the ... i writed it below:</p>

```<code>$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
       $(this).animate({height: "...px", width:"...px"});
   });
});
</code>```

Body:
$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
});

I would like to know how to return the shape back to the original form after expanding it.

Body:
you need to know the width and the height of your form first and replace the value by the ... i writed it below:

$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
       $(this).animate({height: "...px", width:"...px"});
   });
});


问:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ ) at newpackage.Myclass.main(Myclass.java:8)
I am working basic test script on selenium-cucumber and while executing I got this error -

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ ) at newpackage.Myclass.main(Myclass.java:8).

```<code>public class Myclass { public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.gecko.driver","C:\User\karokiaswamy\downloads\geckodriver-v0.15.0-win64\geckodriver.exe");
driver.get("http://Application URL/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//[@id='siteLoginTab']/form/table/tbody/tr[1]/td[1]/input" )).sendKeys("Username");
driver.findElement(By.xpath("//[@id='siteLoginTab']/form/table/tbody/tr[1]/td[2]/input" )).sendKeys("Password");
 driver.findElement(By.xpath("//*[@id='siteLoginTab']/form/table/tbody/tr[1]/td[3]/button")).click();
}
</code>```

答:
I am also facing the same issue of espace sequence </p>

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LaunchFirefox {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            WebDriver driver = new FirefoxDriver();
            System.setProperty("webdriver.gecko.driver","C:\Downloads\Selenium\Selenium_setup\geckodriver-v0.17.0-win64\geckodriver.exe");
    }

}
</code>```

Body:
I am working basic test script on selenium-cucumber and while executing I got this error -

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ ) at newpackage.Myclass.main(Myclass.java:8).

public class Myclass { public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.gecko.driver","C:\User\karokiaswamy\downloads\geckodriver-v0.15.0-win64\geckodriver.exe");
driver.get("http://Application URL/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//[@id='siteLoginTab']/form/table/tbody/tr[1]/td[1]/input" )).sendKeys("Username");
driver.findElement(By.xpath("//[@id='siteLoginTab']/form/table/tbody/tr[1]/td[2]/input" )).sendKeys("Password");
 driver.findElement(By.xpath("//*[@id='siteLoginTab']/form/table/tbody/tr[1]/td[3]/button")).click();
}

Body:
I am also facing the same issue of espace sequence

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LaunchFirefox {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            WebDriver driver = new FirefoxDriver();
            System.setProperty("webdriver.gecko.driver","C:\Downloads\Selenium\Selenium_setup\geckodriver-v0.17.0-win64\geckodriver.exe");
    }

}


问:
How to manipulate coordinates of the drag image during drag move
in some cases I use a specific drag image for some drag'n'drop operations in my application. The image can also be placed when adding relativ to the mouse cursor. That works quite fine.
Is it also possible to manipulate the coordinates of the drag image during drag move? In my case the x ccordinate of the drag image must be fixed and only the y coordinate can change so the drag image can only moved up and down.
So far I found no possibilities to handle that.

Thanks a lot, Szdnez

答:
You can't manipulate it using the HTML 5 drag an drop API, but you can do it with some libraries as the jquery ui draggable.
There's also a ton of libraries out there with the same intent. :)

$( function() {
    $( "#draggable" ).draggable({axis: 'x'});
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
  <p><b>[DRAG ME]</b><p>
  <p>Drag fixed to the x axis</p>
</div>

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

Body:
You can't manipulate it using the HTML 5 drag an drop API, but you can do it with some libraries as the jquery ui draggable.
There's also a ton of libraries out there with the same intent. :)

$( function() {
    $( "#draggable" ).draggable({axis: 'x'});
  } );

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
  <p><b>[DRAG ME]</b><p>
  <p>Drag fixed to the x axis</p>
</div>

</body>
</html>


问:
event.target[matches] error on form submit in Meteor React project
I am struggling with this bug. Here's my code:

It's long, so here's a short version: I have a form to create an event, I want handleSubmit() to handle error messages and if there are none, add event to db. I do import {Events}, in fact the form worked before I made some changes. When I run it, I get an error message: Uncaught TypeError: event.target[matches] is not a function. Thanks for anyone looking into this.

```<code>export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
    })
  }

  if (!this.state.error) {
      Events.insert({title: title, description: description});
      this.props.history.push('/home');
  }
</code>```

and:

```<code>     <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.title}</div>

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.description}</div>

        <button type="submit" className="btn btn-success">Create new event</button>
    </form>
</code>```

答:
So there are two problems with the code:

setState is async. It resolves after the function executes. Workaround: let error = false at the beginning and then set error = true together with setState call.

Empty objects are truthy. Thanks to error variable, we can just change the condition to if(!error). Or do if(error) {return} - this also works.

Oh, and the error message was from a chrome extension. Sucks that chrome doesn't tell you that an error message came from an extension - at least I don't think it does.

Best,

Body:
I am struggling with this bug. Here's my code:

It's long, so here's a short version: I have a form to create an event, I want handleSubmit() to handle error messages and if there are none, add event to db. I do import {Events}, in fact the form worked before I made some changes. When I run it, I get an error message: Uncaught TypeError: event.target[matches] is not a function. Thanks for anyone looking into this.

export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
    })
  }

  if (!this.state.error) {
      Events.insert({title: title, description: description});
      this.props.history.push('/home');
  }

and:

     <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>

{this.state.error.title}

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>

{this.state.error.description}

        <button type="submit" className="btn btn-success">Create new event</button>
    </form>


问:
Call BeanShell function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc
Pre-requisite:

Inside JMeter bin folder, I have edited BeanShellFunction.bshrc file to add my function as follows

```<code>String getMyString()
{
    return "MyString";
}
</code>```

I have enabled the BeanShellFunction.bshrc from jmeter.properties file as

beanshell.function.init = BeanShellFunction.bshrc

When I use the following syntax to call function it works fine.

```<code>${__BeanShell(getMyString())}
</code>```

It works fine for below case:

Question:

How can I call the same function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc.?

Analysis:

I tried with following but no luck:

```<code>String myStr = getMyString();
</code>```

It gives an error as:

Assertion error: true

  Assertion failure: false

  Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``  String myStr = getMyString();  print("MyStr: "+myStr);'' : Typed variable declaration : Command not found: getMyString()

答:
Add the next line to user.properties file (lives under "bin" folder of your JMeter installation)

```<code>beanshell.function.init=BeanShellFunction.bshrc
</code>```

Restart JMeter to pick the property up

Once done you should be able to use it wherever required

Same approach applies to

beanshell.sampler.init

beanshell.assertion.init

beanshell.listener.init

etc.

References:

Configuring JMeter

How to Use BeanShell: JMeter's Favorite Built-in Component

Body:
Pre-requisite:

Inside JMeter bin folder, I have edited BeanShellFunction.bshrc file to add my function as follows

String getMyString()
{
    return "MyString";
}

I have enabled the BeanShellFunction.bshrc from jmeter.properties file as

beanshell.function.init = BeanShellFunction.bshrc

When I use the following syntax to call function it works fine.

${__BeanShell(getMyString())}

It works fine for below case:

Question:

How can I call the same function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc.?

Analysis:

I tried with following but no luck:

String myStr = getMyString();

It gives an error as:

Assertion error: true

  Assertion failure: false

  Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``  String myStr = getMyString();  print("MyStr: "+myStr);'' : Typed variable declaration : Command not found: getMyString()

Body:
Add the next line to user.properties file (lives under "bin" folder of your JMeter installation)

beanshell.function.init=BeanShellFunction.bshrc

Restart JMeter to pick the property up

Once done you should be able to use it wherever required

Same approach applies to

beanshell.sampler.init

beanshell.assertion.init

beanshell.listener.init

etc.

References:

Configuring JMeter

How to Use BeanShell: JMeter's Favorite Built-in Component


问:
How to check if array contains more than one element?
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

```<code>if(array && array.length > 1)
</code>```

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

```<code>if(_.some(array))
</code>```

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

```<code>if(_.several(array))

if(_.many(array))
</code>```

Would I have to write my own extension method or did I just not find the right lodash command, yet?

答:
You can create own lodash mixin for that:

```<code>var myArray = [1, 2, 3];
var anotherArray = [4];

function several(array) {
  return _.get(array, 'length') > 1
}

_.mixin({ 'several': several });

console.log(_.several(myArray)) // ==> true
console.log(_.several(anotherArray)) // ==> false
</code>```

Example: https://jsfiddle.net/ecq7ddey/

Body:
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

if(array && array.length > 1)

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

if(_.some(array))

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

if(_.several(array))

if(_.many(array))

Would I have to write my own extension method or did I just not find the right lodash command, yet?

Body:
You can create own lodash mixin for that:

var myArray = [1, 2, 3];
var anotherArray = [4];

function several(array) {
  return _.get(array, 'length') > 1
}

_.mixin({ 'several': several });

console.log(_.several(myArray)) // ==> true
console.log(_.several(anotherArray)) // ==> false

Example: https://jsfiddle.net/ecq7ddey/


问:
box-sizing: border-box; is not properly working
I am trying to learn css and html5 and got stuck at form . I got a code from w3schools that if i want to make form at rectangular in shape i should use box-sizing: border-box in my css code but its happening here
Can you please have a take a look on my code :

#modal_form input[type=text] {
    width: 320px;
 height: 40px;
    padding: 12px 20px;
    margin: 8px 0;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="modal_form">
        <input type="text" name="name" class="name" placeholder="Full Name"><br>
       <input type="text" name="email" class="email" placeholder="Email address"><br>
        <input type="text" name="phone" class="email" placeholder="Phone no"><br>
       <input type="text" name="website" class="email" placeholder="Your Website"><br>
        <input type="text" name="question" class="email" placeholder="Your Question??">
        <center><input  class="form-control" type="submit" name="contact" id="submit" value="Send Message"></center>
      </form></code>```

Here its coming properly but in my code its coming like this :

May be i am using old template with earlier release of bootstrap and other , So what would be alternative

Thanks in advance@!!!

答:
box-sizing is used to manipulate the collision-box of elements, not the visual shape.

What you are looking for might be border-radius which I think bootstrap applies to your inputs. You should be able to fix it by adding border-radius: 0 to your CSS code. Since here on Stack is no bootstrap the inputs do not render with rounded corners.

Body:
I am trying to learn css and html5 and got stuck at form . I got a code from w3schools that if i want to make form at rectangular in shape i should use box-sizing: border-box in my css code but its happening here
Can you please have a take a look on my code :

#modal_form input[type=text] {
    width: 320px;
 height: 40px;
    padding: 12px 20px;
    margin: 8px 0;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
}

<form id="modal_form">
        <input type="text" name="name" class="name" placeholder="Full Name">

       <input type="text" name="email" class="email" placeholder="Email address">

        <input type="text" name="phone" class="email" placeholder="Phone no">

       <input type="text" name="website" class="email" placeholder="Your Website">

        <input type="text" name="question" class="email" placeholder="Your Question??">
        <input  class="form-control" type="submit" name="contact" id="submit" value="Send Message">
      </form>

Here its coming properly but in my code its coming like this :

May be i am using old template with earlier release of bootstrap and other , So what would be alternative

Thanks in advance@!!!


问:
How to allow only com and net domain name in regular expression in PHP
I am using regular expressions to validate emails in PHP. I want to allow only .com, or .net domain names. How can I achieve this?

My code:

```<code><?php
    $my_email = "name@company.com"

    if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/", $my_email)) {
        echo "$my_email is a valid email address";
    } else {
        echo "$my_email is NOT a valid email address";
    }
?>
</code>```

答:
Don't use regex for this.  The safest/simplest way is using php's filter_var() function and a check on the last four characters without regex.

```<code>if (filter_var($my_email, FILTER_VALIDATE_EMAIL) && in_array(substr($my_email, -4),['.com','.net'])) {
    echo "valid email";
}else{
    echo "invalid email";
}
</code>```

Sorry I could not test this code because my phone crashes when I try to use php sandbox.  (It may have a syntax error -- but the principle is here.)

Body:
I am using regular expressions to validate emails in PHP. I want to allow only .com, or .net domain names. How can I achieve this?

My code:

<?php
    $my_email = "name@company.com"

    if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/", $my_email)) {
        echo "$my_email is a valid email address";
    } else {
        echo "$my_email is NOT a valid email address";
    }
?>

Body:
Don't use regex for this.  The safest/simplest way is using php's filter_var() function and a check on the last four characters without regex.

if (filter_var($my_email, FILTER_VALIDATE_EMAIL) && in_array(substr($my_email, -4),['.com','.net'])) {
    echo "valid email";
}else{
    echo "invalid email";
}

Sorry I could not test this code because my phone crashes when I try to use php sandbox.  (It may have a syntax error -- but the principle is here.)


问:
Find query with conditions
I have a collection of documents where each document has the following properties: userId, permissions.

How can I use the findOne query to return a document that has userId = 41 AND permissions = admin OR permissions = op-admin ?

I've tried the following query but it doesn't returns any results...

```<code>User.findOne(
  {
    'userId': 42
  },
  {
    $and: [
      {
        $or: {'permissions': 'admin'}
      },
      {
        $or: {'permissions': 'op-admin'}
      }
    ]
  }, function(err, doc) {
  if(err) {
    console.log(doc);
    console.log(err);
  }
});
</code>```

Is there something I'm not doing correctly?

答:
try :    </p>

```<code>User.find({
          $and: [  {'userId': 42 } ,
              { $or: [ {'permissions': 'admin'}, {'permissions': 'op-admin'} ] }
          ]})
</code>```

Title: Find query with conditions

Body:
I have a collection of documents where each document has the following properties: userId, permissions.

How can I use the findOne query to return a document that has userId = 41 AND permissions = admin OR permissions = op-admin ?

I've tried the following query but it doesn't returns any results...

User.findOne(
  {
    'userId': 42
  },
  {
    $and: [
      {
        $or: {'permissions': 'admin'}
      },
      {
        $or: {'permissions': 'op-admin'}
      }
    ]
  }, function(err, doc) {
  if(err) {
    console.log(doc);
    console.log(err);
  }
});

Is there something I'm not doing correctly?

Body:
try :

User.find({
          $and: [  {'userId': 42 } ,
              { $or: [ {'permissions': 'admin'}, {'permissions': 'op-admin'} ] }
          ]})


问:
Read/Write Snapshots in Azure/AWS
We're trying to get information about Azure and/or AWS in terms of their ability to create snapshots of data drives that are writable and can be attached to VMs.

Currently we use a model with our test environments on-prem, where we have a clone of a set of production databases/logs on drives that are quite large (+2TB) on our EMC SAN.  Instead of making full copies of the clone for each test environment DB server, we use EMC VNX redirect-on-write snapshots.  This allows us to quickly provision the DB server VM in the test environment without having to make a full copy of the DB/logs, and saves on SAN space, as only the delta from new writes to the snapshot are stored as new data.  This works really well as we only need one full copy of the source DBs/logs.

Does anyone know if Azure or AWS has the ability to do something similar or a reasonable alternative?  Making full copies of the databases/logs for each test environment is not really an option for us.  We started looking at the Azure SQL Database copy feature but we were not sure if this creates a full copies or writable snapshots.

Thanks in advance.

答:
Does anyone know if Azure or AWS has the ability to do something similar or a reasonable alternative?

Azure VM Disk uses Azure Page Blob to store data. Until now, the snapshot of a Azure blob can be read, copied, or deleted, but not modified.

I am sorry to tell that Azure doesn't provide the similar thing to fit your requirement. In Azure, we do need to use AzCopy to copy the whole blob to make the new blob writable.

Title: Read/Write Snapshots in Azure/AWS


问:
Subtle curve on bottom of div
I am trying to achieve a subtle curve at the bottom of my

Here is an example image of what i am trying to achieve

I tried to achieve it by doing this :

```<code>section.box{
    border-bottom-left-radius: 40%;
    border-bottom-right-radius: 40%;
}
</code>```

This is what I'm getting.

What can i do to change this?

UPDATE

What I have tried :

.box{
  height: 300px;
  background-color: white;
}

.round-bottom{
  background-color: pink;
  height: 200px;

  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <section class="round-bottom">

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

答:
use Ellipse border to border-radius you can learn more about it please be refer this https://www.w3schools.com/css/css3_borders.asp

#rcorners9 {
   border-bottom-left-radius: 95% 65%;
    border-bottom-right-radius: 95% 65%;
    background: #FF3352;
    padding: 20px;
    width:100%;
    height: 10px;
    box-shadow: 1px -5px 22px ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="rcorners9"></p></code>```

Title: Subtle curve on bottom of div

Body:
I am trying to achieve a subtle curve at the bottom of my

Here is an example image of what i am trying to achieve

I tried to achieve it by doing this :

section.box{
    border-bottom-left-radius: 40%;
    border-bottom-right-radius: 40%;
}

This is what I'm getting.

What can i do to change this?

UPDATE

What I have tried :

.box{
  height: 300px;
  background-color: white;
}

.round-bottom{
  background-color: pink;
  height: 200px;

  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}

Body:
use Ellipse border to border-radius you can learn more about it please be refer this https://www.w3schools.com/css/css3_borders.asp

#rcorners9 {
   border-bottom-left-radius: 95% 65%;
    border-bottom-right-radius: 95% 65%;
    background: #FF3352;
    padding: 20px;
    width:100%;
    height: 10px;
    box-shadow: 1px -5px 22px ;
}

<p id="rcorners9"></p>


问:
JQuery not working in bootstrap remote Modal
bootstrap 3.Modal work in the remote mode. using input floating label using jquery is not working in remote Modal

index.html

```<code><div class="loginButton col-md-auto col-lg-auto hidden-sm hidden-xs" type="button" data-toggle="modal" data-target="#login"></div>

     <div class="modal fade bs-example-modal-lg" id="login" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-remote="login.html" aria-hidden="true">
            <div class="modal-xxlg" role="document">
                <div class="modal-content loginContainer">
                </div>
            </div>
        </div>
</code>```

login.html

```<code><div class="modal-header">
    <div class="row">
        <h4 class="modal-title " id="myModalLabel">User Login</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
</div>
<div class="modal-body">
    <section class="login-container row">
        <div class="login col-sm-12 col-md-12 col-lg-6">
            <div class="boxed">
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="agent">
                        <form role="form">
                             <div class="form-group float-label-control col-sm-4 ">
                               <label for="">Maximum Count</label>
                               <input type="text" class="form-control" placeholder="Maximum Count">
                             </div>
                        </form>
                    </div>
                    <div role="tabpane2" class="tab-pane" id="customer">
                                            <p>weterter</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>
<div class="modal-footer">
</div>
</code>```

using floating label ref link

答:
You are missing 2 things. Your input must have the empty class and your label must be after the input:

User Login

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                        <form role="form">

                               <input type="text" class="form-control empty" placeholder="Maximum Count">
                               Maximum Count

                        </form>

weterter

```

Body:
bootstrap 3.Modal work in the remote mode. using input floating label using jquery is not working in remote Modal

index.html

login.html

User Login

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                        <form role="form">

                               Maximum Count
                               <input type="text" class="form-control" placeholder="Maximum Count">

                        </form>

weterter

using floating label ref link

Body:
You are missing 2 things. Your input must have the empty class and your label must be after the input:

<div class="modal-header">
    <div class="row">
        <h4 class="modal-title " id="myModalLabel">User Login</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
</div>
<div class="modal-body">
    <section class="login-container row">
        <div class="login col-sm-12 col-md-12 col-lg-6">
            <div class="boxed">
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="agent">
                        <form role="form">
                             <div class="form-group float-label-control col-sm-4 ">
                               <input type="text" class="form-control empty" placeholder="Maximum Count">
                               <label for="">Maximum Count</label>
                             </div>
                        </form>
                    </div>
                    <div role="tabpane2" class="tab-pane" id="customer">
                                            <p>weterter</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>
<div class="modal-footer">
</div>


问:
How to prevent matching two routes with react-router v4?
I have the following two routes: /items and /items/buy.

Each route corresponds to a Tab in a single view. Both routes are rendered with an exact prop, but still, two tabs are being marked as active when navigating to /items/buy.

I already tried using withRouter, but I noticed changing /items to /items/sell fixes the problem, but I don't wanna have that route.

I understand rrv4 is matching the first part of my route /items and the other route too /items/buy, but I think that shouldn't be happening if I'm using exact. Any clues on why this is happening?

Ahh I forgot to say I am already using a Switch.

Thanks for your help!

答:
You need to put your routes in a <Switch> component. The switch will only render the first route that matches.

```<code>import {Route, Switch} from 'react-router-dom';

<Switch>
  <Route exact path="/" component={Main} />
  <Route exact path="/items" component={SomeComponent} />
  <Route exact path="/items/buy" component={SomeOtherComponent} />
  <Route component={NotFound} />
</Switch>
</code>```

Body:
You need to put your routes in a <Switch> component. The switch will only render the first route that matches.

import {Route, Switch} from 'react-router-dom';

<Switch>
  <Route exact path="/" component={Main} />
  <Route exact path="/items" component={SomeComponent} />
  <Route exact path="/items/buy" component={SomeOtherComponent} />
  <Route component={NotFound} />
</Switch>


问:
Locking entity in MVC

Short question

How can I lock my entity so that only one operation by only one user can be performed on it at a time in MVC project?

Long question

I have MVC project where I want my action methods to be [SessionState(SessionStateBehavior.ReadOnly)]. But when doing this users can execute another action methods even before one long running action method has not completed. As I have a lot calculations and action methods have to be executed in predefined order, executing another Action method before one ends creates lots of problems. To give example I have main entity called Report, I have to somehow ensure that one report undergoes only one operation by only one user at a time. So I have to lock my Report. Even if I do not use [SessionState(SessionStateBehavior.ReadOnly)] I have to lock report so that multiple users do not edit same reports at a time and for other specific reasons. Currently I am writing this information to database roughly something like:

```<code>ReportId
LockedUserId
IsInPorcess
</code>```

I have to set IsInProcess to true every time before operation begins and reset it to false after operation completed. As I have lots of action methods I created ActionFilter something like below:

```<code>public class ManageReportLockAttribute
    : FilterAttribute, IActionFilter
{
    public ManageReportLockAttribute()
    {
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        if(lockInfo.IsInProcess)
            RedirectToInformationView();

        lockInfo.IsInProcess = true;
        SaveToDatabase(lockInfo);
        ...
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        lockInfo.IsInProcess = false;
        SaveToDatabase(lockInfo);
        ...
    }
}
</code>```

It works, for most part, but it has some strange problems (see this question for more info).
My question is that "How can I achieve same functionality (locking report) by different more acceptable way?".
I feel like it is something similar to locking when using multithreading, but it is not  exactly same IMO.

Sorry for long, broad and awkward question, but I want a direction to follow. Thanks in advance.

答:
One reason why OnActionExecuted is not called though OnActionExecuting runs as expected is that there are unhandled exceptions that occur in OnActionExecuting. Especially when dealing with the database, there are various reasons that could lead to an exception, e.g.:

User1 starts the process and locks the entity.

User2 also wants to start the process before User1 has saved the change. So the check of IsInProcess does not lead to the redirection and User2 also wants to save the lock. In this case, a concurrency violation should occur because User1 has saved the entity in the meantime.

To illustrate the process over time (C is the check whether IsInProcess is set, S is SaveChanges): first a good case:

```<code>User1     CS
User2       CS (check is done after save, no problem)
</code>```

Now a bad case:

```<code>User1     CS
User2      CS (check takes place after check for User1, but before SaveChanges becomes effective ==> concurrency violation)
</code>```

As the example shows, it is critical to make sure that only one user can place the lock. There are several ways to handle this. In all cases make sure that there are as few reasons for exceptions in OnActionExecuting as possible. Handle and log the exceptions.

Please note that all synchronisation methods will have a negative impact on the performance of your application. So if you haven't already thought about whether you could avoid having to lock the report by restructuring your actions or the data model, this would be the first thing to do.

Easy approach: thread synchronisation

An easy approach is to use thread synchronisation. This approach will only work if the application runs in a single process and not in a web farm/the cloud. You need to decide whether you will be able to change the application if it will be installed in a farm at a later point in time. This sample shows an easy approach (that uses a static object for locking):

```<code>public class ManageReportLockAttribute
    : FilterAttribute, IActionFilter
{
    private static readonly object lockObj = new object();
    // ...
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        if(lockInfo.IsInProcess)
          RedirectToInformationView();
        lock(lockObj)
        {
          // read anew just in case the lock was set in the meantime
          // A new context should be used.
          lockInfo = GetFromDatabase(reportId);
          if(lockInfo.IsInProcess)
            RedirectToInformationView();
          lockInfo.IsInProcess = true;
          SaveToDatabase(lockInfo);
          ...
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
      ...
      lock(lockObj)
      {
        lockInfo = GetFromDatabase(reportId);
        if (lockInfo.IsInProcess) // check whether lock was released in the meantime
        {
          lockInfo.IsInProcess = false;
          SaveToDatabase(lockInfo);
        }
        ...
      }
    }
}
</code>```

For details on using lock see this link. If you need more control, have a look at the overview of thread synchronization with C#. A named mutex is an alternative that provides locking in a more fine coarsed manner.

If you want to lock on reportId instead of a static object, you need to use a lock object that is the same for the same reportId. A dictionary can store the lock objects:

```<code>private static readonly IDictionary<int, object> lockObjectsByReportId = new Dictionary<int, object>();

private static object GetLockObjectByReportId(int reportId)
{
  int lockObjByReportId;
  if (lockObjectsByReportId.TryGetValue(reportId, out lockObjByReportId))
    return lockObjByReportId;
  lock(lockObj)  // use global lock for a short operation
  {
    if (lockObjectsByReportId.TryGetValue(reportId, out lockObjByReportId))
      return lockObjByReportId;
    lockObjByReportId = new object();
    lockObjectsByReportId.Add(reportId, lockObjByReportId);
    return lockObjByReportId;
  }
}
</code>```

Instead of using lockObj in OnActionExecuting and OnActionExecuted, you'd use the function:

```<code>// ...
lock(GetLockObjectByReportId(reportId))
{
  // ...
}
</code>```

Database approach: Transactions and isolation levels

Another way to handle this is to use database transactions and isolation levels. This approach will also work in a multi-server environment. In this case, you'd not use the entity framework for database access but move the code to a stored procedure that is run on the database server. By running the stored procedure in a transaction and picking the right isolation level, you can avoid that a user can read the data while another one is changing them.

This link shows an overview of isolation levels for SQL Server.

Title: Locking entity in MVC

Body:
Short question

How can I lock my entity so that only one operation by only one user can be performed on it at a time in MVC project?

Long question

I have MVC project where I want my action methods to be [SessionState(SessionStateBehavior.ReadOnly)]. But when doing this users can execute another action methods even before one long running action method has not completed. As I have a lot calculations and action methods have to be executed in predefined order, executing another Action method before one ends creates lots of problems. To give example I have main entity called Report, I have to somehow ensure that one report undergoes only one operation by only one user at a time. So I have to lock my Report. Even if I do not use [SessionState(SessionStateBehavior.ReadOnly)] I have to lock report so that multiple users do not edit same reports at a time and for other specific reasons. Currently I am writing this information to database roughly something like:

ReportId
LockedUserId
IsInPorcess

I have to set IsInProcess to true every time before operation begins and reset it to false after operation completed. As I have lots of action methods I created ActionFilter something like below:

public class ManageReportLockAttribute
    : FilterAttribute, IActionFilter
{
    public ManageReportLockAttribute()
    {
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        if(lockInfo.IsInProcess)
            RedirectToInformationView();

        lockInfo.IsInProcess = true;
        SaveToDatabase(lockInfo);
        ...
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        lockInfo.IsInProcess = false;
        SaveToDatabase(lockInfo);
        ...
    }
}

It works, for most part, but it has some strange problems (see this question for more info).
My question is that "How can I achieve same functionality (locking report) by different more acceptable way?".
I feel like it is something similar to locking when using multithreading, but it is not  exactly same IMO.

Sorry for long, broad and awkward question, but I want a direction to follow. Thanks in advance.

Body:
One reason why OnActionExecuted is not called though OnActionExecuting runs as expected is that there are unhandled exceptions that occur in OnActionExecuting. Especially when dealing with the database, there are various reasons that could lead to an exception, e.g.:

User1 starts the process and locks the entity.

User2 also wants to start the process before User1 has saved the change. So the check of IsInProcess does not lead to the redirection and User2 also wants to save the lock. In this case, a concurrency violation should occur because User1 has saved the entity in the meantime.

To illustrate the process over time (C is the check whether IsInProcess is set, S is SaveChanges): first a good case:

User1     CS
User2       CS (check is done after save, no problem)

Now a bad case:

User1     CS
User2      CS (check takes place after check for User1, but before SaveChanges becomes effective ==> concurrency violation)

As the example shows, it is critical to make sure that only one user can place the lock. There are several ways to handle this. In all cases make sure that there are as few reasons for exceptions in OnActionExecuting as possible. Handle and log the exceptions.

Please note that all synchronisation methods will have a negative impact on the performance of your application. So if you haven't already thought about whether you could avoid having to lock the report by restructuring your actions or the data model, this would be the first thing to do.

Easy approach: thread synchronisation

An easy approach is to use thread synchronisation. This approach will only work if the application runs in a single process and not in a web farm/the cloud. You need to decide whether you will be able to change the application if it will be installed in a farm at a later point in time. This sample shows an easy approach (that uses a static object for locking):

public class ManageReportLockAttribute
    : FilterAttribute, IActionFilter
{
    private static readonly object lockObj = new object();
    // ...
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
        ReportLockInfo lockInfo = GetFromDatabase(reportId);
        if(lockInfo.IsInProcess)
          RedirectToInformationView();
        lock(lockObj)
        {
          // read anew just in case the lock was set in the meantime
          // A new context should be used.
          lockInfo = GetFromDatabase(reportId);
          if(lockInfo.IsInProcess)
            RedirectToInformationView();
          lockInfo.IsInProcess = true;
          SaveToDatabase(lockInfo);
          ...
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
      ...
      lock(lockObj)
      {
        lockInfo = GetFromDatabase(reportId);
        if (lockInfo.IsInProcess) // check whether lock was released in the meantime
        {
          lockInfo.IsInProcess = false;
          SaveToDatabase(lockInfo);
        }
        ...
      }
    }
}

For details on using lock see this link. If you need more control, have a look at the overview of thread synchronization with C#. A named mutex is an alternative that provides locking in a more fine coarsed manner.

If you want to lock on reportId instead of a static object, you need to use a lock object that is the same for the same reportId. A dictionary can store the lock objects:

private static readonly IDictionary<int, object> lockObjectsByReportId = new Dictionary<int, object>();

private static object GetLockObjectByReportId(int reportId)
{
  int lockObjByReportId;
  if (lockObjectsByReportId.TryGetValue(reportId, out lockObjByReportId))
    return lockObjByReportId;
  lock(lockObj)  // use global lock for a short operation
  {
    if (lockObjectsByReportId.TryGetValue(reportId, out lockObjByReportId))
      return lockObjByReportId;
    lockObjByReportId = new object();
    lockObjectsByReportId.Add(reportId, lockObjByReportId);
    return lockObjByReportId;
  }
}

Instead of using lockObj in OnActionExecuting and OnActionExecuted, you'd use the function:

// ...
lock(GetLockObjectByReportId(reportId))
{
  // ...
}

Database approach: Transactions and isolation levels

Another way to handle this is to use database transactions and isolation levels. This approach will also work in a multi-server environment. In this case, you'd not use the entity framework for database access but move the code to a stored procedure that is run on the database server. By running the stored procedure in a transaction and picking the right isolation level, you can avoid that a user can read the data while another one is changing them.

This link shows an overview of isolation levels for SQL Server.


问:
AngularJS: How to bind properties of an object to scope
I am new to use AngularJS and I am an absolute beginner. I tried using filters. I tried binding to the properties instead of directly binding the object. But the code shows {{x.people}} as the output instead of showing the list. What am I missing out here? </p>

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

<head>
    <title>ANGULAR APP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
    </script>
</head>

<body ng-app="myApp" ng-controller="myFirstController">
    <p>Type a letter in the input field:</p>
    <p><input type="text" ng-model="test"></p>
    <ul>
        <li ng-repeat="x in model.people">
            {{ x.name }}
        </li>
    </ul>
</body>

<script>
var app = angular.module('myApp', []);
var myFirstController = function($scope) {
    $scope.model = {
        people: [{
                name: 'Jani',
                country: 'Norway'
            },
            {
                name: 'Carl',
                country: 'Sweden'
            },
            {
                name: 'Margareth',
                country: 'England'
            },
            {
                name: 'Hege',
                country: 'Norway'
            },
            {
                name: 'Joe',
                country: 'Denmark'
            },
            {
                name: 'Gustav',
                country: 'Sweden'
            },
            {
                name: 'Birgit',
                country: 'Denmark'
            },
            {
                name: 'Mary',
                country: 'England'
            },
            {
                name: 'Kai',
                country: 'Norway'
            }
        ];
    };
}

app.controller('myFirstController', myFirstController);
</script>
</html>
</code>```

答:
there is an unnecessary ; at the end of your json data:

```<code>$scope.model = {
  people:[
    ...                                   // your data
    {name:'Kai',country:'Norway'}];       // <------ here the ; is illegal
  };
}
</code>```

refer below fixed example:

var app = angular.module('myApp', []);
var myFirstController = function($scope) {
  $scope.model = {
    people: [{
        name: 'Jani',
        country: 'Norway'
      },
      {
        name: 'Carl',
        country: 'Sweden'
      },
      {
        name: 'Margareth',
        country: 'England'
      },
      {
        name: 'Hege',
        country: 'Norway'
      },
      {
        name: 'Joe',
        country: 'Denmark'
      },
      {
        name: 'Gustav',
        country: 'Sweden'
      },
      {
        name: 'Birgit',
        country: 'Denmark'
      },
      {
        name: 'Mary',
        country: 'England'
      },
      {
        name: 'Kai',
        country: 'Norway'
      }
    ]
  };
}

app.controller('myFirstController', myFirstController);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myFirstController">
  <p><input type="text" ng-model="test"></p>
  <ul>
    <li ng-repeat="x in model.people | filter: {name: test}">
      {{ x.name }}
    </li>
  </ul>
</div></code>```

Body:
I am new to use AngularJS and I am an absolute beginner. I tried using filters. I tried binding to the properties instead of directly binding the object. But the code shows {{x.people}} as the output instead of showing the list. What am I missing out here?

<!DOCTYPE html>

    <title>ANGULAR APP</title>

Type a letter in the input field:

<input type="text" ng-model="test">

            {{ x.name }}

Body:
there is an unnecessary ; at the end of your json data:

$scope.model = {
  people:[
    ...                                   // your data
    {name:'Kai',country:'Norway'}];       // <------ here the ; is illegal
  };
}

refer below fixed example:

var app = angular.module('myApp', []);
var myFirstController = function($scope) {
  $scope.model = {
    people: [{
        name: 'Jani',
        country: 'Norway'
      },
      {
        name: 'Carl',
        country: 'Sweden'
      },
      {
        name: 'Margareth',
        country: 'England'
      },
      {
        name: 'Hege',
        country: 'Norway'
      },
      {
        name: 'Joe',
        country: 'Denmark'
      },
      {
        name: 'Gustav',
        country: 'Sweden'
      },
      {
        name: 'Birgit',
        country: 'Denmark'
      },
      {
        name: 'Mary',
        country: 'England'
      },
      {
        name: 'Kai',
        country: 'Norway'
      }
    ]
  };
}

app.controller('myFirstController', myFirstController);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myFirstController">
  <p><input type="text" ng-model="test"></p>
  <ul>
    <li ng-repeat="x in model.people | filter: {name: test}">
      {{ x.name }}
    </li>
  </ul>
</div>


问:
Need fast algorithm to find mutually exclusive networks(relations) from trillions of relationship records
I am explaining my problem with a hypothetical table with two columns(col1, col2) like this:

```<code>col1   col2
A <--> B
A <--> C
E <--> F
B <--> D
E <--> G
</code>```

This table is in a file. In the above case I would like to divide this into mutually exclusive relationship files. So, the results for above table would be two files(tables):

```<code>col1   col2
A <--> B
A <--> C
B <--> D
</code>```

and

```<code>col1   col2
E <--> F
E <--> G
</code>```

The real file has trillions of unique records (relations) and I want to divide it into mutually exclusive relationship files. Need help with any smart algorithms. I am using pyspark to read the table from parquet file. So, any pyspark code would be very nice but not necessary(algorithm is more important).

答:
By "mutually exclusive" you probably mean not having a node in common. This problem is known as the enumeration of connected components in a graph. You can address it with the Union-Find technique.

To every node, you will associate a link to another node that belongs to the same component. When taking a new relation into account, make one of the members link to the other.

See https://en.wikipedia.org/wiki/Disjoint-set_data_structure for details.
This process is fast and you can accelerate it by so-called path-compression techniques.

In the end, every component has a single node that is not linked to any  other and it is not a big deal to list all components and the nodes they include.

Steps in the processing of the given example could be

```<code>A -> B
C -> A -> B
C -> A -> B, E -> F
C -> A -> B -> D, E -> F
C -> A -> B -> D, E -> F -> G
</code>```

(the fact that you get linear lists is purely accidental).

Body:
I am explaining my problem with a hypothetical table with two columns(col1, col2) like this:

col1   col2
A <--> B
A <--> C
E <--> F
B <--> D
E <--> G

This table is in a file. In the above case I would like to divide this into mutually exclusive relationship files. So, the results for above table would be two files(tables):

col1   col2
A <--> B
A <--> C
B <--> D

and

col1   col2
E <--> F
E <--> G

The real file has trillions of unique records (relations) and I want to divide it into mutually exclusive relationship files. Need help with any smart algorithms. I am using pyspark to read the table from parquet file. So, any pyspark code would be very nice but not necessary(algorithm is more important).

Body:
By "mutually exclusive" you probably mean not having a node in common. This problem is known as the enumeration of connected components in a graph. You can address it with the Union-Find technique.

To every node, you will associate a link to another node that belongs to the same component. When taking a new relation into account, make one of the members link to the other.

See https://en.wikipedia.org/wiki/Disjoint-set_data_structure for details.
This process is fast and you can accelerate it by so-called path-compression techniques.

In the end, every component has a single node that is not linked to any  other and it is not a big deal to list all components and the nodes they include.

Steps in the processing of the given example could be

A -> B
C -> A -> B
C -> A -> B, E -> F
C -> A -> B -> D, E -> F
C -> A -> B -> D, E -> F -> G

(the fact that you get linear lists is purely accidental).


问:
Working with matrices using LibreOffice Basic (LibreOffice Calc)
I am going to use the following formula on every cell of a 4 × 6 (m×n in the code) matrix to get the normalized matrix:

The matrix in Calc is:

I use the following Basic code in LibreOffice:

```<code>REM  *****  BASIC  *****

Sub Main

Normalize(5,3)

End Sub

Sub Normalize (ByVal n As Integer,ByVal m As Integer)

Dim Doc As Object
Dim Sheet As Object
Dim SrcCell 'Cell in the source matrix
Dim TargetCell 'Cell in the target matrix where normalized values are saved
Dim TempCell As Object

Dim I 'index
Dim J 'index
Dim JJ 'inner index
Dim Sum 'Sigma x_ij^2 (j=0 to m)
Dim m 'maximum row index
Dim n 'maximum column index

Doc = ThisComponent
Sheet = Doc.Sheets(0)

For I = 0 to n  'traverse columns
    For J=0 to m 'traverse rows
        SrcCell = Sheet.getCellByPosition(I,J)
        'Now apply the normalization formula for this cell
        'Run a new loop to run formula on this cell
        Sum = 0 'Reset Sum to 0
        For JJ=0 to m
            TempCell = Sheet.getCellByPosition(I,JJ)
            Sum = Sum + (TempCell.Value^2)
        Next
        TargetCell = Sheet.getCellByPosition(I+n+1,J) 'Place the normalized cells in a new matrix cell, n+1 cells away

        'Put the sum in the formula
        TargetCell.Value = SrcCell.Value/Sqr(Sum)

    Next

Next

End Sub
</code>```

I want am going to have the normalized matrix appear on the right side of the original one. But nothing appears. What am I doing wrong?

答:
The code uses n and m as parameters but then declares them, destroying the values.  To fix, remove the following two lines.  For readability, move these comments near Sub Normalize.

Dim m 'maximum row index
Dim n 'maximum column index
```

To find such problems with the Basic IDE debugger, press Breakpoint On/Off in the toolbar to set a couple of breakpoints, and also Enable Watch.

Body:
I am going to use the following formula on every cell of a 4 × 6 (m×n in the code) matrix to get the normalized matrix:

The matrix in Calc is:

I use the following Basic code in LibreOffice:

REM  *****  BASIC  *****

Sub Main

Normalize(5,3)

End Sub

Sub Normalize (ByVal n As Integer,ByVal m As Integer)

Dim Doc As Object
Dim Sheet As Object
Dim SrcCell 'Cell in the source matrix
Dim TargetCell 'Cell in the target matrix where normalized values are saved
Dim TempCell As Object

Dim I 'index
Dim J 'index
Dim JJ 'inner index
Dim Sum 'Sigma x_ij^2 (j=0 to m)
Dim m 'maximum row index
Dim n 'maximum column index

Doc = ThisComponent
Sheet = Doc.Sheets(0)

For I = 0 to n  'traverse columns
    For J=0 to m 'traverse rows
        SrcCell = Sheet.getCellByPosition(I,J)
        'Now apply the normalization formula for this cell
        'Run a new loop to run formula on this cell
        Sum = 0 'Reset Sum to 0
        For JJ=0 to m
            TempCell = Sheet.getCellByPosition(I,JJ)
            Sum = Sum + (TempCell.Value^2)
        Next
        TargetCell = Sheet.getCellByPosition(I+n+1,J) 'Place the normalized cells in a new matrix cell, n+1 cells away

        'Put the sum in the formula
        TargetCell.Value = SrcCell.Value/Sqr(Sum)

    Next

Next

End Sub

I want am going to have the normalized matrix appear on the right side of the original one. But nothing appears. What am I doing wrong?

Body:
The code uses n and m as parameters but then declares them, destroying the values.  To fix, remove the following two lines.  For readability, move these comments near Sub Normalize.

Dim m 'maximum row index
Dim n 'maximum column index

To find such problems with the Basic IDE debugger, press Breakpoint On/Off in the toolbar to set a couple of breakpoints, and also Enable Watch.


问:
bootstrap make accordion responsive?
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

```<code>        <div class="row">

            <div class="panel-group" id="accordion">

                <?php
                foreach ($states as &$state) {
                    ?>
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h4 class="panel-title">
                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?></a>
                            </h4>
                        </div>
                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.</div>
                        </div>
                    </div>
                <?php }
                ?>
            </div>

        </div>
</code>```

EDIT

This is my edided html

```<code>            <div class="row">

                <div class="col-md-4 col-xs-12">

                    <div class="panel-group" id="accordion">

                        <?php
                        foreach ($states as &$state) {
                            ?>
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?></a>
                                    </h4>
                                </div>
                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">
                                    <div class="panel-body">test</div>
                                </div>
                            </div>
                        <?php }
                        ?>

                    </div>

                </div>

            </div>
</code>```

and it looks like this now. Only one slim column in desktop resolution

答:
I am not sure this is what you mean, but wouldn't it be enough to wrap your accordion in a col- class?

Like:

```<code><div class="row">
     <div class="col-xs-12 col-md-4">
        <div class="panel-group" id="accordion">

            <?php
            foreach ($states as &$state) {
                ?>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                <?php echo $state; ?></a>
                        </h4>
                    </div>
                    <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                            minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                            commodo consequat.</div>
                    </div>
                </div>
            <?php }
            ?>
        </div>
   </div><!-- colse col-md-4 -->
    </div>
</code>```

Title: bootstrap make accordion responsive?

Body:
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

                <?php
                foreach ($states as &$state) {
                    ?>

                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?>

                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.

                <?php }
                ?>

EDIT

This is my edided html

                        <?php
                        foreach ($states as &$state) {
                            ?>

                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?>

                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">

test

                        <?php }
                        ?>

and it looks like this now. Only one slim column in desktop resolution

Body:
I am not sure this is what you mean, but wouldn't it be enough to wrap your accordion in a col- class?

Like:

<div class="row">
     <div class="col-xs-12 col-md-4">
        <div class="panel-group" id="accordion">

            <?php
            foreach ($states as &$state) {
                ?>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                <?php echo $state; ?></a>
                        </h4>
                    </div>
                    <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                            minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                            commodo consequat.</div>
                    </div>
                </div>
            <?php }
            ?>
        </div>
   </div><!-- colse col-md-4 -->
    </div>


问:
Why are there so many data structures absent from high level languages?
Why is it that higher level languages (Javascript, PHP, etc.) don't offer data structures such as linked lists, queues, binary trees, etc. as part of their standard library? Is it for historical/practical/cultural reasons or is there something more fundamental that I'm missing.</p>

答:
There are many definitions of "high level" when it comes to languages, but I will take it in this context to refer to languages that are purpose-built for a specific domain (4GL anyone?).  Such "specific domains" are typically restricted in scope, for example: web page construction, report writing, database querying, etc.  Within that limited scope, there is frequently little need for anything but the most basic data structures.

Is There a Need?

Let's consider the case of Javascript.  The scope of this language was originally very bounded, being a scripting language than ran within the confines of a web browser.  It was concerned primarily with providing a small amount of dynamic behaviour on otherwise static web pages.  Furthermore, the limitations of the technology made it impractical to write large components in that environment (notably performance and the sandbox model).

Since Javascript was confined to address "small problems", there was little need for a rich set of data structures.  As data structures go, the Javascript's map is very flexible.  You must remember that Basic and FORTRAN went a long way providing only arrays -- maps are considerably more flexible than that.  Javascript appears to be undergoing a transformation, escaping the sandbox.  Some very ambitious systems are being built in Javascript, both within and outside of the browser.  And the technology is advancing to keep up with it (witness the new Javascript engines, persistence models, and so on).  I anticipate that the demand for more interesting data structures will increase, and that the demand will be met.

Library capabilities generally appear as needs arise.  Many of the basic data structures are so easy to implement that it hardly seems worth adding them to a library -- especially if that library needs to go through some sort of standardization process.  This is why so many languages (of all levels) do not provide them out of the box.  But I think that there is another force at work that will change all that... the rise of multiprogramming.

A New Need Arising?

It wasn't too long ago that the code that most developers wrote ran within the confines of a single thread.  But now, our systems are full of threads, web workers, agents, coroutines, clusters, clouds and all manner of concurrent systems.  This changes the whole complexion of implementing data structures from scratch.

In a single-threaded context, it is trivial to implement a linked list in almost any language.  But add concurrency to the mix and now it takes a great deal of effort to get it right.  One really needs to be a specialist to stand a chance at all.  That is why you see rich collection frameworks in all the latest languages.  The need to share data structures across thread boundaries (or worse) is being fulfilled.

History... But Not The Future

So, to summarize, I think the reason why rich data structures are conspicuously absent from many languages is largely historical.  The need was not great enough to justify the effort.  But there are new forces at work, in the form of highly concurrent systems, that force language libraries to provide industrial strength implementations of the richer data structures.