问:
StringTokenizer NoSuchElements
I have created a method that reads a file set like this (//... are comments, ignore them):

```<code>5 // n jobs
2 // n tools
1 4 5 6 2
1 5 4 2 3
</code>```

The matrix represents the tools used for each job but it doesn't really matter here.

Here is the method :

```<code>public static JobS inputJobMatrix(){
    String line = ""; // Line in tokenizer
    int jobN = inputJobN(); //First number of the file (jobs) works
    int toolN = inputToolN(); //Second number of the file (tools) works
    //Instancing JobS object
    JobS inputJobS = new JobS(jobN, toolN);
    int[][] tabFill = new int[jobN][toolN];
    int[] tabFillOrder = new int[jobN];
    try {
        // Initializing reader.
        FileReader fr = new FileReader("input.txt");
        BufferedReader br = new BufferedReader(fr);
        StringTokenizer st = new StringTokenizer(line);
        for(int i=0; i<3; i++){ //ReachFirstLine of matrix
            line = br.readLine();
            //System.out.println(line);
        }
        //Instancing tab for Job Order 1...n
        int[] a = new int[jobN];
        for (int i=0; i<jobN; i++){
            a[i]=i+1;
        }
        //Filling Order tab with Job order
        JobS.fillLine(tabFillOrder, a, 0); //Fills the tab with the tab a (make a copy of it we could say)
        //Reading the matrix line by line and filling tab line
        for(int i=0; i<jobN; i++){
            for(int j=0; j<toolN; j++){
                String str = st.nextToken();
                System.out.println(str);
                tabFill[i][j] = Integer.parseInt(str);
            }
            line = br.readLine();
        }
        inputJobS.setJobS(tabFill);
        br.close();

    } catch (IOException e) {
        System.out.println("File not found exception in inputJobMatrix.");
    }
    return inputJobS;

}
</code>```

Which results in :

```<code>Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at pProgra.ReadJobS.inputJobMatrix(ReadJobS.java:84)
at pProgra.PPMain.main(PPMain.java:14)
</code>```

I've tried looking for problems in my loops but didnt find any, and i can't understand why it doesn't work.
The goal here is to fill a bidimensionnal int array with the matrix of the input file (for exemple the one i've given previously with jobs and tools) and use that array for my object (JobS, i'll give the constructor here too if it can help) :

```<code>public class JobS {
private int[] jobOrder;
private int[][] jobS;

public JobS(int jobs, int tools){// Creates one more line for the title (jobOrder).
    super();
    int[][] tab = new int[jobs][tools];
    int[] tab2 = new int[jobs];
    this.jobS = tab;
    this.jobOrder = tab2;
}
</code>```

And the setter i use at the end:

```<code>public void setJobS(int[][] jobS) {
    this.jobS = jobS;
}
</code>```

I tried detailing the code as much as possible with comments, I hope you will understand what i want to do.

This is the first time i'm trying to do a "complex" application so maybe i'm just stupid and forgot something, but right now i've been searching for an hour and still have no clue what is causing this ..

Hope you can help, thanks in advance !
L.L.

答:
as you can see the String line is empty:

```<code> String line = ""; // Line in tokenizer
</code>```

so here st is empty:

```<code>StringTokenizer st = new StringTokenizer(line);
</code>```

hence when you call this:

```<code>String str = st.nextToken();
</code>```

an exception occurs.

ensure that the line has some data first, by instantiating the StringTokenizer after the for loop.

Example

change this:

```<code>StringTokenizer st = new StringTokenizer(line);
for(int i=0; i<3; i++){ //ReachFirstLine of matrix
       line = br.readLine();
       //System.out.println(line);
}
</code>```

to this:

```<code>for(int i=0; i<3; i++){ //ReachFirstLine of matrix
        line = br.readLine();
        //System.out.println(line);
}
StringTokenizer st = new StringTokenizer(line);
</code>```

side note - this code:

```<code>line = br.readLine();
</code>```

will overwrite the value of line at each iteration within the loop, that could be what you wanted but if you want to append all the lines of text the readLine() gets then you can do this:

```<code>line += br.readLine();
</code>```

Title: StringTokenizer NoSuchElements

Body:
I have created a method that reads a file set like this (//... are comments, ignore them):

5 // n jobs
2 // n tools
1 4 5 6 2
1 5 4 2 3

The matrix represents the tools used for each job but it doesn't really matter here.

Here is the method :

public static JobS inputJobMatrix(){
    String line = ""; // Line in tokenizer
    int jobN = inputJobN(); //First number of the file (jobs) works
    int toolN = inputToolN(); //Second number of the file (tools) works
    //Instancing JobS object
    JobS inputJobS = new JobS(jobN, toolN);
    int[][] tabFill = new int[jobN][toolN];
    int[] tabFillOrder = new int[jobN];
    try {
        // Initializing reader.
        FileReader fr = new FileReader("input.txt");
        BufferedReader br = new BufferedReader(fr);
        StringTokenizer st = new StringTokenizer(line);
        for(int i=0; i<3; i++){ //ReachFirstLine of matrix
            line = br.readLine();
            //System.out.println(line);
        }
        //Instancing tab for Job Order 1...n
        int[] a = new int[jobN];
        for (int i=0; i<jobN; i++){
            a[i]=i+1;
        }
        //Filling Order tab with Job order
        JobS.fillLine(tabFillOrder, a, 0); //Fills the tab with the tab a (make a copy of it we could say)
        //Reading the matrix line by line and filling tab line
        for(int i=0; i<jobN; i++){
            for(int j=0; j<toolN; j++){
                String str = st.nextToken();
                System.out.println(str);
                tabFill[i][j] = Integer.parseInt(str);
            }
            line = br.readLine();
        }
        inputJobS.setJobS(tabFill);
        br.close();

    } catch (IOException e) {
        System.out.println("File not found exception in inputJobMatrix.");
    }
    return inputJobS;

}

Which results in :

Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at pProgra.ReadJobS.inputJobMatrix(ReadJobS.java:84)
at pProgra.PPMain.main(PPMain.java:14)

I've tried looking for problems in my loops but didnt find any, and i can't understand why it doesn't work.
The goal here is to fill a bidimensionnal int array with the matrix of the input file (for exemple the one i've given previously with jobs and tools) and use that array for my object (JobS, i'll give the constructor here too if it can help) :

public class JobS {
private int[] jobOrder;
private int[][] jobS;

public JobS(int jobs, int tools){// Creates one more line for the title (jobOrder).
    super();
    int[][] tab = new int[jobs][tools];
    int[] tab2 = new int[jobs];
    this.jobS = tab;
    this.jobOrder = tab2;
}

And the setter i use at the end:

public void setJobS(int[][] jobS) {
    this.jobS = jobS;
}

I tried detailing the code as much as possible with comments, I hope you will understand what i want to do.

This is the first time i'm trying to do a "complex" application so maybe i'm just stupid and forgot something, but right now i've been searching for an hour and still have no clue what is causing this ..

Hope you can help, thanks in advance !
L.L.

Body:
as you can see the String line is empty:

 String line = ""; // Line in tokenizer

so here st is empty:

StringTokenizer st = new StringTokenizer(line);

hence when you call this:

String str = st.nextToken();

an exception occurs.

ensure that the line has some data first, by instantiating the StringTokenizer after the for loop.

Example

change this:

StringTokenizer st = new StringTokenizer(line);
for(int i=0; i<3; i++){ //ReachFirstLine of matrix
       line = br.readLine();
       //System.out.println(line);
}

to this:

for(int i=0; i<3; i++){ //ReachFirstLine of matrix
        line = br.readLine();
        //System.out.println(line);
}
StringTokenizer st = new StringTokenizer(line);

side note - this code:

line = br.readLine();

will overwrite the value of line at each iteration within the loop, that could be what you wanted but if you want to append all the lines of text the readLine() gets then you can do this:

line += br.readLine();


来源: stackexchange

问:
identifying the device for iPad iOS 4.2
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?</p>

```<code>#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif
</code>```

答:
check device version and the code accordingly

```<code>float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version == 4.2)
    {
        CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;

    }
else
    self.view.frame = frame;
</code>```

Use this code it may help you.

ContentLicense: CC BY-SA 2.5

Title: identifying the device for iPad iOS 4.2

Body:
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif

Body:
check device version and the code accordingly

float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version == 4.2)
    {
        CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;

    }
else
    self.view.frame = frame;

Use this code it may help you.

ContentLicense: CC BY-SA 3.0


问:
Swift IF statement to perform action only once
I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

```<code>if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {

    }
</code>```

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

答:
Make sure meteBlueTimer is declared as optional.

```<code>var meteBlueTimer: Timer?
</code>```

Then simply check if it is nil or not.

```<code>if score >= 200 {
    if meteBlueTimer == nil {
        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
    }
} else {
}
</code>```

This way you only create the meteBlueTimer once.

Body:
I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {

    }

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

Body:
Make sure meteBlueTimer is declared as optional.

var meteBlueTimer: Timer?

Then simply check if it is nil or not.

if score >= 200 {
    if meteBlueTimer == nil {
        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
    }
} else {
}

This way you only create the meteBlueTimer once.


问:
android: EditText numberDecimal - how to start the keyboard as minimized
I have an EditText with these values:

```<code>android:digits="0123456789"
android:inputType="numberDecimal"
</code>```

As you see, I would like to insert only digits 0-9.

my problem is that when I reach the layout containing this EditText, the smartphone keyboard is displayed so it hides the screen before I can see the screen content. (although I didn't press on the edit text box!)

I would like the keyboard to be minimized as default.

I want that ONLY AFTER I press on the editText box, the keyboard will be displayed.

Is there any possibility to do so?

答:
Your EditText is gaining focus on activity load. To prevent this you can do as following:

METHOD 1: Add below attribute to your parent layout

```<code>android:focusableInTouchMode="true"
</code>```

METHOD 2: In manifest add the following attribute to your activity inside activity tag:

```<code>android:windowSoftInputMode="stateAlwaysHidden"
</code>```

Hope this helps.

Body:
I have an EditText with these values:

android:digits="0123456789"
android:inputType="numberDecimal"

As you see, I would like to insert only digits 0-9.

my problem is that when I reach the layout containing this EditText, the smartphone keyboard is displayed so it hides the screen before I can see the screen content. (although I didn't press on the edit text box!)

I would like the keyboard to be minimized as default.

I want that ONLY AFTER I press on the editText box, the keyboard will be displayed.

Is there any possibility to do so?

Body:
Your EditText is gaining focus on activity load. To prevent this you can do as following:

METHOD 1: Add below attribute to your parent layout

android:focusableInTouchMode="true"

METHOD 2: In manifest add the following attribute to your activity inside activity tag:

android:windowSoftInputMode="stateAlwaysHidden"

Hope this helps.


问:
Issues with Wordpress permalink /index.php/%postname% instead of %postname%
I've tried to change my permalinks from example.com/index.php/postname to example.com/postname, but nothing has worked. When I change them in Wordpress, I get 404 errors for example.com/postname. I've noticed this is a common issue, but none of the suggested solutions have worked.

Mod_rewrite is enabled on the Apache server. The .htaccess file has been updated. Still nothing. In the meantime, I'm wondering if I could do a redirect that would send anyone with the example.com/postname link to example.com/index.php/postname. What's the best way to do that?

答:
You generally need to save permalink structure twice. If that doesnt work install wp 2017 theme >  delete your theme > reinstall your theme from scratch.

If you have cloned your website - you should go to the original site, back it up and then deploy it! a good plugin to  do this is updrafts if you don't know how to do it mannually. Don't use a cloning plugin - some plugins/themes don't work with them.


问:
Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }
```
<p>The <code>UseSqlServer</code> method is recognized if I put it directly into the context:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }
</code>```

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

答:
I believe this can be solved by adding a project reference to Microsoft.EntityFrameworkCore.SqlServer.Design

```<code>Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
</code>```

Microsoft.EntityFrameworkCore.SqlServer wasn't directly installed in my project, but the .Design package will install it anyway as a prerequisite.

ContentLicense: CC BY-SA 4.0

Body:
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }

The UseSqlServer method is recognized if I put it directly into the context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

Body:
I believe this can be solved by adding a project reference to Microsoft.EntityFrameworkCore.SqlServer.Design

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Microsoft.EntityFrameworkCore.SqlServer wasn't directly installed in my project, but the .Design package will install it anyway as a prerequisite.


问:
Printing the second half of a linked list in reverse order
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

```<code>void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}
</code>```

答:
Working code here:
http://ideone.com/bbzsSy

2 issues:

while(current->next!=NULL) should be: while(current!=NULL)

This way you be sure that you can dereferencing the pointer, plus you also push the last node.

for(int i=0;i<mid;i++) should be: for(int i=0;i<lastFordward;i++)

Where lastFordward=(c%2)?mid-1:mid;

This way avoid to print the mid position twice when c is even.

Body:
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}


问:
How to show pdf in browser and allow to download/open it by adobe reader?
I need to make possible to preview the pdf file in the browser window for example in  and to make some button which allow to open it in Adobe Reader program for edit purpose.

The problem I encountered is that if browser know how to treat PDF's files it will not allow me to download it, and always open it in a new tab. and if I config browser not to open PDF file inside browser it allow me to download file but it will not show me the PDF inside

any body have some Idea how can i combine this two requirements in one html page?

i need the solution for Internet Explorer 11

答:
It's possible but there's a bit of plumbing involved. Basically, you don't link to the PDF directly, you link to an HTML page that uses an object element to display the PDF in most of the window. You can then have a header that holds a button that calls a JavaScript to fetch the PDF and save it locally. My example uses download2.js for that part. It even works in IE 11 though I don't think it will work in anything lower than IE 8.

See the example at the URL below.
http://practicalpdf.com/solutions/practicalpdf/preview-with-button/wrapper-with-button.html


问:
End Keyframe Animation Using CSS3
I've created a simple bar animation using keyframes in CSS and applying it to an id tag

#progress-skill {
    animation: color-bar 2s, animate-bar 2s;
    animation-fill-mode: forwards;
    position: relative;
    border-radius: 3px;
    width: 400px;
}

@keyframes color-bar {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar {
   from {width: 0px; }
   to {width: 200px; }
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar" id="progress-skill"><span>50%</span></div>
</div></code>```

The animation works fine, with the exception that the color will always end up being the 100% background-color no matter what the percentage is. Is there any way to force the animation to stop at certain percentages? Basically what I'm looking for here is an animation background-color triggered by the width of the bar. If the bar is 50% long then it should be the 50% background-color and stop at that point. The same should hold true for 25% or 75%.

I'm not looking for a javascript solution, but I'm willing to compromise if that's the only method possible.

答:
I'm pretty sure that you can't stop an animation the way that you are asking. My best suggestion would be to create several variations for each percentage, using class names rather than ids, like so:

.progress-bar {
    position: relative;
    border-radius: 3px;
    width: 400px;
}

.progress-bar-5 {
    animation: color-bar-5 2s, animate-bar-5 2s;
    animation-fill-mode: forwards;
}
.progress-bar-25 {
    animation: color-bar-25 2s, animate-bar-25 2s;
    animation-fill-mode: forwards;
}
.progress-bar-50 {
    animation: color-bar-50 2s, animate-bar-50 2s;
    animation-fill-mode: forwards;
}
.progress-bar-75 {
    animation: color-bar-75 2s, animate-bar-75 2s;
    animation-fill-mode: forwards;
}
.progress-bar-100 {
    animation: color-bar-100 2s, animate-bar-100 2s;
    animation-fill-mode: forwards;
}

@keyframes color-bar-5 {
   100% { background-color: red;}
}

@keyframes color-bar-25 {
   20% { background-color: red;}
   100% { background-color: orange;}
}

@keyframes color-bar-50 {
   10% { background-color: red;}
   50% { background-color: orange;}
   100% { background-color: yellow;}
}

@keyframes color-bar-75 {
   7% { background-color: red;}
   33% { background-color: orange;}
   67% { background-color: yellow;}
   100% { background-color: green;}
}

@keyframes color-bar-100 {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar-5 {
   from {width: 0px; }
   to {width: 10px; }
}

@keyframes animate-bar-25 {
   from {width: 0px; }
   to {width: 50px; }
}

@keyframes animate-bar-50 {
   from {width: 0px; }
   to {width: 100px; }
}

@keyframes animate-bar-75 {
   from {width: 0px; }
   to {width: 150px; }
}

@keyframes animate-bar-100 {
   from {width: 0px; }
   to {width: 200px; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-50"><span>50%</span></div>
</div>

<div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-25"><span>25%</span></div>
</div>

<div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-75"><span>75%</span></div>
</div></code>```

Title: End Keyframe Animation Using CSS3

Body:
I've created a simple bar animation using keyframes in CSS and applying it to an id tag

#progress-skill {
    animation: color-bar 2s, animate-bar 2s;
    animation-fill-mode: forwards;
    position: relative;
    border-radius: 3px;
    width: 400px;
}

@keyframes color-bar {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar {
   from {width: 0px; }
   to {width: 200px; }
}

SKILL NAME

50%

The animation works fine, with the exception that the color will always end up being the 100% background-color no matter what the percentage is. Is there any way to force the animation to stop at certain percentages? Basically what I'm looking for here is an animation background-color triggered by the width of the bar. If the bar is 50% long then it should be the 50% background-color and stop at that point. The same should hold true for 25% or 75%.

I'm not looking for a javascript solution, but I'm willing to compromise if that's the only method possible.

Body:
I'm pretty sure that you can't stop an animation the way that you are asking. My best suggestion would be to create several variations for each percentage, using class names rather than ids, like so:

.progress-bar {
    position: relative;
    border-radius: 3px;
    width: 400px;
}

.progress-bar-5 {
    animation: color-bar-5 2s, animate-bar-5 2s;
    animation-fill-mode: forwards;
}
.progress-bar-25 {
    animation: color-bar-25 2s, animate-bar-25 2s;
    animation-fill-mode: forwards;
}
.progress-bar-50 {
    animation: color-bar-50 2s, animate-bar-50 2s;
    animation-fill-mode: forwards;
}
.progress-bar-75 {
    animation: color-bar-75 2s, animate-bar-75 2s;
    animation-fill-mode: forwards;
}
.progress-bar-100 {
    animation: color-bar-100 2s, animate-bar-100 2s;
    animation-fill-mode: forwards;
}

@keyframes color-bar-5 {
   100% { background-color: red;}
}

@keyframes color-bar-25 {
   20% { background-color: red;}
   100% { background-color: orange;}
}

@keyframes color-bar-50 {
   10% { background-color: red;}
   50% { background-color: orange;}
   100% { background-color: yellow;}
}

@keyframes color-bar-75 {
   7% { background-color: red;}
   33% { background-color: orange;}
   67% { background-color: yellow;}
   100% { background-color: green;}
}

@keyframes color-bar-100 {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar-5 {
   from {width: 0px; }
   to {width: 10px; }
}

@keyframes animate-bar-25 {
   from {width: 0px; }
   to {width: 50px; }
}

@keyframes animate-bar-50 {
   from {width: 0px; }
   to {width: 100px; }
}

@keyframes animate-bar-75 {
   from {width: 0px; }
   to {width: 150px; }
}

@keyframes animate-bar-100 {
   from {width: 0px; }
   to {width: 200px; }
}

<div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-50"><span>50%</span></div>
</div>

<div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-25"><span>25%</span></div>
</div>

<div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar progress-bar-75"><span>75%</span></div>
</div>


答:
Declare your timers as optional

```<code>var meteBlueTimer : Timer?
var meteRedTimer : Timer?
</code>```

Then check if the timer is not running (nil). Set the invalidated timers to nil.

```<code>if score >= 200 && meteBlueTimer == nil {
       meteRedTimer?.invalidate()
       meteRedTimer = nil
       meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

} else { ...
</code>```

Title: Swift IF statement to perform action only once

Body:
Declare your timers as optional

var meteBlueTimer : Timer?
var meteRedTimer : Timer?

Then check if the timer is not running (nil). Set the invalidated timers to nil.

if score >= 200 && meteBlueTimer == nil {
       meteRedTimer?.invalidate()
       meteRedTimer = nil
       meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

} else { ...


问:
Haskell, List as input for a function, How?
I've been given the following question in my coursework;

Define a function

```<code>flatten :: [(Char,Int)] -> String
</code>```

that flattens a list of pairs of characters and digits to a string. For example:

```<code>flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"
</code>```

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

```<code>Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]
</code>```

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

```<code>flatten :: [(Char, Int)] -> String
flatten [] = []
</code>```

i figure my next line should go something like;

```<code>flatten ???? = concat (????)
</code>```

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

答:
```<code>flatten = mconcat. map (\(c,i) -> [c] ++ show i)
</code>```

Body:
I've been given the following question in my coursework;

Define a function

flatten :: [(Char,Int)] -> String

that flattens a list of pairs of characters and digits to a string. For example:

flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

flatten :: [(Char, Int)] -> String
flatten [] = []

i figure my next line should go something like;

flatten ???? = concat (????)

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?


问:
Error when installing scipy in PyCharm?
I get the following error when attempting to install scipy to PyCharm 3.2:

Collecting scipy
  Using cached scipy-0.19.0.zip
Installing collected packages: scipy
  Running setup.py install for scipy: started
    Running setup.py install for scipy: finished with status 'error'
    Complete output from command C:\Users\leigh\AppData\Local\Programs\Python\Python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\leigh\AppData\Local\Temp\pycharm-packaging\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\leigh\AppData\Local\Temp\pip-8kx0fj8t-record\install-record.txt --single-version-externally-managed --compile:

```<code>Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)
</code>```

Does anyone know how to deal with this?

答:
I am not sure, but you might find your solution in this stackoverflow thread: Can't install Scipy through pip.
If your problem persists, assuming you're on Windows (10), you could try:

Clone library from Github.

```<code>git clone https://github.com/scipy/scipy.git
</code>```

Using CMD, navigate to the scipy folder

```<code>cd C:\..(your path)..\scipy
</code>```

Then install by

```<code>python setup.py install
</code>```

Hope it works out for you!

Title: Error when installing scipy in PyCharm?

Body:
I get the following error when attempting to install scipy to PyCharm 3.2:

Collecting scipy
  Using cached scipy-0.19.0.zip
Installing collected packages: scipy
  Running setup.py install for scipy: started
    Running setup.py install for scipy: finished with status 'error'
    Complete output from command C:\Users\leigh\AppData\Local\Programs\Python\Python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\leigh\AppData\Local\Temp\pycharm-packaging\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\leigh\AppData\Local\Temp\pip-8kx0fj8t-record\install-record.txt --single-version-externally-managed --compile:

Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

Does anyone know how to deal with this?

Body:
I am not sure, but you might find your solution in this stackoverflow thread: Can't install Scipy through pip.
If your problem persists, assuming you're on Windows (10), you could try:

Clone library from Github.

git clone https://github.com/scipy/scipy.git

Using CMD, navigate to the scipy folder

cd C:\..(your path)..\scipy

Then install by

python setup.py install

Hope it works out for you!


问:
WCF Impersonation Level Error on System.Data.OracleClient
I currently have a WCF service running in IIS7 and I have have added impersonation on each of the public web methods with the following:

```<code>[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void TestMethod(){}
</code>```

When ever I call this method from my test client application I get the following error:

Could not load file or assembly 'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=waeraewrar' or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid.

I'm currently using Microsoft Enterprise Library 3.1, and .Net 4.0.

Sample code:

```<code>WcfService client = new WcfService();
client.TestMethod();
</code>```

答:
Try configuring the client to allow an impersonation level of impersonation. For example:

```<code><system.serviceModel>
    <client>
      <endpoint address="http://xxxxx/Services/xxService.svc"
                binding="wsHttpBinding"
                contract="IServiceContract"
                behaviorConfiguration = "ImpersonationBehavior" />
    </client>
      <behaviors>
          <endpointBehaviors>
               <behavior name="ImpersonationBehavior">
                   <clientCredentials>
                       <windows allowedImpersonationLevel = "Impersonation" />
                   </clientCredentials>
               </behavior>
          <endpointBehaviors>
       </behaviors>
</system.serviceModel>
</code>```

See this article for more on impersonation and delegation.

Body:
I currently have a WCF service running in IIS7 and I have have added impersonation on each of the public web methods with the following:

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void TestMethod(){}

When ever I call this method from my test client application I get the following error:

Could not load file or assembly 'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=waeraewrar' or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid.

I'm currently using Microsoft Enterprise Library 3.1, and .Net 4.0.

Sample code:

WcfService client = new WcfService();
client.TestMethod();

Body:
Try configuring the client to allow an impersonation level of impersonation. For example:

<system.serviceModel>
    <client>
      <endpoint address="http://xxxxx/Services/xxService.svc"
                binding="wsHttpBinding"
                contract="IServiceContract"
                behaviorConfiguration = "ImpersonationBehavior" />
    </client>
      <behaviors>
          <endpointBehaviors>
               <behavior name="ImpersonationBehavior">
                   <clientCredentials>
                       <windows allowedImpersonationLevel = "Impersonation" />
                   </clientCredentials>
               </behavior>
          <endpointBehaviors>
       </behaviors>
</system.serviceModel>

See this article for more on impersonation and delegation.


问:
How to build Boost::program_options
I wanted to use boost::program_options. After I installed boost, I think that I have to build separatly program_options (http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html). But I don't know how to do it.

I am trying to compile the C:\Program Files\boost\boost_1_42\libs\program_options\example\first.cpp (http://www.boost.org/doc/libs/1_42_0/doc/html/program_options/tutorial.html) but probably due to I didn't build the library I have this error:

```<code>LINK : fatal error LNK1104: cannot open file 'libboost_program_options-vc90-mt-gd-1_42.lib'
</code>```

EDIT: I used the installers supplied by BoostPro Computing so I skipped the installation of the binaries (http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html#install-visual-studio-binaries)

EDIT: I also followed the instructions at http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html#build-from-the-visual-studio-ide

答:
After reading the Boost 1.54 Getting Started on Windows guide these are the steps that you should take (program_options is a header only library). You need to have a MSVC compiler installed.

Download Boost's source code from here and install it.

From a command line (preferably the Developer Command Prompt for VS):

bootstrap.bat

bjam.exe --build-type=complete msvc stage --with-program_options

This will finish in a couple of minutes and that's it! The libraries are located in the directory .\bin.v2\libs\program_options\build.

BTW you could see which libraries you can build using bjam --show-libraries.

Title: How to build Boost::program_options

Body:
I wanted to use boost::program_options. After I installed boost, I think that I have to build separatly program_options (http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html). But I don't know how to do it.

I am trying to compile the C:\Program Files\boost\boost_1_42\libs\program_options\example\first.cpp (http://www.boost.org/doc/libs/1_42_0/doc/html/program_options/tutorial.html) but probably due to I didn't build the library I have this error:

LINK : fatal error LNK1104: cannot open file 'libboost_program_options-vc90-mt-gd-1_42.lib'

EDIT: I used the installers supplied by BoostPro Computing so I skipped the installation of the binaries (http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html#install-visual-studio-binaries)

EDIT: I also followed the instructions at http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html#build-from-the-visual-studio-ide


问:
Need to save two tables from different jsp pages with foreign key relationship using hibernate dao implementation method
Image of table relationship reference

After submit from bank jsp page and after submit from card jsp all in one image because of limitation of newbie

I am new to stackoverflow as well SPRING. I have tried to create two tables with foreign key concept . I have followed some examples on stackoverflow as well as from other resourcefull websites and manged to create two tables with onetomany relationship. But the problem is i have to get the first row id under cart_id column when i submit from card jsp page. Instead after submit from card jsp page there is new row created under bankadmin table and it's id is being returned. I am confused and have no idea how to correct ot resolve this issue. Please  be kind and guide me. And also i have been searching for a week in stackoverflow couldn't find anything that helped me. Thanks in advance.

Bankadmin Model

```<code>    @Entity
    @Table(name = "bankAdmin")
    public class bankAdmin implements Serializable{

    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column (name = "bcode", nullable=false)
    @Id private int bcode;

    @Column (name = "bname")
    private String bname;

    @Column (name = "address")
    private String address;

    @Column (name = "phno")
    private int phno;

    @OneToMany(mappedBy="bankAdmin",cascade = CascadeType.ALL)
    private Set<Cards> cards;
</code>```

Card model

```<code>    @Entity
    @Table(name = "cards")
    public class Cards implements Serializable {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="cname", unique=true)
    @Id private int cname;

    @Column (name = "ctype")
    private String ctype;

    @Column (name = "min_sal")
    private int min_sal;

    @Column (name = "year_fee")
    private int year_fee;

    @Column (name = "rewards")
    private String rewards;

    @Column (name = "jperks")
    private String jperks;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="cart_id", nullable=false)
    private bankAdmin bankAdmin;
    public Cards(){}

    public Cards(String ctype, int min_sal, int year_fee, String rewards, String jperks, bankAdmin b){//int cname,
        this.ctype=ctype;
        this.min_sal=min_sal;
        this.year_fee=year_fee;
        this.jperks=jperks;
        this.rewards=rewards;
        this.bankAdmin=b;
    }

    public bankAdmin getBankAdmin() {
        return bankAdmin;
    }
    public void setBankAdmin(bankAdmin bankAdmin) {
        this.bankAdmin = bankAdmin;
    }
</code>```

CardDaoImpl

```<code>    public class CardsDaoImpl implements CardsDao{

    @Autowired
    SessionFactory sessionfactory;

    public void save(Cards cards) {
        Session session = null;
        Transaction tx = null;

        try
        {
            session = this.sessionfactory.openSession();
            tx = session.beginTransaction();

            bankAdmin bankadmin =new bankAdmin(); //=null;
            String _ctype = cards.getctype();
            int _min_sal = cards.getmin_sal();
            int _year_fee = cards.getyear_fee();
            String _rewards = cards.getrewards();
            String _jperks = cards.getjperks();
            Set<Cards> card = new HashSet<Cards>();
            Cards config =  new Cards(_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin);
            card.add(config);
            bankadmin.setcards(card);
//          System.out.println("bankadmin: before " + bankadmin);
//          bankadmin.setbname(bankadmin.getbname());// "SBI"
//          bankadmin.setphno(bankadmin.getphno());//1234567890
//          bankadmin.setaddress(bankadmin.getaddress());//Bengaluru
//          System.out.println("bankadmin: after " + bankadmin);

//          int _cname = cards.getcname();

//          int bankadmin = bankadmin.getbcode();

            //_cname,_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin
//          card.add(config);
//          config.setBankAdmin(cards.getBankAdmin(bankadmin));

//          config.setcname(cards.getcname());
//          config.setctype(cards.getctype());
//          config.setmin_sal(cards.getmin_sal());
//          config.setyear_fee(cards.getyear_fee());
//          config.setrewards(cards.getrewards());
//          config.setjperks(cards.getjperks());
//          config.setBankAdmin(cards.getBankAdmin());
            session.save(bankadmin);
            session.save(config);
            tx.commit();
        }
        catch (HibernateException e)
        {
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

//  get lms lights config from DB
    public List<Cards> Ccards() {
        Session session = null;
//      Transaction tx = null;
        List<Cards> Ccards = null;

        try{
            session = this.sessionfactory.openSession();
            Ccards = session.createQuery("FROM Cards").list();
            System.out.println("cards dao impl executed...");
            System.out.println("cards config : "+ Ccards.toString());

        }
        catch (Exception e)
        {
            System.out.println("bankAdmin Dao impl Ex : " + e);
        }
        finally
        {
            session.close();
        }

        return Ccards;
    }

}
</code>```

BankDaoImpl

```<code>    public class bankAdminDaoImpl implements bankAdminDao{
    @Autowired
    SessionFactory sessionfactory;

    public void save(bankAdmin badmin) {
        Session session = null;
        Transaction tx = null;

        try
        {
            session = this.sessionfactory.openSession();
            tx = session.beginTransaction();
//          bankAdmin bankadmin = new bankAdmin();
            bankAdmin config =  new bankAdmin();
            config.setbcode(badmin.getbcode());
            config.setbname(badmin.getbname());
            config.setaddress(badmin.getaddress());
            config.setphno(badmin.getphno());

            session.save(config);//save//persist
            tx.commit();
        }
        catch (HibernateException e)
        {
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

//  get lms lights config from DB
    public List<bankAdmin> BbankAdmin() {
        Session session = null;
//      Transaction tx = null;
        List<bankAdmin> BbankAdmin = null;

        try{
            session = this.sessionfactory.openSession();
            BbankAdmin = session.createQuery("FROM bankAdmin").list();
            System.out.println("bankAdmin dao impl executed...");
            System.out.println("bankAdmin config : "+ BbankAdmin.toString());

        }
        catch (Exception e)
        {
            System.out.println("bankAdmin Dao impl Ex : " + e);
        }
        finally
        {
            session.close();
        }

        return BbankAdmin;
    }

}
</code>```

答:
Okay. I have posted the solution to your problem.

First of all, Spring framework is wonderful to work with. The framework got a lot of features, that you should take advantage of. I am not sure if I will be able to cover everything in this post, so please feel free to ask me.

I have created a simple Spring Boot application. I got total of 6 files that are important which is posted below.

Notice that I renamed your classes to CamelCase with capital starting letter. such as BankAdmin. This is considered the standard way of writing java classes. Also note that i renamed Cards to Card, so remember to rename your table in the database aswell. Also remember to rename the bankadmin table to bank_admin.

There are thee annotations that you have to look into. @Transactional, @Autowired, and PersistenceContext.

So a quick and easy explanation. @Transactional manages all transactions for you, so you do not have to begin and commit transactions. @Autowired creates objects for you, so you do not have to manage your object dependencies yourself. PersistenceContext basically creates and EntityManager for you and manages it for you. You do not have to create session nor EntitManagerFactory. These three annotations are explained very brief, so you should read about them yourself.

I also removed @Table(name = "bankAdmin") and @Table(name = "cards"). JPA can lookup these tables automatically if you follow the standard way of naming classes and database tables. It is actually pretty simple, but I still encourage you to look into this by yourself. In short, capital camelcase is turned into lowercase with _ inbetween each word that start with a capital letter. I.e. If your class name is BankAdmin then JPA will automatically look for table named bank_admin in your database.

application.properties - details about your database

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/stackoverflow?useSSL=false
spring.datasource.username = root
spring.datasource.password = root

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
</code>```

The below code is only written to test the functionality

```<code>    @SpringBootApplication
    public class StackoverflowApplication {

    public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(StackoverflowApplication.class, args);

        //Calling a class that is only made with the purpose of testing
        Verification ts = ctx.getBean(Verification.class);
        ts.run();
    }
    }

    @Component
    class Verification{

    @Autowired
    private BankAdminDao bad;

    @Autowired
    private CardsDao cd;

    void run(){
        //Create a new BankAdmin
        BankAdmin ba = new BankAdmin();
        ba.setAddress("someStreet");
        ba.setPhno(12341234);
        ba.setBname("myBanker");

        //Create two cards and add them to a HashSet.
        Card c1 = new Card("Visa", 1000, 1999, "Alot of", "Babes", ba);
        Card c2 = new Card("Master Card", 2000, 500, "someThing", "anotherThing", ba);
        Set<Card> cardList = new HashSet<>();
        cardList.add(c1);
        cardList.add(c2);

        //Create a associatio between the BankAdmin and list of Cards
        ba.setCards(cardList);

        //Save them to the database.
        bad.save(ba);

        //Here we add a Card to an existing BankAdmin with the id 6 in the database.

        //Create a new Card.
        //The BankAdmin is set to null, because we not have not yet loaded the BankAdmin
        Card c3 = new Card("Visa", 9999, 1337, "Alot of", "Male Babes", null);

        //Save Card c3 with the BankAdmin id 6
        cd.save(c3, 6);

    }
    }
</code>```

BankAdmin

```<code>    @Entity
    public class BankAdmin implements Serializable{

    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column (name = "bcode", nullable=false)
    @Id private int bcode;

    @Column (name = "bname")
    private String bname;

    @Column (name = "address")
    private String address;

    @Column (name = "phno")
    private int phno;

    @OneToMany(mappedBy="bankAdmin",cascade=CascadeType.ALL)
    private Set<Card> cards;

    //Getters and Setters have been removed to reduce the amount of code.
    }
</code>```

BankAdminDao

```<code>    @Repository
    //Transactional makes transaction automatical, so you do not have to begin and commit transactions yourself!
    @Transactional
    public class BankAdminDao{

    //This makes your life a lot eaier!
    //It will take care of your EntitManagerFactory and Sessions
    @PersistenceContext
    EntityManager em;

    public void save(BankAdmin bank) {
        em.merge(bank);
    }

    //get lms lights config from DB
    public List<BankAdmin> getAllBankAdmin() {
         List<BankAdmin> bankList = (List<BankAdmin>)em.createQuery("SELECT b FROM BankAdmin b");
         return bankList;
    }

    public BankAdmin getBankAdmin(int bankId) {
        return em.find(BankAdmin.class, bankId);
    }
    }
</code>```

Card

```<code>    @Entity
    public class Card implements Serializable {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="cname", unique=true)
    @Id private int cname;

    @Column (name = "ctype")
    private String ctype;

    @Column (name = "min_sal")
    private int min_sal;

    @Column (name = "year_fee")
    private int year_fee;

    @Column (name = "rewards")
    private String rewards;

    @Column (name = "jperks")
    private String jperks;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="cart_id", nullable=false)
    private BankAdmin bankAdmin;

    public Card(){}

    public Card(String ctype, int min_sal, int year_fee, String rewards, String jperks, BankAdmin b){
        this.ctype=ctype;
        this.min_sal=min_sal;
        this.year_fee=year_fee;
        this.jperks=jperks;
        this.rewards=rewards;
        this.bankAdmin=b;
    }

    public BankAdmin getBankAdmin() {
        return bankAdmin;
    }
    public void setBankAdmin(BankAdmin bankAdmin) {
        this.bankAdmin = bankAdmin;
    }
    }
</code>```

CardDao

```<code>    @Repository
    @Transactional
    public class CardsDao{

        @PersistenceContext
        EntityManager em;

        @Autowired
        BankAdminDao bad;

        public void save(Card cards, int bankId) {
            BankAdmin bank = bad.getBankAdmin(bankId);
            cards.setBankAdmin(bank);
            bank.getCards().add(cards);
            em.merge(bank);
        }

        public List<Card> getAllCards() {
            List<Card> cardList = (List<Card>)em.createQuery("SELECT c FROM Cards c");
             return cardList;
        }

        public Card getCard(int cardId){
            return em.find(Card.class, cardId);
        }
    }
</code>```

Body:
Image of table relationship reference

After submit from bank jsp page and after submit from card jsp all in one image because of limitation of newbie

I am new to stackoverflow as well SPRING. I have tried to create two tables with foreign key concept . I have followed some examples on stackoverflow as well as from other resourcefull websites and manged to create two tables with onetomany relationship. But the problem is i have to get the first row id under cart_id column when i submit from card jsp page. Instead after submit from card jsp page there is new row created under bankadmin table and it's id is being returned. I am confused and have no idea how to correct ot resolve this issue. Please  be kind and guide me. And also i have been searching for a week in stackoverflow couldn't find anything that helped me. Thanks in advance.

Bankadmin Model

    @Entity
    @Table(name = "bankAdmin")
    public class bankAdmin implements Serializable{

    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column (name = "bcode", nullable=false)
    @Id private int bcode;

    @Column (name = "bname")
    private String bname;

    @Column (name = "address")
    private String address;

    @Column (name = "phno")
    private int phno;

    @OneToMany(mappedBy="bankAdmin",cascade = CascadeType.ALL)
    private Set<Cards> cards;

Card model

    @Entity
    @Table(name = "cards")
    public class Cards implements Serializable {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="cname", unique=true)
    @Id private int cname;

    @Column (name = "ctype")
    private String ctype;

    @Column (name = "min_sal")
    private int min_sal;

    @Column (name = "year_fee")
    private int year_fee;

    @Column (name = "rewards")
    private String rewards;

    @Column (name = "jperks")
    private String jperks;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="cart_id", nullable=false)
    private bankAdmin bankAdmin;
    public Cards(){}

    public Cards(String ctype, int min_sal, int year_fee, String rewards, String jperks, bankAdmin b){//int cname,
        this.ctype=ctype;
        this.min_sal=min_sal;
        this.year_fee=year_fee;
        this.jperks=jperks;
        this.rewards=rewards;
        this.bankAdmin=b;
    }

    public bankAdmin getBankAdmin() {
        return bankAdmin;
    }
    public void setBankAdmin(bankAdmin bankAdmin) {
        this.bankAdmin = bankAdmin;
    }

CardDaoImpl

    public class CardsDaoImpl implements CardsDao{

    @Autowired
    SessionFactory sessionfactory;

    public void save(Cards cards) {
        Session session = null;
        Transaction tx = null;

        try
        {
            session = this.sessionfactory.openSession();
            tx = session.beginTransaction();

            bankAdmin bankadmin =new bankAdmin(); //=null;
            String _ctype = cards.getctype();
            int _min_sal = cards.getmin_sal();
            int _year_fee = cards.getyear_fee();
            String _rewards = cards.getrewards();
            String _jperks = cards.getjperks();
            Set<Cards> card = new HashSet<Cards>();
            Cards config =  new Cards(_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin);
            card.add(config);
            bankadmin.setcards(card);
//          System.out.println("bankadmin: before " + bankadmin);
//          bankadmin.setbname(bankadmin.getbname());// "SBI"
//          bankadmin.setphno(bankadmin.getphno());//1234567890
//          bankadmin.setaddress(bankadmin.getaddress());//Bengaluru
//          System.out.println("bankadmin: after " + bankadmin);

//          int _cname = cards.getcname();

//          int bankadmin = bankadmin.getbcode();

            //_cname,_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin
//          card.add(config);
//          config.setBankAdmin(cards.getBankAdmin(bankadmin));

//          config.setcname(cards.getcname());
//          config.setctype(cards.getctype());
//          config.setmin_sal(cards.getmin_sal());
//          config.setyear_fee(cards.getyear_fee());
//          config.setrewards(cards.getrewards());
//          config.setjperks(cards.getjperks());
//          config.setBankAdmin(cards.getBankAdmin());
            session.save(bankadmin);
            session.save(config);
            tx.commit();
        }
        catch (HibernateException e)
        {
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

//  get lms lights config from DB
    public List<Cards> Ccards() {
        Session session = null;
//      Transaction tx = null;
        List<Cards> Ccards = null;

        try{
            session = this.sessionfactory.openSession();
            Ccards = session.createQuery("FROM Cards").list();
            System.out.println("cards dao impl executed...");
            System.out.println("cards config : "+ Ccards.toString());

        }
        catch (Exception e)
        {
            System.out.println("bankAdmin Dao impl Ex : " + e);
        }
        finally
        {
            session.close();
        }

        return Ccards;
    }

}

BankDaoImpl

    public class bankAdminDaoImpl implements bankAdminDao{
    @Autowired
    SessionFactory sessionfactory;

    public void save(bankAdmin badmin) {
        Session session = null;
        Transaction tx = null;

        try
        {
            session = this.sessionfactory.openSession();
            tx = session.beginTransaction();
//          bankAdmin bankadmin = new bankAdmin();
            bankAdmin config =  new bankAdmin();
            config.setbcode(badmin.getbcode());
            config.setbname(badmin.getbname());
            config.setaddress(badmin.getaddress());
            config.setphno(badmin.getphno());

            session.save(config);//save//persist
            tx.commit();
        }
        catch (HibernateException e)
        {
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

//  get lms lights config from DB
    public List<bankAdmin> BbankAdmin() {
        Session session = null;
//      Transaction tx = null;
        List<bankAdmin> BbankAdmin = null;

        try{
            session = this.sessionfactory.openSession();
            BbankAdmin = session.createQuery("FROM bankAdmin").list();
            System.out.println("bankAdmin dao impl executed...");
            System.out.println("bankAdmin config : "+ BbankAdmin.toString());

        }
        catch (Exception e)
        {
            System.out.println("bankAdmin Dao impl Ex : " + e);
        }
        finally
        {
            session.close();
        }

        return BbankAdmin;
    }

}

Body:
Okay. I have posted the solution to your problem.

First of all, Spring framework is wonderful to work with. The framework got a lot of features, that you should take advantage of. I am not sure if I will be able to cover everything in this post, so please feel free to ask me.

I have created a simple Spring Boot application. I got total of 6 files that are important which is posted below.

Notice that I renamed your classes to CamelCase with capital starting letter. such as BankAdmin. This is considered the standard way of writing java classes. Also note that i renamed Cards to Card, so remember to rename your table in the database aswell. Also remember to rename the bankadmin table to bank_admin.

There are thee annotations that you have to look into. @Transactional, @Autowired, and PersistenceContext.

So a quick and easy explanation. @Transactional manages all transactions for you, so you do not have to begin and commit transactions. @Autowired creates objects for you, so you do not have to manage your object dependencies yourself. PersistenceContext basically creates and EntityManager for you and manages it for you. You do not have to create session nor EntitManagerFactory. These three annotations are explained very brief, so you should read about them yourself.

I also removed @Table(name = "bankAdmin") and @Table(name = "cards"). JPA can lookup these tables automatically if you follow the standard way of naming classes and database tables. It is actually pretty simple, but I still encourage you to look into this by yourself. In short, capital camelcase is turned into lowercase with _ inbetween each word that start with a capital letter. I.e. If your class name is BankAdmin then JPA will automatically look for table named bank_admin in your database.

application.properties - details about your database

spring.datasource.url=jdbc:mysql://localhost:3306/stackoverflow?useSSL=false
spring.datasource.username = root
spring.datasource.password = root

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update

The below code is only written to test the functionality

    @SpringBootApplication
    public class StackoverflowApplication {

    public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(StackoverflowApplication.class, args);

        //Calling a class that is only made with the purpose of testing
        Verification ts = ctx.getBean(Verification.class);
        ts.run();
    }
    }

    @Component
    class Verification{

    @Autowired
    private BankAdminDao bad;

    @Autowired
    private CardsDao cd;

    void run(){
        //Create a new BankAdmin
        BankAdmin ba = new BankAdmin();
        ba.setAddress("someStreet");
        ba.setPhno(12341234);
        ba.setBname("myBanker");

        //Create two cards and add them to a HashSet.
        Card c1 = new Card("Visa", 1000, 1999, "Alot of", "Babes", ba);
        Card c2 = new Card("Master Card", 2000, 500, "someThing", "anotherThing", ba);
        Set<Card> cardList = new HashSet<>();
        cardList.add(c1);
        cardList.add(c2);

        //Create a associatio between the BankAdmin and list of Cards
        ba.setCards(cardList);

        //Save them to the database.
        bad.save(ba);

        //Here we add a Card to an existing BankAdmin with the id 6 in the database.

        //Create a new Card.
        //The BankAdmin is set to null, because we not have not yet loaded the BankAdmin
        Card c3 = new Card("Visa", 9999, 1337, "Alot of", "Male Babes", null);

        //Save Card c3 with the BankAdmin id 6
        cd.save(c3, 6);

    }
    }

BankAdmin

    @Entity
    public class BankAdmin implements Serializable{

    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column (name = "bcode", nullable=false)
    @Id private int bcode;

    @Column (name = "bname")
    private String bname;

    @Column (name = "address")
    private String address;

    @Column (name = "phno")
    private int phno;

    @OneToMany(mappedBy="bankAdmin",cascade=CascadeType.ALL)
    private Set<Card> cards;

    //Getters and Setters have been removed to reduce the amount of code.
    }

BankAdminDao

    @Repository
    //Transactional makes transaction automatical, so you do not have to begin and commit transactions yourself!
    @Transactional
    public class BankAdminDao{

    //This makes your life a lot eaier!
    //It will take care of your EntitManagerFactory and Sessions
    @PersistenceContext
    EntityManager em;

    public void save(BankAdmin bank) {
        em.merge(bank);
    }

    //get lms lights config from DB
    public List<BankAdmin> getAllBankAdmin() {
         List<BankAdmin> bankList = (List<BankAdmin>)em.createQuery("SELECT b FROM BankAdmin b");
         return bankList;
    }

    public BankAdmin getBankAdmin(int bankId) {
        return em.find(BankAdmin.class, bankId);
    }
    }

Card

    @Entity
    public class Card implements Serializable {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="cname", unique=true)
    @Id private int cname;

    @Column (name = "ctype")
    private String ctype;

    @Column (name = "min_sal")
    private int min_sal;

    @Column (name = "year_fee")
    private int year_fee;

    @Column (name = "rewards")
    private String rewards;

    @Column (name = "jperks")
    private String jperks;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="cart_id", nullable=false)
    private BankAdmin bankAdmin;

    public Card(){}

    public Card(String ctype, int min_sal, int year_fee, String rewards, String jperks, BankAdmin b){
        this.ctype=ctype;
        this.min_sal=min_sal;
        this.year_fee=year_fee;
        this.jperks=jperks;
        this.rewards=rewards;
        this.bankAdmin=b;
    }

    public BankAdmin getBankAdmin() {
        return bankAdmin;
    }
    public void setBankAdmin(BankAdmin bankAdmin) {
        this.bankAdmin = bankAdmin;
    }
    }

CardDao

    @Repository
    @Transactional
    public class CardsDao{

        @PersistenceContext
        EntityManager em;

        @Autowired
        BankAdminDao bad;

        public void save(Card cards, int bankId) {
            BankAdmin bank = bad.getBankAdmin(bankId);
            cards.setBankAdmin(bank);
            bank.getCards().add(cards);
            em.merge(bank);
        }

        public List<Card> getAllCards() {
            List<Card> cardList = (List<Card>)em.createQuery("SELECT c FROM Cards c");
             return cardList;
        }

        public Card getCard(int cardId){
            return em.find(Card.class, cardId);
        }
    }


问:
Using seq_along and lapply to process multiple dataframes (CAPM)
I have 48 dataframes and I wish to calculate a linear regression for each of the stocks in each of the dataframes (the CAPM). Each dataframe contains the same amount of stocks which is around 470, the S&P 500 and has 36 months worth of data. Originally I had one large dataframe but I have successfully managed to split the data into the 48 dataframes (this might not have been the smartest move but it is the way I solved the problem).

When I run the following code, it works fine. Noting that I have hard coded in Block 1.

```<code>  beta_results <- lapply(symbols, function(x) {
  temp <-  as.data.frame(Block1)
  input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
  capm <- lm(input)
  coefficients(capm)
 })
</code>```

Now rather than change the coding for each of the 48 blocks (ie Block1  to Block2 etc), I attempted the following, which in hindsight is complete rubbish. What I need is a way to increment the i from 1 to 48. I had tried to put all the dataframes in list, but given the way I have regression working I would be processing two lists and that was beyond me.

```<code>beta_results <- lapply(seq_along(symbols), function(i,x) {
 temp <-  as.data.frame(paste0("Block",i))
 input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
 capm <- lm(input)
coefficients(capm)
})
</code>```

Code for some example dataframes etc are:

```<code> symbols <- c("A", "AAPL", "BRKB")
</code>```

Block1 to BlockN would take the form of

```<code>             A      AAPL  BRKB    SP500
2016-04-29 -0.139  0.111  0.122    0.150
2016-05-31  0.071  0.095  0.330    0.200
2016-06-30 -0.042 -0.009  0.230    0.150
2016-07-29  0.090  0.060  0.200    0.100
2016-08-31  0.023  0.013  0.005    0.050
2016-09-30  0.065  0.088  0.002    0.100
</code>```

答:
@Parfait's answer is the correct one for OPs question of using lapply to process a list of data frames.

The following example shows how data.table can be used to get the coefficients of lm(stock~SP500) for each stock (using the Block1 example data):

```<code>library(data.table)
dt <- structure(list(date = c("2016-04-29", "2016-05-31", "2016-06-30",
"2016-07-29", "2016-08-31", "2016-09-30"), A = c(-0.139, 0.071,
-0.042, 0.09, 0.023, 0.065), AAPL = c(0.111, 0.095, -0.009, 0.06,
0.013, 0.088), BRKB = c(0.122, 0.33, 0.23, 0.2, 0.005, 0.002),
    SP500 = c(0.15, 0.2, 0.15, 0.1, 0.05, 0.1)), .Names = c("date",
"A", "AAPL", "BRKB", "SP500"), row.names = c(NA, -6L), class = "data.frame")

setDT(dt)
# Convert to long format for easier lm
dt_melt <- melt(dt, id.vars = c("date", "SP500"))
# Extract coefficients by doing lm for each unique variable (i.e. stock)
dt_lm <- dt_melt[, as.list(coefficients(lm(value~SP500))), by = variable]
# Fix column names
setnames(dt_lm, c("stock", "intercept", "slope"))

> dt_lm
   stock   intercept      slope
1:     A  0.05496970 -0.3490909
2:  AAPL  0.01421212  0.3636364
3:  BRKB -0.10751515  2.0454545
</code>```

Body:
I have 48 dataframes and I wish to calculate a linear regression for each of the stocks in each of the dataframes (the CAPM). Each dataframe contains the same amount of stocks which is around 470, the S&P 500 and has 36 months worth of data. Originally I had one large dataframe but I have successfully managed to split the data into the 48 dataframes (this might not have been the smartest move but it is the way I solved the problem).

When I run the following code, it works fine. Noting that I have hard coded in Block 1.

  beta_results <- lapply(symbols, function(x) {
  temp <-  as.data.frame(Block1)
  input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
  capm <- lm(input)
  coefficients(capm)
 })

Now rather than change the coding for each of the 48 blocks (ie Block1  to Block2 etc), I attempted the following, which in hindsight is complete rubbish. What I need is a way to increment the i from 1 to 48. I had tried to put all the dataframes in list, but given the way I have regression working I would be processing two lists and that was beyond me.

beta_results <- lapply(seq_along(symbols), function(i,x) {
 temp <-  as.data.frame(paste0("Block",i))
 input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
 capm <- lm(input)
coefficients(capm)
})

Code for some example dataframes etc are:

 symbols <- c("A", "AAPL", "BRKB")

Block1 to BlockN would take the form of

             A      AAPL  BRKB    SP500
2016-04-29 -0.139  0.111  0.122    0.150
2016-05-31  0.071  0.095  0.330    0.200
2016-06-30 -0.042 -0.009  0.230    0.150
2016-07-29  0.090  0.060  0.200    0.100
2016-08-31  0.023  0.013  0.005    0.050
2016-09-30  0.065  0.088  0.002    0.100

Body:
@Parfait's answer is the correct one for OPs question of using lapply to process a list of data frames.

The following example shows how data.table can be used to get the coefficients of lm(stock~SP500) for each stock (using the Block1 example data):

library(data.table)
dt <- structure(list(date = c("2016-04-29", "2016-05-31", "2016-06-30",
"2016-07-29", "2016-08-31", "2016-09-30"), A = c(-0.139, 0.071,
-0.042, 0.09, 0.023, 0.065), AAPL = c(0.111, 0.095, -0.009, 0.06,
0.013, 0.088), BRKB = c(0.122, 0.33, 0.23, 0.2, 0.005, 0.002),
    SP500 = c(0.15, 0.2, 0.15, 0.1, 0.05, 0.1)), .Names = c("date",
"A", "AAPL", "BRKB", "SP500"), row.names = c(NA, -6L), class = "data.frame")

setDT(dt)
# Convert to long format for easier lm
dt_melt <- melt(dt, id.vars = c("date", "SP500"))
# Extract coefficients by doing lm for each unique variable (i.e. stock)
dt_lm <- dt_melt[, as.list(coefficients(lm(value~SP500))), by = variable]
# Fix column names
setnames(dt_lm, c("stock", "intercept", "slope"))

> dt_lm
   stock   intercept      slope
1:     A  0.05496970 -0.3490909
2:  AAPL  0.01421212  0.3636364
3:  BRKB -0.10751515  2.0454545


问:
Debounce without initial delay
Is there an operator in RxJS that debounces without delaying the "first event in a burst", but delaying (and always emitting) the "last event in a burst"?

Something like this:

---a----b-c-d-----e-f---

after awesome-debounce(2 dashes) becomes:

---a----b------d--e----f

while a normal debounce would be:

-----a---------d-------f

It's kind of a mix between throttle and debounce...

答:
Hmmm, this is the easiest solution I can think of. The interesting part for you is the awesomeDebounce() function that creates the sub-chain.

It basically just combines throttle() and debounceTime() operators:

const Rx = require('rxjs');
const chai = require('chai');

let scheduler = new Rx.TestScheduler((actual, expected) => {
  chai.assert.deepEqual(actual, expected);
  console.log(actual);
});

function awesomeDebounce(source, timeWindow = 1000, scheduler = Rx.Scheduler.async) {
  let shared = source.share();
  let notification = shared
      .switchMap(val => Rx.Observable.of(val).delay(timeWindow, scheduler))
      .publish();

  notification.connect();

  return shared
    .throttle(() => notification)
    .merge(shared.debounceTime(timeWindow, scheduler))
    .distinctUntilChanged();
}

let sourceMarbles =   '---a----b-c-d-----e-f---';
let expectedMarbles = '---a----b------d--e----f';

// Create the test Observable
let observable = scheduler
  .createHotObservable(sourceMarbles)
  .let(source => awesomeDebounce(source, 30, scheduler));

scheduler.expectObservable(observable).toBe(expectedMarbles);
scheduler.flush();
```

The inner notification Observable is used only for the throttle() operator so I can reset its timer manually when I need. I also had to turn this Observable into "hot" to be independent on the internal subscriptions from throttle().

Title: Debounce without initial delay

Body:
Hmmm, this is the easiest solution I can think of. The interesting part for you is the awesomeDebounce() function that creates the sub-chain.

It basically just combines throttle() and debounceTime() operators:

const Rx = require('rxjs');
const chai = require('chai');

let scheduler = new Rx.TestScheduler((actual, expected) => {
  chai.assert.deepEqual(actual, expected);
  console.log(actual);
});

function awesomeDebounce(source, timeWindow = 1000, scheduler = Rx.Scheduler.async) {
  let shared = source.share();
  let notification = shared
      .switchMap(val => Rx.Observable.of(val).delay(timeWindow, scheduler))
      .publish();

  notification.connect();

  return shared
    .throttle(() => notification)
    .merge(shared.debounceTime(timeWindow, scheduler))
    .distinctUntilChanged();
}

let sourceMarbles =   '---a----b-c-d-----e-f---';
let expectedMarbles = '---a----b------d--e----f';

// Create the test Observable
let observable = scheduler
  .createHotObservable(sourceMarbles)
  .let(source => awesomeDebounce(source, 30, scheduler));

scheduler.expectObservable(observable).toBe(expectedMarbles);
scheduler.flush();

The inner notification Observable is used only for the throttle() operator so I can reset its timer manually when I need. I also had to turn this Observable into "hot" to be independent on the internal subscriptions from throttle().


问:
php code logic for transferring data from one page to another
i made a (php) form, and used php session and post to transfer the form data to another page, which gives the user an option to have a look at the data and if wrong he shall move to the main form..

now here is what i did

on page1 i made a main form say form1, when user clicks on submit, i saved the data to DB and added that id to a session, and sent that session to next page using the same id
on next page i called from db matching the same id and displayed data accordingly..

now i displayed the data (on the second page) inside a div styled with css, the logic for this second page is giving the user the choice if the data is wrong he can edit, and bottom of this div i added a button with code

```<code><a href="#" class="button3">Edit</a>
</code>```

now my question is this, what shall be next? my target is, if user clicks on this edit button he shall be taken to main form (i.e. page1, form1) and there he shall has the option of editing the data in the same id. How can i achieve this friends?

Also i used

```<code><?php session_start(); ?>
</code>```

on top of both the pages...

答: If you already have all the data in your session you can simply link back to the first page. All you have to do is set all of your fields on the first page to pre-fill with the session data as long as it isset. This way, when you go back the forms will auto fill with the data the user has already entered and they can simply change what is needed.

Body:
i made a (php) form, and used php session and post to transfer the form data to another page, which gives the user an option to have a look at the data and if wrong he shall move to the main form..

now here is what i did

on page1 i made a main form say form1, when user clicks on submit, i saved the data to DB and added that id to a session, and sent that session to next page using the same id
on next page i called from db matching the same id and displayed data accordingly..

now i displayed the data (on the second page) inside a div styled with css, the logic for this second page is giving the user the choice if the data is wrong he can edit, and bottom of this div i added a button with code

Edit

now my question is this, what shall be next? my target is, if user clicks on this edit button he shall be taken to main form (i.e. page1, form1) and there he shall has the option of editing the data in the same id. How can i achieve this friends?

Also i used

<?php session_start(); ?>

on top of both the pages...


问:
ASP.Net MVC vs. Ruby on Rails
If you were starting a new web development project would you use ASP.Net MVC 2 or Ruby on Rails?

I have recently invested some time in to learning Ruby on Rails because I wanted to learn a solid web development framework.  Then I took a new job where I will be using ASP.Net MVC 2.

I know this question is very subjective, but I am planning to write some websites on my own, outside of work, and I would like to get some opinions from others.

答: Since you'll be working with ASP.NET MVC, if I were you I would learn Ruby on Rails on your personal projects. Learning both will make you a stronger programmer because you can see the same solution from multiple perspectives.</p>

Title: ASP.Net MVC vs. Ruby on Rails


问:
How to change width between li items based on number of li items
I'm trying to create a "reusable" progress tracker bar and I need to change the width between the li items based on the number of li items.

I found this JavaScript code from this other question:

```<code>$('.lesson-nav ul li').width( 100 / $(".lesson-nav ul li").length + '%' );
</code>```

I'm so close.  Can someone help with what is wrong that is making it not work?

$('.progressTrackerBar ul li').width(100 / $(".progressTrackerBar ul li").length + '%');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*row with border*/

.progressTrackerBarRow {
  display: inline-block;
  width: 700px;
  height: 80px;
  border-style: solid;
  border-width: thin;
  border-color: blue;
}

/*remove bullets*/

ul#progressTrackerBar {
  list-style-type: none;
}

/*horizontal list*/

ul#progressTrackerBar li {
  float: left;
  display: inline;
  /*width: 14%;  /*Space between circles*/
  /*width: var(--w);*/
  position: relative;
  text-align: center;
  font-size: large;
}

/*circles*/

ul#progressTrackerBar li:before {
  content: '';
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #9bbdfa;
  display: block;
  text-align: center;
  margin: -5px auto 1px auto;
  /*top right bottom left*/
  border-radius: 50%;
  background: radial-gradient(at 70% bottom, #9bbdfa, white);
}

/*lines*/

ul#progressTrackerBar li:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 10px;
  left: -50%;
  z-index: -1;
}

/*remove first line*/

ul#progressTrackerBar li:first-child:after {
  content: none;
}

/*active circle text*/

ul#progressTrackerBar li.active {
  /*color: #8f6bfb;*/
  font-weight: 600;
}

/*active circle border*/

ul#progressTrackerBar li.active:before {
  background: radial-gradient(at 70% bottom, #5444e1, white);
  border-color: #5444e1;
}

/*active line*/

ul#progressTrackerBar li.active+li:after {
  background-color: #5444e1;
}</code>```

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6

Step 7

```

答:
Your selector was not quite right.  Use $('#progressTrackerBar li') instead

$('#progressTrackerBar li').width(100 / $("#progressTrackerBar li").length + '%');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*row with border*/

.progressTrackerBarRow {
  display: inline-block;
  width: 700px;
  height: 80px;
  border-style: solid;
  border-width: thin;
  border-color: blue;
}

/*remove bullets*/

ul#progressTrackerBar {
  list-style-type: none;
}

/*horizontal list*/

ul#progressTrackerBar li {
  float: left;
  display: inline;
  /*width: 14%;  /*Space between circles*/
  /*width: var(--w);*/
  position: relative;
  text-align: center;
  font-size: large;
}

/*circles*/

ul#progressTrackerBar li:before {
  content: '';
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #9bbdfa;
  display: block;
  text-align: center;
  margin: -5px auto 1px auto;
  /*top right bottom left*/
  border-radius: 50%;
  background: radial-gradient(at 70% bottom, #9bbdfa, white);
}

/*lines*/

ul#progressTrackerBar li:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 10px;
  left: -50%;
  z-index: -1;
}

/*remove first line*/

ul#progressTrackerBar li:first-child:after {
  content: none;
}

/*active circle text*/

ul#progressTrackerBar li.active {
  /*color: #8f6bfb;*/
  font-weight: 600;
}

/*active circle border*/

ul#progressTrackerBar li.active:before {
  background: radial-gradient(at 70% bottom, #5444e1, white);
  border-color: #5444e1;
}

/*active line*/

ul#progressTrackerBar li.active+li:after {
  background-color: #5444e1;
}</code>```

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6

Step 7

```

Body:
I'm trying to create a "reusable" progress tracker bar and I need to change the width between the li items based on the number of li items.

I found this JavaScript code from this other question:

$('.lesson-nav ul li').width( 100 / $(".lesson-nav ul li").length + '%' );

I'm so close.  Can someone help with what is wrong that is making it not work?

$('.progressTrackerBar ul li').width(100 / $(".progressTrackerBar ul li").length + '%');

/*row with border*/

.progressTrackerBarRow {
  display: inline-block;
  width: 700px;
  height: 80px;
  border-style: solid;
  border-width: thin;
  border-color: blue;
}

/*remove bullets*/

ul#progressTrackerBar {
  list-style-type: none;
}

/*horizontal list*/

ul#progressTrackerBar li {
  float: left;
  display: inline;
  /*width: 14%;  /*Space between circles*/
  /*width: var(--w);*/
  position: relative;
  text-align: center;
  font-size: large;
}

/*circles*/

ul#progressTrackerBar li:before {
  content: '';
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #9bbdfa;
  display: block;
  text-align: center;
  margin: -5px auto 1px auto;
  /*top right bottom left*/
  border-radius: 50%;
  background: radial-gradient(at 70% bottom, #9bbdfa, white);
}

/*lines*/

ul#progressTrackerBar li:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 10px;
  left: -50%;
  z-index: -1;
}

/*remove first line*/

ul#progressTrackerBar li:first-child:after {
  content: none;
}

/*active circle text*/

ul#progressTrackerBar li.active {
  /*color: #8f6bfb;*/
  font-weight: 600;
}

/*active circle border*/

ul#progressTrackerBar li.active:before {
  background: radial-gradient(at 70% bottom, #5444e1, white);
  border-color: #5444e1;
}

/*active line*/

ul#progressTrackerBar li.active+li:after {
  background-color: #5444e1;
}

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6

Step 7

Body:
Your selector was not quite right.  Use $('#progressTrackerBar li') instead

$('#progressTrackerBar li').width(100 / $("#progressTrackerBar li").length + '%');

/*row with border*/

.progressTrackerBarRow {
  display: inline-block;
  width: 700px;
  height: 80px;
  border-style: solid;
  border-width: thin;
  border-color: blue;
}

/*remove bullets*/

ul#progressTrackerBar {
  list-style-type: none;
}

/*horizontal list*/

ul#progressTrackerBar li {
  float: left;
  display: inline;
  /*width: 14%;  /*Space between circles*/
  /*width: var(--w);*/
  position: relative;
  text-align: center;
  font-size: large;
}

/*circles*/

ul#progressTrackerBar li:before {
  content: '';
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #9bbdfa;
  display: block;
  text-align: center;
  margin: -5px auto 1px auto;
  /*top right bottom left*/
  border-radius: 50%;
  background: radial-gradient(at 70% bottom, #9bbdfa, white);
}

/*lines*/

ul#progressTrackerBar li:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 10px;
  left: -50%;
  z-index: -1;
}

/*remove first line*/

ul#progressTrackerBar li:first-child:after {
  content: none;
}

/*active circle text*/

ul#progressTrackerBar li.active {
  /*color: #8f6bfb;*/
  font-weight: 600;
}

/*active circle border*/

ul#progressTrackerBar li.active:before {
  background: radial-gradient(at 70% bottom, #5444e1, white);
  border-color: #5444e1;
}

/*active line*/

ul#progressTrackerBar li.active+li:after {
  background-color: #5444e1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row progressTrackerBarRow" align="center">
  <div class="container" style="width: 100%;">
    <ul id="progressTrackerBar">
      <li id="1" class="active">Step 1</li>
      <li id="2">Step 2</li>
      <li id="3">Step 3</li>
      <li id="4">Step 4</li>
      <li id="5">Step 5</li>
      <li id="6">Step 6</li>
      <li id="7">Step 7</li>
    </ul>
  </div>
</div>


答:
You need to target the correct li element:</p>

```<code>$('#progressTrackerBar li').width( 100 / $("#progressTrackerBar li").length + '%' );
</code>```

Title: How to change width between li items based on number of li items

Body:
You need to target the correct li element:

$('#progressTrackerBar li').width( 100 / $("#progressTrackerBar li").length + '%' );