问:
Rails mapping by max size and loop
In my rails application I'm looking to display in a table some results mapping by max size.

Controller

```<code>@max_length = [@result.generals, @result.measurements.in_groups_of(3)].map(&:size).max
</code>```

The problem i'm facing is my @result.measurement has 3 dates for each measurement in which I want to display across the row.

This is what I'm looking to achieve:

But with the code below, this is my result - It stops at the first date:

How can I go about looping the @result.measurements?

```<code><table>
    <tr>
        <th colspan="2">General</th>
        <th colspan="6">Measurements</th>
    </tr>
    <tr>
        <td>Number</td>
        <td>Town</td>
        <td>Date</td>
        <td>Length</td>
        <td>Date</td>
        <td>Length</td>
        <td>Date</td>
        <td>Length</td>
    </tr>
    <% @max_length.times do |data| %>
    <tr>
        <td><%= @result.generals.[data].try(:number) %></td>
        <td><%= @result.generals.[data].try(:town) %></td>
        <td><%= @result.measurements.[data].try(:date) %></td>
        <td><%= @result.measurements.[data].try(:length) %></td>
    </tr>
    <% end %>
    </table>
</code>```

答:
Your code is doing exactly what you are asking it to do: to display a single td for the measurements. In order to have three lots of the columns, you need to loop over the data eg something like:

```<code><table>
<tr>
    <th colspan="2">General</th>
    <th colspan="6">Measurements</th>
</tr>
<tr>
    <td>Number</td>
    <td>Town</td>
    <td>Date</td>
    <td>Length</td>
    <td>Date</td>
    <td>Length</td>
    <td>Date</td>
    <td>Length</td>
</tr>
<% @result.measurements.in_groups_of(3).each do |general, measurements| %>
<tr>
    <td><%= general.try(:number) %></td>
    <td><%= general.try(:town) %></td>
    <% measurements.each do |m|
      <td><%= m.try(:date) %></td>
      <td><%= m.try(:length) %></td>
    <% end %>
</tr>
<% end %>
</table>
</code>```

Note: of course I have not bug-tested this - it will probably not work exactly as is - because I do not have a copy of your data (and you have not provided an example) so you'll need to adapt what I've written to what you have so that it works...

At present I don't know how your general relates to your measurements.

can you provide some example data that you would expect to be returned by the fetching-code and I can adapt this example to fit.

Title: Rails mapping by max size and loop

Body:
In my rails application I'm looking to display in a table some results mapping by max size.

Controller

@max_length = [@result.generals, @result.measurements.in_groups_of(3)].map(&:size).max

The problem i'm facing is my @result.measurement has 3 dates for each measurement in which I want to display across the row.

This is what I'm looking to achieve:

But with the code below, this is my result - It stops at the first date:

How can I go about looping the @result.measurements?

        General
        Measurements

        Number
        Town
        Date
        Length
        Date
        Length
        Date
        Length

    <% @max_length.times do |data| %>

        <%= @result.generals.[data].try(:number) %>
        <%= @result.generals.[data].try(:town) %>
        <%= @result.measurements.[data].try(:date) %>
        <%= @result.measurements.[data].try(:length) %>

    <% end %>

Body:
Your code is doing exactly what you are asking it to do: to display a single td for the measurements. In order to have three lots of the columns, you need to loop over the data eg something like:

<table>
<tr>
    <th colspan="2">General</th>
    <th colspan="6">Measurements</th>
</tr>
<tr>
    <td>Number</td>
    <td>Town</td>
    <td>Date</td>
    <td>Length</td>
    <td>Date</td>
    <td>Length</td>
    <td>Date</td>
    <td>Length</td>
</tr>
<% @result.measurements.in_groups_of(3).each do |general, measurements| %>
<tr>
    <td><%= general.try(:number) %></td>
    <td><%= general.try(:town) %></td>
    <% measurements.each do |m|
      <td><%= m.try(:date) %></td>
      <td><%= m.try(:length) %></td>
    <% end %>
</tr>
<% end %>
</table>

Note: of course I have not bug-tested this - it will probably not work exactly as is - because I do not have a copy of your data (and you have not provided an example) so you'll need to adapt what I've written to what you have so that it works...

At present I don't know how your general relates to your measurements.

can you provide some example data that you would expect to be returned by the fetching-code and I can adapt this example to fit.


来源: stackexchange

问:
Update SQL Data Mismatch In Criteria Error
First of all I'm using MS Access OleDb and I tried many times with and without parameters for UPDATE SQL query.

Photo update thing not the fact for now, when I try to update button I get:

Data type mismatch in criteria expression.

and that error drives me crazy, please help me. Thank you!

ktN comes from KayitNo as Public Int32 from header and when I clicked to datagrid for update (in that time retrieves other columns to textboxes and datetimePickers etc.)

```<code>OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TSP.accdb");
OleDbCommand komut = new OleDbCommand("UPDATE TSP_Data SET SeriNo=@SeriNo,PartNo=@PartNo,PID=@PID,Model=@Model,UretimTarihi=@UretimTarihi,Teknisyen=@Teknisyen,ServisGiris=@ServisGiris,Ariza=@Ariza,TeknisyenNotu=@TeknisyenNotu,YapilanIslem=@YapilanIslem,MudahaleSonucu=@MudahaleSonucu,BoardUzerindekiYeri=@BoardUzerindekiYeri,TamirSeviyesi=@TamirSeviyesi,SonKontrolSonucu=@SonKontrolSonucu,TeslimEdilenTarih=@TeslimEdilenTarih,UrunDurumu=@UrunDurumu Where KayitNo="+ktN,con);

komut.Parameters.AddWithValue("@SeriNo",Convert.ToString(sNText.Text));
komut.Parameters.AddWithValue("@PartNo", Convert.ToString(partNoText.Text));
komut.Parameters.AddWithValue("@PID",pidText.Text);
komut.Parameters.AddWithValue("@Model",Convert.ToString(modelText.Text));
komut.Parameters.AddWithValue("@UretimTarihi",uretimTarihi.Value);
komut.Parameters.AddWithValue("@Teknisyen", Convert.ToString(teknisyenSec.SelectedItem));
komut.Parameters.AddWithValue("@ServisGiris", serviseGirisTarihi.Value);
komut.Parameters.AddWithValue("@Ariza", Convert.ToString(arizaText.Text));
komut.Parameters.AddWithValue("@TeknisyenNotu", Convert.ToString(teknisyenNotuText.Text));
komut.Parameters.AddWithValue("@YapilanIslem", Convert.ToString(yapilanIslemText.Text));
komut.Parameters.AddWithValue("@MudahaleSonucu", Convert.ToString(mudahaleSonucuSec.SelectedItem));
komut.Parameters.AddWithValue("@BoardUzerindekiYeri", Convert.ToString(boardYeriText.Text));
komut.Parameters.AddWithValue("@TamirSeviyesi", Convert.ToString(tamirSeviyesiSec.SelectedItem));
komut.Parameters.AddWithValue("@CaseID", caseIDText.Text);
komut.Parameters.AddWithValue("@SonKontrolSonucu", Convert.ToString(sonKontrolSonucuSec.SelectedItem));
komut.Parameters.AddWithValue("@TeslimEdilenTarih", teslimEdilenTarih.Value);
komut.Parameters.AddWithValue("@UrunDurumu", Convert.ToString(urunDurumuSec.SelectedItem));
</code>```

// komut.Parameters.Add("@Foto", OleDbType.Binary, foto.Length).Value = foto;
    con.Open();
    komut.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("Successful");

The Table Design in order like this:

```<code>KayitNo(Int,PK,AutomaticNumber)
SeriNo(Long Text)
PartNo(Long Text)
PID(Int)
Model(Long Text)
UretimTarihi(Date/Time)
Teknisyen(Text)
ServisGiris(Date/Time)
Ariza(Long Text)
TeknisyenNotu(Long Text)
YapilanIslem(Long Text)
MudahaleSonucu(Long Text)
BoardUzerindekiYeri(Long Text)
TamirSeviyesi(Long Text)
CaseID (Int)
SonKontrolSonucu(Text)
TeslimEdilenTarih(Date/Time)
UrunDurumu(LongText)
Foto(OLE OBJECT)
</code>```

答:
DateTime values need to be converted from string to sql datetime

Try: OleDbCommand komut = new OleDbCommand("UPDATE TSP_Data SET UretimTarihi= convert(varchar(50),@UretimTarihi,101) Where KayitNo="+ktN, con);

With: komut.Parameters.AddWithValue("@UretimTarihi",uretimTarihi.Value.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss"));

Or with DateTimeOffset.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'zzz")

Have your tried entering the values one by one, to determine which one is giving the errors? Not sure if there's multiple problems, with your insert string. But for certain i've encountered datetime errors when inserting values.

ContentLicense: CC BY-SA 3.0

Body:
First of all I'm using MS Access OleDb and I tried many times with and without parameters for UPDATE SQL query.

Photo update thing not the fact for now, when I try to update button I get:

Data type mismatch in criteria expression.

and that error drives me crazy, please help me. Thank you!

ktN comes from KayitNo as Public Int32 from header and when I clicked to datagrid for update (in that time retrieves other columns to textboxes and datetimePickers etc.)

OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TSP.accdb");
OleDbCommand komut = new OleDbCommand("UPDATE TSP_Data SET SeriNo=@SeriNo,PartNo=@PartNo,PID=@PID,Model=@Model,UretimTarihi=@UretimTarihi,Teknisyen=@Teknisyen,ServisGiris=@ServisGiris,Ariza=@Ariza,TeknisyenNotu=@TeknisyenNotu,YapilanIslem=@YapilanIslem,MudahaleSonucu=@MudahaleSonucu,BoardUzerindekiYeri=@BoardUzerindekiYeri,TamirSeviyesi=@TamirSeviyesi,SonKontrolSonucu=@SonKontrolSonucu,TeslimEdilenTarih=@TeslimEdilenTarih,UrunDurumu=@UrunDurumu Where KayitNo="+ktN,con);

komut.Parameters.AddWithValue("@SeriNo",Convert.ToString(sNText.Text));
komut.Parameters.AddWithValue("@PartNo", Convert.ToString(partNoText.Text));
komut.Parameters.AddWithValue("@PID",pidText.Text);
komut.Parameters.AddWithValue("@Model",Convert.ToString(modelText.Text));
komut.Parameters.AddWithValue("@UretimTarihi",uretimTarihi.Value);
komut.Parameters.AddWithValue("@Teknisyen", Convert.ToString(teknisyenSec.SelectedItem));
komut.Parameters.AddWithValue("@ServisGiris", serviseGirisTarihi.Value);
komut.Parameters.AddWithValue("@Ariza", Convert.ToString(arizaText.Text));
komut.Parameters.AddWithValue("@TeknisyenNotu", Convert.ToString(teknisyenNotuText.Text));
komut.Parameters.AddWithValue("@YapilanIslem", Convert.ToString(yapilanIslemText.Text));
komut.Parameters.AddWithValue("@MudahaleSonucu", Convert.ToString(mudahaleSonucuSec.SelectedItem));
komut.Parameters.AddWithValue("@BoardUzerindekiYeri", Convert.ToString(boardYeriText.Text));
komut.Parameters.AddWithValue("@TamirSeviyesi", Convert.ToString(tamirSeviyesiSec.SelectedItem));
komut.Parameters.AddWithValue("@CaseID", caseIDText.Text);
komut.Parameters.AddWithValue("@SonKontrolSonucu", Convert.ToString(sonKontrolSonucuSec.SelectedItem));
komut.Parameters.AddWithValue("@TeslimEdilenTarih", teslimEdilenTarih.Value);
komut.Parameters.AddWithValue("@UrunDurumu", Convert.ToString(urunDurumuSec.SelectedItem));

// komut.Parameters.Add("@Foto", OleDbType.Binary, foto.Length).Value = foto;
    con.Open();
    komut.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("Successful");

The Table Design in order like this:

KayitNo(Int,PK,AutomaticNumber)
SeriNo(Long Text)
PartNo(Long Text)
PID(Int)
Model(Long Text)
UretimTarihi(Date/Time)
Teknisyen(Text)
ServisGiris(Date/Time)
Ariza(Long Text)
TeknisyenNotu(Long Text)
YapilanIslem(Long Text)
MudahaleSonucu(Long Text)
BoardUzerindekiYeri(Long Text)
TamirSeviyesi(Long Text)
CaseID (Int)
SonKontrolSonucu(Text)
TeslimEdilenTarih(Date/Time)
UrunDurumu(LongText)
Foto(OLE OBJECT)


问:
Need SQL help with copying rows
I have a table that has a bunch of columns.

There is one primary key that is an ID as an int data type and no foreign keys. This PK is set with Identity Specification with the increment and seed both set at 1 whatever that means. It is set to Yes for Not For Replication. There are two other rows that are important, the year for the data and a reference number both of which I will be using to specifically select which rows to copy.

Is there any way using SQL or a combination of SQL and C# to copy a specific set of rows by reference number and assign each row a unique primary key ID by itself? The number of rows that will be copied may be different each time so it needs to be flexible. As in the system picks the ID without any more trouble or have it possibly get the max ID, and increment it by one for each row that is copied or whatever. I will also put a new year in the column but that is easy enough compared to the main problem of having it set the primary key ID's by itself for each row through a SQL statement for this type of column...

Please help! I'm not a total SQL newbie but I am still learning and have never come across this type of problem with the specific Not For Replication etc issues before.

答:
Since your primary key is an identity column you can select the rows you want (except don't select the identity column) and reinsert them into the same table:</p>

```<code>INSERT INTO table1 (col1, col2, col3)
SELECT (col1, col2, col3) FROM table1
WHERE ....
</code>```

ContentLicense: CC BY-SA 2.5

Title: Need SQL help with copying rows

Body:
Since your primary key is an identity column you can select the rows you want (except don't select the identity column) and reinsert them into the same table:

INSERT INTO table1 (col1, col2, col3)
SELECT (col1, col2, col3) FROM table1
WHERE ....


问:
MTKView in Cocoa doesn't draw in Retina
I have a MTKView in Cocoa.

I'm displaying a texture with drawable.texture - but the texture only shows over a quarter of the screen - Non-Retina.

Do I need to do any additional setup to get this to work?

```<code>class MyView : MTKView
</code>```

The following code has no-affect:

```<code>let scale = NSScreen.mainScreen()!.backingScaleFactor
var s = frame.size
s.width *= scale
s.height *= scale

metalLayer.contentsScale = scale
metalLayer.framebufferOnly = false
metalLayer.drawableSize = s
</code>```

Update:

Here's the method I have to load the texture from the image:

```<code>func textureFromImage(image: NSImage, inout tex:MTLTexture?) {

    let textureLoader = MTKTextureLoader(device: self.device!)
    do {
        tex = try textureLoader.newTextureWithCGImage(image.CGImage, options: nil)
    }
    catch {
        fatalError("Can't load texture")
    }
}
</code>```

and the code to present:

```<code>let commandBuffer = commandQueue.commandBuffer()
    let commandEncoder = commandBuffer.computeCommandEncoder()
    commandEncoder.setComputePipelineState(pipelineState)
    commandEncoder.setTexture(originalTexture, atIndex: 0)
    commandEncoder.setTexture(drawable.texture, atIndex: 1)
    commandEncoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)
    commandEncoder.endEncoding()
    commandBuffer.presentDrawable(drawable)
    commandBuffer.commit();
</code>```

All of the sizes for the original input image and texture are the same size as the view.

答: Try changing the contentScaleFactor for the view to 1.</p>

Title: MTKView in Cocoa doesn't draw in Retina

Body:
I have a MTKView in Cocoa.

I'm displaying a texture with drawable.texture - but the texture only shows over a quarter of the screen - Non-Retina.

Do I need to do any additional setup to get this to work?

class MyView : MTKView

The following code has no-affect:

let scale = NSScreen.mainScreen()!.backingScaleFactor
var s = frame.size
s.width *= scale
s.height *= scale

metalLayer.contentsScale = scale
metalLayer.framebufferOnly = false
metalLayer.drawableSize = s

Update:

Here's the method I have to load the texture from the image:

func textureFromImage(image: NSImage, inout tex:MTLTexture?) {

    let textureLoader = MTKTextureLoader(device: self.device!)
    do {
        tex = try textureLoader.newTextureWithCGImage(image.CGImage, options: nil)
    }
    catch {
        fatalError("Can't load texture")
    }
}

and the code to present:

let commandBuffer = commandQueue.commandBuffer()
    let commandEncoder = commandBuffer.computeCommandEncoder()
    commandEncoder.setComputePipelineState(pipelineState)
    commandEncoder.setTexture(originalTexture, atIndex: 0)
    commandEncoder.setTexture(drawable.texture, atIndex: 1)
    commandEncoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)
    commandEncoder.endEncoding()
    commandBuffer.presentDrawable(drawable)
    commandBuffer.commit();

All of the sizes for the original input image and texture are the same size as the view.


问:
React state is array of objects which are react elements
I'm running into an issue right now trying to render a list using react, where I'm saving my react elements into the state, but the problem I'm getting is that the console outputs this:

Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

Here is what the state looks like which causes the error:

export default class UserData extends Component {
  constructor() {
    super();
    this.state = {
      resultsItems: {}
    }
  };

  componentDidMount() {

    fetch(url)
      .then(results => {
        return results.json();
      }).then(data => {
        console.log(data.items);
        let items = data.items.map((item) => {
          console.log(item.title);
          return (

item.title

          )
        });

        this.setState({resultsItems: items});
        console.log("state", this.state.resultsItems);
      })
      .catch(error => console.log(error))
  };

  render() {
    return (

        <button onClick={() => this.props.updateLoginStatus(false)}>
          Logout
        </button>

          ID: {this.props.user}
          {this.state.resultsItems}

    )
  }
}```

答:
It seems like you are correctly setting an array to your state on componentDidMount, however the initial state in your constructor is an object and not an array!

So change this:

```<code>this.state = {
  resultsItems: {}
}
</code>```

to this:

```<code>this.state = {
  resultsItems: []
}
</code>```

Body:
It seems like you are correctly setting an array to your state on componentDidMount, however the initial state in your constructor is an object and not an array!

So change this:

this.state = {
  resultsItems: {}
}

to this:

this.state = {
  resultsItems: []
}


问:
How to Display HTML Table Using Golang Template
I am trying to use html/template package to display a table of information in a web page in Golang. The current implementation of the template I have outputs to standard out.

I want to be able to pass the page content generated by the template to another function that will render my web page.

How to achieve this?

Explanation of code attached below. Basically, I want to capture the result of t.Execute(os.Stdout, persons) where persons is a slice of string. I know that t.Execute only returns an error. But it prints to standard out the template t along with the person name values. I wanted to capture the combined template and person array texts into a variable instead. I would like to assign the content to the body variable in my code below.

```<code>    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

    if err := t.Execute(os.Stdout, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: []byte(body)}
    renderTemplate(w, "view", p)
}
</code>```

答:
Execute the template to a bytes.Buffer.  Use the contents of the buffer as the body.

```<code>t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

var body bytes.Buffer
if err := t.Execute(&body, persons); err != nil {
   log.Fatal(err)
}
title := "User Info Page"
p := &Page{Title: title, Body: body.Bytes()}
renderTemplate(w, "view", p)
</code>```

If it's also a requirement to print to stdout, then add the following code after executing the template:

```<code>os.Stdout.Write(body.Bytes())
</code>```

Body:
I am trying to use html/template package to display a table of information in a web page in Golang. The current implementation of the template I have outputs to standard out.

I want to be able to pass the page content generated by the template to another function that will render my web page.

How to achieve this?

Explanation of code attached below. Basically, I want to capture the result of t.Execute(os.Stdout, persons) where persons is a slice of string. I know that t.Execute only returns an error. But it prints to standard out the template t along with the person name values. I wanted to capture the combined template and person array texts into a variable instead. I would like to assign the content to the body variable in my code below.

    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

    if err := t.Execute(os.Stdout, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: []byte(body)}
    renderTemplate(w, "view", p)
}

Body:
Execute the template to a bytes.Buffer.  Use the contents of the buffer as the body.

t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

var body bytes.Buffer
if err := t.Execute(&body, persons); err != nil {
   log.Fatal(err)
}
title := "User Info Page"
p := &Page{Title: title, Body: body.Bytes()}
renderTemplate(w, "view", p)

If it's also a requirement to print to stdout, then add the following code after executing the template:

os.Stdout.Write(body.Bytes())


问:
Ribbon shape using for loop in C++
I've been trying all day creating different for loop combinations in c++ and I can't seem to get the right one.

I want my output to look like this:

Ribbon

How can you display this without using arrays?

EDIT: I tried like this but I can't replicate it on the opposite end. This has been so far the closest output I've got.

```<code>for(int i = 0; i < 6; i++)
{
    cout<<"*";

    for(int j = 5; j > i; j--)
    {
        cout<<" ";
    }

    for(int k = 0; k <= i; k++)
    {
        cout<<"*";
    }

    cout<<endl;

}
</code>```

OUTPUT:

Fail ribbon

答:
One option is to increment the number of stars on each row, then go back down once you reached the midpoint.

```<code>void printChar(char c, int count)
{
    for (int i = 0; i < count; i++)
        std::cout << c;
}

int main()
{
    const int len = 10;

    int stars = 0;

    while (++stars <= len / 2)
    {
        int spaces = len - stars * 2;

        printChar('*', stars);
        printChar(' ', spaces);
        printChar('*', stars);
        std::cout << "\n";
    }
    stars--;
    while (--stars > 0)
    {
        int spaces = len - stars * 2;

        printChar('*', stars);
        printChar(' ', spaces);
        printChar('*', stars);
        std::cout << "\n";
    }

    return 0;
}
</code>```

Title: Ribbon shape using for loop in C++

Body:
I've been trying all day creating different for loop combinations in c++ and I can't seem to get the right one.

I want my output to look like this:

Ribbon

How can you display this without using arrays?

EDIT: I tried like this but I can't replicate it on the opposite end. This has been so far the closest output I've got.

for(int i = 0; i < 6; i++)
{
    cout<<"*";

    for(int j = 5; j > i; j--)
    {
        cout<<" ";
    }

    for(int k = 0; k <= i; k++)
    {
        cout<<"*";
    }

    cout<<endl;

}

OUTPUT:

Fail ribbon

Body:
One option is to increment the number of stars on each row, then go back down once you reached the midpoint.

void printChar(char c, int count)
{
    for (int i = 0; i < count; i++)
        std::cout << c;
}

int main()
{
    const int len = 10;

    int stars = 0;

    while (++stars <= len / 2)
    {
        int spaces = len - stars * 2;

        printChar('*', stars);
        printChar(' ', spaces);
        printChar('*', stars);
        std::cout << "\n";
    }
    stars--;
    while (--stars > 0)
    {
        int spaces = len - stars * 2;

        printChar('*', stars);
        printChar(' ', spaces);
        printChar('*', stars);
        std::cout << "\n";
    }

    return 0;
}


问:
How to render NotFound Component react-router-config
I am new to react I would like to implement server side rendering with react router 4 I am using this package react-router-config to write plain routes But I don't why not found component is not rendering it always access the parents routes and in parent routes if user not authenticated they will redirected .Not found is not rendering as expected

Code

```<code>import Home from './containers/Home';
import PrivateLayout from './containers/PrivateLayout';
import NewTest from './containers/NewTest'
import TestBoard from './containers/TestBoard';
import Profile from './containers/Profile';
import NotFound from './containers/NotFound';
import PublicLayout from './containers/PublicLayout';
export default [
    {
        ...Home,
        path:'/',
        exact:true
    },
    {
        ...PublicLayout,
        routes:[
            {
                ...Profile,
                path:'/@:username',
                exact:true
            },
            {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    }
                ]
            },

        ]
    },
    {
        ...NotFound,
    },
]
</code>```

index.js

```<code>import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './Routes';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import { renderRoutes } from 'react-router-config';
import { BrowserRouter ,Switch} from 'react-router-dom';
import reducers from './reducers';
import './index.css';
import axios from 'axios';
import { Map } from 'immutable';
import CONFIG from './config'

const axiosInstance = axios.create({
    baseURL:CONFIG.HOST,
    withCredentials: true
});

const INITIAL_STATE = window.INITIAL_STATE || {};

Object
    .keys(INITIAL_STATE)
    .forEach(key => {
        INITIAL_STATE[key] = Map(INITIAL_STATE[key]);
    });

const store = createStore(reducers,INITIAL_STATE, applyMiddleware(reduxThunk.withExtraArgument(axiosInstance)));

window.store = store;

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <Switch>
               <div>{renderRoutes(Routes)}</div>
            </Switch>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));
</code>```

UPDATE #1

Why different Layout ?

I have common Header (or) Logged In Header to be showed on both profile Page and private Layout Components .To be clear Profile page will displayed even user logged out But Private Layout content will not be displayed it will be redirected

Example Import

```<code>import React,{Component} from 'react';

class NotFound extends Component{
    render(){
        return(
            <h1>Not Found</h1>
        )
    }
}

export default {
    component:NotFound
}
</code>```

After Updating the Zarcode Answer I got an error Like this

index.js:2177 Warning: React does not recognize the computedMatch
  prop on a DOM element. If you intentionally want it to appear in the
  DOM as a custom attribute, spell it as lowercase computedmatch
  instead. If you accidentally passed it from a parent component, remove
  it from the DOM element.
      in div (at index.js:39)
      in Switch (at index.js:38)
      in Router (created by BrowserRouter)
      in BrowserRouter (at index.js:37)
      in Provider (at index.js:36)

And HTML Render Looked Like this

UPDATE #2

I noticed wired Behaviour If I changed the notFound component inside the private routes it is working But the problem it is working for only Logged in Routes.

```<code>...
    {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    },
                    {
                        ...NotFound,
                    },
                ]
            }
...
</code>```

答:
NotFound won't ever get rendered since it'll always match PublicLayout's path first.

I'd recommend adding a namespace, for example:

```<code>export default [
    {
        ...Home,
        path:'/',
        exact:true
    },
    {
        ...PublicLayout,
        path: '/public', // Added
        routes:[
            {
                ...Profile,
                path:'/@:username',
                exact:true
            },
            {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    }
                ]
            },

        ]
    },

    {
        ...NotFound,
    },
]
</code>```

Body:
I am new to react I would like to implement server side rendering with react router 4 I am using this package react-router-config to write plain routes But I don't why not found component is not rendering it always access the parents routes and in parent routes if user not authenticated they will redirected .Not found is not rendering as expected

Code

import Home from './containers/Home';
import PrivateLayout from './containers/PrivateLayout';
import NewTest from './containers/NewTest'
import TestBoard from './containers/TestBoard';
import Profile from './containers/Profile';
import NotFound from './containers/NotFound';
import PublicLayout from './containers/PublicLayout';
export default [
    {
        ...Home,
        path:'/',
        exact:true
    },
    {
        ...PublicLayout,
        routes:[
            {
                ...Profile,
                path:'/@:username',
                exact:true
            },
            {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    }
                ]
            },

        ]
    },
    {
        ...NotFound,
    },
]

index.js

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './Routes';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import { renderRoutes } from 'react-router-config';
import { BrowserRouter ,Switch} from 'react-router-dom';
import reducers from './reducers';
import './index.css';
import axios from 'axios';
import { Map } from 'immutable';
import CONFIG from './config'

const axiosInstance = axios.create({
    baseURL:CONFIG.HOST,
    withCredentials: true
});

const INITIAL_STATE = window.INITIAL_STATE || {};

Object
    .keys(INITIAL_STATE)
    .forEach(key => {
        INITIAL_STATE[key] = Map(INITIAL_STATE[key]);
    });

const store = createStore(reducers,INITIAL_STATE, applyMiddleware(reduxThunk.withExtraArgument(axiosInstance)));

window.store = store;

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <Switch>

{renderRoutes(Routes)}

            </Switch>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));

UPDATE #1

Why different Layout ?

I have common Header (or) Logged In Header to be showed on both profile Page and private Layout Components .To be clear Profile page will displayed even user logged out But Private Layout content will not be displayed it will be redirected

Example Import

import React,{Component} from 'react';

class NotFound extends Component{
    render(){
        return(

Not Found

        )
    }
}

export default {
    component:NotFound
}

After Updating the Zarcode Answer I got an error Like this

index.js:2177 Warning: React does not recognize the computedMatch
  prop on a DOM element. If you intentionally want it to appear in the
  DOM as a custom attribute, spell it as lowercase computedmatch
  instead. If you accidentally passed it from a parent component, remove
  it from the DOM element.
      in div (at index.js:39)
      in Switch (at index.js:38)
      in Router (created by BrowserRouter)
      in BrowserRouter (at index.js:37)
      in Provider (at index.js:36)

And HTML Render Looked Like this

UPDATE #2

I noticed wired Behaviour If I changed the notFound component inside the private routes it is working But the problem it is working for only Logged in Routes.

...
    {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    },
                    {
                        ...NotFound,
                    },
                ]
            }
...

Body:
NotFound won't ever get rendered since it'll always match PublicLayout's path first.

I'd recommend adding a namespace, for example:

export default [
    {
        ...Home,
        path:'/',
        exact:true
    },
    {
        ...PublicLayout,
        path: '/public', // Added
        routes:[
            {
                ...Profile,
                path:'/@:username',
                exact:true
            },
            {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    }
                ]
            },

        ]
    },

    {
        ...NotFound,
    },
]


问:
QML Qt- Parse XML and convert it as a LisView's ListModel
I'm new to Qt and QML. With that said, I am making a editable list in QML which I would like to import and export as XML file. Right now I'm stuck on importing it from XML file and setting it as my ListView's model from the C++ side.

I'm hoping I can transform the XML to a form
I want to be able to add, remove and edit rows in my ListView from the QML side, so using XmlListModel looks like a bad idea, i.e. it doesn't offer those abilities.

my main.qml in which I am choosing the file location:

```<code>    FileDialog {
        id: exportDialog
        title: "Please choose an XML TV file"
        nameFilters: [("*.xml")]

        onAccepted: {
            fileio.parse(importDialog.fileUrl)
        }
        onRejected: {
            console.log("Canceled")
        }
    }
</code>```

My C++ header file in which I would like the conversion to happen:

```<code>#ifndef FILEIO_H
#define FILEIO_H

#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QDebug>

class FileIO : public QObject
{
    Q_OBJECT

public slots:
    bool parse(const QString& source)
    {
        if (source.isEmpty())
            return false;

        QFile file(source);
        if (!file.open(QFile::WriteOnly | QFile::Truncate))
            return false;

        QFile* mjau = new QFile(source);
        if (!mjau->open(QIODevice::ReadOnly | QIODevice::Text)) {
                printf("Load XML File Problem");
                return false;
        }

        QXmlStreamReader reader(mjau);
        while(!reader.atEnd() && !reader.hasError()) {
            if(reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "parent") {
                 qDebug() << reader.readElementText();
                //printf(reader.readElementText())
            }
        }
    }
public:
    FileIO() {}
};

#endif // FILEIO_H
</code>```

Example of xml file I'd like to parse, multitude of  entries:

```<code><notes>
    <note>
        <heading>Help</heading>
        <body>I want to make this work!</body>
    </note>
    <note>
        <heading>Because</heading>
        <body>I love QML <3</body>
    </note>
    ...
</notes>
</code>```

To something like this:

```<code>ListModel {
    id: notes
    ListElement {
        heading: "Help"
        body: "I want to make this work!"
    }
    ListElement {
        heading: "Because"
        body: "I love QML <3"
    }
}
</code>```

Right now, when I choose the XML file nothing happens, but that same file is "cleaned out", becomes a blank .xml file.
How could I parse it properly, and after that, convert the parsed data into QML's ListView ListModel or any model that can support editing from the QML's side?

--UPDATE--
Parsing of the XML file will be a one-time procedure, after the parse I intend to work with the data in javascript, so it would be cool if  the data could be parsed in JSON object structure.

答:
In the end, I've usedQDomDocument class to read XML file, iterate through all of the nodes and write values that I want to JSON objects like so:

QDomElement root = doc.firstChildElement();
QDomNodeList programme = root.elementsByTagName("node");
nodeCollection.push_back(ListElements(program, "title", "lang"));
```

<p>...</p>

<pre class="lang-cpp prettyprint-override"><code>QJsonObject ListElements (QDomElement root, QString tagname, QString attribute)
{

        QDomNodeList items = root.elementsByTagName(tagname);

        for(int i = 0; i < items.count(); i++)
        {
            QDomNode itemnode = items.at(i);
            if (itemnode.isElement())
            {
                QDomElement itemElement = itemnode.toElement();
                qInfo() << itemElement.tagName(); // <-element name
                qInfo() << itemElement.attribute("lang"); // <-element attribute
                qInfo() << itemElement.text(); // <-element text

// putting the values above inside JSOn object:

                auto nodeData = QJsonObject(
                {
                qMakePair(QString(itemElement.tagName()), QJsonValue(itemElement.text())),
                qMakePair(QString("lang"), QJsonValue(itemElement.attribute("lang"))),
                });

                return nodeData;
            }
        }
    }
</code>```

so this:

  <node>
    <title lang="en">Title1</title>
    <category lang="en">Category1</category>
    <desc lang="en">Description1</desc>
  </node>
```

<p>becomes (this is what <code>ListElements</code> returns):</p>

<pre class="lang-cpp prettyprint-override"><code> QJsonObject({"title":"Title1","lang":"en"})
 QJsonObject({"category":"Category1","lang":"en"})
 QJsonObject({"desc":"Description1","lang":"en"})
</code>```

Body:
I'm new to Qt and QML. With that said, I am making a editable list in QML which I would like to import and export as XML file. Right now I'm stuck on importing it from XML file and setting it as my ListView's model from the C++ side.

I'm hoping I can transform the XML to a form
I want to be able to add, remove and edit rows in my ListView from the QML side, so using XmlListModel looks like a bad idea, i.e. it doesn't offer those abilities.

my main.qml in which I am choosing the file location:

    FileDialog {
        id: exportDialog
        title: "Please choose an XML TV file"
        nameFilters: [("*.xml")]

        onAccepted: {
            fileio.parse(importDialog.fileUrl)
        }
        onRejected: {
            console.log("Canceled")
        }
    }

My C++ header file in which I would like the conversion to happen:

#ifndef FILEIO_H
#define FILEIO_H

#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QDebug>

class FileIO : public QObject
{
    Q_OBJECT

public slots:
    bool parse(const QString& source)
    {
        if (source.isEmpty())
            return false;

        QFile file(source);
        if (!file.open(QFile::WriteOnly | QFile::Truncate))
            return false;

        QFile* mjau = new QFile(source);
        if (!mjau->open(QIODevice::ReadOnly | QIODevice::Text)) {
                printf("Load XML File Problem");
                return false;
        }

        QXmlStreamReader reader(mjau);
        while(!reader.atEnd() && !reader.hasError()) {
            if(reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "parent") {
                 qDebug() << reader.readElementText();
                //printf(reader.readElementText())
            }
        }
    }
public:
    FileIO() {}
};

#endif // FILEIO_H

Example of xml file I'd like to parse, multitude of  entries:

<notes>
    <note>
        <heading>Help</heading>
        I want to make this work!
    </note>
    <note>
        <heading>Because</heading>
        I love QML <3
    </note>
    ...
</notes>

To something like this:

ListModel {
    id: notes
    ListElement {
        heading: "Help"
        body: "I want to make this work!"
    }
    ListElement {
        heading: "Because"
        body: "I love QML <3"
    }
}

Right now, when I choose the XML file nothing happens, but that same file is "cleaned out", becomes a blank .xml file.
How could I parse it properly, and after that, convert the parsed data into QML's ListView ListModel or any model that can support editing from the QML's side?

--UPDATE--
Parsing of the XML file will be a one-time procedure, after the parse I intend to work with the data in javascript, so it would be cool if  the data could be parsed in JSON object structure.

Body:
In the end, I've usedQDomDocument class to read XML file, iterate through all of the nodes and write values that I want to JSON objects like so:

QDomElement root = doc.firstChildElement();
QDomNodeList programme = root.elementsByTagName("node");
nodeCollection.push_back(ListElements(program, "title", "lang"));

...

QJsonObject ListElements (QDomElement root, QString tagname, QString attribute)
{

        QDomNodeList items = root.elementsByTagName(tagname);

        for(int i = 0; i < items.count(); i++)
        {
            QDomNode itemnode = items.at(i);
            if (itemnode.isElement())
            {
                QDomElement itemElement = itemnode.toElement();
                qInfo() << itemElement.tagName(); // <-element name
                qInfo() << itemElement.attribute("lang"); // <-element attribute
                qInfo() << itemElement.text(); // <-element text

// putting the values above inside JSOn object:

                auto nodeData = QJsonObject(
                {
                qMakePair(QString(itemElement.tagName()), QJsonValue(itemElement.text())),
                qMakePair(QString("lang"), QJsonValue(itemElement.attribute("lang"))),
                });

                return nodeData;
            }
        }
    }

so this:

  <node>
    <title lang="en">Title1</title>
    <category lang="en">Category1</category>
    <desc lang="en">Description1</desc>
  </node>

becomes (this is what ListElements returns):

 QJsonObject({"title":"Title1","lang":"en"})
 QJsonObject({"category":"Category1","lang":"en"})
 QJsonObject({"desc":"Description1","lang":"en"})


问:
How to get the attributes of an element when clicked in ng-repeat
I have an anchor tag with multiple data-* attributes and the anchor will be repeated several times using ng-repeat. I want to grab the value of the attributes for when a single element is clicked.

I am using JQuery to get the attribute values and it is easy using $(this).attr('attribute').

However, this only works with a single button on the page. This does not work when multiple buttons are rendered using ng-repeat. I am assuming this is because multiple buttons are rendered with the same attribute names and jquery does not know how to differentiate between them. How can I get the data-* attribute values of the element that is clicked?

```<code>//JQuery
//Works when only a single editButton is on the page but not when multiple buttons are rendered using ng-repeat
     $('.editButton').on('click', function () {
        var filepath_id = $(this).attr('data-filepath-id');
        var requested_filepath = $(this).attr('data-requested-filepath');
        var requested_filename = $(this).attr('data-requested-filename');
      })

//HTML
//Confirmed that each editButton element has the correct attribute values depending on the item
  tr(ng-repeat='item in vm.items')
    a.editButton.btn.btn-primary(
      data-toggle="modal",
      data-filepath-id="{{item.id}}",
      data-requested-filepath="{{item.requested_filepath}}",
      data-requested-filename="{{item.filename}}",
      href="#editFilepathPopup"
      ) Edit
</code>```

答:
Think I can help. In angularJS the event listener is an attribute in the html element. Example :

```<code>ng-repeat = "item in vm.items" ng-click="onClickFunction();"
</code>```

If you want to get a specific item's attributes, place the item as a parameter in your event function.

```<code>ng-repeat = "item in vm.items" ng-click="vm.onClickFunction(item);"
</code>```

Now in your angular controller you create that click function. This is where you can do more logic like setting values to your controller values.

```<code>onClickFunction(itemParam) {
console.log("this is itemParam", itemParam);
var x = itemParam.requested_filepath;
this.x = itemParam.requested_filepath;
}
</code>```

Body:
I have an anchor tag with multiple data-* attributes and the anchor will be repeated several times using ng-repeat. I want to grab the value of the attributes for when a single element is clicked.

I am using JQuery to get the attribute values and it is easy using $(this).attr('attribute').

However, this only works with a single button on the page. This does not work when multiple buttons are rendered using ng-repeat. I am assuming this is because multiple buttons are rendered with the same attribute names and jquery does not know how to differentiate between them. How can I get the data-* attribute values of the element that is clicked?

//JQuery
//Works when only a single editButton is on the page but not when multiple buttons are rendered using ng-repeat
     $('.editButton').on('click', function () {
        var filepath_id = $(this).attr('data-filepath-id');
        var requested_filepath = $(this).attr('data-requested-filepath');
        var requested_filename = $(this).attr('data-requested-filename');
      })

//HTML
//Confirmed that each editButton element has the correct attribute values depending on the item
  tr(ng-repeat='item in vm.items')
    a.editButton.btn.btn-primary(
      data-toggle="modal",
      data-filepath-id="{{item.id}}",
      data-requested-filepath="{{item.requested_filepath}}",
      data-requested-filename="{{item.filename}}",
      href="#editFilepathPopup"
      ) Edit

Body:
Think I can help. In angularJS the event listener is an attribute in the html element. Example :

ng-repeat = "item in vm.items" ng-click="onClickFunction();"

If you want to get a specific item's attributes, place the item as a parameter in your event function.

ng-repeat = "item in vm.items" ng-click="vm.onClickFunction(item);"

Now in your angular controller you create that click function. This is where you can do more logic like setting values to your controller values.

onClickFunction(itemParam) {
console.log("this is itemParam", itemParam);
var x = itemParam.requested_filepath;
this.x = itemParam.requested_filepath;
}


问:
SwaggerUI/YAML - should NOT have additional properties additionalProperty: requestBody
Designing an API using editor.swagger.io I find myself unable to add a requestBody attribute, getting an error I cannot address:

```<code>Schema error at paths['/projects/{projectId}/user'].post
should NOT have additional properties
additionalProperty: requestBody
Jump to line 91
</code>```

I don't understand what I'm doing wrong, especially after looking at the requestBody documentation. Research has brought me nothing other than the tendency for errors to be misleading.

EDIT: From what the answers here have shown, it looks like the editor is supposed to use OpenAPI 2.0, but actually expects 3.0 while returning errors for both. I'd use some help on what to use, given that I've included a

```<code>swagger: "2.0"
</code>```

line at the beginning of the document.
While testing with openapi: 3.0.0 as shown by @Mike in his answer, I just get more errors about allowed additional properties.

Here's what's generating the error, line 91 being post: .

```<code>/projects/{projectId}/user:
      post:
        tags:
        - projects
        summary: Modify project user.
        operationId: modifyProjectUser
        parameters:
        - name: projectId
          in: path
          description: ID of the project
          required: true
          type: integer
          format: int32
        requestBody:
          content:
            application/json:
              schema:
              $ref: '#/definitions/User'
        responses:
          "200":
            description: Successful operation
            schema:
              type: array
              items:
                $ref: "#/definitions/User"
        security:
        - api_key: []
</code>```

答:
This error message looked familiar.  Try inserting a schema: underneath your parameter's required: line, then indent the type: and format: lines.

Since I have not yet set up my own SwaggerUI server. I took your code snippet and pasted it into SwaggerHub.  Then I removed the $ref: lines just to further simplify the codebase.  Here's a screenshot of the error-free result.

Body:
Designing an API using editor.swagger.io I find myself unable to add a requestBody attribute, getting an error I cannot address:

Schema error at paths['/projects/{projectId}/user'].post
should NOT have additional properties
additionalProperty: requestBody
Jump to line 91

I don't understand what I'm doing wrong, especially after looking at the requestBody documentation. Research has brought me nothing other than the tendency for errors to be misleading.

EDIT: From what the answers here have shown, it looks like the editor is supposed to use OpenAPI 2.0, but actually expects 3.0 while returning errors for both. I'd use some help on what to use, given that I've included a

swagger: "2.0"

line at the beginning of the document.
While testing with openapi: 3.0.0 as shown by @Mike in his answer, I just get more errors about allowed additional properties.

Here's what's generating the error, line 91 being post: .

/projects/{projectId}/user:
      post:
        tags:
        - projects
        summary: Modify project user.
        operationId: modifyProjectUser
        parameters:
        - name: projectId
          in: path
          description: ID of the project
          required: true
          type: integer
          format: int32
        requestBody:
          content:
            application/json:
              schema:
              $ref: '#/definitions/User'
        responses:
          "200":
            description: Successful operation
            schema:
              type: array
              items:
                $ref: "#/definitions/User"
        security:
        - api_key: []


问:
do I need to use full text search for domain names and Ip address?
I do have domain names and ip address of it. this is almost 200k so when I redesign a table do I need to enable FULL TEXT SEARCH functionality of MySQL??

I want search table with domain names and IP address as well. means I search by domain then it should show IP address and if I search with IP then it should show domain names.

答: That depends a bit on your data structure. If you have separate columns with domain names and IP addresses, this is not useful: just search for strings (or partial strings, with LIKE). If you have a large body of text (in a single column/field) which also includes domain names and IP addresses, then FULL TEXT SEARCH may be useful. </p>


问:
how to increment the values of (0,0,0) in minimal steps to make given array
According to the question we have given a array N of 3 elements lets [a,b,c] given a>0 ,b>0,c>0.We have to make a array X=[0,0,0] to N by following the given rules . The rules to increment the  X is given by

Each time you can increment any two values of X by 1 Eg: [0,1,1] (or) [1,0,1]

Incrementing only one value or three values at a time  in X is not allowed

you should not increment the values of X to more than the corresponding value in N

Count the number of increments you have done on X and return the answer.

If we cant make the array X to N . print the  possible array  of X that is nearer to the N  i.e, the  difference between the corresponding elements in the array should be as minimal as possible

Ex:

```<code>1) given N=[6,6,6]
</code>```

steps:

```<code>[0,1,1] -> [0,2,2] -> [0,3,3] -> [1,4,3] -> [2,5,3] -> [3,6,3] -> [4,6,4] ->[5,6,5] -> [6,6,6]
</code>```

The number of steps is 9

```<code>2) given N=[6,6,7]
</code>```

steps:

```<code>[0,1,1] -> [0,2,2] -> [0,3,3] -> [1,4,3] -> [2,5,3] -> [3,6,3] -> [4,6,4] ->[5,6,5] -> [6,6,6].
</code>```

From here we cannot increment the array because it is violating the rules . The difference [6,6,7] and [6,6,6] is 1 . so [6,6,6] is the optimal answer for given N

```<code>3) given N=[0,0,7]
</code>```

We cannot increment any two values of X . so answer is [0,0,0] for [0,0,7]

Now is there any method or any direct formula to solve this problem in the efficient way. Thanks in advance . sorry for my poor explanation and title

答:
Hint: you want to reach (a,b,c) like for instance (6,6,6).
Let factor this into the equation

```<code>x(1,1,0) + y(1,0,1) + z(0,1,1) = (a,b,c)
</code>```

having x being the number of times (1,1,0) is applied, and similarly for y and z. Thus

```<code>x + y = a
x + z = b
y + z = c
</code>```

giving

```<code>x = (a + b - c) / 2
y = (c - b + a) / 2
z = (b - a + c) / 2
</code>```

and x, y and z must be all >= 0 and integers.

Result is the sum of x, y and z.

The program to do that is on your side. Hint:

display a line to ask the user to enter a, b and c (see printf and scanf)

calculate the values of x, y and z based on above equations

check if they're >= 0 and integers (if not display that this isn't possible and stop)

calculate x+y+z and display the result as a solution

Body:
According to the question we have given a array N of 3 elements lets [a,b,c] given a>0 ,b>0,c>0.We have to make a array X=[0,0,0] to N by following the given rules . The rules to increment the  X is given by

Each time you can increment any two values of X by 1 Eg: [0,1,1] (or) [1,0,1]

Incrementing only one value or three values at a time  in X is not allowed

you should not increment the values of X to more than the corresponding value in N

Count the number of increments you have done on X and return the answer.

If we cant make the array X to N . print the  possible array  of X that is nearer to the N  i.e, the  difference between the corresponding elements in the array should be as minimal as possible

Ex:

1) given N=[6,6,6]

steps:

[0,1,1] -> [0,2,2] -> [0,3,3] -> [1,4,3] -> [2,5,3] -> [3,6,3] -> [4,6,4] ->[5,6,5] -> [6,6,6]

The number of steps is 9

2) given N=[6,6,7]

steps:

[0,1,1] -> [0,2,2] -> [0,3,3] -> [1,4,3] -> [2,5,3] -> [3,6,3] -> [4,6,4] ->[5,6,5] -> [6,6,6].

From here we cannot increment the array because it is violating the rules . The difference [6,6,7] and [6,6,6] is 1 . so [6,6,6] is the optimal answer for given N

3) given N=[0,0,7]

We cannot increment any two values of X . so answer is [0,0,0] for [0,0,7]

Now is there any method or any direct formula to solve this problem in the efficient way. Thanks in advance . sorry for my poor explanation and title

Body:
Hint: you want to reach (a,b,c) like for instance (6,6,6).
Let factor this into the equation

x(1,1,0) + y(1,0,1) + z(0,1,1) = (a,b,c)

having x being the number of times (1,1,0) is applied, and similarly for y and z. Thus

x + y = a
x + z = b
y + z = c

giving

x = (a + b - c) / 2
y = (c - b + a) / 2
z = (b - a + c) / 2

and x, y and z must be all >= 0 and integers.

Result is the sum of x, y and z.

The program to do that is on your side. Hint:

display a line to ask the user to enter a, b and c (see printf and scanf)

calculate the values of x, y and z based on above equations

check if they're >= 0 and integers (if not display that this isn't possible and stop)

calculate x+y+z and display the result as a solution


问:
Regex for groovy not working
Please find below my code. I am trying to iterate through files and in a directory and print out all the match to the regex: (&)(.+?\b)
however this doesn't seem to work (it returns an empty string). Where did I go wrong?

```<code>import groovy.io.FileType

class FileExample {
    static void main(String[] args) {

        def list = []

        def dir = new File("*path to dir*")
        dir.eachFileRecurse (FileType.FILES) { file ->
            list << file.name;
            def s= "${file.text}";
            def w = s.toString();
            w.readLines().grep(~/(&)(.+?\b)/)
        }
    }
}
</code>```

答:
I figured it out:

```<code>import groovy.io.FileType
class FileExample {
   static void main(String[] args) {

        def list = []
        def dir = new File("/path/to/directory/containingfiles")
        def p = []
        dir.eachFileRecurse (FileType.FILES) {
            file -> list << file.name
            def s = file.text
            def findtp = (s =~ /(&)(.+?\b)/)
            findtp.each {
                p.push(it[2])
                // As I'm only interested in the second matched group
            }
        }
        p.each {
            println it
            }
        }
    }
</code>```

Now, all the matched strings are stored in the array p and can be printed/used elsewhere by p[0] etc.

Title: Regex for groovy not working

Body:
Please find below my code. I am trying to iterate through files and in a directory and print out all the match to the regex: (&)(.+?\b)
however this doesn't seem to work (it returns an empty string). Where did I go wrong?

import groovy.io.FileType

class FileExample {
    static void main(String[] args) {

        def list = []

        def dir = new File("*path to dir*")
        dir.eachFileRecurse (FileType.FILES) { file ->
            list << file.name;
            def s= "${file.text}";
            def w = s.toString();
            w.readLines().grep(~/(&)(.+?\b)/)
        }
    }
}

Body:
I figured it out:

import groovy.io.FileType
class FileExample {
   static void main(String[] args) {

        def list = []
        def dir = new File("/path/to/directory/containingfiles")
        def p = []
        dir.eachFileRecurse (FileType.FILES) {
            file -> list << file.name
            def s = file.text
            def findtp = (s =~ /(&)(.+?\b)/)
            findtp.each {
                p.push(it[2])
                // As I'm only interested in the second matched group
            }
        }
        p.each {
            println it
            }
        }
    }

Now, all the matched strings are stored in the array p and can be printed/used elsewhere by p[0] etc.


问:
block bad server request while using lowest server overhead
Our web server is occasionally getting slammed with loads of requests for an (exchange server) file that doesn't exist on our (apache) web server:

autodiscover/autodiscover.xml

How can I respond to those requests in a way that requires the least load on our server?

(When these requests happen, our VPS memory usage spikes and goes over our RAM allocation.)

I want the server to respond, with the lowest overhead, telling them basically to go away; that file doesn't exist here; stop; bad request (you get the idea.)

Right now, the server returns a 404 error page which means that our WordPress installation is evoked. It returns our custom 404 WordPress error page. That involves a lot of overhead that I'd like to avoid.

I suspect that these requests come from some sort of hacking attempts, but I'm just guessing at that. At any rate, I just want to intercept them and block or stop them as quickly and efficiently as possible.

(I've put IP blocks on the IP addresses they come from but I think that is just playing whack-a-mole.)

I've put this in our htaccess file but it doesn't do what I want:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^autodiscover/autodiscover.xml$ "-" [forbidden,last]
</IfModule>
</code>```

Is there something wrong with this rule?

Can I or should I use our htaccess file in another way to do what I want? Is there a better way to do it than using htaccess? Could we be returning something other than a 404 response? Perhaps a 400 or 403 response? How would we do that? We are on a VPS server to which I do not have direct access.

答:
Any attempt to Deny access to the file, whether via Deny or an [F] forbidden flag, results in WordPress kicking in and responding with a 404 error page.

To avoid this, I have created a custom 421 error page (which seemed most appropriate), placed it outside of the WordPress directory, and used an htaccess Redirect from the bad-request file name to the custom error page.

Redirect /autodiscover/autodiscover.xml /path/to/error-421-autodiscover-xml.php

This returns the custom error page (only 1KB) without WordPress being invoked. Creating a custom error page specific to the one file with the bad-request file in the name of the error code file should help to identify these calls in our log files.

If you ran an Exchange server elsewhere for email, then it might be appropriate to redirect from the web server to the Exhange server using htacess on the web server. An appropriate htaccess rule might be:

RedirectMatch 302 (?i)^/autodiscover/(.*)$ https://mail.example.com/autodiscover/$1

See: https://glennmatthys.wordpress.com/2013/10/14/redirect-autodiscover-urls-using-htaccess/

@janh is certainly right that a mechanism to intercept the request before it even hits our Apache server would be ideal, but it is beyond what we can do right now.

(The /autodiscover/autodiscover.xml seems to be a file used by Exchange servers to route traffic to the mail server. According to our web hosting company, it is not unusual for Apache servers to be hit with requests for this file. Some of these requests may come from malicious bots searching for access to a mail server; some may come from misconfigured smart phone email clients or other misdirected requests intended for an Exchange server.)

Body:
Our web server is occasionally getting slammed with loads of requests for an (exchange server) file that doesn't exist on our (apache) web server:

autodiscover/autodiscover.xml

How can I respond to those requests in a way that requires the least load on our server?

(When these requests happen, our VPS memory usage spikes and goes over our RAM allocation.)

I want the server to respond, with the lowest overhead, telling them basically to go away; that file doesn't exist here; stop; bad request (you get the idea.)

Right now, the server returns a 404 error page which means that our WordPress installation is evoked. It returns our custom 404 WordPress error page. That involves a lot of overhead that I'd like to avoid.

I suspect that these requests come from some sort of hacking attempts, but I'm just guessing at that. At any rate, I just want to intercept them and block or stop them as quickly and efficiently as possible.

(I've put IP blocks on the IP addresses they come from but I think that is just playing whack-a-mole.)

I've put this in our htaccess file but it doesn't do what I want:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^autodiscover/autodiscover.xml$ "-" [forbidden,last]
</IfModule>

Is there something wrong with this rule?

Can I or should I use our htaccess file in another way to do what I want? Is there a better way to do it than using htaccess? Could we be returning something other than a 404 response? Perhaps a 400 or 403 response? How would we do that? We are on a VPS server to which I do not have direct access.


问:
how to run PHP in a Angualr2 CLI
I am using Angular2 CLI for my frontend framework and using PHP for my backend.

```<code>    this.http.post('assets/modify.php', '')
    .subscribe(result => {
        console.log("success post php file");
      }
    );
</code>```

I want to use post method to run modify.php. However, I got error:
POST XXXXX/assets/modify.php 404 (Not Found)

I can use get method to read the PHP with the same URL, it is working fine. But how can I use Post to run the PHP.

modify.php:

```<code><?php

//lode the file
$contents = file_get_contents('button.json');

//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);

//Modify the counter variable.
$contentsDecoded['button1Status'] = "booked";

//Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);

//Save the file.
file_put_contents('button.json', $json);

?>
</code>```

The folder structure is:

app------ user---------------  user.component.ts(I am runing get or post method here)

assets----button.json
          modify.php

when I use get method :

Request URL:http://localhost:4200/assets/modify.php
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4200
Referrer Policy:no-referrer-when-downgrade

when I use post method:

Request URL:http://localhost:4200/assets/modify.php
Request Method:POST
Status Code:404 Not Found
Remote Address:127.0.0.1:4200
Referrer Policy:no-referrer-when-downgrade

**Just for a update from people's help.

I found this and it help me figure out what happened to my scenario:

executing php files in a angular2cli app

SO I am thinking at the development stage, I need to have a web server can run PHP code.Will have a try on the build-in PHP Server.**

答:
Try fully qualifying or at least a good relative URL.  I'm going to assume assets is at your docroot, if not then adjust that root slash accordingly:

eg:

```<code>/assets/modify.php
</code>```

or:

```<code>https://mywebhost/assets/modify.php
</code>```

Your example PHP file doesn't seem to care about anything being sent to it, why use the POST method in the ajax, why not just use GET?

Title: how to run PHP in a Angualr2 CLI

Body:
I am using Angular2 CLI for my frontend framework and using PHP for my backend.

    this.http.post('assets/modify.php', '')
    .subscribe(result => {
        console.log("success post php file");
      }
    );

I want to use post method to run modify.php. However, I got error:
POST XXXXX/assets/modify.php 404 (Not Found)

I can use get method to read the PHP with the same URL, it is working fine. But how can I use Post to run the PHP.

modify.php:

<?php

//lode the file
$contents = file_get_contents('button.json');

//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);

//Modify the counter variable.
$contentsDecoded['button1Status'] = "booked";

//Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);

//Save the file.
file_put_contents('button.json', $json);

?>

The folder structure is:

app------ user---------------  user.component.ts(I am runing get or post method here)

assets----button.json
          modify.php

when I use get method :

Request URL:http://localhost:4200/assets/modify.php
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4200
Referrer Policy:no-referrer-when-downgrade

when I use post method:

Request URL:http://localhost:4200/assets/modify.php
Request Method:POST
Status Code:404 Not Found
Remote Address:127.0.0.1:4200
Referrer Policy:no-referrer-when-downgrade

**Just for a update from people's help.

I found this and it help me figure out what happened to my scenario:

executing php files in a angular2cli app

SO I am thinking at the development stage, I need to have a web server can run PHP code.Will have a try on the build-in PHP Server.**

Body:
Try fully qualifying or at least a good relative URL.  I'm going to assume assets is at your docroot, if not then adjust that root slash accordingly:

eg:

/assets/modify.php

or:

https://mywebhost/assets/modify.php

Your example PHP file doesn't seem to care about anything being sent to it, why use the POST method in the ajax, why not just use GET?


问:
Seg fault when using strtok
I am trying to read each number from an input that looks like this:

```<code>179    2358 5197    867
5541    172 4294    1397
2637    136 3222    591
</code>```

... and get the min/max of each row going line by line and then getting each number in the line using strtok, but I get a seg fault error in the second while loop.

The code:

```<code>#include "header.h"
#include <string.h>

int main(void) {
  int8_t* line = malloc(sizeof(int8_t) * 75);
  int8_t* temp;

  int32_t minim, maxim;
  int32_t current;

  stdin = fopen("stdin", "r");
  while (fgets(line, 75 * sizeof(int8_t), stdin)) {
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  return 0;
}
</code>```

The header:

```<code>#ifndef HEADER_H
# define HEADER_H

# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>

  typedef                   char  int8_t;
  typedef   signed     short int int16_t;
  typedef   signed           int int32_t;
  typedef   signed long long int int64_t;

  typedef unsigned          char  uint8_t;
  typedef unsigned     short int uint16_t;
  typedef unsigned           int uint32_t;
  typedef unsigned long long int uint64_t;

#endif
</code>```

I just don't get what it might be wrong. Thanks.

答:
```<code>stdin = fopen("stdin", "r");
</code>```

This isn’t doing what you think it is.  This tries to open a file in the current directory named “stdin”.  It does not open the standard input stream.

You most likely don’t have a file by this name, so this function probably fails and returns NULL.  And because you don’t check the return value, you pass a NULL pointer to fgets.  This invokes undefined behavior, which in this case manifests as a crash.

The standard input stream is already open when your program starts.  So remove the fopen call and it should work.

Title: Seg fault when using strtok

Body:
I am trying to read each number from an input that looks like this:

179    2358 5197    867
5541    172 4294    1397
2637    136 3222    591

... and get the min/max of each row going line by line and then getting each number in the line using strtok, but I get a seg fault error in the second while loop.

The code:

#include "header.h"
#include <string.h>

int main(void) {
  int8_t* line = malloc(sizeof(int8_t) * 75);
  int8_t* temp;

  int32_t minim, maxim;
  int32_t current;

  stdin = fopen("stdin", "r");
  while (fgets(line, 75 * sizeof(int8_t), stdin)) {
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  return 0;
}

The header:

#ifndef HEADER_H
# define HEADER_H

# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>

  typedef                   char  int8_t;
  typedef   signed     short int int16_t;
  typedef   signed           int int32_t;
  typedef   signed long long int int64_t;

  typedef unsigned          char  uint8_t;
  typedef unsigned     short int uint16_t;
  typedef unsigned           int uint32_t;
  typedef unsigned long long int uint64_t;

#endif

I just don't get what it might be wrong. Thanks.

Body:
stdin = fopen("stdin", "r");

This isn’t doing what you think it is.  This tries to open a file in the current directory named “stdin”.  It does not open the standard input stream.

You most likely don’t have a file by this name, so this function probably fails and returns NULL.  And because you don’t check the return value, you pass a NULL pointer to fgets.  This invokes undefined behavior, which in this case manifests as a crash.

The standard input stream is already open when your program starts.  So remove the fopen call and it should work.


问:
How to receive AJAX (json) response in a divs with same class name individually?
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

```<code>$('.trigger_button_inside_divs').click(my_ajax_function);
</code>```

And this is how my ajax looks like:

```<code>function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}
</code>```

HTML looks like this:

```<code><div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
</code>```

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

```<code>(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()
</code>```

答:
The problem is that your class selector is indeed selecting all your divs at the same time.

Solution, set identifiers for your divs as such:

```<code><div class="my_div" id="my_div_1">
</code>```

and then you can use those id's to fill in the data:

```<code>$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);
</code>```

and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')

Body:
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

$('.trigger_button_inside_divs').click(my_ajax_function);

And this is how my ajax looks like:

function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}

HTML looks like this:

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()

Body:
The problem is that your class selector is indeed selecting all your divs at the same time.

Solution, set identifiers for your divs as such:

<div class="my_div" id="my_div_1">

and then you can use those id's to fill in the data:

$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);

and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')


问:
qml button not firing, same with MouseArea
Ive created a new QML project based on Qt 5.9.3.  I setup a simple ApplicationWindow with a Button as well as my own button (MyButton) and I never get the onClicked() event to fire (apparently) for either of them.  My application window pops up with 2 buttons showing.  Clicking on either of them shows nothing in my console output.

Im also pre-compiling my qml source files in the .pro file if that even matters.  I get some Font errors on startup which I fix in the C++ to
get some fonts going so I can see something, other than that there are no
errors or warnings.  Ive spent a couple hours just trying to get a simple
mouse click event through with no luck.

Any help is appreciated.

Here's my main.qml:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: "App Title"
    color: "white"

    Button {
        text: "Button"
        onClicked: {
            console.log("clicked")
        }
    }
    MyButton {
        anchors.right: parent.right
        anchors.top: parent.top
        onClicked: {
            console.log("my button clicked")
        }
    }
}
</code>```

and MyButton.qml

```<code>import QtQuick 2.7

Rectangle {
    id: button
    width: 100
    height: 50
    color: "yellow"

    signal clicked()

    MouseArea {
        id: mouseArea
        anchors.fill: button
        visible: false
        enabled: true
        onClicked: {
            console.log("my button mouse clicked")
            clicked()
        }
    }
}
</code>```

UPDATE:  I did a very stupid thing.  in my main.cpp file which I did
not include I thought I would be cleaner and move my QQmlEngine init code
into its own separate method.  Of course when the engine reference went
out of scope it caused my issue.  I didn't look there because I wrongly assumed that the qml code wouldn't work at all if something were wrong there. Sorry to get back on this so late, its been a very busy week and sorry for wasting bandwidth.  Thank you for the great debugging suggestions as well for future reference!

答:
I don't know about your problem with the Button from QtQuick.Controls 2.0 - it works perfectly for me.

With your own implementation of the MyButton, that does not work for me either.

The reason is that visible: false will deactivate the MouseArea (and all the children of it) - setting enabled: true won't change that.

Setting visible: false is unnecessary anyway, as a MouseArea has nothing to render - being effictively invisible.

Once you have changed that, you should get a warning:

Error: Insufficient arguments

as you call the signal clicked of the MouseArea which requires an argument (MouseEvent). To call your self-defined signal, call button.clicked() instead.R

If you still don't get anyting, you will need to take further debugging steps.

Check whether you can generate any output using console.log for example by adding Component.onComplete: console.log("Output works") to one of your objects.

Check whether your input is really broken, by changing the color of the Rectangle when the MouseArea is clicked: color: (mouseArea.pressed ? 'red' : 'green')

Install an eventFilter to your QGuiApplication (in C++) that will print something, if an MouseEvent is registered.

Body:
Ive created a new QML project based on Qt 5.9.3.  I setup a simple ApplicationWindow with a Button as well as my own button (MyButton) and I never get the onClicked() event to fire (apparently) for either of them.  My application window pops up with 2 buttons showing.  Clicking on either of them shows nothing in my console output.

Im also pre-compiling my qml source files in the .pro file if that even matters.  I get some Font errors on startup which I fix in the C++ to
get some fonts going so I can see something, other than that there are no
errors or warnings.  Ive spent a couple hours just trying to get a simple
mouse click event through with no luck.

Any help is appreciated.

Here's my main.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: "App Title"
    color: "white"

    Button {
        text: "Button"
        onClicked: {
            console.log("clicked")
        }
    }
    MyButton {
        anchors.right: parent.right
        anchors.top: parent.top
        onClicked: {
            console.log("my button clicked")
        }
    }
}

and MyButton.qml

import QtQuick 2.7

Rectangle {
    id: button
    width: 100
    height: 50
    color: "yellow"

    signal clicked()

    MouseArea {
        id: mouseArea
        anchors.fill: button
        visible: false
        enabled: true
        onClicked: {
            console.log("my button mouse clicked")
            clicked()
        }
    }
}

UPDATE:  I did a very stupid thing.  in my main.cpp file which I did
not include I thought I would be cleaner and move my QQmlEngine init code
into its own separate method.  Of course when the engine reference went
out of scope it caused my issue.  I didn't look there because I wrongly assumed that the qml code wouldn't work at all if something were wrong there. Sorry to get back on this so late, its been a very busy week and sorry for wasting bandwidth.  Thank you for the great debugging suggestions as well for future reference!


问:
JSP error java.lang.ClassNotFoundException
I created this jsp file and i am using Tomcat and postgresql. I have created a database in postgresql and want to access that database through jsp. When I run the code I get the error

java.lang.ClassNotFoundException: org.postgresql.Driver
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181)

I have my jar file in the web-inf/lib .

Here is the jsp

```<code><%@ page import="java.sql.*" %>
This program test connectivity of PostgreSQL from JSP<br>
Contents of students table (created by  create table readers (reader_id integer, reader_f name, reader_l name, date_of_birth date, address text, phone numeric(11), sex character(1)) <br>
id  name<br>
-----------<br>

<%
String connectionURL =
"jdbc:postgresql://cop4710-postgresql.cs.fiu.edu:5099/fall17_smete008?user=fall17_smete008&password=4742244s";

Connection connection = null;
Statement statement = null;
ResultSet rs = null;

%>

<html><body>

<%
Class.forName("org.postgresql.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL);
statement = connection.createStatement();
rs = statement.executeQuery("SELECT * FROM readers");

while (rs.next()) {
out.println(rs.getString("reader_id")+"<br>");
out.println(rs.getString("reader_f")+"<br>");
}

rs.close();
%>

 <dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901-1.jdbc4</version>
</dependency>
</body></html>
</code>```

Can you please help me figure out what i am getting this error?

答:
Copy your jar driver to Tomcat lib folder and add <scope>provided</scope> to maven dependency.
Also it is better not to mix business logic code with frontend implementation.

Body:
I created this jsp file and i am using Tomcat and postgresql. I have created a database in postgresql and want to access that database through jsp. When I run the code I get the error

java.lang.ClassNotFoundException: org.postgresql.Driver
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181)

I have my jar file in the web-inf/lib .

Here is the jsp

<%@ page import="java.sql.*" %>
This program test connectivity of PostgreSQL from JSP

Contents of students table (created by  create table readers (reader_id integer, reader_f name, reader_l name, date_of_birth date, address text, phone numeric(11), sex character(1))

id  name

-----------

<%
String connectionURL =
"jdbc:postgresql://cop4710-postgresql.cs.fiu.edu:5099/fall17_smete008?user=fall17_smete008&password=4742244s";

Connection connection = null;
Statement statement = null;
ResultSet rs = null;

%>

<%
Class.forName("org.postgresql.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL);
statement = connection.createStatement();
rs = statement.executeQuery("SELECT * FROM readers");

while (rs.next()) {
out.println(rs.getString("reader_id")+"
");
out.println(rs.getString("reader_f")+"
");
}

rs.close();
%>

 <dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901-1.jdbc4</version>
</dependency>

Can you please help me figure out what i am getting this error?


问:
Problem with cellForRowAtIndexPath and NSBundle mainBundle
have an idea to solve this problem?

This is the correct and wrong way respectly:

This is working code:

```<code>- (UITableViewCell *)[...] cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @try {
        newsRow = ((NewsRowController *)[tableView dequeueReusableCellWithIdentifier:@"cell"]);
        if (newsRow == nil) {
            if ( [[Device GetModel] isEqualToString:@"iPad Simulator"] ||
                 [[Device GetModel] isEqualToString:@"iPad"])
                [[NSBundle mainBundle] loadNibNamed:@"NewsRow_ipad" owner:self options:nil];
            else [[NSBundle mainBundle] loadNibNamed:@"NewsRow" owner:self options:nil];

            if ([tableArray count] > 0)
                [newsRow setData:[tableArray objectAtIndex:indexPath.row]];
        }
    }
    @catch (NSException * e) {
        NSLog(@"a!!!!!");
    }
    return newsRow;
}
</code>```

...but because in my 3g device it's slowly when i scroll table up/down i changed the code in this way, inserting Device check in viewDidLoad and pass it in cellForRowAtIndexPath:

```<code>NSArray *cRow;
@property (nonatomic, retain) NSArray *cRow;
[...]
@syntetize cRow;

- (void)viewDidLoad {
[...]
    if ( [[Device GetModel] isEqualToString:@"iPad Simulator"]
        ||
        [[Device GetModel] isEqualToString:@"iPad"])
        cRow  = [[[NSBundle mainBundle] loadNibNamed:@"NewsRow_ipad" owner:self options:nil] retain];
        else cRow = [[[NSBundle mainBundle] loadNibNamed:@"NewsRow" owner:self options:nil] retain];
[...]
}

- (UITableViewCell *)[...] cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @try {
        newsRow = ((NewsRowController *)[tableView dequeueReusableCellWithIdentifier:@"cell"]);
        if (newsRow == nil) {

            //
            // ADDED CODE.
            //
            newsRow = [cRow objectAtIndex:0];
            //

            if ([tableArray count] > 0)
                [newsRow setData:[tableArray objectAtIndex:indexPath.row]];
        }
    }
    @catch (NSException * e) {
        NSLog(@"a!!!!!");
    }
    return newsRow;
}
</code>```

Now the table show me only a row. If i scroll, the row change, but it show only one row...

What's the problem?

Any helps?

thanks,

A

答:
In this case when you call dequeueReusableCellWithIdentifier: you will get nil back because there are no cells that can be dequeued. You need to load the nib each time you get a nil cell back otherwise you won't be adding any cells to the table after the first one.

If calling GetModel is what is slowing you could call that in viewDidLoad and store it for usage later on.

More than likely your table is not scrolling smoothly because of the amount of views you are drawing in each cell. If your background will always be a solid color you should make sure that all the views you are adding to the cell or opaque. If you need an image or a gradient background then you should look at drawing the cell all in one view. Apple has a good example of how to do this here: TableViewSuite. Specifically checkout the TimeZoneView file.

Body:
have an idea to solve this problem?

This is the correct and wrong way respectly:

This is working code:

- (UITableViewCell *)[...] cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @try {
        newsRow = ((NewsRowController *)[tableView dequeueReusableCellWithIdentifier:@"cell"]);
        if (newsRow == nil) {
            if ( [[Device GetModel] isEqualToString:@"iPad Simulator"] ||
                 [[Device GetModel] isEqualToString:@"iPad"])
                [[NSBundle mainBundle] loadNibNamed:@"NewsRow_ipad" owner:self options:nil];
            else [[NSBundle mainBundle] loadNibNamed:@"NewsRow" owner:self options:nil];

            if ([tableArray count] > 0)
                [newsRow setData:[tableArray objectAtIndex:indexPath.row]];
        }
    }
    @catch (NSException * e) {
        NSLog(@"a!!!!!");
    }
    return newsRow;
}

...but because in my 3g device it's slowly when i scroll table up/down i changed the code in this way, inserting Device check in viewDidLoad and pass it in cellForRowAtIndexPath:

NSArray *cRow;
@property (nonatomic, retain) NSArray *cRow;
[...]
@syntetize cRow;

- (void)viewDidLoad {
[...]
    if ( [[Device GetModel] isEqualToString:@"iPad Simulator"]
        ||
        [[Device GetModel] isEqualToString:@"iPad"])
        cRow  = [[[NSBundle mainBundle] loadNibNamed:@"NewsRow_ipad" owner:self options:nil] retain];
        else cRow = [[[NSBundle mainBundle] loadNibNamed:@"NewsRow" owner:self options:nil] retain];
[...]
}

- (UITableViewCell *)[...] cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @try {
        newsRow = ((NewsRowController *)[tableView dequeueReusableCellWithIdentifier:@"cell"]);
        if (newsRow == nil) {

            //
            // ADDED CODE.
            //
            newsRow = [cRow objectAtIndex:0];
            //

            if ([tableArray count] > 0)
                [newsRow setData:[tableArray objectAtIndex:indexPath.row]];
        }
    }
    @catch (NSException * e) {
        NSLog(@"a!!!!!");
    }
    return newsRow;
}

Now the table show me only a row. If i scroll, the row change, but it show only one row...

What's the problem?

Any helps?

thanks,

A


问:
Why won't my function stop?
I have a return statement, and my condition is definitely being met. Yet the function still runs, not sure why.

```<code><script>
var loop = true;
fade();
// rotate navigation banners
    function fade(){
        var divs = jQuery('.site-wide-notification');
        var current = jQuery('.first-notification');
        var currentIndex = divs.index(current),
            nextIndex = currentIndex + 1;

        if (nextIndex >= divs.length){
            nextIndex = 0;
        }
        var next = divs.eq(nextIndex);
        next.stop().fadeIn(2000, function(){
            jQuery(this).addClass('first-notification');
            setTimeout(fade, 3000);
        });
        current.stop().fadeOut(2000, function(){
            jQuery(this).removeClass('first-notification');
        });

        jQuery('.site-wide-notification').click(function(){
            console.log('Closed');
            jQuery('.site-wide-notification').css('display', 'none');
            loop = false;
        });
        if (!loop){
            console.log('stop da loop');
            return false;
        }
    }
</code>```

This code is meant to rotate some banners at the top, fading them in and out, and when the user clicks on any of them it will set them all to display: none. When the user clicks on any of them the console.log('Closed') appears and loop is set to false, then the if !loop statement is entered and the console prints stop da loop, but the fade function continues running despite its return.

答:
It doesn't matter whether your function returns false (in the !loop case) or undefined (otherwise). When you call fade(), it sets up a timer to call fade() again. Unconditionally.

Move your if (!loop) return; test to the top of the function. That way, if the loop isn't supposed to continue, the function bails out before setting up the next iteration.

Title: Why won't my function stop?