问:
Need div to return to previous background color with JavaScript (no jquery)
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}</code>```

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

```

答:
I believe you need some sort of overlay and not color the background to gray. I may be wrong.
Here is the snippet with some addition. you would get an idea.

  window.addEventListener('load', function() {
    var button = document.getElementById('alert-trigger');
    if (button.addEventListener)
      button.addEventListener('click', addAlert);
  });

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  var modal = document.getElementById('overlaydiv');
  modal.setAttribute('class','overlay');
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<title>Timeout Warning</title>
For your security, this session is about to end due to inactivity.
<button id="contBtn" onclick="destroy()" type="button">Continue Session</button>
';
  setTimeout(function() {
    destroy();
  }, 10000);
}

function destroy(){
   var modal = document.getElementById('overlaydiv');
    document.getElementById('example').innerHTML = '';
    modal.setAttribute('class','hidden');

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

.overlay{
width:100%;
height:100%;
background-color:gray;
opacity:0.9;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}

.modal{
width:200px;
height:200px;
border-color:red;
position:absolute;
top:50px;
left:50px;
z-index:9999;
}

.hidden{
display:none;
}</code>```

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" >Display Session Manager</button>

```

Body:
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

Body:
I believe you need some sort of overlay and not color the background to gray. I may be wrong.
Here is the snippet with some addition. you would get an idea.

  window.addEventListener('load', function() {
    var button = document.getElementById('alert-trigger');
    if (button.addEventListener)
      button.addEventListener('click', addAlert);
  });

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  var modal = document.getElementById('overlaydiv');
  modal.setAttribute('class','overlay');
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '<div class="modal"><span style="display:inline;width:28px;height:28px;border-color:red"><title>Timeout Warning</title></span><p>For your security, this session is about to end due to inactivity.</p><button id="contBtn" onclick="destroy()" type="button">Continue Session</button></div>';
  setTimeout(function() {
    destroy();
  }, 10000);
}

function destroy(){
   var modal = document.getElementById('overlaydiv');
    document.getElementById('example').innerHTML = '';
    modal.setAttribute('class','hidden');

}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

.overlay{
width:100%;
height:100%;
background-color:gray;
opacity:0.9;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}

.modal{
width:200px;
height:200px;
border-color:red;
position:absolute;
top:50px;
left:50px;
z-index:9999;
}

.hidden{
display:none;
}

<div id="example" role="alert"></div>
<div id="e1">
  <h1>Testing Banner Timeout</h1>
  <p>This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.</p>
  <p>If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.</p>
  <button id="alert-trigger" >Display Session Manager</button>
</div>
<div id="overlaydiv"  class="hidden"></div>


来源: stackexchange

问:
How to force JavaScript integer to keep a zero before numbers?
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

```<code>var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);
</code>```

答: You cannot. You need to keep it as string if you need a leading zero.</p>

ContentLicense: CC BY-SA 4.0

Body:
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);

ContentLicense: CC BY-SA 3.0


问:
Images won't show up on Bootstrap Carousel
The images won't show up on my bootstrap carousel or when I just use the  class to display the picture by itself. I am using bootstrap and express.
I have double checked that I am including the pathway to the image folder and I still do not know what is causing the issue.

Here is the index.html code where I am having the issue with the bootstrap carousel.

```<code>    <!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Sample website using Bootstrap and Express</title>

        <!---CDN LINKS-->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

        <script src="website.js"></script>
    </head>
    <body>
        <div>
            <div>
                <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="/">Home<span class="sr-only">(current)</span></a></li>
                        <li><a href="/gallery">Gallery</a></li>
                        <li><a href="/display">Display</a></li>
                        <li><a href="/about">About us</a></li>
                    </ul>
                </nav>
            </div>
            <br/>
            <div class="jumbotron"> <p>
            This is a place for some sample contant.
            </p>
            </div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <div id="myCarousel" class="carousel slide" data-ride="carousel">
                          <!-- Indicators -->
                          <ol class="carousel-indicators">
                            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                            <li data-target="#myCarousel" data-slide-to="1"></li>
                            <li data-target="#myCarousel" data-slide-to="2"></li>
                          </ol>

                          <!-- Wrapper for slides -->
                          <div class="carousel-inner" role="listbox">
                            <div class="item active">
                              <img src="images/pic1.png" alt="Picture 1">
                              <div class="carousel-caption">
                                <h3>Picture 1</h3>
                                <p>Add text here.</p>
                              </div>
                            </div>

                            <div class="item">
                              <img src="images/pic1.png" alt="Picture 2">
                              <div class="carousel-caption">
                                <h3>Picture 2</h3>
                                <p>Sample text.</p>
                              </div>
                            </div>

                            <div class="item">
                              <img src="images/pic1.png" alt="Picture 3">
                              <div class="carousel-caption">
                                <h3>Picture 3</h3>
                                <p>Sample text.</p>
                              </div>
                            </div>

                          <!-- Left and right controls -->
                          <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
                            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                            <span class="sr-only">Previous</span>
                          </a>
                          <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
                            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                            <span class="sr-only">Next</span>
                          </a>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

Here is the page where I just try to use the picture by itself, my gallery.html file.

```<code><html>
    <head>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
        <div>
            <div>
                <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
                    <ul class="nav navbar-nav">
                        <li><a href="/">Home</a></li>
                        <li class="active"><a href="/gallery">Gallery<span class="sr-only">(current)</span></a></li>
                        <li><a href="/display">Display</a></li>
                        <li><a href="/about">About us</a></li>
                    </ul>
                </nav>
            </div>
            <br/>
            <div class="jumbotron">
            <p>
            Put the gallery details here.
            </p>
            </div>
            <div class="container">
              <h2>Image</h2>
              <img src="Sketch.png" class="img-rounded" alt="Sample Picture" width="304" height="236">
            </div>
        </div>
    </body>
<html>
</code>```

And I am not sure if this is needed, but here is my website.js file in case.

```<code>var express = require('express');
var app = express();
var router = express.Router();

var path = __dirname + '/views/';

app.set('port', 8070);
app.use('/', router);

router.get('/', function(req, res){
    res.sendFile(path + 'index.html');
});

router.get('/gallery', function(req, res){
    res.sendFile(path + 'gallery.html');
});

router.get('/display', function(req, res){
    res.sendFile(path + 'display.html');
});

router.get('/about', function(req, res){
    res.sendFile(path + 'about.html');
});

app.use('*', function(req, res){
    res.send('Error 404: Not Found!');
});

app.listen(app.get('port'), function(){
    console.log('Express started on http://localhost:' + app.get('port') + ': press Ctrl-C to terminate.');
});
</code>```

So I have tried using .png and .jpg, neither worked. I have tried putting the images in an images folder and using images/pic1.png and that didnt work. I have tried /images/pic1.png and also ../images/pic1.png. I am not sure what the issue here is. Thank you.

答:
  All html's are in views, images are in images.

change the image src in the gallery to:  <img src="/images/Sketch.png"....

You should add an handler for the img files requested
(if you are using path.join require the path module).

one way of doing it is with the express.static function, by using it you are telling express to look for all of the requests with /images in the uri, in a specific directory, if not found it will proceed to the next handler.

```<code>   var express = require('express');
   var app = express();
   var router = express.Router();

   var path = require('path');
   var viewsPath = path.join(__dirname, 'views');

   app.set('port', 8070);
   //assuming that the images are in the 'images' directory
   app.use('/images' ,express.static('images'));

   app.use('/', router);

   router.get('/', function(req, res){
       res.sendFile(path.join(viewsPath,'index.html'));
   });

   router.get('/gallery', function(req, res){
      res.sendFile(path.join(viewsPath, 'gallery.html'));
   });

   router.get('/display', function(req, res){
      res.sendFile(path.join(viewsPath, 'display.html'));
   });

   router.get('/about', function(req, res){
     res.sendFile(path.join(viewsPath, 'about.html'));
   });

   app.use('*', function(req, res){
     res.send('Error 404: Not Found!');
   });

   app.listen(app.get('port'), function(){
       console.log('Express started on http://localhost:' + app.get('port') + ': press Ctrl-C to terminate.');
  });
</code>```

using express.static you can serve all static files from a given directory(relative to the directory from which you are running node), /images in this case.

https://expressjs.com/en/starter/static-files.html

Body:
The images won't show up on my bootstrap carousel or when I just use the  class to display the picture by itself. I am using bootstrap and express.
I have double checked that I am including the pathway to the image folder and I still do not know what is causing the issue.

Here is the index.html code where I am having the issue with the bootstrap carousel.

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Sample website using Bootstrap and Express</title>

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

Home(current)

Gallery

Display

About us

            This is a place for some sample contant.

Picture 1

Add text here.

Picture 2

Sample text.

Picture 3

Sample text.

                            Previous

                            Next

Here is the page where I just try to use the picture by itself, my gallery.html file.

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

Home

Gallery(current)

Display

About us

            Put the gallery details here.

Image

And I am not sure if this is needed, but here is my website.js file in case.

var express = require('express');
var app = express();
var router = express.Router();

var path = __dirname + '/views/';

app.set('port', 8070);
app.use('/', router);

router.get('/', function(req, res){
    res.sendFile(path + 'index.html');
});

router.get('/gallery', function(req, res){
    res.sendFile(path + 'gallery.html');
});

router.get('/display', function(req, res){
    res.sendFile(path + 'display.html');
});

router.get('/about', function(req, res){
    res.sendFile(path + 'about.html');
});

app.use('*', function(req, res){
    res.send('Error 404: Not Found!');
});

app.listen(app.get('port'), function(){
    console.log('Express started on http://localhost:' + app.get('port') + ': press Ctrl-C to terminate.');
});

So I have tried using .png and .jpg, neither worked. I have tried putting the images in an images folder and using images/pic1.png and that didnt work. I have tried /images/pic1.png and also ../images/pic1.png. I am not sure what the issue here is. Thank you.

Body:
  All html's are in views, images are in images.

change the image src in the gallery to:  <img src="/images/Sketch.png"....

You should add an handler for the img files requested
(if you are using path.join require the path module).

one way of doing it is with the express.static function, by using it you are telling express to look for all of the requests with /images in the uri, in a specific directory, if not found it will proceed to the next handler.

   var express = require('express');
   var app = express();
   var router = express.Router();

   var path = require('path');
   var viewsPath = path.join(__dirname, 'views');

   app.set('port', 8070);
   //assuming that the images are in the 'images' directory
   app.use('/images' ,express.static('images'));

   app.use('/', router);

   router.get('/', function(req, res){
       res.sendFile(path.join(viewsPath,'index.html'));
   });

   router.get('/gallery', function(req, res){
      res.sendFile(path.join(viewsPath, 'gallery.html'));
   });

   router.get('/display', function(req, res){
      res.sendFile(path.join(viewsPath, 'display.html'));
   });

   router.get('/about', function(req, res){
     res.sendFile(path.join(viewsPath, 'about.html'));
   });

   app.use('*', function(req, res){
     res.send('Error 404: Not Found!');
   });

   app.listen(app.get('port'), function(){
       console.log('Express started on http://localhost:' + app.get('port') + ': press Ctrl-C to terminate.');
  });

using express.static you can serve all static files from a given directory(relative to the directory from which you are running node), /images in this case.

https://expressjs.com/en/starter/static-files.html


问:
C - Creating animation in terminal - auto-updating 2D array
I'm trying to make an animation which will make a basic circle from dots. I got stuck, because i do not know how to make an array to auto-update herself to make an animation. My program has an issue, because it shows only the last point on circle and other, previous points has vanished due to system("clear") command, but i do not know how to make it the proper way.
Thanks in advance!</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void){

char tab[43][132];
int a, b, t;
double x_kropki, y_kropki;

for (t=0 ; t<360 ; t++) {
    x_kropki=floor(10*cos((t*pi)/180))+60;
    y_kropki=floor(10*sin((t*pi)/180))+20;
    for (a=0 ; a<43 ; a++, printf("\n")) for (b=0 ; b<132 ; b++) {
    if ((int)y_kropki==a && (int)x_kropki==b){
        tab[a][b]='.';
        printf("%c", tab[a][b]);
        }else {
            tab[a][b]=' ';
            printf("%c", tab[a][b]);
        }
    }
    system("clear");
}

return 0;
}
</code>```

答:
What is the animation supposed to look like? Do you want the circle to grow slowly? Then you need to add a delay (sleep or similar) or else it will finish the whole process too quickly for the screen to draw and for your eyes to notice.

Also you should not clear the progress after every new dot (of the 360 dots in total, it seems). To achieve that, you will need to change your approach a bit. Here's what the loop could look like:

Draw nothing

Draw dot 1

Clear

Draw dot 1 and 2

Clear

Draw dot 1 and 2 and 3

You see that after clearing, you need to repeat printing the progress so far. At loop iteration 180, you need to print the last 179 dots again plus the 180th. Wait a few milliseconds, then clear, then the same for 181.

How you do that? You repeat the for loop:

```<code>int dot, maxDots;
for (maxDots = 0; maxDots < 360; maxDots++) {
    for (dot = 0; dot < maxDots; dot++) {
        // your location calculations and printing for each dot
    }
    system("clear");
 }
</code>```

This should at least give you some kind of growing circle. But you will notice that the printing approach is hard to get right, because once a line has been finished, you cannot go back.  If you start at the top and go your way around 180 degrees, down line by line, you will then need to go up line by line until you reach the top again. That won't work easily. Instead of printing directly, as @Weather Vane suggested, store the to-be-printed result of each animation stage in a buffer. That is an abstraction of on-screen coordinates. A very simple approach would be a two-dimensional array that you can manipulate freely, then print the whole array en bloc.

Body:
I'm trying to make an animation which will make a basic circle from dots. I got stuck, because i do not know how to make an array to auto-update herself to make an animation. My program has an issue, because it shows only the last point on circle and other, previous points has vanished due to system("clear") command, but i do not know how to make it the proper way.
Thanks in advance!

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

int main(void){

char tab[43][132];
int a, b, t;
double x_kropki, y_kropki;

for (t=0 ; t<360 ; t++) {
    x_kropki=floor(10*cos((t*pi)/180))+60;
    y_kropki=floor(10*sin((t*pi)/180))+20;
    for (a=0 ; a<43 ; a++, printf("\n")) for (b=0 ; b<132 ; b++) {
    if ((int)y_kropki==a && (int)x_kropki==b){
        tab[a][b]='.';
        printf("%c", tab[a][b]);
        }else {
            tab[a][b]=' ';
            printf("%c", tab[a][b]);
        }
    }
    system("clear");
}

return 0;
}

Body:
What is the animation supposed to look like? Do you want the circle to grow slowly? Then you need to add a delay (sleep or similar) or else it will finish the whole process too quickly for the screen to draw and for your eyes to notice.

Also you should not clear the progress after every new dot (of the 360 dots in total, it seems). To achieve that, you will need to change your approach a bit. Here's what the loop could look like:

Draw nothing

Draw dot 1

Clear

Draw dot 1 and 2

Clear

Draw dot 1 and 2 and 3

You see that after clearing, you need to repeat printing the progress so far. At loop iteration 180, you need to print the last 179 dots again plus the 180th. Wait a few milliseconds, then clear, then the same for 181.

How you do that? You repeat the for loop:

int dot, maxDots;
for (maxDots = 0; maxDots < 360; maxDots++) {
    for (dot = 0; dot < maxDots; dot++) {
        // your location calculations and printing for each dot
    }
    system("clear");
 }

This should at least give you some kind of growing circle. But you will notice that the printing approach is hard to get right, because once a line has been finished, you cannot go back.  If you start at the top and go your way around 180 degrees, down line by line, you will then need to go up line by line until you reach the top again. That won't work easily. Instead of printing directly, as @Weather Vane suggested, store the to-be-printed result of each animation stage in a buffer. That is an abstraction of on-screen coordinates. A very simple approach would be a two-dimensional array that you can manipulate freely, then print the whole array en bloc.


问:
oserror python 3.5.4 on win 10 1709 when using nosetest or print
Since I upgraded my win 10 version 1703 to version 1709 (Fall Update), I have a persistent problem OSError when using print or nose command. My log with nose:

```<code>======================================================================
ERROR: test_future_link_to_update_3
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\case.py", line 134, in run
    self.runTest(result)
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\case.py", line 152, in runTest
    test(result)
  File "c:\program files\python35\Lib\unittest\case.py", line 653, in __call__
    return self.run(*args, **kwds)
  File "c:\program files\python35\Lib\unittest\case.py", line 621, in run
    result.addSuccess(self)
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\proxy.py", line 165, in addSuccess
    self.result.addSuccess(self.test)
  File "c:\program files\python35\Lib\unittest\runner.py", line 64, in addSuccess
    self.stream.flush()
OSError: raw write() returned invalid length 2 (should have been between 0 and 1)
</code>```

I can pass this problem by commenting self.stream.flush() but it's not a solution:

```<code>def addSuccess(self, test):
    super(TextTestResult, self).addSuccess(test)
    if self.showAll:
       self.stream.writeln("ok")
    elif self.dots:
       self.stream.write('.')
       # self.stream.flush()
</code>```

Other log when using print:

```<code>Traceback (most recent call last):
  File "c:\program files\python35\Lib\multiprocessing\pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "c:\program files\python35\Lib\multiprocessing\pool.py", line 47, in starmapstar
    return list(itertools.starmap(args[0], args[1]))
  File "C:\Users\SDN\Work\git\pop-extrapole\extrapolation\extrapole.py", line 1463, in popcorn_process
    print(lk)
OSError: raw write() returned invalid length 46 (should have been between 0 and 23)
</code>```

Does anyone have an idea about that?

Thanks,
Uwevil

答:
Do you use the bash of "Git for Windows"?

If you use, Try to add the administrator rights to the property settings of  \Program Files\Git\git-bash.exeand \Program Files\Git\usr\bin\bash.exe.

I could solved by it. But I think that this is not best solution.

And the other solution is the using PowerShell.

Body:
Since I upgraded my win 10 version 1703 to version 1709 (Fall Update), I have a persistent problem OSError when using print or nose command. My log with nose:

======================================================================
ERROR: test_future_link_to_update_3
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\case.py", line 134, in run
    self.runTest(result)
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\case.py", line 152, in runTest
    test(result)
  File "c:\program files\python35\Lib\unittest\case.py", line 653, in __call__
    return self.run(*args, **kwds)
  File "c:\program files\python35\Lib\unittest\case.py", line 621, in run
    result.addSuccess(self)
  File "c:\users\sdn\work\git\pop-extrapole\env\lib\site-packages\nose\proxy.py", line 165, in addSuccess
    self.result.addSuccess(self.test)
  File "c:\program files\python35\Lib\unittest\runner.py", line 64, in addSuccess
    self.stream.flush()
OSError: raw write() returned invalid length 2 (should have been between 0 and 1)

I can pass this problem by commenting self.stream.flush() but it's not a solution:

def addSuccess(self, test):
    super(TextTestResult, self).addSuccess(test)
    if self.showAll:
       self.stream.writeln("ok")
    elif self.dots:
       self.stream.write('.')
       # self.stream.flush()

Other log when using print:

Traceback (most recent call last):
  File "c:\program files\python35\Lib\multiprocessing\pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "c:\program files\python35\Lib\multiprocessing\pool.py", line 47, in starmapstar
    return list(itertools.starmap(args[0], args[1]))
  File "C:\Users\SDN\Work\git\pop-extrapole\extrapolation\extrapole.py", line 1463, in popcorn_process
    print(lk)
OSError: raw write() returned invalid length 46 (should have been between 0 and 23)

Does anyone have an idea about that?

Thanks,
Uwevil


问:
How to read blob (pickle) files from GCS in a Google Cloud DataFlow job?
I try to run a DataFlow pipeline remotely which will use a pickle file.
Locally, I can use the code below to invoke the file.

```<code>with open (known_args.file_path, 'rb') as fp:
     file = pickle.load(fp)
</code>```

However, I find it not valid when the path is about cloud storage(gs://...):

```<code>IOError: [Errno 2] No such file or directory: 'gs://.../.pkl'
</code>```

I kind of understand why it is not working but I cannot find the right way to do it.

答: open() is the standard Python library function that does not understand Google Cloud Storage paths. You need to use the Beam FileSystems API instead, which is aware of it and of other filesystems supported by Beam.

Body:
I try to run a DataFlow pipeline remotely which will use a pickle file.
Locally, I can use the code below to invoke the file.

with open (known_args.file_path, 'rb') as fp:
     file = pickle.load(fp)

However, I find it not valid when the path is about cloud storage(gs://...):

IOError: [Errno 2] No such file or directory: 'gs://.../.pkl'

I kind of understand why it is not working but I cannot find the right way to do it.


问:
Rails 4: schema.db shows "Could not dump table "events" because of following NoMethodError# undefined method `[]' for nil:NilClass"
I've been working on a Rails 4.0 application with sqlite (default for Rails development environment) for events (hackathons) which has a parent model, Event, for which there can be many Press_Blurbs.

First I ran some scaffolding generators which created some migrations that I ran seemingly without issue:

```<code>class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :city
      t.string :theme
      t.datetime :hackathon_start
      t.datetime :hackathon_end
      t.datetime :show_start
      t.datetime :show_end
      t.text :about
      t.string :hack_rsvp_url
      t.string :show_rsvp_url

      t.timestamps
    end
  end
end

class CreatePressBlurbs < ActiveRecord::Migration
  def change
    create_table :press_blurbs do |t|
      t.string :headline
      t.string :source_name
      t.string :source_url
      t.string :logo_uri

      t.timestamps
    end
  end
end
</code>```

Then I added some relationships to the models:

```<code>class Event < ActiveRecord::Base
  has_many :press_blurbs
end

class PressBlurb < ActiveRecord::Base
  belongs_to :event
end
</code>```

...and added/ran a migration to add a table reference:

```<code>class AddEventRefToPressBlurbs < ActiveRecord::Migration
  def change
    add_column :press_blurbs, :event, :reference
  end
end
</code>```

Nevertheless, when I look at schema.db this is what I see instead of tables definitions:

```<code># Could not dump table "events" because of following NoMethodError
#   undefined method `[]' for nil:NilClass

# Could not dump table "press_blurbs" because of following NoMethodError
#   undefined method `[]' for nil:NilClass
</code>```

Other unrelated tables show up in schema.rb perfectly fine, but these do not. Any idea what's going on?

答: Just in case this helps someone. I was doing this on a sqlite dev db, and as mentioned above, it was likely in a wonky state from all my experimental migrations. By deleting the sqlite file, recreating and running all the migrations, it is now fine.</p>

Body:
I've been working on a Rails 4.0 application with sqlite (default for Rails development environment) for events (hackathons) which has a parent model, Event, for which there can be many Press_Blurbs.

First I ran some scaffolding generators which created some migrations that I ran seemingly without issue:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :city
      t.string :theme
      t.datetime :hackathon_start
      t.datetime :hackathon_end
      t.datetime :show_start
      t.datetime :show_end
      t.text :about
      t.string :hack_rsvp_url
      t.string :show_rsvp_url

      t.timestamps
    end
  end
end

class CreatePressBlurbs < ActiveRecord::Migration
  def change
    create_table :press_blurbs do |t|
      t.string :headline
      t.string :source_name
      t.string :source_url
      t.string :logo_uri

      t.timestamps
    end
  end
end

Then I added some relationships to the models:

class Event < ActiveRecord::Base
  has_many :press_blurbs
end

class PressBlurb < ActiveRecord::Base
  belongs_to :event
end

...and added/ran a migration to add a table reference:

class AddEventRefToPressBlurbs < ActiveRecord::Migration
  def change
    add_column :press_blurbs, :event, :reference
  end
end

Nevertheless, when I look at schema.db this is what I see instead of tables definitions:

# Could not dump table "events" because of following NoMethodError
#   undefined method `[]' for nil:NilClass

# Could not dump table "press_blurbs" because of following NoMethodError
#   undefined method `[]' for nil:NilClass

Other unrelated tables show up in schema.rb perfectly fine, but these do not. Any idea what's going on?


问:
Javascript onclick event for text
I have an array of objects in Javascript that I'm displaying with document.write, where each element of the array has a single character that can be used to display it.

Is it possible to have an onclick event that modifies the data in the array?

```<code>var initializeArray = function(){
    for(var i = 0; i < HEIGHT; i++){
        maze[i] = new Array(WIDTH)
    }

    //Initialize all to walls
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            maze[i][j] = new Cell(cellType.WALL);
            maze[i][j].onclick = cycle; //The line in question that does not work
        }
    }
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            document.write(symbols[maze[i][j].type]);
        }
        document.write("<br>");
    }
}
</code>```

In the above, the WALL character is represented by a #, and the cycle() function changes a # to a space, and vice-versa.

I'm not sure how to connect the document.write symbol to the underlying data in the array.

答:
I was able to solve this by writing an HTML element with an onclick function instead of just a piece of text:</p>

```<code>var printCell = function(cell){
    document.write("<span class='cell' onClick='cycle(this)'>" + symbols[cell.type]) + "</span>";
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            printCell(maze[i][j]);
        }
        document.write("<br>");
    }
}
</code>```

Title: Javascript onclick event for text

Body:
I have an array of objects in Javascript that I'm displaying with document.write, where each element of the array has a single character that can be used to display it.

Is it possible to have an onclick event that modifies the data in the array?

var initializeArray = function(){
    for(var i = 0; i < HEIGHT; i++){
        maze[i] = new Array(WIDTH)
    }

    //Initialize all to walls
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            maze[i][j] = new Cell(cellType.WALL);
            maze[i][j].onclick = cycle; //The line in question that does not work
        }
    }
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            document.write(symbols[maze[i][j].type]);
        }
        document.write("
");
    }
}

In the above, the WALL character is represented by a #, and the cycle() function changes a # to a space, and vice-versa.

I'm not sure how to connect the document.write symbol to the underlying data in the array.

Body:
I was able to solve this by writing an HTML element with an onclick function instead of just a piece of text:

var printCell = function(cell){
    document.write("<span class='cell' onClick='cycle(this)'>" + symbols[cell.type]) + "</span>";
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            printCell(maze[i][j]);
        }
        document.write("<br>");
    }
}


问:
using async pipe to the property on template
```<code>export class MyClass {
    data: MyData;
    constructor(private dataService: DataService) {
      this.dataService.getData().subscribe((myData) => {
        this.data = myData;
      });
    }
}
</code>```

data is successfully retrieved trough web service. MyData object has property firstName which I want to represent inside template using async pipe.

I tried with

```<code><input required [ngModel]="data.firstName | async" (ngModelChange)="onChange($event)" name="firstName">
</code>```

this approach doesn't bind property to the template at all, [(ngModel)]="data.firstName" works but I've been told that this approach cannot be used together with async pipe.

Update:

```<code>getData(): Observable<MyData>{
        return Observable.from([this.fakeData()]
            .map(res=>res as MyData));
    }
</code>```

答:
Either use

```<code>export class MyClass {
    data: Promise;
    constructor(private dataService: DataService) {
      this.data = this.dataService.getData()
    }
}
</code>```

The | async pipe is already the subscribing

with

```<code><input required [ngModel]="(data | async)?.firstName" (ngModelChange)="onChange($event)" name="firstName">
</code>```

or with your code

```<code><input required [ngModel]="data?.firstName" (ngModelChange)="onChange($event)" name="firstName">
</code>```

where I just added ? to avoid an error while the data is not yet available.

Body:
export class MyClass {
    data: MyData;
    constructor(private dataService: DataService) {
      this.dataService.getData().subscribe((myData) => {
        this.data = myData;
      });
    }
}

data is successfully retrieved trough web service. MyData object has property firstName which I want to represent inside template using async pipe.

I tried with

<input required [ngModel]="data.firstName | async" (ngModelChange)="onChange($event)" name="firstName">

this approach doesn't bind property to the template at all, [(ngModel)]="data.firstName" works but I've been told that this approach cannot be used together with async pipe.

Update:

getData(): Observable<MyData>{
        return Observable.from([this.fakeData()]
            .map(res=>res as MyData));
    }

Body:
Either use

export class MyClass {
    data: Promise;
    constructor(private dataService: DataService) {
      this.data = this.dataService.getData()
    }
}

The | async pipe is already the subscribing

with

<input required [ngModel]="(data | async)?.firstName" (ngModelChange)="onChange($event)" name="firstName">

or with your code

<input required [ngModel]="data?.firstName" (ngModelChange)="onChange($event)" name="firstName">

where I just added ? to avoid an error while the data is not yet available.


问:
Using a Chrome extension to insert characters into sites such as Facebook
I have created a chrome extension to allow users to right-click in a textbox, and insert special characters. This works on many sites such as StackOverflow, but does not work on sites such as Facebook. This is because Facebook is not using a standard text box form control. Instead for each line in a text message, it seems to be using a div > div > span > span construct. Is there a way to create a Chrome extension to target page components such as this?

An portion of my Chrome extension code looks like this:

main.js:

```<code>chrome.contextMenus.create({
  title: "\u038F",
  contexts:["editable"],
  onclick: function(info, tab){
      chrome.tabs.sendMessage(tab.id, {action: "insertCharacter", character: '\u038F'});
  }
});
</code>```

content.js

```<code>chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    var objField = document.activeElement;

    if (request.action == "insertCharacter"){
        insertAtCursor(objField, request.character);
    }
});

function insertAtCursor(sField, sValue){
    if (sField.selectionStart || sField.selectionStart == '0'){
        var nStart = sField.selectionStart;
        var nEnd = sField.selectionEnd;

        sField.value = sField.value.substring(0, nStart) + sValue + sField.value.substring(nEnd, sField.value.length);
        sField.selectionStart = nStart + sValue.length;
        sField.selectionEnd = nStart + sValue.length;
    }
    else {
        sField.value += sValue;
    }
}
</code>```

Is there a more general purpose way I can do this to handle various situations on different sites? If not, is there a way to specifically target Facebook as most of the time myself (and likely others) are going to be using my extension on Facebook. (Of course having it work for email sites such as GMail would be a benefit as well).

答:
In case it helps someone else, this is what I modified my code to based on wOxxOm's suggestion:

```<code>chrome.extension.onMessage.addListener(function(request, sender, sendResponse){

    if (request.action == "insertCharacter"){
        insertAtCursor(request.character);
    }

});

function insertAtCursor(sValue){
    document.execCommand("insertText", false, sValue);
}
</code>```

It's much more compact than my original approach and insertText handles the selection aspect automatically.

Body:
I have created a chrome extension to allow users to right-click in a textbox, and insert special characters. This works on many sites such as StackOverflow, but does not work on sites such as Facebook. This is because Facebook is not using a standard text box form control. Instead for each line in a text message, it seems to be using a div > div > span > span construct. Is there a way to create a Chrome extension to target page components such as this?

An portion of my Chrome extension code looks like this:

main.js:

chrome.contextMenus.create({
  title: "\u038F",
  contexts:["editable"],
  onclick: function(info, tab){
      chrome.tabs.sendMessage(tab.id, {action: "insertCharacter", character: '\u038F'});
  }
});

content.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    var objField = document.activeElement;

    if (request.action == "insertCharacter"){
        insertAtCursor(objField, request.character);
    }
});

function insertAtCursor(sField, sValue){
    if (sField.selectionStart || sField.selectionStart == '0'){
        var nStart = sField.selectionStart;
        var nEnd = sField.selectionEnd;

        sField.value = sField.value.substring(0, nStart) + sValue + sField.value.substring(nEnd, sField.value.length);
        sField.selectionStart = nStart + sValue.length;
        sField.selectionEnd = nStart + sValue.length;
    }
    else {
        sField.value += sValue;
    }
}

Is there a more general purpose way I can do this to handle various situations on different sites? If not, is there a way to specifically target Facebook as most of the time myself (and likely others) are going to be using my extension on Facebook. (Of course having it work for email sites such as GMail would be a benefit as well).

Body:
In case it helps someone else, this is what I modified my code to based on wOxxOm's suggestion:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){

    if (request.action == "insertCharacter"){
        insertAtCursor(request.character);
    }

});

function insertAtCursor(sValue){
    document.execCommand("insertText", false, sValue);
}

It's much more compact than my original approach and insertText handles the selection aspect automatically.


问:
is a reduction in free disk space a good overall indicator of a `work_mem` setting that is too low?
As I understand it (after a fair amount of searching online)...

1- If a component of a query (sort, join, etc.) uses more RAM/memory than my work_mem setting or the total memory used by all current operations on the server exceeds available OS memory, the query will start writing to disk.

Is that true?

2- Postgres (and many other good DB engines) use memory to cache a lot so queries go faster; therefore, the server should indicate low free memory even if the server isn't really starved for memory. So low free memory doesn't really indicate anything other than a good DB engine and healthy utilization.

Is that true?

3- If both #1 and #2 above are true, holding everything else content, if I want a board indicator of a work_mem setting that is too low or not enough overall OS memory, I should look to see if the server free disk space is going down?

Am I thinking about this correctly?

links:

https://www.postgresql.org/docs/current/static/runtime-config-resource.html

http://patshaughnessy.net/2016/1/22/is-your-postgres-query-starved-for-memory

https://www.enterprisedb.com/monitor-cpu-and-memory-percentage-used-each-process-postgresqlppas-9

https://dba.stackexchange.com/questions/18484/tuning-postgresql-for-large-amounts-of-ram

I know I can set log_temp_files and look at individual temp files to tune the work_mem setting, but I wanted an overall gauge I could use to determine if possibly work_mem is too low before I start digging around looking at temp file sizes that exceed my work_mem setting.

I have PostgreSQL 10.

答:
Processing a query takes a number of steps:

generate (all)possible plans

estimate the cost of execution of these plans (in terms of resources: disk I/O,buffers,memory,CPU), based on tuning constants and statistics.

pick the "optimal" plan , based on tuning constants

execute the chosen plan.

In most cases, a plan that is expected (step2) to need more work_mem than your work_mem setting will not be chosen in step3. (because "spilling to disk" is considered very expensive)
Once step4 detects that it is needing more work_mem, its only choice is to spill to disk. Shit happens... At least this doesn't rely on the OS's page-swapping the the overcommitted memory.)

The rules are very simple:

hash-joins are often optimal but will cost memory

don't try to use more memory than you have

if there is a difference between expected(step2) and observed(step4) memory, your statistics are wrong. You will be punished by spill-to-disk.

a lack of usable indexes will cause hash joins or seqscans.

sorting uses work_mem, too. The mechanism is similar :bad estimates yield bad plans.

CTE's are often/allways(?) materialized. This will splill to disk once your bufferspace overflows.

CTE's don't have statistics, and don't have indices.

A few guidelines/advice:

use a correct data model (and don't denormalize)

use the correct PK/FK's and secundary indices.

run ANALYZE the_table_name; to gather fresh statistics after huge modifications to the table's structure or data.

Monitoring:

check the Postgres logfile

check the query plan, compare observed <--> expected

monitor the system resource usage (on Linux: via top/vmstat/iostat)


问:
Count matches at the end of a string
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

```<code>e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0
</code>```

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

```<code>var occurrences = string.match(/(-1)*$/).length;
</code>```

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.

答:
Walk backwards and count?

var string = "2-1-1-1-1";
var find =   "-1";
var match =  0;

for (var i = string.length; i >= 0; i -= find.length) {
  if (string.substr(i - find.length, find.length) == find)
    match++;
  else
    break;
}

console.log("="+match)```

Title: Count matches at the end of a string

Body:
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

var occurrences = string.match(/(-1)*$/).length;

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.


问:
Processing a Django UploadedFile as UTF-8 with universal newlines
In my django application, I provide a form that allows users to upload a file. The file can be in a variety of formats (Excel, CSV), come from a variety of platforms (Mac, Linux, Windows), and be encoded in a variety of encodings (ASCII, UTF-8).

For the purpose of this question, let's assume that I have a view which is receiving request.FILES['file'], which is an instance of InMemoryUploadedFile, called file. My problem is that InMemoryUploadedFile objects (like file):

Do not support UTF-8 encoding (I see a \xef\xbb\xbf at the beginning of the file, which as I understand is a flag meaning 'this file is UTF-8').

Do not support universal newlines (which probably the majority of the files uploaded to this system will need).

Complicating the issue is that I wish to pass the file in to the python csv module, which does not natively support Unicode. I will happily accept answers that avoid this issue - once I get django playing nice with UTF-8 I'm sure I can bludgeon csv into doing the same. (Similarly, please ignore the requirement to support Excel - I am waiting until CSV works before I tackle parsing Excel files.)

I have tried using StringIO,mmap,codec, and any of a wide variety of ways of accessing the data in an InMemoryUploadedFile object. Each approach has yielded differing errors, none so far have been perfect. This shows some of the code that I feel came the closest:

```<code>import csv
import codecs

class CSVParser:
    def __init__(self,file):
        # 'file' is assumed to be an InMemoryUploadedFile object.
        dialect = csv.Sniffer().sniff(codecs.EncodedFile(file,"utf-8").read(1024))
        file.open() # seek to 0
        self.reader = csv.reader(codecs.EncodedFile(file,"utf-8"),
                                 dialect=dialect)
        try:
            self.field_names = self.reader.next()
        except StopIteration:
            # The file was empty - this is not allowed.
            raise ValueError('Unrecognized format (empty file)')

        if len(self.field_names) <= 1:
            # This probably isn't a CSV file at all.
            # Note that the csv module will (incorrectly) parse ALL files, even
            # binary data. This will catch most such files.
            raise ValueError('Unrecognized format (too few columns)')

        # Additional methods snipped, unrelated to issue
</code>```

Please note that I haven't spent too much time on the actual parsing algorithm so it may be wildly inefficient, right now I'm more concerned with getting encoding to work as expected.

The problem is that the results are also not encoded, despite being wrapped in the Unicode codecs.EncodedFile file wrapper.

EDIT: It turns out, the above code does in fact work. codecs.EncodedFile(file,"utf-8") is the ticket. It turns out the reason I thought it didn't work was that the terminal I was using does not support UTF-8. Live and learn!

答:
As mentioned above, the code snippet I provided was in fact working as intended - the problem was with my terminal, and not with python encoding.

If your view needs to access a UTF-8 UploadedFile, you can just use utf8_file = codecs.EncodedFile(request.FILES['file_field'],"utf-8") to open a file object in the correct encoding.

I also noticed that, at least for InMemoryUploadedFiles, opening the file through the codecs.EncodedFile wrapper does NOT reset the seek() position of the file descriptor. To return to the beginning of the file (again, this may be InMemoryUploadedFile specific) I just used request.FILES['file_field'].open() to send the seek() position back to 0.

Body:
In my django application, I provide a form that allows users to upload a file. The file can be in a variety of formats (Excel, CSV), come from a variety of platforms (Mac, Linux, Windows), and be encoded in a variety of encodings (ASCII, UTF-8).

For the purpose of this question, let's assume that I have a view which is receiving request.FILES['file'], which is an instance of InMemoryUploadedFile, called file. My problem is that InMemoryUploadedFile objects (like file):

Do not support UTF-8 encoding (I see a \xef\xbb\xbf at the beginning of the file, which as I understand is a flag meaning 'this file is UTF-8').

Do not support universal newlines (which probably the majority of the files uploaded to this system will need).

Complicating the issue is that I wish to pass the file in to the python csv module, which does not natively support Unicode. I will happily accept answers that avoid this issue - once I get django playing nice with UTF-8 I'm sure I can bludgeon csv into doing the same. (Similarly, please ignore the requirement to support Excel - I am waiting until CSV works before I tackle parsing Excel files.)

I have tried using StringIO,mmap,codec, and any of a wide variety of ways of accessing the data in an InMemoryUploadedFile object. Each approach has yielded differing errors, none so far have been perfect. This shows some of the code that I feel came the closest:

import csv
import codecs

class CSVParser:
    def __init__(self,file):
        # 'file' is assumed to be an InMemoryUploadedFile object.
        dialect = csv.Sniffer().sniff(codecs.EncodedFile(file,"utf-8").read(1024))
        file.open() # seek to 0
        self.reader = csv.reader(codecs.EncodedFile(file,"utf-8"),
                                 dialect=dialect)
        try:
            self.field_names = self.reader.next()
        except StopIteration:
            # The file was empty - this is not allowed.
            raise ValueError('Unrecognized format (empty file)')

        if len(self.field_names) <= 1:
            # This probably isn't a CSV file at all.
            # Note that the csv module will (incorrectly) parse ALL files, even
            # binary data. This will catch most such files.
            raise ValueError('Unrecognized format (too few columns)')

        # Additional methods snipped, unrelated to issue

Please note that I haven't spent too much time on the actual parsing algorithm so it may be wildly inefficient, right now I'm more concerned with getting encoding to work as expected.

The problem is that the results are also not encoded, despite being wrapped in the Unicode codecs.EncodedFile file wrapper.

EDIT: It turns out, the above code does in fact work. codecs.EncodedFile(file,"utf-8") is the ticket. It turns out the reason I thought it didn't work was that the terminal I was using does not support UTF-8. Live and learn!

ContentLicense: CC BY-SA 2.5


问:
Basic Auth on Apache Forward Proxy
Website X is a public site that can be accessed only via Basic Authentication. Once I browse to it, I'll be prompted with a dialog box where I need to type in my username and password to authorize myself and access the website. With that said, I'm looking into setting up a forward proxy using Apache to do the Basic-Auth automatically, so I don't get prompted each time I access the site.

I've configured a forward proxy using Apache 2.4, and it seems to work fine as a forward proxy, as I could access HTTP and HTTPS websites through it. However, the Basic-Auth I'm trying to do on the X website, doesn't work. I still get the dialog box each time I navigate to the site.

In the "httpd.conf", I tried multiple configurations, one example is:

```<code>AuthType Basic
AuthName "Restricted Site"
# (Following line optional)
AuthBasicProvider file
AuthUserFile password.file
Require valid-user
</code>```

Mentioning that the password.file contains my username and password as a result of executing the command line:

```<code>htpasswd -c password.file MyUser
</code>```

The Apache starts successfully without throwing any errors.

IMHO, what I'm trying to do sounds technically possible. However, after several hours of trial and error, it doesn't seem as easy as I thought it would be. Suggestions?

答:
[You] --a--> [Forward Proxy] --b--> [Server]

If you in connection b have to use Basic auth and don't want to use it in connection a. you can use RequestHeader set Authorization "Basic ..." to add the Authorization header to all requests.

Title: Basic Auth on Apache Forward Proxy

Body:
Website X is a public site that can be accessed only via Basic Authentication. Once I browse to it, I'll be prompted with a dialog box where I need to type in my username and password to authorize myself and access the website. With that said, I'm looking into setting up a forward proxy using Apache to do the Basic-Auth automatically, so I don't get prompted each time I access the site.

I've configured a forward proxy using Apache 2.4, and it seems to work fine as a forward proxy, as I could access HTTP and HTTPS websites through it. However, the Basic-Auth I'm trying to do on the X website, doesn't work. I still get the dialog box each time I navigate to the site.

In the "httpd.conf", I tried multiple configurations, one example is:

AuthType Basic
AuthName "Restricted Site"
# (Following line optional)
AuthBasicProvider file
AuthUserFile password.file
Require valid-user

Mentioning that the password.file contains my username and password as a result of executing the command line:

htpasswd -c password.file MyUser

The Apache starts successfully without throwing any errors.

IMHO, what I'm trying to do sounds technically possible. However, after several hours of trial and error, it doesn't seem as easy as I thought it would be. Suggestions?


问:
"Is not a working copy" error when trying to commit SVN
I'm so confused about this.. I think there's something missing in the error that could help, but I'm not sure.

When trying to commit to an SVN repository, NetBeans is returning this error:

org.apache.subversion.javahl.ClientException: E155007: {0} is not a
  working copy

Upon reading up, I've tried several things, including Updating, Cleaning Up, and Checking out.. (checking out actually screwed things up a fair bit and duplicated my project).

But all of them, still return the error. I believe the {0} part is meant to be showing a file that isn't under version control, is that correct?

Not sure where to go from here, and I can't make any more commits. If possible, I don't want to have to just abandon, and create a new project and SVN repository from scratch.

My Netbeans SVN properties shows this:

答: I ran into this when my project wasn't set up correctly on the SVN server.  Make sure to check-out your project, merge as needed, THEN commit.</p>


答:
Try this. This runs Ok for all of your tested values

function countOnesAtTheEnd(s){
var array = s.split("-");

var count = 0;
for(var i =1; i<array.length; i++)
{
if(array[i] =="1"){
 count++;
 }
 else count = 0;

}
console.log(count);
}
countOnesAtTheEnd("1");
countOnesAtTheEnd("1-1");
countOnesAtTheEnd("1-1-1");
countOnesAtTheEnd("1-2-1");
countOnesAtTheEnd("1-2-1-2-1");
countOnesAtTheEnd("2-1-1-1-1");
countOnesAtTheEnd("1-1-2");```

Title: Count matches at the end of a string


问:
setting empty value inside select if is empty select AngularJS
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

```<code>demo
</code>```

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

```<code>    <div ng-app="test" ng-controller="select">
  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>
</div>
</code>```

答:
```<code><option ng-repeat=" item in downloadsLists" >{{$index || "n/a"}}</option>
</code>```

Body:
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

demo

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>


问:
Print out an array in uppercase Java
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

```<code>package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}
</code>```

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

答:
You can use toUpperCase() to get in upper case.

Your code is too big and not efficient. you should use loop for this. How about making it shorter like below:

```<code>public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n");
        // create scanner object to get user input

        Scanner userInput = new Scanner(System.in);
        for(int i=1;i<=10;i++)
        {
            System.out.println(i+": ");
            names10[i-1] = userInput.nextLine().toUpperCase();
        }

        for(int i =1;i<=10;i++)
            System.out.println(names10[i-1]);
    }
</code>```

Title: Print out an array in uppercase Java

Body:
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

Body:
You can use toUpperCase() to get in upper case.

Your code is too big and not efficient. you should use loop for this. How about making it shorter like below:

public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n");
        // create scanner object to get user input

        Scanner userInput = new Scanner(System.in);
        for(int i=1;i<=10;i++)
        {
            System.out.println(i+": ");
            names10[i-1] = userInput.nextLine().toUpperCase();
        }

        for(int i =1;i<=10;i++)
            System.out.println(names10[i-1]);
    }


问:
Hackerrank Objective-c int pointer not correct value
If I want an int of an array from an index like: "int value = ar[n]", I always getting huge integers. Which represent the max size of it (I think).

Input (stdin)

```<code>4
3 2 1 3
</code>```

Code:

```<code>int main(int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int n;
    scanf("%i",&n);
    int ar[n];

    int counter = 0;
    int tempValue;

    for(int ar_i = 0; ar_i < n; ar_i++){

       int value = ar[ar_i];

        if(tempValue < ar[ar_i]){

            counter = 1;
            tempValue = ar[ar_i];
            printf("%i", tempValue);
        }else if(tempValue == value){

            counter = counter + 1;
        }
    }

    [pool drain];
    return 0;
}
</code>```

printf("%i", tempValue); for example gives an output "1598483120".
Casting any object to (int) doesn't help.

Did I do something wrong? Or what is going on?

答:
You define int ar[n], but you do not initialize it with values. Accessing uninitialized variables, as you do when writing int value = ar[ar_i] then, is undefined behaviour; this often leads to "garbage" values, though other behaviour is - of course - possible as well. The same applies to variable tempValue.

So always initialize your variables before accessing them, e.g. with for (int i=0; i<n; i++) arr[i] = 0; and int tempValue=0.

Note further that - if you are using objective-c - your IDE (XCode probably) might not use C but C++ for your .mm-source file; Then a variable-length-array like int arr[n] may not be supported.

Body:
If I want an int of an array from an index like: "int value = ar[n]", I always getting huge integers. Which represent the max size of it (I think).

Input (stdin)

4
3 2 1 3

Code:

int main(int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int n;
    scanf("%i",&n);
    int ar[n];

    int counter = 0;
    int tempValue;

    for(int ar_i = 0; ar_i < n; ar_i++){

       int value = ar[ar_i];

        if(tempValue < ar[ar_i]){

            counter = 1;
            tempValue = ar[ar_i];
            printf("%i", tempValue);
        }else if(tempValue == value){

            counter = counter + 1;
        }
    }

    [pool drain];
    return 0;
}

printf("%i", tempValue); for example gives an output "1598483120".
Casting any object to (int) doesn't help.

Did I do something wrong? Or what is going on?


问:
Python code to click a button using css selectors
I am brand new to python and am trying to modify some existing code. I have a form with the following elements:

```<code><div class="v-actions">
    <input type="submit" value="Save"/>
    <input type="button" value="Accept"/>
    <input type="button" value="Reject"/>
</div>
</code>```

If it exists, I want to click the Accept button. If not, I want to log that it is not found. Currently, the code is this:

```<code>from bs4 import BeautifulSoup
import datetime
import getpass
from gmail import Gmail
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep

....

self.chrome_session = webdriver.Chrome()

....

links = self.chrome_session.find_elements_by_class_name('link-record')
links = [(link.text, link.get_attribute('href').decode('utf-8'))
         for link in links]
if len(links) == 0:
    print("No work orders available at {0}".format(
        datetime.datetime.now()))
else:
    for link_text, link_url in links:
        print("Clicking work order {0}".format(link_text))
        self.chrome_session.get(link_url)
        potential_input = self.chrome_session.find_element_by_class_name('v-actions').find_element_by_tag_name('input');
        if potential_input.get_attribute('value') == 'Accept':
            potential_input.click()
            print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
        else:
            print("Accept input not found.")
....
</code>```

In jquery, the selector would be something like:

```<code>div.v-actions input[value=Accept]
</code>```

I am not sure how to do this with Python. I would rather not loop through all the inputs. I just want to find if the specific input exists and accept it if it does.

How do I translate the css selector to Python?

UPDATE

I am trying this now:

```<code>potential_input = self.chrome_session.find_element_by_xpath("//div[@class='v-actions']/input[@value='Accept']")
if potential_input.is_displayed():
    print("Accept input not found")
else:
    potential_input.click()
    print("Accepted work order {0} at {1}.".format(link_text,
                                                   datetime.datetime.now()))
</code>```

I am not sure how to test if it found the element. I get this error:

```<code>selenium.common.exceptions.ElementNotVisibleException: Message: {"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:49795","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"sessionId\": \"7b58b250-ca34-11e7-967d-6fd95b435952\", \"id\": \":wdc:1510771259080\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/7b58b250-ca34-11e7-967d-6fd95b435952/element/:wdc:1510771259080/click"}}
</code>```

I am not sure if my selector is wrong, or if my test to see if it was found is bad.

UPDATE 2

I have modified the code to the following:

```<code>for link_text, link_url in links:
    print("Clicking work order {0}".format(link_text))
    self.chrome_session.get(link_url)
    try:
        self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click()
        print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
    except ElementNotVisibleException:
        print("Accept input not found")
self.chrome_session.back()
</code>```

Now the code executes, and it acts like it worked (it prints Accepted work order {0}), but it didn't correctly fire the .click() because the record still exists in the list. But, if I manually click accept, it correctly processes the job.

Is my selector still wrong? Or, is the click function incorrectly applied?

答:
Use XPath to select your input and be pythonic by asking for forgiveness if you try to select something that is not there/visible:

```<code>from selenium.common.exceptions import ElementNotVisibleException

try:
    potential_input = driver.find_element_by_xpath("//div[@class='v-actions']/input[@value='Accept']")
    print("Input found!")
    potential_input.click()
    print("Input clicked!")
except ElementNotVisibleException:
    # Asked for forgiveness for
    # attempting to select element
    # that isn't there/visible
    print("Input not there!")
</code>```

Sourced from Selenium XPath and Exceptions docs.

Body:
I am brand new to python and am trying to modify some existing code. I have a form with the following elements:

    <input type="submit" value="Save"/>
    <input type="button" value="Accept"/>
    <input type="button" value="Reject"/>

If it exists, I want to click the Accept button. If not, I want to log that it is not found. Currently, the code is this:

from bs4 import BeautifulSoup
import datetime
import getpass
from gmail import Gmail
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep

....

self.chrome_session = webdriver.Chrome()

....

links = self.chrome_session.find_elements_by_class_name('link-record')
links = [(link.text, link.get_attribute('href').decode('utf-8'))
         for link in links]
if len(links) == 0:
    print("No work orders available at {0}".format(
        datetime.datetime.now()))
else:
    for link_text, link_url in links:
        print("Clicking work order {0}".format(link_text))
        self.chrome_session.get(link_url)
        potential_input = self.chrome_session.find_element_by_class_name('v-actions').find_element_by_tag_name('input');
        if potential_input.get_attribute('value') == 'Accept':
            potential_input.click()
            print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
        else:
            print("Accept input not found.")
....

In jquery, the selector would be something like:

div.v-actions input[value=Accept]

I am not sure how to do this with Python. I would rather not loop through all the inputs. I just want to find if the specific input exists and accept it if it does.

How do I translate the css selector to Python?

UPDATE

I am trying this now:

potential_input = self.chrome_session.find_element_by_xpath("//div[@class='v-actions']/input[@value='Accept']")
if potential_input.is_displayed():
    print("Accept input not found")
else:
    potential_input.click()
    print("Accepted work order {0} at {1}.".format(link_text,
                                                   datetime.datetime.now()))

I am not sure how to test if it found the element. I get this error:

selenium.common.exceptions.ElementNotVisibleException: Message: {"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:49795","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"sessionId\": \"7b58b250-ca34-11e7-967d-6fd95b435952\", \"id\": \":wdc:1510771259080\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/7b58b250-ca34-11e7-967d-6fd95b435952/element/:wdc:1510771259080/click"}}

I am not sure if my selector is wrong, or if my test to see if it was found is bad.

UPDATE 2

I have modified the code to the following:

for link_text, link_url in links:
    print("Clicking work order {0}".format(link_text))
    self.chrome_session.get(link_url)
    try:
        self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click()
        print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
    except ElementNotVisibleException:
        print("Accept input not found")
self.chrome_session.back()

Now the code executes, and it acts like it worked (it prints Accepted work order {0}), but it didn't correctly fire the .click() because the record still exists in the list. But, if I manually click accept, it correctly processes the job.

Is my selector still wrong? Or, is the click function incorrectly applied?

Body:
Use XPath to select your input and be pythonic by asking for forgiveness if you try to select something that is not there/visible:

from selenium.common.exceptions import ElementNotVisibleException

try:
    potential_input = driver.find_element_by_xpath("//div[@class='v-actions']/input[@value='Accept']")
    print("Input found!")
    potential_input.click()
    print("Input clicked!")
except ElementNotVisibleException:
    # Asked for forgiveness for
    # attempting to select element
    # that isn't there/visible
    print("Input not there!")

Sourced from Selenium XPath and Exceptions docs.


答:
Explanation

Transforming String into their uppercase-equivalents can easily be achieved by using the String#toUpperCase (documentation) function, analogously there is as String#toLowerCase (documentation) method.

So you need to access each element of your array and then call the method on it:

```<code>// Print in uppercase
for (String name : names) {
    System.out.println(name.toUpperCase());
}
</code>```

Or if your not familiar with the enhanced-for (foreach), a version using a regular for loop:

```<code>// Print in uppercase
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i].toUpperCase());
}
</code>```

Full code with improvements

You also don't need to save all those variables, just store them inside your array. After that loop the array and transform the variables:

```<code>public static void main(String[] args) {
    String[] names = new String[10];

    // Ask for names 10-times
    System.out.println("Please enter the ten names:");
    // Use try-with-resource for scanner-management
    try (Scanner userInput = new Scanner(System.in)) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + ": ");
            // Ensure that message is readable before
            // asking for input
            System.out.flush();

            // Store the input
            names[i] = userInput.nextLine();
        }
    }
    // Scanner is auto-closed due to try-with-resource

    // Print in lowercase
    for (String name : names) {
        System.out.println(name.toLowerCase());
    }

    // Print in uppercase
    for (String name : names) {
        System.out.println(name.toUpperCase());
    }
}
</code>```

Locale

You can even set a Locale object since the upper- and lowercase may change in some languages. See the documentation for some examples.

Title: Print out an array in uppercase Java

Body:
Explanation

Transforming String into their uppercase-equivalents can easily be achieved by using the String#toUpperCase (documentation) function, analogously there is as String#toLowerCase (documentation) method.

So you need to access each element of your array and then call the method on it:

// Print in uppercase
for (String name : names) {
    System.out.println(name.toUpperCase());
}

Or if your not familiar with the enhanced-for (foreach), a version using a regular for loop:

// Print in uppercase
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i].toUpperCase());
}

Full code with improvements

You also don't need to save all those variables, just store them inside your array. After that loop the array and transform the variables:

public static void main(String[] args) {
    String[] names = new String[10];

    // Ask for names 10-times
    System.out.println("Please enter the ten names:");
    // Use try-with-resource for scanner-management
    try (Scanner userInput = new Scanner(System.in)) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + ": ");
            // Ensure that message is readable before
            // asking for input
            System.out.flush();

            // Store the input
            names[i] = userInput.nextLine();
        }
    }
    // Scanner is auto-closed due to try-with-resource

    // Print in lowercase
    for (String name : names) {
        System.out.println(name.toLowerCase());
    }

    // Print in uppercase
    for (String name : names) {
        System.out.println(name.toUpperCase());
    }
}

Locale

You can even set a Locale object since the upper- and lowercase may change in some languages. See the documentation for some examples.


问:
Implementing Generic Method
Trying to implement this:

Interface:

```<code>public interface IStoreReader
{
    Task<IEnumerable<T>> Get<T>(UserDb user);
}
</code>```

Implementation:

```<code>public async Task<IEnumerable<ConversationDb>> Get<ConversationDb>(UserDb user)
{
    return await _convoRepo.Get(user.UserId); // error here
}
</code>```

Convo repo:

```<code>public async Task<IEnumerable<ConversationDb>> Get(string userId)
{
      return await // get from db - this works fine
}
</code>```

Error:

答:
I think you have two classes called ConversationDb in two different namespaces.

The type being returned by the repo is not the same type as the one defined in your implementation. Look at the definition of the types and you will see they come from different places.

The error message is very clear. You are asking the compiler to cast:

```<code>System.Collections.Generic.IEnumerable<SomeNamespace.ConversationDb>
</code>```

to

```<code>System.Collections.Generic.IEnumerable<ConversationDb>
</code>```

You must have imported the namespace for the second case but the repo is returning the first case.

Title: Implementing Generic Method

Body:
Trying to implement this:

Interface:

public interface IStoreReader
{
    Task<IEnumerable<T>> Get<T>(UserDb user);
}

Implementation:

public async Task<IEnumerable<ConversationDb>> Get<ConversationDb>(UserDb user)
{
    return await _convoRepo.Get(user.UserId); // error here
}

Convo repo:

public async Task<IEnumerable<ConversationDb>> Get(string userId)
{
      return await // get from db - this works fine
}

Error:

Body:
I think you have two classes called ConversationDb in two different namespaces.

The type being returned by the repo is not the same type as the one defined in your implementation. Look at the definition of the types and you will see they come from different places.

The error message is very clear. You are asking the compiler to cast:

System.Collections.Generic.IEnumerable<SomeNamespace.ConversationDb>

to

System.Collections.Generic.IEnumerable<ConversationDb>

You must have imported the namespace for the second case but the repo is returning the first case.


问:
Return an unknown object in an ApiController witih EF?
Is it possible to return a result set from the database without knowing the schema in advanced?

I'm exposing the ability for the client to pass parameters to a stored procedure via API:

```<code>    [Route("TheRequest")]
    public object Get([FromUri] TheRequest request)
</code>```

This will then return:

```<code>_repository.Database.SqlQuery<object>(request.ToSqlString());   //execute sql against a stored procedure, passing in the required parameters to it
</code>```

When attempting to do this, I believe that the controller doesn't know how to serialize the object returned. This is what postman returns:

Is it possible to return a Json serialized object response from the database without knowing the object schema?

答:
Is it possible to return a result set from the database without knowing the schema in advanced?

In regards to just EF, the answer is not really.  EF was designed for you to know the schema in advance.  So you can still use DAO off of the ContextDb.Database but there isn't much point to using EF you you do that.

Now if the question was, can I generically typed instance from EF then sure, no problem:

```<code>var result = DbContext.Set<T>().FirstOrDefault();
</code>```

This code doesn't know what it's pulling at compile time.

Is it possible to return a Json serialized object response from the database without knowing the object schema?

Sorta, as I mentioned before, you can't use EF as it was intended, but you could certainly do something like

```<code>public ActionResult Index(string type)
{
  var entityType = Type.GetType(type);
  // reflection
  var methods = typeof(ContextDb).GetMethods("Set");

  // Not tested, but something like the following
  // Find the Generic Version
  var method = methods.Where(m => m.IsGenericMethod).FirstOrDefault();
  // Make the method info for the typed method
  var methodInfo = method.MakeGenericMethod(entityType);
  // Invoke method, cast as needed, get value
  var result = (methodInfo.Invoke(ContextDb) as DbSet).FirstOrDefault();

  return Json(result);
}
</code>```

Body:
Is it possible to return a result set from the database without knowing the schema in advanced?

I'm exposing the ability for the client to pass parameters to a stored procedure via API:

    [Route("TheRequest")]
    public object Get([FromUri] TheRequest request)

This will then return:

_repository.Database.SqlQuery<object>(request.ToSqlString());   //execute sql against a stored procedure, passing in the required parameters to it

When attempting to do this, I believe that the controller doesn't know how to serialize the object returned. This is what postman returns:

Is it possible to return a Json serialized object response from the database without knowing the object schema?

Body:
Is it possible to return a result set from the database without knowing the schema in advanced?

In regards to just EF, the answer is not really.  EF was designed for you to know the schema in advance.  So you can still use DAO off of the ContextDb.Database but there isn't much point to using EF you you do that.

Now if the question was, can I generically typed instance from EF then sure, no problem:

var result = DbContext.Set<T>().FirstOrDefault();

This code doesn't know what it's pulling at compile time.

Is it possible to return a Json serialized object response from the database without knowing the object schema?

Sorta, as I mentioned before, you can't use EF as it was intended, but you could certainly do something like

public ActionResult Index(string type)
{
  var entityType = Type.GetType(type);
  // reflection
  var methods = typeof(ContextDb).GetMethods("Set");

  // Not tested, but something like the following
  // Find the Generic Version
  var method = methods.Where(m => m.IsGenericMethod).FirstOrDefault();
  // Make the method info for the typed method
  var methodInfo = method.MakeGenericMethod(entityType);
  // Invoke method, cast as needed, get value
  var result = (methodInfo.Invoke(ContextDb) as DbSet).FirstOrDefault();

  return Json(result);
}


问:
`dotnet sln add` wrong project type GUID
When I do dotnet sln add {myProject.csproj} for a .NET Core/Standard project, it adds it as project type (I think) {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} instead of .NET Core's {9A19103F-16F7-4668-BE54-9A1E7A4F7556}.

Hence, when I open the solution in Visual Studio, it complains and "upgrades" the csproj to a .NET Framework csproj, not a .NET Core one. I can manually edit the sln but it's a chore.

Am I doing something wrong? Are there arguments I'm missing?

答:
The CLI is actually doing the right thing here, this is a VS/Project System bug.

The CLI calls into msbuild to get the default project type GUID to use. MSBuild sets the $(DefaultProjectTypeGuid) for C# and VB projects to the "classic" one to allow the CLI to add both "classic" and "SDK-style" projects to a solution.

The classic GUID (FAE04EC0…) is then triggering a selection logic that looks if TargetFramework or TargetFrameworks is set in the project to determine if the "new" or "classic" project systems will be used. The idea is that at some point only the new project system will be used and the classic project system may no longer be part of VS in some future update (this is the tone of a lot of comments on GitHub).

According to the logged GitHub issue, the bug is that when the new project system is elected, the solution is updated to the "new" GUID which VS/the solution shouldn't see.


答:
You need to work on the first element of the returned array:

```<code>string.match(/(-1)*$/)[0].length/2
</code>```

Find the length of first element which is the matched string of "-1" at the end and divide by 2 since the string "-1" is of length 2.

To quote from MDN String.prototype.match():

Return value

If the string matches the expression, it will return an Array
  containing the entire matched string as the first element, followed by
  any results captured in parentheses. If there were no matches, null is
  returned.

function count() {
  console.log(string.match(/(-1)*$/)[0].length / 2)
}

var string = "1"
// 0
count();

string = "1-1"
// 1
count();

string = "1-1-1"
// 2
count();

string = "1-2-1"
// 1
count();

string = "1-2-1-2-1"
// 1
count();

string = "2-1-1-1-1"
// 4
count();

string = "1-1-2"
// 0
count();```

Title: Count matches at the end of a string

Body:
You need to work on the first element of the returned array:

string.match(/(-1)*$/)[0].length/2

Find the length of first element which is the matched string of "-1" at the end and divide by 2 since the string "-1" is of length 2.

To quote from MDN String.prototype.match():

Return value

If the string matches the expression, it will return an Array
  containing the entire matched string as the first element, followed by
  any results captured in parentheses. If there were no matches, null is
  returned.

function count() {
  console.log(string.match(/(-1)*$/)[0].length / 2)
}

var string = "1"
// 0
count();

string = "1-1"
// 1
count();

string = "1-1-1"
// 2
count();

string = "1-2-1"
// 1
count();

string = "1-2-1-2-1"
// 1
count();

string = "2-1-1-1-1"
// 4
count();

string = "1-1-2"
// 0
count();