问:
using html and css only flexbox
How to align like this because the text with progress bar are hard to align using flex box.

should i make 3 seperate div or 2 div? because text with progressbar content are hard to align

https://jsfiddle.net/ypsmkLrb/1/ MY CODE

```<code>*{
    padding:0;
    margin:0;
}
body{
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.container{
    width:1200px;
    margin:auto;
    background-color:teal;
}
.about-header{
    padding-bottom:25px;
    text-align: center;
}
.about-img img{
    height:200px;
    width:auto;
}
.about-img{
    height:200px;
    width:auto;
}
.about-row{
    display: flex;
    flex-wrap: wrap;
    font-size: 11px;
}
.about-content{
    line-height:1.6;
    padding-left: 20px;
    border:solid
}
.about-content img{
    height:15px;
    width:auto;
 }
.bar-row-one{
    display:flex;
    align-items:flex-start;
    justify-content:space-around;
}
 .bar-row-two{
    display:flex;
    justify-content:space-around;
}
</code>```

答:
What I understand from your comment that you looking for center alignment of the content area. If this is right, I think you missed few attributes for flex properties in ".about-row" class, please try below snippet :

*{
              padding:0;
              margin:0;
          }
          body{
              font-family:Verdana, Geneva, Tahoma, sans-serif;
          }
          .container{
              width:1200px;
              margin:auto;
              background-color:teal;
          }
          .about-header{
              padding-bottom:25px;
              text-align: center;
          }
          .about-img img{
              height:200px;
              width:auto;
          }
          .about-img{
              height:200px;
              width:auto;
          }
          .about-row{
              display: flex;
              flex-direction: row;
              font-size: 11px;
              justify-content: center;
              align-items: flex-start;
          }
          .about-content{
              line-height:1.6;
              padding-left: 20px;
              border:solid
          }
          .about-content img{
              height:15px;
              width:auto;
           }
          .bar-row-one{
              display:flex;
              align-items:flex-start;
              justify-content:space-around;
          }
           .bar-row-two{
              display:flex;
              justify-content:space-around;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <section id="about">
        <div class="container">
            <div class="about-header">
                <h1>About</h1>
            </div>
            <div class="about-row">
                <div class="about-img">
                    <img src="https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528_1280.jpg" alt="farm_5">
                </div>
                <div class="about-content">
                    <p>Lorem Ipsum dolor sit amet, vix vocent habemus petentium ea , ex vix nonumy scripta.<br/>
                        Per ne alia stet clita. No admodum detracto pericula vim, te dicit utamur molestie nec. No phaedrum molestiae assueverit duo
                     </p></br>
                     <p>Et tritani recusabo oportere sea, per at noster vivedum deterruisset. Mea te libris mandamus deseruisse.<br/>
                        Dicat zril epicurei ex pri, ad posse occurreret posidonium mei, ut vis sint explicari.<br/>
                        In vidisse volucptatibus vix. Ectram dissentiunt an sit, duo ea utinam imperdiet. His et nobis hendrerit,<br/>
                        Illum delicata no sea, cu fabulas recusabo adhorreant has. Probo luciluis perfecto ei vix, purto noluisse constetur an pro.
                     </p>
                    <div class="bar-row-one">
                        <div class="bar1">
                            <label class="bar-label">Graphic</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                        <div class="bar2">
                            <label class="bar-label">System</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                    </div>
                    <div class="bar-row-two">
                        <div class="bar3">
                            <label class="bar-label-web"> Web</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                        <div class="bar4">
                            <label class="bar-label-ui/ux">UI/UX</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section></code>```

Title: using html and css only flexbox

Body:
How to align like this because the text with progress bar are hard to align using flex box.

should i make 3 seperate div or 2 div? because text with progressbar content are hard to align

https://jsfiddle.net/ypsmkLrb/1/ MY CODE

*{
    padding:0;
    margin:0;
}
body{
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.container{
    width:1200px;
    margin:auto;
    background-color:teal;
}
.about-header{
    padding-bottom:25px;
    text-align: center;
}
.about-img img{
    height:200px;
    width:auto;
}
.about-img{
    height:200px;
    width:auto;
}
.about-row{
    display: flex;
    flex-wrap: wrap;
    font-size: 11px;
}
.about-content{
    line-height:1.6;
    padding-left: 20px;
    border:solid
}
.about-content img{
    height:15px;
    width:auto;
 }
.bar-row-one{
    display:flex;
    align-items:flex-start;
    justify-content:space-around;
}
 .bar-row-two{
    display:flex;
    justify-content:space-around;
}

Body:
What I understand from your comment that you looking for center alignment of the content area. If this is right, I think you missed few attributes for flex properties in ".about-row" class, please try below snippet :

*{
              padding:0;
              margin:0;
          }
          body{
              font-family:Verdana, Geneva, Tahoma, sans-serif;
          }
          .container{
              width:1200px;
              margin:auto;
              background-color:teal;
          }
          .about-header{
              padding-bottom:25px;
              text-align: center;
          }
          .about-img img{
              height:200px;
              width:auto;
          }
          .about-img{
              height:200px;
              width:auto;
          }
          .about-row{
              display: flex;
              flex-direction: row;
              font-size: 11px;
              justify-content: center;
              align-items: flex-start;
          }
          .about-content{
              line-height:1.6;
              padding-left: 20px;
              border:solid
          }
          .about-content img{
              height:15px;
              width:auto;
           }
          .bar-row-one{
              display:flex;
              align-items:flex-start;
              justify-content:space-around;
          }
           .bar-row-two{
              display:flex;
              justify-content:space-around;
          }

 <section id="about">
        <div class="container">
            <div class="about-header">
                <h1>About</h1>
            </div>
            <div class="about-row">
                <div class="about-img">
                    <img src="https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528_1280.jpg" alt="farm_5">
                </div>
                <div class="about-content">
                    <p>Lorem Ipsum dolor sit amet, vix vocent habemus petentium ea , ex vix nonumy scripta.<br/>
                        Per ne alia stet clita. No admodum detracto pericula vim, te dicit utamur molestie nec. No phaedrum molestiae assueverit duo
                     </p></br>
                     <p>Et tritani recusabo oportere sea, per at noster vivedum deterruisset. Mea te libris mandamus deseruisse.<br/>
                        Dicat zril epicurei ex pri, ad posse occurreret posidonium mei, ut vis sint explicari.<br/>
                        In vidisse volucptatibus vix. Ectram dissentiunt an sit, duo ea utinam imperdiet. His et nobis hendrerit,<br/>
                        Illum delicata no sea, cu fabulas recusabo adhorreant has. Probo luciluis perfecto ei vix, purto noluisse constetur an pro.
                     </p>
                    <div class="bar-row-one">
                        <div class="bar1">
                            <label class="bar-label">Graphic</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                        <div class="bar2">
                            <label class="bar-label">System</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                    </div>
                    <div class="bar-row-two">
                        <div class="bar3">
                            <label class="bar-label-web"> Web</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                        <div class="bar4">
                            <label class="bar-label-ui/ux">UI/UX</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>


来源: stackexchange

问:
copy local files to aks premium or standard storage
I am new to k8s in azure (I have used k8s in a non-cloud server) and I dont find info on how can I copy local files/directories to aks's premium or standard storage.

This link PVC shows how to create a PVC and how to mount it in a pod, but I cannot find how do I copy files from my local pc to aks's premium or standard storage.

答: To copy files you can use azcopy for azure files and azure storage explorer for azure managed disk.</p>

ContentLicense: CC BY-SA 4.0


问:
Firebase storage to store image and using the url in realtime database from firebase functions
We have firebase nodejs functions where we get base64 image data from our partner site. This data we are storing into firebase storage like below:

```<code>const storageRef = admin.storage().bucket(bucketName)
const fileRef = storageRef.file('myimage.png')
await fileRef.save(base64Image)
</code>```

The bucket used here for this purpose has readonly true so security is not a concern. How do I get the url of the image stored in bucket to put in my realtime db?

In UI way, I can directly upload image from the firebase console and can see the link. I need this link.

Based on my research on google, I see getting a download url is an issue on server side due to security of the bucket and you need to get signedUrl that expires. In my case as it is public so I am hoping there's a way to get the url.

An alternate way would be to bypass the bucket completely and store the base64 image directly into realtime db, but I'm not comfortable with that due to very large length of base64 strings. My images ideally would be in the range of few kbs.

How to deal with this?

答:
You have two options:

Use a server-side generate signed URL with a very long expiration date.

Generate a (non-expiring) download URL client-side.

To use download URLs, you'd need to:

Write the path of the image to the database when it uploads.

Have the clients detect of there is a download URL for their image in the database.

If there is no download URL, have the client generate the download URL from the path, and write it to the database.

Body:
We have firebase nodejs functions where we get base64 image data from our partner site. This data we are storing into firebase storage like below:

const storageRef = admin.storage().bucket(bucketName)
const fileRef = storageRef.file('myimage.png')
await fileRef.save(base64Image)

The bucket used here for this purpose has readonly true so security is not a concern. How do I get the url of the image stored in bucket to put in my realtime db?

In UI way, I can directly upload image from the firebase console and can see the link. I need this link.

Based on my research on google, I see getting a download url is an issue on server side due to security of the bucket and you need to get signedUrl that expires. In my case as it is public so I am hoping there's a way to get the url.

An alternate way would be to bypass the bucket completely and store the base64 image directly into realtime db, but I'm not comfortable with that due to very large length of base64 strings. My images ideally would be in the range of few kbs.

How to deal with this?


问:
ASP.NET Arraylist, ButtonClick event, retireve string value from the arraylist when button is clicked
I am creating a website and wish to make a 'flashcard' page which shows interesting facts about the topic the site is based on (music).

I have created an arraylist and added some 'facts' to it as a string value.

I have a textbox on my page and I have a button and I want to show a different fact each time the button is clicked to the textbox.

What would be the best way to go about it?

Sorry I am a newbie here and am just getting to grips with ASP.NET and VS.

EDIT

Thanks, I have now changed it to list. Now I have stored multiple string values to that list and have set a string field called 'abc' (like so);

```<code>public partial class _Default : System.Web.UI.Page
{

    private String abc;

    public void do9()
    {
        List<String> list = new List<String>();
        list.Add("aaa");
        list.Add("bbb");
        list.Add("ccc");
        list.Add("ddd");
        list.Add("eee");

        foreach (String prime in list) // Loop through List with foreach
        {
            abc = prime;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        do9();
        TextBox1.Text = abc;
    }

}
</code>```

Now how can I return a different list value upon the buttonclicked event? Currently it only returns 'eee'. Say I want it to return "aaa" etc instead when the button is clicked each time.

Thanks again!

答:
Arraylist fell out of style with the generics that we got back in .NET 2.0. You should consider using a List<string> instead. I also suggest a shuffling algorithm like the Fisher-Yates shuffle.

I probably wouldn't do this server side at all but more likely in JavaScript. Here's Fisher-Yates shuffle in JavaScript.

EDIT

Here's one way to get a random element from a List.

```<code>private static List<string> QuoteArray = new List<string>
    {
        "All generalizations are false, including this one.",
        "Be careful about reading health books. You may die of a misprint.",
        "If you tell the truth, you don't have to remember anything.",
        "It usually takes me more than three weeks to prepare a good impromptu speech",
        "Water, taken in moderation, cannot hurt anybody.",
        "When I was younger I could remember anything, whether it happened or not."
    };

private static int LastQuoteIndex;
</code>```

and in som class somewhere:

```<code>int i = 0;
var rnd = new Random();
do
{
    i = rnd.Next(QuoteArray.Count);
}
while (i == LastQuoteIndex);

LastQuoteIndex = i;
TextBox1.Text = QuoteArray[i];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a website and wish to make a 'flashcard' page which shows interesting facts about the topic the site is based on (music).

I have created an arraylist and added some 'facts' to it as a string value.

I have a textbox on my page and I have a button and I want to show a different fact each time the button is clicked to the textbox.

What would be the best way to go about it?

Sorry I am a newbie here and am just getting to grips with ASP.NET and VS.

EDIT

Thanks, I have now changed it to list. Now I have stored multiple string values to that list and have set a string field called 'abc' (like so);

public partial class _Default : System.Web.UI.Page
{

    private String abc;

    public void do9()
    {
        List<String> list = new List<String>();
        list.Add("aaa");
        list.Add("bbb");
        list.Add("ccc");
        list.Add("ddd");
        list.Add("eee");

        foreach (String prime in list) // Loop through List with foreach
        {
            abc = prime;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        do9();
        TextBox1.Text = abc;
    }

}

Now how can I return a different list value upon the buttonclicked event? Currently it only returns 'eee'. Say I want it to return "aaa" etc instead when the button is clicked each time.

Thanks again!

Body:
Arraylist fell out of style with the generics that we got back in .NET 2.0. You should consider using a List<string> instead. I also suggest a shuffling algorithm like the Fisher-Yates shuffle.

I probably wouldn't do this server side at all but more likely in JavaScript. Here's Fisher-Yates shuffle in JavaScript.

EDIT

Here's one way to get a random element from a List.

private static List<string> QuoteArray = new List<string>
    {
        "All generalizations are false, including this one.",
        "Be careful about reading health books. You may die of a misprint.",
        "If you tell the truth, you don't have to remember anything.",
        "It usually takes me more than three weeks to prepare a good impromptu speech",
        "Water, taken in moderation, cannot hurt anybody.",
        "When I was younger I could remember anything, whether it happened or not."
    };

private static int LastQuoteIndex;

and in som class somewhere:

int i = 0;
var rnd = new Random();
do
{
    i = rnd.Next(QuoteArray.Count);
}
while (i == LastQuoteIndex);

LastQuoteIndex = i;
TextBox1.Text = QuoteArray[i];


问:
How can I reverse the page order in Gatsby?
I need to change the page order of my blog posts so that new posts get ordered to the top instead of the bottom.

Right now, older posts are at the top of the page.

Here's my gatsby-node.js. How can I reverse the order?

```<code>const path = require('path');

// registering our posts

exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createPage } = boundActionCreators;

  const postTemplate = path.resolve('src/templates/blog-post.js');

  return graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            html
            id
            frontmatter {
              path
              title
              date
              author
            }
          }
        }
      }
    }
  `).then(res => {
    if (res.errors) {
      return Promise.reject(res.errors);
    }
    res.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.frontmatter.path,
        component: postTemplate,
      });
    });
  });
};
</code>```

答:
Your GraphQL result gets passed to your createPage() function where the pages are created in the order given by the result set. You can order the GraphQL result set inside your query:

```<code>    {
      allMarkdownRemark( sort: { fields: [frontmatter___date]
                                 order: DESC } // order by date descending
      ) {
        edges {
          node {
            html
            id
            frontmatter {
              path
              title
              date
              author
            }
          }
        }
      }
    }
  `
</code>```

See the Gatsby GraphQL documentation for more options.

Body:
I need to change the page order of my blog posts so that new posts get ordered to the top instead of the bottom.

Right now, older posts are at the top of the page.

Here's my gatsby-node.js. How can I reverse the order?

const path = require('path');

// registering our posts

exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createPage } = boundActionCreators;

  const postTemplate = path.resolve('src/templates/blog-post.js');

  return graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            html
            id
            frontmatter {
              path
              title
              date
              author
            }
          }
        }
      }
    }
  `).then(res => {
    if (res.errors) {
      return Promise.reject(res.errors);
    }
    res.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.frontmatter.path,
        component: postTemplate,
      });
    });
  });
};

Body:
Your GraphQL result gets passed to your createPage() function where the pages are created in the order given by the result set. You can order the GraphQL result set inside your query:

    {
      allMarkdownRemark( sort: { fields: [frontmatter___date]
                                 order: DESC } // order by date descending
      ) {
        edges {
          node {
            html
            id
            frontmatter {
              path
              title
              date
              author
            }
          }
        }
      }
    }
  `

See the Gatsby GraphQL documentation for more options.


问:
How to translate the menu navbar in core ui react?
I am using the admin template for react : coreui. To translate my labels in the component, I am using react-intl.

I would like to translate the navbar which is a simple array like that :

```<code>    export default {
  items: [
    {
        title: true,
        name: 'ESSAI DOM',
    },
    {
        name: 'Schools',
        url: '/schools',
        icon: 'fa fa-university'
    },
.... other items...
  ],
};
</code>```

My translations are in a json like that (example for 'french'):

```<code>{
    "Schools.Schools.title": "Ecoles"
}
</code>```

In this example, I would like to write something like :

```<code>    {
     name : some_function(languageId, 'Schools.Schools.title'),
     .....
}
</code>```

How can I do that?

答:
I found the solution like that :

```<code>    export default {
  items: [
    {
        name : <FormattedMessage id="Navigation.home" defaultMessage="Home" />,
        url: '/',
        icon: 'fa fa-home'
    },
    {
        name : <FormattedMessage id="Navigation.schools" defaultMessage="Schools" />,
        url: '/schools',
        icon: 'fa fa-university'
    },
  ],
};
</code>```

I did not know we can manipulate React component outside a class.

Body:
I am using the admin template for react : coreui. To translate my labels in the component, I am using react-intl.

I would like to translate the navbar which is a simple array like that :

    export default {
  items: [
    {
        title: true,
        name: 'ESSAI DOM',
    },
    {
        name: 'Schools',
        url: '/schools',
        icon: 'fa fa-university'
    },
.... other items...
  ],
};

My translations are in a json like that (example for 'french'):

{
    "Schools.Schools.title": "Ecoles"
}

In this example, I would like to write something like :

    {
     name : some_function(languageId, 'Schools.Schools.title'),
     .....
}

How can I do that?

Body:
I found the solution like that :

    export default {
  items: [
    {
        name : <FormattedMessage id="Navigation.home" defaultMessage="Home" />,
        url: '/',
        icon: 'fa fa-home'
    },
    {
        name : <FormattedMessage id="Navigation.schools" defaultMessage="Schools" />,
        url: '/schools',
        icon: 'fa fa-university'
    },
  ],
};

I did not know we can manipulate React component outside a class.


问:
Dynamically add TextViews to a leaderboard screen
I have a leaderboard screen in my app where i want to add each users score.
So far I have been able to retrieve the scores from the the database but I want to show these scores on a leaderboard screen.

I have this code, but the for loop sets the text of the textView and instead of each score being displayed, only the last score of the loop is displayed. Is there anyway to not overwrite the textView and instead have multiple textViews created and displayed?

```<code>package com.example.securityapp;

import androidx.appcompat.app.AppCompatActivity;

import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import static java.lang.System.in;

public class leaderboard extends AppCompatActivity {

    DatabaseReference databaseUsers;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    FirebaseAuth mAuth;
    TextView score;
    private static final String TAG = "leaderboard";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leaderboard);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();
        score = (TextView) findViewById(R.id.tableText);

        database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        System.out.println("The score is: " + snapshot.toString());
                        score.setText(snapshot.toString());
                    }
                }

            @Override
            public void onCancelled(DatabaseError databaseError) {
             // Getting Post failed, log a message
             Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

    }

});

        }
}
</code>```

答:
Just Append the string when the loop starts again

Take A Global Variable String s=" ";

s = s + snapshoot.toString();

Body:
I have a leaderboard screen in my app where i want to add each users score.
So far I have been able to retrieve the scores from the the database but I want to show these scores on a leaderboard screen.

I have this code, but the for loop sets the text of the textView and instead of each score being displayed, only the last score of the loop is displayed. Is there anyway to not overwrite the textView and instead have multiple textViews created and displayed?

package com.example.securityapp;

import androidx.appcompat.app.AppCompatActivity;

import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import static java.lang.System.in;

public class leaderboard extends AppCompatActivity {

    DatabaseReference databaseUsers;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    FirebaseAuth mAuth;
    TextView score;
    private static final String TAG = "leaderboard";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leaderboard);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();
        score = (TextView) findViewById(R.id.tableText);

        database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        System.out.println("The score is: " + snapshot.toString());
                        score.setText(snapshot.toString());
                    }
                }

            @Override
            public void onCancelled(DatabaseError databaseError) {
             // Getting Post failed, log a message
             Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

    }

});

        }
}


问:
How to create a custom network in hyperledger fabric with ansible?
I'm trying to create a demo network with 2 organization with 1 peer in each using vs code and ibm blockchain platform,I tried creating json files but things got complicated with the wallet.so with the new fabric update things should be easier with ansible but don't know where or how to start.  </p>

答:
You first need to understand how to setup a network using the Ansible role for IBM Blockchain Platform. More information can be found here
https://github.com/IBM-Blockchain/ansible-role-blockchain-platform-manager

and examples can be found here
https://github.com/IBM-Blockchain/ansible-examples

Once you have created your network you can then import the gateways and wallets generated by the ansible role into the IBM Blockchain Extension by adding a new environment according to the information in the github issue here
https://github.com/IBM-Blockchain/blockchain-vscode-extension/issues/1848


问:
Auto increment MySQL decimal number problems
I am building an application that will have one table of clients that has an autoincrement id INT field. Then I have an HTML "case" form where the user will have to chose a client from the dropdown, then add some info about "case" that will go into another table.

That means that the client will have an id of 1,2,3 and so on. And I would like that the case adds one decimal number on id number of the client chosen from dropdown. So for Client number two + 1: 2.1, 2.2 and so on. Client number 3, 3.1, 3.2 etc.

What is the best way to add that case filed to SQL? I see if I chose Decimal for a case id field I'm getting number 3.4 as 3.400 because I have chosen decimal 4,3 (MySQL) for testing. I Need to have such decimals because the number of cases can go to hundreds, I can not trim that. I'm struggling with the type of MySQL fields and how to approach this problem.
I'd appreciate some guidance.

The only thing I can think of is to pass the value of a client and then do id + "." + 1, and store it as decimal 1,1 (MySQL), will that auto autoincrement to 1.2 and so on?

答:
The MySQL auto-increment mechanism only increments by whole integers. Sorry, that's the way it is implemented.

The best way to design your Case table in MySQL is this:

```<code>CREATE TABLE Cases (
  case_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  client_id INT NOT NULL,
  ...other attributes of the case...
  FOREIGN KEY (client_id) REFERENCES Client (client_id)
);
</code>```

It will have one auto-increment counter for the table, and all clients will need to share this number. This means the case numbers won't always be consecutive for a given client, and they won't start at 1 for each client. Sorry, that's the way auto-increment works in MySQL.

The question has been asked many times with some variation of, "how can I make an auto-increment that renumbers for each group?" You could read the MAX(case_id) for the given client for which you need to insert a case, and then using the max case_id + 1 in your INSERT. In other words, forget about using the auto-increment feature, and calculate the id yourself.

You have to lock the table while doing this to avoid race conditions; two concurrent users could be inserting at the same time, and read the same value for MAX(case_id) and try to insert the same value.

Your plan of using decimal numbers will lead to problems.

What if one day you have a client with more than 999 cases? You'd have to reformat all your case id's, not only for the client with 1000 cases, but for all clients. Any references to the case id's that you had sent out in paper statements and reports would become invalid.

How would you do an SQL query to search for all cases for a given client? If you had client_id in its own column, it would be a query like SELECT ... FROM Case WHERE client_id = 3 but if you have to do a query like ... WHERE case_id BETWEEN 3.000 AND 3.999 it's less clear and harder to optimize. It's also harder to explain to a new programmer you hire for the project. If you end up extending the id format to 4 digits past the decimal, you'd have to rewrite all these SQL queries.

Body:
The MySQL auto-increment mechanism only increments by whole integers. Sorry, that's the way it is implemented.

The best way to design your Case table in MySQL is this:

CREATE TABLE Cases (
  case_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  client_id INT NOT NULL,
  ...other attributes of the case...
  FOREIGN KEY (client_id) REFERENCES Client (client_id)
);

It will have one auto-increment counter for the table, and all clients will need to share this number. This means the case numbers won't always be consecutive for a given client, and they won't start at 1 for each client. Sorry, that's the way auto-increment works in MySQL.

The question has been asked many times with some variation of, "how can I make an auto-increment that renumbers for each group?" You could read the MAX(case_id) for the given client for which you need to insert a case, and then using the max case_id + 1 in your INSERT. In other words, forget about using the auto-increment feature, and calculate the id yourself.

You have to lock the table while doing this to avoid race conditions; two concurrent users could be inserting at the same time, and read the same value for MAX(case_id) and try to insert the same value.

Your plan of using decimal numbers will lead to problems.

What if one day you have a client with more than 999 cases? You'd have to reformat all your case id's, not only for the client with 1000 cases, but for all clients. Any references to the case id's that you had sent out in paper statements and reports would become invalid.

How would you do an SQL query to search for all cases for a given client? If you had client_id in its own column, it would be a query like SELECT ... FROM Case WHERE client_id = 3 but if you have to do a query like ... WHERE case_id BETWEEN 3.000 AND 3.999 it's less clear and harder to optimize. It's also harder to explain to a new programmer you hire for the project. If you end up extending the id format to 4 digits past the decimal, you'd have to rewrite all these SQL queries.


问:
What's the best way to save trivial user states (e.g. dismissed welcome msg) in database?
Should I use (create) a column for every new state? Or one field with a bunch of comma separated states (alternatively a json obj)? Any suggestions welcome.

UPDATE

First let me day thanks for the answers. I just want to clear up, what options I see:

Put a column for every state in the user row (initial plan) / Can get messy with lots of states (in the future)

Put one column with json/xml data in the user row / Easy to maintain (no db change required), but doesn't feel right

Have a dedicated states table (thx lhiles)/ Sounds cool, how would this table look like?

I'm looking for pros/cons of the different implementations. Again: Thanks!

答:
You can save state using an ENUM if the states are mutually exclusive; e.g. person is male or female.

Or using a SET if states can co-exist; e.g. person is a member of (AA and CA and SOsA*)

A sample table using both:

```<code>CREATE TABLE test.table1(
  test_enum ENUM('male', 'female') DEFAULT 'male',
  test_set SET('AA', 'CA', 'SOsA') DEFAULT NULL
)
ENGINE = INNODB;
</code>```

If you're using an ENUM I personally would recommend you set an explicit default value other than null, because most of the time a choice must be made.

Link: http://dev.mysql.com/doc/refman/5.1/en/constraint-enum.html

* (stackoverflow sufferers anonymous)

Body:
You can save state using an ENUM if the states are mutually exclusive; e.g. person is male or female.

Or using a SET if states can co-exist; e.g. person is a member of (AA and CA and SOsA*)

A sample table using both:

CREATE TABLE test.table1(
  test_enum ENUM('male', 'female') DEFAULT 'male',
  test_set SET('AA', 'CA', 'SOsA') DEFAULT NULL
)
ENGINE = INNODB;

If you're using an ENUM I personally would recommend you set an explicit default value other than null, because most of the time a choice must be made.

Link: http://dev.mysql.com/doc/refman/5.1/en/constraint-enum.html

* (stackoverflow sufferers anonymous)


问:
Function was unable to start. Microsoft.Azure.DocumentDB.Core: PartitionKey value must be supplied for this operation.?
I have a simple azure function cosmos trigger set up, like so:

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}
</code>```

When I run the function I get an error:

The listener for function 'Functions.FeedNotifier' was unable to
  start. Microsoft.Azure.Documents.ChangeFeedProcessor: Host was already
  initialized.

I did try to add a partitionKey field to th ebindings to no avail.

答: Seems to be related to this issue. Try  with single-partition lease collection and also mentioned here

Body:
I have a simple azure function cosmos trigger set up, like so:

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}

When I run the function I get an error:

The listener for function 'Functions.FeedNotifier' was unable to
  start. Microsoft.Azure.Documents.ChangeFeedProcessor: Host was already
  initialized.

I did try to add a partitionKey field to th ebindings to no avail.


问:
Rails URLs goes backwards
I am having a weird problem. I have two models in my app, downtowns and properties. Downtowns should have multiple properties and properties should have one downtown.

On my downtown show page i loop through the properties through each downtown and then offer links to these properties.

Problem is.....when i click on each property, the url goes backwards. IE, a downtown with an ID of 1 and a property with an ID of 8 should go

```<code>downtown/1/properties/8
</code>```

yet it keeps going

```<code>downtown/8/properties/1
</code>```

I think this is so weird and i have no clue what i've been doing wrong here.

On my downtown show page, i loop through each property

```<code>%h2= @downtown.name
- if @downtown.properties.present?
  %p
    - @downtown.properties.collect do |property|
      = link_to property.name, downtown_property_path(property)

- else
  No downtowns for now.
</code>```

My routes are the basic nested routing here

```<code>  resources :downtowns do
    resources :properties
  end
</code>```

my properties controller is

```<code>class PropertiesController < Downtown::ApplicationController
  before_action :find_property, only: [:show, :edit, :update, :destroy]

  def new
    @property = @downtown.properties.new
  end

  def create
    @property = @downtown.properties.new(property_params)

    if @property.save
      redirect_to @downtown
    else
      render :new
    end
  end

  def show
  end

  private

  def property_params
    params.require(:property).permit(:name, :downtown, :downtown_id......)
  end

  def find_property
    @property = Property.find(params[:id])
  end
end
</code>```

My downtown controller is

```<code>class DowntownsController < ApplicationController
  before_action :find_downtown, only: [:show, :edit, :update, :destroy]

  def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  private

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end

  def find_downtown
    @downtown = Downtown.find(params[:id])
  end
end
</code>```

Finally in my properties form i have a polymorphic path

```<code>= simple_form_for([@property, @downtown]) do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year
</code>```

答:
Nested route path take multiple arguments Rails Guide.

In your case, it should be downtown_property_path(@downtown, property)

Title: Rails URLs goes backwards

Body:
I am having a weird problem. I have two models in my app, downtowns and properties. Downtowns should have multiple properties and properties should have one downtown.

On my downtown show page i loop through the properties through each downtown and then offer links to these properties.

Problem is.....when i click on each property, the url goes backwards. IE, a downtown with an ID of 1 and a property with an ID of 8 should go

downtown/1/properties/8

yet it keeps going

downtown/8/properties/1

I think this is so weird and i have no clue what i've been doing wrong here.

On my downtown show page, i loop through each property

%h2= @downtown.name
- if @downtown.properties.present?
  %p
    - @downtown.properties.collect do |property|
      = link_to property.name, downtown_property_path(property)

- else
  No downtowns for now.

My routes are the basic nested routing here

  resources :downtowns do
    resources :properties
  end

my properties controller is

class PropertiesController < Downtown::ApplicationController
  before_action :find_property, only: [:show, :edit, :update, :destroy]

  def new
    @property = @downtown.properties.new
  end

  def create
    @property = @downtown.properties.new(property_params)

    if @property.save
      redirect_to @downtown
    else
      render :new
    end
  end

  def show
  end

  private

  def property_params
    params.require(:property).permit(:name, :downtown, :downtown_id......)
  end

  def find_property
    @property = Property.find(params[:id])
  end
end

My downtown controller is

class DowntownsController < ApplicationController
  before_action :find_downtown, only: [:show, :edit, :update, :destroy]

  def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  private

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end

  def find_downtown
    @downtown = Downtown.find(params[:id])
  end
end

Finally in my properties form i have a polymorphic path

= simple_form_for([@property, @downtown]) do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year


问:
Is there a bug with Math.max() when you use .push()?
I am trying to get the max score in an array of constantly updating values. (example.push(score));

I have an initial value of 4 in my array, but when I pass in any value greater than 4 it will return both 4 and the value greater than it.

This is my code.

```<code>setInterval(function(){

var arr = [4];

var randInt = Math.floor(1 + Math.random() * 9);

arr.push(randInt);

var max = Math.max(...arr);

console.log(max);

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

expected output would be any of the following:
 4, 5, 6, 7, 8, or 9

actual output is:
 4, 5 or 4, 6 or  4, 7 or 4, 8 or  4, 9

答:
In the code example above a new instance of the arr variable is always created, so that's why it will compare 4 or n.
If you want to print the max from 4 to 9 you simply just do the following:

```<code>const arr = [4];

while(arr.length !== 6){ // your condition could be different

   arr.push(arr[arr.length - 1] + 1);
   console.log(Math.max(...arr));
}

</code>```

If you need further explanation, please write down the whole example and what is the final achievement.

Body:
I am trying to get the max score in an array of constantly updating values. (example.push(score));

I have an initial value of 4 in my array, but when I pass in any value greater than 4 it will return both 4 and the value greater than it.

This is my code.

setInterval(function(){

var arr = [4];

var randInt = Math.floor(1 + Math.random() * 9);

arr.push(randInt);

var max = Math.max(...arr);

console.log(max);

}, 100);

expected output would be any of the following:
 4, 5, 6, 7, 8, or 9

actual output is:
 4, 5 or 4, 6 or  4, 7 or 4, 8 or  4, 9

Body:
In the code example above a new instance of the arr variable is always created, so that's why it will compare 4 or n.
If you want to print the max from 4 to 9 you simply just do the following:

const arr = [4];

while(arr.length !== 6){ // your condition could be different

   arr.push(arr[arr.length - 1] + 1);
   console.log(Math.max(...arr));
}

If you need further explanation, please write down the whole example and what is the final achievement.


问:
Efficient way to extract area of raster in R
I am trying to extract the area below 5000 feet for a 5 state area using the 30 meter (1 arc second) resolution NED (National Elevation Dataset), by state.  I have a shapefile of the states, and a large (about 4GB) raster of the NED.  I am using the velox package, which speeds things up significantly, but I feel there has to be a faster way to do this (it still takes a long time).

With the velox package, I make the raster into a velox object, then extract the cells using velox's extract function.  Since I know the resolution of each cell, I count the # of cells below 5000 feet in each state and multiply by the area of each cell.

```<code>DEM_velox <- velox(NED)
DEM_cells <- DEM$extract(DEM_velox,sp=state_shapefile)
</code>```

Isn't there a better and much faster way to do this?  I know there's the area function from the raster package, and the gArea function from the rgeos package, but those are for polygons (shapefiles), not rasters, as far as I can tell.  Any help on this would be great.

答:
This is an example of solving your problem for California using a loop with a set of smaller rasters (69 in total) that covered the entire state and avoiding extract.

Raster DEMs were downloaded from the NRCS Spatial Data Gateway.

The extract function was avoided through a mask of each raster that sets elevations outside the state boundary to NA before counting the number of cells below your critical elevation using cellStats along with the function sum.  This sums the number of cells below 5000' elevation, because the raster is converted to TRUE/FALSE values through ras_masked <= crit_elev before summation.  A separate test indicated the extract approach was 5-6 times slower than the mask approach.

The execution time for the loop was 400 seconds.

```<code>library(raster)
crit_elev <- 5000 / 3.2808 #critical elevation in meters
demDir <- yourDEMdirectoryHERE
CADir <- yourStateBoundaryDirectoryHERE
list.files(demDir)
fnames <-list.files(demDir, full.names = TRUE)[grepl('*.tif$', list.files(demDir))]
length(fnames) #69 rasters that cover CA but some do spill over state boundary, so mask is necessary

#read in state boundary and project to DEM crs
list.files(CADir)
CA_TA.shp <- shapefile(file.path(CADir, 'california_CA_TA.shp'))
CA_UTM11N <- spTransform(CA_TA.shp, crs(raster(fnames[1])))

#loop to solve the problem for CA
elev_count <- vector(mode='integer', length = length(fnames)) #this is where we will keep track of how many cells in each dem are below the crit_elev
system.time(for (i in seq_along(fnames)) {
  ras_masked <- mask(raster(fnames[i]), CA_UTM11N)
  elev_count[i] <- cellStats(ras_masked <= crit_elev, sum)
  print(i)
})
#user  system elapsed
#175.76  224.67  400.70
#count cells below 5000 ft, multiply by resolution (30 m) and divide by 10,000 to get hectares
sum(elev_count) * 30 * 30 / 10000
#[1] 19247149
</code>```

Body:
I am trying to extract the area below 5000 feet for a 5 state area using the 30 meter (1 arc second) resolution NED (National Elevation Dataset), by state.  I have a shapefile of the states, and a large (about 4GB) raster of the NED.  I am using the velox package, which speeds things up significantly, but I feel there has to be a faster way to do this (it still takes a long time).

With the velox package, I make the raster into a velox object, then extract the cells using velox's extract function.  Since I know the resolution of each cell, I count the # of cells below 5000 feet in each state and multiply by the area of each cell.

DEM_velox <- velox(NED)
DEM_cells <- DEM$extract(DEM_velox,sp=state_shapefile)

Isn't there a better and much faster way to do this?  I know there's the area function from the raster package, and the gArea function from the rgeos package, but those are for polygons (shapefiles), not rasters, as far as I can tell.  Any help on this would be great.

Body:
This is an example of solving your problem for California using a loop with a set of smaller rasters (69 in total) that covered the entire state and avoiding extract.

Raster DEMs were downloaded from the NRCS Spatial Data Gateway.

The extract function was avoided through a mask of each raster that sets elevations outside the state boundary to NA before counting the number of cells below your critical elevation using cellStats along with the function sum.  This sums the number of cells below 5000' elevation, because the raster is converted to TRUE/FALSE values through ras_masked <= crit_elev before summation.  A separate test indicated the extract approach was 5-6 times slower than the mask approach.

The execution time for the loop was 400 seconds.

library(raster)
crit_elev <- 5000 / 3.2808 #critical elevation in meters
demDir <- yourDEMdirectoryHERE
CADir <- yourStateBoundaryDirectoryHERE
list.files(demDir)
fnames <-list.files(demDir, full.names = TRUE)[grepl('*.tif$', list.files(demDir))]
length(fnames) #69 rasters that cover CA but some do spill over state boundary, so mask is necessary

#read in state boundary and project to DEM crs
list.files(CADir)
CA_TA.shp <- shapefile(file.path(CADir, 'california_CA_TA.shp'))
CA_UTM11N <- spTransform(CA_TA.shp, crs(raster(fnames[1])))

#loop to solve the problem for CA
elev_count <- vector(mode='integer', length = length(fnames)) #this is where we will keep track of how many cells in each dem are below the crit_elev
system.time(for (i in seq_along(fnames)) {
  ras_masked <- mask(raster(fnames[i]), CA_UTM11N)
  elev_count[i] <- cellStats(ras_masked <= crit_elev, sum)
  print(i)
})
#user  system elapsed
#175.76  224.67  400.70
#count cells below 5000 ft, multiply by resolution (30 m) and divide by 10,000 to get hectares
sum(elev_count) * 30 * 30 / 10000
#[1] 19247149


问:
Can you use the name of a Check-box to access its value?
I am currently working on a Word document with ActiveX check-boxes.

You can use the following line of code to access a check-box :

ActiveDocument.InlineShapes(n).OLEFormat.Object

where n is an integer representing the position of that check-box in the document. Unfortunately for me, if any check-box or option button is added before a check-box, the position of that check-box change, thus a given n can point to a different check-box.

My question : is there a way to replace the n with the name (or something else as long as it cannot be changed by adding a new check-box) of the check-box ?

Thank you in advance.

答:
It is possible to check the name of an ActiveX control, but not as an index value of a collection when the control is on the document surface. If you want to work like that I recommend using either the legacy Forms controls (same place in the Ribbon as the activeX controls list) or a Checkbox type of content control.

ActiveX controls can be indexed by a name when the control is on a VBA UserForm, because that's the environment the controls were designed for. Word "wraps" them up in a field code and treats them as a graphic, so VBA code has to go through a couple layers of interface in order to access them on a document as an ActiveX control.

The following code demonstrates how to address an ActiveX control by its name.

Loop through the InlineShapes collection

Check whether the type is an ActiveX control

Check whether it's a checkbox

Check the name property

Code:

```<code>Sub ActiveXControlByName()
    Dim ils As Word.InlineShape
    Dim cb As MSForms.CheckBox

    For Each ils In ActiveDocument.InlineShapes
        If ils.Type = wdInlineShapeOLEControlObject Then
            If ils.OleFormat.ClassType = "Forms.CheckBox.1" Then
                Set cb = ils.OleFormat.Object
                If cb.Name = "cb2" Then
                    cb.value = False
                    Exit For
                End If
            End If
        End If
    Next
End Sub
</code>```

Body:
It is possible to check the name of an ActiveX control, but not as an index value of a collection when the control is on the document surface. If you want to work like that I recommend using either the legacy Forms controls (same place in the Ribbon as the activeX controls list) or a Checkbox type of content control.

ActiveX controls can be indexed by a name when the control is on a VBA UserForm, because that's the environment the controls were designed for. Word "wraps" them up in a field code and treats them as a graphic, so VBA code has to go through a couple layers of interface in order to access them on a document as an ActiveX control.

The following code demonstrates how to address an ActiveX control by its name.

Loop through the InlineShapes collection

Check whether the type is an ActiveX control

Check whether it's a checkbox

Check the name property

Code:

Sub ActiveXControlByName()
    Dim ils As Word.InlineShape
    Dim cb As MSForms.CheckBox

    For Each ils In ActiveDocument.InlineShapes
        If ils.Type = wdInlineShapeOLEControlObject Then
            If ils.OleFormat.ClassType = "Forms.CheckBox.1" Then
                Set cb = ils.OleFormat.Object
                If cb.Name = "cb2" Then
                    cb.value = False
                    Exit For
                End If
            End If
        End If
    Next
End Sub


问:
How to print file contents with filename before each line?
I have several files, say, a,b,c, I would like to something like

```<code> > cat a b c
</code>```

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

```<code>#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()
</code>```

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

答:
grep(1) and sed(1)can do this for you: grep -H '' <files> | sed 's/:/,/':

```<code>$ cat a ; cat b ; cat c
hello

world
from space
$ grep -H '' * | sed 's/:/,/'
a,hello
b,
b,
b,world
c,from space
</code>```

Body:
I have several files, say, a,b,c, I would like to something like

 > cat a b c

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

Body:
grep(1) and sed(1)can do this for you: grep -H '' <files> | sed 's/:/,/':

$ cat a ; cat b ; cat c
hello

world
from space
$ grep -H '' * | sed 's/:/,/'
a,hello
b,
b,
b,world
c,from space


问:
Problems with getElementById
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.

i have js file (script.js)

```<code> function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());
</code>```

and my index.html where i'm using div's tags

```<code>     <div class="result">
        <div class="history">
            <p  id="history-value">55555</p>
        </div>
        <div class="output">
            <p id="output-value" class="output-value">7777777</p>
        </div>
    </div>
</code>```

in beginning of course referense to js

```<code><head>
    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">
    <script src="script.js">
        </script>
</head>
</code>```

But allert are not working. I can't see nothing. If i use

```<code>console.log (document.getElementById("history-value").innerText );
</code>```

it shows null in console window.

Please explain me what's wrong with it?

答: The problem is that your

Title: Problems with getElementById

Body:
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.

i have js file (script.js)

 function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());

and my index.html where i'm using div's tags

55555

7777777

in beginning of course referense to js

    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">

But allert are not working. I can't see nothing. If i use

console.log (document.getElementById("history-value").innerText );

it shows null in console window.

Please explain me what's wrong with it?

Body:
The problem is that your <script> tag appears in the <head> section of your document, and when the script loads, the rest of your HTML has not yet been loaded by the browser, so the <p id="history-value"> tag effectively does not yet exist as far as the browser is concerned.

In this case, you should put your <script> tag just before the </body> tag, or at the very least after the <p id="history-value"> tag, so that <p> tag appears before the Javascript attempts to read it.


答:
It looks like the script runs when there is no history-value element.
Are you sure you are running the code after document has been loaded?

Your code work in the following snippet (but I guess is due to the fact that javscript is loaded at the end of the document).

But to make sure you can place into a

document.addEventListener( 'DOMContentLoaded', function( event ) {
  // your code here
})
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getHistory(){
  return document.getElementById("history-value").innerText;
}

document.addEventListener( 'DOMContentLoaded', function( event ) {
  alert(getHistory());
});</code>```

55555

7777777

```

Title: Problems with getElementById

Body:
It looks like the script runs when there is no history-value element.
Are you sure you are running the code after document has been loaded?

Your code work in the following snippet (but I guess is due to the fact that javscript is loaded at the end of the document).

But to make sure you can place into a

document.addEventListener( 'DOMContentLoaded', function( event ) {
  // your code here
})

function getHistory(){
  return document.getElementById("history-value").innerText;
}

document.addEventListener( 'DOMContentLoaded', function( event ) {
  alert(getHistory());
});

<div class="result">
  <div class="history">
    <p id="history-value">55555</p>
  </div>
  <div class="output">
    <p id="output-value" class="output-value">7777777</p>
  </div>
</div>


问:
Typescript: type starting with a pipe
I recently ran into this typescript syntax:

```<code>type Foo = | 5 | 6;
</code>```

Turns out that this does compile, to my surprise. Is there any significance to that first pipe character? Or is it functionally equivalent to:

```<code>type Foo = 5 | 6;
</code>```

答:
Leading pipe characters are ignored in union type definitions to give developers more formatting freedom.

You can check PR#12386 on the official TypeScript repository for more info.

Title: Typescript: type starting with a pipe

Body:
I recently ran into this typescript syntax:

type Foo = | 5 | 6;

Turns out that this does compile, to my surprise. Is there any significance to that first pipe character? Or is it functionally equivalent to:

type Foo = 5 | 6;


答:
you can concat the string everytime but if you want to save them , you can use sharedPrefenrece.
First you can save the scores in sharedPreference and everytime that the onDataChanged function is called , you can concat the newScore to the previous scores.
like this :

```<code>SharedPreference sharedPreference = getSharedPreference("Scores" , MODE_PRIVATE); // in the top of database callback
</code>```

and in the onDataChanged function :

```<code>sharedPreference.edit().putString("score" , sharedPreference.getString("score" , "") + " " + snapShot.toString);
</code>```

Title: Dynamically add TextViews to a leaderboard screen

Body:
you can concat the string everytime but if you want to save them , you can use sharedPrefenrece.
First you can save the scores in sharedPreference and everytime that the onDataChanged function is called , you can concat the newScore to the previous scores.
like this :

SharedPreference sharedPreference = getSharedPreference("Scores" , MODE_PRIVATE); // in the top of database callback

and in the onDataChanged function :

sharedPreference.edit().putString("score" , sharedPreference.getString("score" , "") + " " + snapShot.toString);


问:
How do I set up azure dev ops for a 2d unity project
I'm not sure if this is possible, I couldn't find any resources for building a 2d unity project (though there is for a 3d).
The project I am currently working on is in a github repo and I would like to put it on dev ops. Every time a commit is made I would like to build and run unit and integration tests so that my team will know if something is not working correctly instead of manually doing it. It would also be nice to put inno installer in the build process (to make sure the installer would work without any problems, I don't know if that is possible on dev ops though).

On the 3d project (link: https://dinomite-studios.github.io/unity-azure-pipelines-tasks/), I don't know if it would work for a 2d project.

Thank you for taking the time to look at my question! If there is any clarification that I can make please let me know!

答: I think you should try if it works with 2d, and get back to this question if it doesn't work normally.


问:
if condition using javascript
am trying to perform an if condition in javascript, but i cannot get the output. i tried the code below:

function myfunc(size){

    var m = parseInt(size);
    var size2 = (m).toString();
  if(m <= 2){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');

    }
  if(m > 2 || <= 4){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

    }

  if(m > 4 || <= 6){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

    }
  if(m > 6 || <= 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );

    }
  if(m > 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');

    }

  }```

how can i solve this?

答:
You need to use "&&" instead of "||" in your 'if' conditions, and also correct your syntax. You have to do if(m>2 && m<=4).

The OR condition ( || ) means that that condition will execute IF the value of m is greater than 2 OR less than 4. Now 1 is also less than 4, so it can execute for 1 as well.

If you write '&&' instead, it will mean that it should ONLY execute if m is greater than 2 AND less than or equal to 4.

Title: if condition using javascript

Body:
am trying to perform an if condition in javascript, but i cannot get the output. i tried the code below:

function myfunc(size){

    var m = parseInt(size);
    var size2 = (m).toString();
  if(m <= 2){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');

    }
  if(m > 2 || <= 4){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

    }

  if(m > 4 || <= 6){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

    }
  if(m > 6 || <= 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );

    }
  if(m > 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');

    }

  }

how can i solve this?


问:
IN clause for Oracle Prepared Statement in Python cx_Oracle
I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python.

E.g. query - select name from employee where id in ('101', '102', '103')

On python side, I have a list [101, 102, 103] which I converted to a string like this ('101', '102', '103') and used the following code in python -

```<code>import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()
results = cursor.execute('select name from employee where id in :id_list', id_list=ALL_IDS)
names = [x[0] for x in cursor.description]
rows = results.fetchall()
</code>```

This doesn't work. Am I doing something wrong?

答:
Otra opción es dar formato a una cadena con la consulta.</p>

```<code>import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()

query = """
select name from employee where id in ('{}')
""".format("','".join(map(str, ids)))

results = cursor.execute(query)
names = [x[0] for x in cursor.description]
rows = results.fetchall()

</code>```

Body:
I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python.

E.g. query - select name from employee where id in ('101', '102', '103')

On python side, I have a list [101, 102, 103] which I converted to a string like this ('101', '102', '103') and used the following code in python -

import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()
results = cursor.execute('select name from employee where id in :id_list', id_list=ALL_IDS)
names = [x[0] for x in cursor.description]
rows = results.fetchall()

This doesn't work. Am I doing something wrong?

Body:
Otra opción es dar formato a una cadena con la consulta.

import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()

query = """
select name from employee where id in ('{}')
""".format("','".join(map(str, ids)))

results = cursor.execute(query)
names = [x[0] for x in cursor.description]
rows = results.fetchall()


问:
IPC through shared memory and pipe gives segmentation fault: 11 in C
I am trying to share a file between parent and child processes. Parent sends the file via a pipe and child write that lines into shared memory so that parent can read and print out the file via shared memory. However, I am getting segmentation fault: 11. Besides, I did something similar like the code below, but that time I could not get the correct content and even I was getting different results at each call.

I am not sure about increasing the pointer part. But, it is better to have an extra eye on the code.

Edit: I corrected char* to char[] and segmentation fault is now gone. However, I get different results at each run, some extra characters are seen in output.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>

#define SHM_NAME_1 "Child 1"

int main(){

    pid_t pid;
    FILE *file;
    char *infile = "in.txt";

    pid = fork();

    if(pid < 0){
        fprintf(stderr, "Fork failed\n");
        return 1;
    }

    if(pid > 0){ // parent

        file = fopen(infile, "r");

        if(file == 0){
            fprintf(stderr, "File failed\n");
            return 1;
        }
        // close read end of pipe
        mknod("FIFO", S_IFIFO | 0666, 0);
        int fd = open("FIFO", O_WRONLY);

        char str[300];
        while(fgets(str, sizeof(str), file) > 0)
        {
            // write all lines of file
            write(fd, str, strlen(str));
        }
        // close file and pipe
        close(fd);
        fclose(file);
        // wait for child to write to shared memory
        wait(NULL);

        // open shared segment
        int shm_first = shm_open(SHM_NAME_1, O_RDONLY, 0666);

        if (shm_first == -1) {
            fprintf(stderr, "Failed: Shared Memory 1");
            exit(-1);
        }

        // create memory pointer
        void *ptr = mmap(0,4096, PROT_READ, MAP_SHARED, shm_first, 0);

        if (ptr == MAP_FAILED) {
            printf("Map failed 1\n");
            return -1;
        }
        // print out result and unlibk shared segment
        fprintf(stdout, "Normal input: \n%s\n", ptr);
        shm_unlink(SHM_NAME_1);

    } else { // child

        // create the shared segment for the first time
        int shm_child_1 = shm_open(SHM_NAME_1, O_CREAT | O_RDWR, 0666);

        // configure the size of the shared memory segment
        ftruncate(shm_child_1,4096);
        // map the pointer to the segment
        void *ptr_child_1 = mmap(0,4096, PROT_READ | PROT_WRITE, MAP_SHARED, shm_child_1, 0);

        if (ptr_child_1 == MAP_FAILED)
        {
            printf("Map failed in first child\n");
            return -1;
        }

        mknod("FIFO", S_IFIFO | 0666, 0);
        int fd = open("FIFO", O_RDONLY);

        int num;
        char s[300];
        while((num = read(fd, s, sizeof(s)))> 0)
        {
            sprintf(ptr_child_1, "%s", s);
            ptr_child_1 += num;
        }

        close(fd);
        exit(0);

    }

    return 0;
}
</code>```

答:
One quick observation.

In the following code, you have a char pointer that is not initialized to point to anything. Which causes fgets to copy what it reads from file to some arbitrary place in memory.

```<code>    char *str;
    while(fgets(str, 100, file) > 0)
</code>```

Now that the buffer issues are resolved, there is also an issue with the braces in the following expression

```<code>    while((num = read(fd, s, sizeof(s)) > 0))
</code>```

num is going to be 1 or 0 rather than the number of bytes read or 0 for eof. This should be

```<code>    while((num = read(fd, s, sizeof(s))) > 0)
</code>```

Once you have the number of bytes read, you need to zero terminate the buffer. Because you are using sprintf which expects the argument for %s to be a zero terminated string.

```<code>    while((num = read(fd, s, sizeof(s)))> 0)
    {
        s[num] = '\0';  // Terminate the string to the number of bytes read
        sprintf(ptr_child_1, "%s", s);
        ptr_child_1 += num;
    }
</code>```

Body:
I am trying to share a file between parent and child processes. Parent sends the file via a pipe and child write that lines into shared memory so that parent can read and print out the file via shared memory. However, I am getting segmentation fault: 11. Besides, I did something similar like the code below, but that time I could not get the correct content and even I was getting different results at each call.

I am not sure about increasing the pointer part. But, it is better to have an extra eye on the code.

Edit: I corrected char* to char[] and segmentation fault is now gone. However, I get different results at each run, some extra characters are seen in output.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>

#define SHM_NAME_1 "Child 1"

int main(){

    pid_t pid;
    FILE *file;
    char *infile = "in.txt";

    pid = fork();

    if(pid < 0){
        fprintf(stderr, "Fork failed\n");
        return 1;
    }

    if(pid > 0){ // parent

        file = fopen(infile, "r");

        if(file == 0){
            fprintf(stderr, "File failed\n");
            return 1;
        }
        // close read end of pipe
        mknod("FIFO", S_IFIFO | 0666, 0);
        int fd = open("FIFO", O_WRONLY);

        char str[300];
        while(fgets(str, sizeof(str), file) > 0)
        {
            // write all lines of file
            write(fd, str, strlen(str));
        }
        // close file and pipe
        close(fd);
        fclose(file);
        // wait for child to write to shared memory
        wait(NULL);

        // open shared segment
        int shm_first = shm_open(SHM_NAME_1, O_RDONLY, 0666);

        if (shm_first == -1) {
            fprintf(stderr, "Failed: Shared Memory 1");
            exit(-1);
        }

        // create memory pointer
        void *ptr = mmap(0,4096, PROT_READ, MAP_SHARED, shm_first, 0);

        if (ptr == MAP_FAILED) {
            printf("Map failed 1\n");
            return -1;
        }
        // print out result and unlibk shared segment
        fprintf(stdout, "Normal input: \n%s\n", ptr);
        shm_unlink(SHM_NAME_1);

    } else { // child

        // create the shared segment for the first time
        int shm_child_1 = shm_open(SHM_NAME_1, O_CREAT | O_RDWR, 0666);

        // configure the size of the shared memory segment
        ftruncate(shm_child_1,4096);
        // map the pointer to the segment
        void *ptr_child_1 = mmap(0,4096, PROT_READ | PROT_WRITE, MAP_SHARED, shm_child_1, 0);

        if (ptr_child_1 == MAP_FAILED)
        {
            printf("Map failed in first child\n");
            return -1;
        }

        mknod("FIFO", S_IFIFO | 0666, 0);
        int fd = open("FIFO", O_RDONLY);

        int num;
        char s[300];
        while((num = read(fd, s, sizeof(s)))> 0)
        {
            sprintf(ptr_child_1, "%s", s);
            ptr_child_1 += num;
        }

        close(fd);
        exit(0);

    }

    return 0;
}

Body:
One quick observation.

In the following code, you have a char pointer that is not initialized to point to anything. Which causes fgets to copy what it reads from file to some arbitrary place in memory.

    char *str;
    while(fgets(str, 100, file) > 0)

Now that the buffer issues are resolved, there is also an issue with the braces in the following expression

    while((num = read(fd, s, sizeof(s)) > 0))

num is going to be 1 or 0 rather than the number of bytes read or 0 for eof. This should be

    while((num = read(fd, s, sizeof(s))) > 0)

Once you have the number of bytes read, you need to zero terminate the buffer. Because you are using sprintf which expects the argument for %s to be a zero terminated string.

    while((num = read(fd, s, sizeof(s)))> 0)
    {
        s[num] = '\0';  // Terminate the string to the number of bytes read
        sprintf(ptr_child_1, "%s", s);
        ptr_child_1 += num;
    }


问:
nginx progy pass doesn't work in Wordpress admin
I have two web sites urls like example.com and wp-example.site.cloud.
wp-example is Wordpress blog of example.com and I want to open it in example.com/blog so I did it in example.com nginx.

```<code>location ^~ /blog {

        rewrite /blog/(.*) /$1  break;
        proxy_http_version 1.1;
       proxy_set_header Host $http_host;
        proxy_request_buffering off; # Disable any internal request bufferring.
        proxy_pass http://wp.lunato;
        server_name_in_redirect off;
     #   proxy_set_header Host $host:$server_port;

    }
</code>```

It works fine but when I open Wordpress admin  the blog is removed from url and return 404 for me.
The main page of Wordpress is fine but when I open a page from menu there is no /blog in the url and returns 404.
Any idea for this problem?

答:
i solved it

wordpress change url automaticity with a js code so i add a js in wp-admin/admin-footer.php this code add /blog in url after wordpress remove it :D

Body:
I have two web sites urls like example.com and wp-example.site.cloud.
wp-example is Wordpress blog of example.com and I want to open it in example.com/blog so I did it in example.com nginx.

location ^~ /blog {

        rewrite /blog/(.*) /$1  break;
        proxy_http_version 1.1;
       proxy_set_header Host $http_host;
        proxy_request_buffering off; # Disable any internal request bufferring.
        proxy_pass http://wp.lunato;
        server_name_in_redirect off;
     #   proxy_set_header Host $host:$server_port;

    }

It works fine but when I open Wordpress admin  the blog is removed from url and return 404 for me.
The main page of Wordpress is fine but when I open a page from menu there is no /blog in the url and returns 404.
Any idea for this problem?


答:
Your directory names are sorted in chronological order, which makes this easy. The list of directories in chronological order is just *, or [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] to be more precise. So you want to delete all but the last 10 of them.

```<code>set [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
while [ $# -gt 10 ]; do
  rm -rf "$1"
  shift
fi
</code>```

(While there are more than 10 directories left, delete the oldest one.)

Title: Linux - Save only recent 10 folders and delete the rest

Body:
I have a folder that contains versions of my application, each time I upload a new version a new sub-folder is created for it, the sub-folder name is the current timestamp, here is a printout of the main folder used (ls -l |grep ^d):

drwxrwxr-x 7 root root 4096 2011-03-31 16:18 20110331161649
drwxrwxr-x 7 root root 4096 2011-03-31 16:21 20110331161914
drwxrwxr-x 7 root root 4096 2011-03-31 16:53 20110331165035
drwxrwxr-x 7 root root 4096 2011-03-31 16:59 20110331165712
drwxrwxr-x 7 root root 4096 2011-04-03 20:18 20110403201607
drwxrwxr-x 7 root root 4096 2011-04-03 20:38 20110403203613
drwxrwxr-x 7 root root 4096 2011-04-04 14:39 20110405143725
drwxrwxr-x 7 root root 4096 2011-04-06 15:24 20110406151805
drwxrwxr-x 7 root root 4096 2011-04-06 15:36 20110406153157
drwxrwxr-x 7 root root 4096 2011-04-06 16:02 20110406155913
drwxrwxr-x 7 root root 4096 2011-04-10 21:10 20110410210928
drwxrwxr-x 7 root root 4096 2011-04-10 21:50 20110410214939
drwxrwxr-x 7 root root 4096 2011-04-10 22:15 20110410221414
drwxrwxr-x 7 root root 4096 2011-04-11 22:19 20110411221810
drwxrwxr-x 7 root root 4096 2011-05-01 21:30 20110501212953
drwxrwxr-x 7 root root 4096 2011-05-01 23:02 20110501230121
drwxrwxr-x 7 root root 4096 2011-05-03 21:57 20110503215252
drwxrwxr-x 7 root root 4096 2011-05-06 16:17 20110506161546
drwxrwxr-x 7 root root 4096 2011-05-11 10:00 20110511095709
drwxrwxr-x 7 root root 4096 2011-05-11 10:13 20110511100938
drwxrwxr-x 7 root root 4096 2011-05-12 14:34 20110512143143
drwxrwxr-x 7 root root 4096 2011-05-13 22:13 20110513220824
drwxrwxr-x 7 root root 4096 2011-05-14 22:26 20110514222548
drwxrwxr-x 7 root root 4096 2011-05-14 23:03 20110514230258

I'm looking for a command that will leave the last 10 versions (sub-folders) and deletes the rest.

Any thoughts?

Body:
Your directory names are sorted in chronological order, which makes this easy. The list of directories in chronological order is just *, or [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] to be more precise. So you want to delete all but the last 10 of them.

set [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
while [ $# -gt 10 ]; do
  rm -rf "$1"
  shift
fi

(While there are more than 10 directories left, delete the oldest one.)


问:
Can you explain what run time error is how to fix it
```<code>void adde(int& v, char array[5])
{

    if (v > 5) {
        v = -1;
    }

    for (int k = 0; k < 5; k++) {
        if (array[k] == 'C') {
            array[k] = '-';
        }
    }
    v++;
    array[v] = 'C';
}
</code>```

this is my function

```<code>int mov = -1;
char item[5];
for (int i = 0; i < 5; i++) {
    item[i] = '-';
}
cout << "Initially " << endl;
for (int i = 0; i < 5; i++) {
    cout << "[" << i + 1 << " ] ";
}
cout << endl;
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 1, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 2, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 3, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 4, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 5, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
</code>```

My code works fine till here.
After the last item i want my cursor to point back to first index
but shows weird Library Run time error
After it runs this highlighted part of code
cout << "After Item 6, " << endl;

adde(mov, item);

for (int j = 0; j < 5; j++) {       cout << item[j] << "    ";  } }

答:
Heading ##You did a simple mistake. No need for a debbugger here. Arrays in C/C++ start with index 0. So if you have an array of size 5, like in your example char item[5];, the valid indices are 0,1,2,3,4. But not 5.

In your function adde you simply have the wrong boundary check. In your very first statement you have written:

```<code>if (v > 5) {
</code>```

then later

```<code>    v++;
    array[v] = 'C';
</code>```

So, if v is >3, for example 4 or 5, you will increment it and access array[5] or array[6], which is out of bounds and produces an error.

You may simply correct it and use

```<code>if (v > 3) {
</code>```

as you first statement. This will fix the problem:

```<code>#include <iostream>

void adde(int& v, char array[5])
{

    if (v > 3) {
        v = -1;
    }

    for (int k = 0; k < 5; k++) {
        if (array[k] == 'C') {
            array[k] = '-';
        }
    }
    v++;
    array[v] = 'C';
}

int main() {
    int mov = -1;
    char item[5];
    for (int i = 0; i < 5; i++) {
        item[i] = '-';
    }
    std::cout << "Initially " << std::endl;
    for (int i = 0; i < 5; i++) {
        std::cout << "[" << i + 1 << " ] ";
    }
    std::cout << std::endl;
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 1, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 2, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 3, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 4, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 5, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }

    std::cout << std::endl;
    std::cout << "After Item 6, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    return 0;
}
</code>```

Please additionally note:

The design is not very good. Please do not use C-style arrays in C++. Please avoid pointer decays in calls to functions. Please rethink you complete design. I can see, what you are doing. This can be done easier in C++, but for a really good or approriate solution, we need to know the requriements.

Body:
void adde(int& v, char array[5])
{

    if (v > 5) {
        v = -1;
    }

    for (int k = 0; k < 5; k++) {
        if (array[k] == 'C') {
            array[k] = '-';
        }
    }
    v++;
    array[v] = 'C';
}

this is my function

int mov = -1;
char item[5];
for (int i = 0; i < 5; i++) {
    item[i] = '-';
}
cout << "Initially " << endl;
for (int i = 0; i < 5; i++) {
    cout << "[" << i + 1 << " ] ";
}
cout << endl;
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 1, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 2, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 3, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 4, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;
cout << "After Item 5, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
    cout << item[j] << "    ";
}
cout << endl;

My code works fine till here.
After the last item i want my cursor to point back to first index
but shows weird Library Run time error
After it runs this highlighted part of code
cout << "After Item 6, " << endl;

adde(mov, item);

for (int j = 0; j < 5; j++) {       cout << item[j] << "    ";  } }

Body:
Heading ##You did a simple mistake. No need for a debbugger here. Arrays in C/C++ start with index 0. So if you have an array of size 5, like in your example char item[5];, the valid indices are 0,1,2,3,4. But not 5.

In your function adde you simply have the wrong boundary check. In your very first statement you have written:

if (v > 5) {

then later

    v++;
    array[v] = 'C';

So, if v is >3, for example 4 or 5, you will increment it and access array[5] or array[6], which is out of bounds and produces an error.

You may simply correct it and use

if (v > 3) {

as you first statement. This will fix the problem:

#include <iostream>

void adde(int& v, char array[5])
{

    if (v > 3) {
        v = -1;
    }

    for (int k = 0; k < 5; k++) {
        if (array[k] == 'C') {
            array[k] = '-';
        }
    }
    v++;
    array[v] = 'C';
}

int main() {
    int mov = -1;
    char item[5];
    for (int i = 0; i < 5; i++) {
        item[i] = '-';
    }
    std::cout << "Initially " << std::endl;
    for (int i = 0; i < 5; i++) {
        std::cout << "[" << i + 1 << " ] ";
    }
    std::cout << std::endl;
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 1, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 2, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 3, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 4, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    std::cout << "After Item 5, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }

    std::cout << std::endl;
    std::cout << "After Item 6, " << std::endl;
    adde(mov, item);
    for (int j = 0; j < 5; j++) {
        std::cout << item[j] << "    ";
    }
    std::cout << std::endl;
    return 0;
}

Please additionally note:

The design is not very good. Please do not use C-style arrays in C++. Please avoid pointer decays in calls to functions. Please rethink you complete design. I can see, what you are doing. This can be done easier in C++, but for a really good or approriate solution, we need to know the requriements.


问:
Producing tasks on-demand in producer-consumer pattern
Let's consider the following situation in producer-consumer pattern:

I cannot wait with a task to be performed. I want to produce task on demand (eg. with Supplier) when a consumer is ready to process it. In SynchronousQueue I need to have actual task when executing put() method. How to solve my problem?

I know that I could solve it by design - just make a set of workers and tell them to produceTask-consume-Task-repeat, but I'm looking for another way.

To be more specific:
Let's consider that I have remote http resource A. I can get a 'task' from it to process in my worker threads. Results are sent asynchronously. But the thing is that I should not get a task from A if I am not able to process it right now.

答:
"I want to produce task on demand (eg. with Supplier) when a consumer is ready to process it."
One example of producing data on demand is Reactive Streams protocol, where Subscriber (consumer) requests Publisher (producer) to push next chunk of data with Subscription.request() method.

This protocol is implemented in RxJava and other libraries.


问:
How to combine 2 Gatsby sites in one domain?
I want to combine 2 Gatsby sites in one domain, for example, Gatsby1 (landing page) in mydomain.com, and Gatsby2 (blog) in mydomain.com/blog, how can I do that?</p>

答:
Create two Gatbsy projects. One can be configured from the root mydomain.com. One needs to use path prefixes:

gatsby-config.js

module.exports = {
  pathPrefix: `/blog`,
}
```

When you build you need to use a flag: gatsby build --prefix-paths.

Body:
Create two Gatbsy projects. One can be configured from the root mydomain.com. One needs to use path prefixes:

gatsby-config.js

module.exports = {
  pathPrefix: `/blog`,
}

When you build you need to use a flag: gatsby build --prefix-paths.


答:
You are wrongly implementing the if condition with || operator. You should do it like eg : if(m > 2 ||m<= 4)

function myfunc(size){

    var m = parseInt(size);
    var size2 = (m).toString();
  if(m <= 2){
    alert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');

    }
  if(m > 2 ||m<= 4){
    alert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

    }

  if(m > 4 || m<= 6){
    alert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

    }
  if(m > 6 || m<= 8){
    alert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );

    }
  if(m > 8){
    alert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');

    }

  }

    myfunc("5")```

Title: if condition using javascript


答:
I'd like to provide an answer that may simplify your routing.

If your properties can only reference one downtown (which seems to be the case according to your controllers), then you don't need to have URLs such as downtown/1/properties/8.

To access the property with id 8, you should simply go and use properties/8, since in the controller action, you'll be able to load the related downtown (with id=1) since it is referenced in the property record. The show action for a nested resource typically doesn't need to go through the parent.

PS: Accessing nested resources through the parent resource is mostly useful when the child resource (properties in your case) can have several parent resources linked to it (downtowns).

Title: Rails URLs goes backwards

Body:
I am having a weird problem. I have two models in my app, downtowns and properties. Downtowns should have multiple properties and properties should have one downtown.

On my downtown show page i loop through the properties through each downtown and then offer links to these properties.

Problem is.....when i click on each property, the url goes backwards. IE, a downtown with an ID of 1 and a property with an ID of 8 should go

downtown/1/properties/8

yet it keeps going

downtown/8/properties/1

I think this is so weird and i have no clue what i've been doing wrong here.

On my downtown show page, i loop through each property

%h2= @downtown.name
- if @downtown.properties.present?
  %p
    - @downtown.properties.collect do |property|
      = link_to property.name, downtown_property_path(property)

- else
  No downtowns for now.

My routes are the basic nested routing here

  resources :downtowns do
    resources :properties
  end

my properties controller is

class PropertiesController < Downtown::ApplicationController
  before_action :find_property, only: [:show, :edit, :update, :destroy]

  def new
    @property = @downtown.properties.new
  end

  def create
    @property = @downtown.properties.new(property_params)

    if @property.save
      redirect_to @downtown
    else
      render :new
    end
  end

  def show
  end

  private

  def property_params
    params.require(:property).permit(:name, :downtown, :downtown_id......)
  end

  def find_property
    @property = Property.find(params[:id])
  end
end

My downtown controller is

class DowntownsController < ApplicationController
  before_action :find_downtown, only: [:show, :edit, :update, :destroy]

  def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  private

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end

  def find_downtown
    @downtown = Downtown.find(params[:id])
  end
end

Finally in my properties form i have a polymorphic path

= simple_form_for([@property, @downtown]) do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year