问:
Returning undefined value - Node.js
I have the below function which correctly takes from the response the prefix and the suffix of the image and makes a variable result,which holds the url of the venue image. However when i return the result, i keep having undefined.What is going wrong here?

function getPhotoUrl(venue_id,venue_location,venue_query){
  request({
      url: 'https://api.foursquare.com/v2/venues/'+venue_id+'/photos',
      json:true,
      method: 'GET',
      qs: {
        client_id: 'my_id',
        client_secret: 'my_secret',
        near:venue_location,
        query: venue_query,
        v: '20171114',
        limit: 1
      }
    }, function(err, res, body) {
        var result="";
        if (err) {
          console.error(err);
        } else {
          console.log(body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix);
      }
      result=body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix;
      return result;
    }
  );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- begin snippet: js hide: false console: true babel: false --></code>```

答:
Try using async / await. Wrap your execution in a Promise to resolve the return value and reject the error value. This way you can just await on the function and get the return value. Keep in mind await stops the execution until the returned promise is fulfilled.

```<code>function getPhotoUrl(venue_id,venue_location,venue_query){
  return new Promise((resolve, reject) => {
    request({
      url: 'https://api.foursquare.com/v2/venues/'+venue_id+'/photos',
      json:true,
      method: 'GET',
      qs: {
        client_id: 'my_id',
        client_secret: 'my_secret',
        near:venue_location,
        query: venue_query,
        v: '20171114',
        limit: 1
      }
    }, function(err, res, body) {
        var result="";
        if (err)
          reject(err);
      }
      result=body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix;
      resolve(result);
    });
  })
}

await getPhotoUrl('', '', '')
</code>```

Title: Returning undefined value - Node.js

Body:
Try using async / await. Wrap your execution in a Promise to resolve the return value and reject the error value. This way you can just await on the function and get the return value. Keep in mind await stops the execution until the returned promise is fulfilled.

function getPhotoUrl(venue_id,venue_location,venue_query){
  return new Promise((resolve, reject) => {
    request({
      url: 'https://api.foursquare.com/v2/venues/'+venue_id+'/photos',
      json:true,
      method: 'GET',
      qs: {
        client_id: 'my_id',
        client_secret: 'my_secret',
        near:venue_location,
        query: venue_query,
        v: '20171114',
        limit: 1
      }
    }, function(err, res, body) {
        var result="";
        if (err)
          reject(err);
      }
      result=body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix;
      resolve(result);
    });
  })
}

await getPhotoUrl('', '', '')


来源: stackexchange

问:
How to format a DateTime object so it shows 24:00 instead of 00:00 in PHP?
I have a PHP program that shows two DateTime (or DateTimeImmutable) objects: start and end. To be human readable, midnight should be displayed as 00:00 for start but 24:00 for end.

Example:

```<code>$start = new DateTime('2017-01-01T22:00:00');
$end   = new DateTime('2017-01-02T00:00:00');
$format = 'Y-m-d H:i';
$startString = $start->format($format);
$endString   = $end->format($format); // What to do here instead?
printf("From %s to %s.\n",  $startString, $endString);
</code>```

Actual output:

```<code>From 2017-01-01 22:00 to 2017-01-02 00:00.
</code>```

Wanted output:

```<code>From 2017-01-01 22:00 to 2017-01-01 24:00.
</code>```

I'm looking for a solution that works for any $format string, that is, I don't want a separate solution for each date format that occurs in the application.

答:
This is the best I could come up with. The idea is to replace 'H' in the format string with '24', but keeping everything else as-is.

```<code><?php
function endFormat($dateTime, $format)
{
    $d = DateTimeImmutable::createFromMutable($dateTime);
    if ($d == $d->setTime(0, 0)) {
        $yesterday = $d->sub(new DateInterval('P1D'));
        $format24 = str_replace('H', '24', $format);
        return $yesterday->format($format24);
    } else {
        return $d->format($format);
    }
}

$start = new DateTime('2017-01-01T22:00:00');
$end   = new DateTime('2017-01-02T00:00:00');
$format = 'Y-m-d H:i';
$startString = $start->format($format);
$endString   = endFormat($end, $format);
printf("From %s to %s.\n",  $startString, $endString);
</code>```

Output:

```<code>From 2017-01-01 22:00 to 2017-01-01 24:00.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a PHP program that shows two DateTime (or DateTimeImmutable) objects: start and end. To be human readable, midnight should be displayed as 00:00 for start but 24:00 for end.

Example:

$start = new DateTime('2017-01-01T22:00:00');
$end   = new DateTime('2017-01-02T00:00:00');
$format = 'Y-m-d H:i';
$startString = $start->format($format);
$endString   = $end->format($format); // What to do here instead?
printf("From %s to %s.\n",  $startString, $endString);

Actual output:

From 2017-01-01 22:00 to 2017-01-02 00:00.

Wanted output:

From 2017-01-01 22:00 to 2017-01-01 24:00.

I'm looking for a solution that works for any $format string, that is, I don't want a separate solution for each date format that occurs in the application.

Body:
This is the best I could come up with. The idea is to replace 'H' in the format string with '24', but keeping everything else as-is.

<?php
function endFormat($dateTime, $format)
{
    $d = DateTimeImmutable::createFromMutable($dateTime);
    if ($d == $d->setTime(0, 0)) {
        $yesterday = $d->sub(new DateInterval('P1D'));
        $format24 = str_replace('H', '24', $format);
        return $yesterday->format($format24);
    } else {
        return $d->format($format);
    }
}

$start = new DateTime('2017-01-01T22:00:00');
$end   = new DateTime('2017-01-02T00:00:00');
$format = 'Y-m-d H:i';
$startString = $start->format($format);
$endString   = endFormat($end, $format);
printf("From %s to %s.\n",  $startString, $endString);

Output:

From 2017-01-01 22:00 to 2017-01-01 24:00.


问:
CSS align and size
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left"><h3 class="header">Calendar</h3></div>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
</div>
<div class="nav">
  <ul>
    <li class="nav">Link one</li>
    <li class="nav">Link two</li>
    <li class="nav">Link three</li>
    <li class="nav">Link four</li>
  </ul>
</div>
<div class="form"></div>
<div class="content"></div>
<div class="footer"></div></code>```

Regards,
Elio Fernandes

答: Change your div.right padding:1rem to padding: 12px and your issue will be fixed. Having a 1rem padding expands it thus it is bigger than the left part.  Or you can use padding: 1rem 1rem 12px 1rem; so you get 1rem on all sides but 12px only on the bottom

Title: CSS align and size

Body:
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}

Calendar

    Year<select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>

Link one

Link two

Link three

Link four

Regards,
Elio Fernandes


问:
Random Color Background
I am trying to get this code to change the background color to a random color when I press 'r'. So far everything is working ok other than changing the background color to a random color. This program is a screen saver that I have to generate random shapes in random positions with random colors.      </p>

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class ScreenSaver1 extends JPanel {
    private JFrame frame = new JFrame("FullSize");
    private Rectangle rectangle;
    boolean full;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.BLACK);
    }

    ScreenSaver1() {
        // Remove the title bar, min, max, close stuff
        frame.setUndecorated(true);
        // Add a Key Listener to the frame
        frame.addKeyListener(new KeyHandler());
        // Add this panel object to the frame
        frame.add(this);
        // Get the dimensions of the screen
        rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getDefaultScreenDevice().getDefaultConfiguration().getBounds();
        // Set the size of the frame to the size of the screen
        frame.setSize(rectangle.width, rectangle.height);
        frame.setVisible(true);
        // Remember that we are currently at full size
        full = true;
    }

// This method will run when any key is pressed in the window
class KeyHandler extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
        // Terminate the program.
        if (e.getKeyChar() == 'x') {
            System.out.println("Exiting");
            System.exit(0);
        }
        else if (e.getKeyChar() == 'r') {
            System.out.println("Change background color");
            setBackground(new Color((int)Math.random() * 256, (int)Math.random() * 256, (int)Math.random() * 256));
        }
        else if (e.getKeyChar() == 'z') {
            System.out.println("Resizing");
            frame.setSize((int)rectangle.getWidth() / 2, (int)rectangle.getHeight());
        }
    }

}

public static void main(String[] args) {
        ScreenSaver1 obj = new ScreenSaver1();
    }
}
</code>```

答:
Try this:

```<code>(int)(Math.random() * 256)
</code>```

Or this:

```<code>Random gen= new Random();
getContentPane().setBackground(Color.Black);
</code>```

To get random colors, try this:

```<code>.setBackground(Color.(gen.nextInt(256), gen.nextInt(256),
                gen.nextInt(256));
</code>```

Title: Random Color Background

Body:
I am trying to get this code to change the background color to a random color when I press 'r'. So far everything is working ok other than changing the background color to a random color. This program is a screen saver that I have to generate random shapes in random positions with random colors.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class ScreenSaver1 extends JPanel {
    private JFrame frame = new JFrame("FullSize");
    private Rectangle rectangle;
    boolean full;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.BLACK);
    }

    ScreenSaver1() {
        // Remove the title bar, min, max, close stuff
        frame.setUndecorated(true);
        // Add a Key Listener to the frame
        frame.addKeyListener(new KeyHandler());
        // Add this panel object to the frame
        frame.add(this);
        // Get the dimensions of the screen
        rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getDefaultScreenDevice().getDefaultConfiguration().getBounds();
        // Set the size of the frame to the size of the screen
        frame.setSize(rectangle.width, rectangle.height);
        frame.setVisible(true);
        // Remember that we are currently at full size
        full = true;
    }

// This method will run when any key is pressed in the window
class KeyHandler extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
        // Terminate the program.
        if (e.getKeyChar() == 'x') {
            System.out.println("Exiting");
            System.exit(0);
        }
        else if (e.getKeyChar() == 'r') {
            System.out.println("Change background color");
            setBackground(new Color((int)Math.random() * 256, (int)Math.random() * 256, (int)Math.random() * 256));
        }
        else if (e.getKeyChar() == 'z') {
            System.out.println("Resizing");
            frame.setSize((int)rectangle.getWidth() / 2, (int)rectangle.getHeight());
        }
    }

}

public static void main(String[] args) {
        ScreenSaver1 obj = new ScreenSaver1();
    }
}

Body:
Try this:

(int)(Math.random() * 256)

Or this:

Random gen= new Random();
getContentPane().setBackground(Color.Black);

To get random colors, try this:

.setBackground(Color.(gen.nextInt(256), gen.nextInt(256),
                gen.nextInt(256));


问:
Could not cast value of type 'NSTaggedPointerString' to 'NSNumber' - from PHP to Swift
I am trying to convert response from PHP to swift Dictionary but I couldn't figure out how to do it.

Wondering why I use [String: [String: Int]] does not work.

Tried to use NSDictionary but don't think this is a correct way but it seems almost there.

Swift code

```<code>Alamofire.request(requestString, method: .post, parameters: data, encoding:URLEncoding.default, headers: [:]).responseJSON { (response) in
    switch response.result {
        case .success(_):
            if let response = response.result.value as? [String: Any] {
                let updatedData = response["existData"] as! NSDictionary
                print(updatedData)
                let updatedData2 = response["existData"] as? [String: [String: Int]]
                print("updatedData2", updatedData2)
                var convertData = [String: [String: Int]]()
                for key in Array(updatedData.allKeys) {
                    var convertInsideData = [String: Int]()
                    if let array = updatedData[key] as? NSDictionary {
                        for (k, v) in array {
                            print(k, "-", v)
                            convertInsideData[k as! String] = v as! Int
                        }
                    }
                    convertData[key as! String] = convertInsideData
                }
       .....................
</code>```

First print,

```<code>{
    All =     {
        Maybelline = 2;
    };
}
updatedData2 Optional(["All": ["Maybelline": 2]])
Maybelline - 2
</code>```

Second print, then crash in convertInsideData[k as! String] = v as! Int

```<code>{
    All =     {
        Maybelline = 2;
        Sephora = 2;
    };
}
updatedData2 nil
Sephora - 2
Maybelline - 2
Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
2017-11-14 23:52:04.939332+0800 LeanCloudStarter[10014:272299] Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
</code>```

Response from PHP should be like this

```<code>$existData = array("All"=>array("Maybelline"=>2, "Sephora"=>2));
echo json_encode("existData"=>$existData));
</code>```

答:
I suggest you to use optionals, then your Int value seems to be a String in your Json, try:</p>

```<code>for (k, v) in array {
    print(k, "-", v)
    if let stringV = v as? String {
        convertInsideData[k as! String] = Int(stringV)
    } else if let numberV = v as? NSNumber {
        convertInsideData[k as! String] = v.intValue
    }
}
</code>```

Body:
I am trying to convert response from PHP to swift Dictionary but I couldn't figure out how to do it.

Wondering why I use [String: [String: Int]] does not work.

Tried to use NSDictionary but don't think this is a correct way but it seems almost there.

Swift code

Alamofire.request(requestString, method: .post, parameters: data, encoding:URLEncoding.default, headers: [:]).responseJSON { (response) in
    switch response.result {
        case .success(_):
            if let response = response.result.value as? [String: Any] {
                let updatedData = response["existData"] as! NSDictionary
                print(updatedData)
                let updatedData2 = response["existData"] as? [String: [String: Int]]
                print("updatedData2", updatedData2)
                var convertData = [String: [String: Int]]()
                for key in Array(updatedData.allKeys) {
                    var convertInsideData = [String: Int]()
                    if let array = updatedData[key] as? NSDictionary {
                        for (k, v) in array {
                            print(k, "-", v)
                            convertInsideData[k as! String] = v as! Int
                        }
                    }
                    convertData[key as! String] = convertInsideData
                }
       .....................

First print,

{
    All =     {
        Maybelline = 2;
    };
}
updatedData2 Optional(["All": ["Maybelline": 2]])
Maybelline - 2

Second print, then crash in convertInsideData[k as! String] = v as! Int

{
    All =     {
        Maybelline = 2;
        Sephora = 2;
    };
}
updatedData2 nil
Sephora - 2
Maybelline - 2
Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
2017-11-14 23:52:04.939332+0800 LeanCloudStarter[10014:272299] Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).

Response from PHP should be like this

$existData = array("All"=>array("Maybelline"=>2, "Sephora"=>2));
echo json_encode("existData"=>$existData));

Body:
I suggest you to use optionals, then your Int value seems to be a String in your Json, try:

for (k, v) in array {
    print(k, "-", v)
    if let stringV = v as? String {
        convertInsideData[k as! String] = Int(stringV)
    } else if let numberV = v as? NSNumber {
        convertInsideData[k as! String] = v.intValue
    }
}


问:
PCL voxel downsampling filter as a function
I would like to use some of the filters as 'functions' so that I use the same filter to different input clouds i.e pass different cloud as an argument. For example the voxel filter (see below) can it be used for different input clouds. If I have cloud A and B, i have to define sor1 and sor2, because I can't use the same sor on both, or maybe it is possible but I don't know how to do it. Can someone share some ideas on this.</p>

```<code> // Create the filtering object
 pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
 sor.setInputCloud (cloud);
 sor.setLeafSize (0.01f, 0.01f, 0.01f);
 sor.filter (*cloud_filtered);
</code>```

答:
Yeah just call setInputCloud() again for a new cloud and then filter().

Or you can just put it all in a function and create a new object every time for simplicity.

```<code>voxelFilter(cloud)
{
   // Create the filtering object
   pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
   sor.setInputCloud (cloud);
   sor.setLeafSize (0.01f, 0.01f, 0.01f);
   sor.filter (*cloud_filtered);
   return cloud_filtered;
}
</code>```

Body:
I would like to use some of the filters as 'functions' so that I use the same filter to different input clouds i.e pass different cloud as an argument. For example the voxel filter (see below) can it be used for different input clouds. If I have cloud A and B, i have to define sor1 and sor2, because I can't use the same sor on both, or maybe it is possible but I don't know how to do it. Can someone share some ideas on this.

 // Create the filtering object
 pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
 sor.setInputCloud (cloud);
 sor.setLeafSize (0.01f, 0.01f, 0.01f);
 sor.filter (*cloud_filtered);

Body:
Yeah just call setInputCloud() again for a new cloud and then filter().

Or you can just put it all in a function and create a new object every time for simplicity.

voxelFilter(cloud)
{
   // Create the filtering object
   pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
   sor.setInputCloud (cloud);
   sor.setLeafSize (0.01f, 0.01f, 0.01f);
   sor.filter (*cloud_filtered);
   return cloud_filtered;
}


问:
MediaRecorder start error codes
I want to record raw h.264 video without sound and possibly HW accelerated (and stream it later). So I decided to use MediaRecorder (and the socket hack for streaming).

I have the following code:

```<code>final MediaRecorder recorder = new MediaRecorder();
final Camera camera = Camera.open();
camera.unlock();
recorder.setCamera(camera);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
final CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
recorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
recorder.setVideoFrameRate(profile.videoFrameRate);
recorder.setVideoEncodingBitRate(profile.videoBitRate);
recorder.prepare();
recorder.start();
</code>```

And bam! This in logcat:

```<code>E/MediaRecorder﹕ start failed: -38
</code>```

I started googling, and found plenty of questions and answers, but none about my error code -38.

So I tried to look at Android source code, and noticed it's native method, and I don't know where to look for that.

So my big question is: Is there some list of those error codes, so I could find what error -38 means?`

Also know tjat I'm targeting API 10 (Gingerbread) and building with latest SDK 21.

答:
I have meet this error code in my call recorder app.
this error code will show in logcat when you start media recorder while the Microphone is in use in another app like a Voice Assistant (for example: Ok google, etc) or another call recorder application.

Title: MediaRecorder start error codes

Body:
I want to record raw h.264 video without sound and possibly HW accelerated (and stream it later). So I decided to use MediaRecorder (and the socket hack for streaming).

I have the following code:

final MediaRecorder recorder = new MediaRecorder();
final Camera camera = Camera.open();
camera.unlock();
recorder.setCamera(camera);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
final CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
recorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
recorder.setVideoFrameRate(profile.videoFrameRate);
recorder.setVideoEncodingBitRate(profile.videoBitRate);
recorder.prepare();
recorder.start();

And bam! This in logcat:

E/MediaRecorder﹕ start failed: -38

I started googling, and found plenty of questions and answers, but none about my error code -38.

So I tried to look at Android source code, and noticed it's native method, and I don't know where to look for that.

So my big question is: Is there some list of those error codes, so I could find what error -38 means?`

Also know tjat I'm targeting API 10 (Gingerbread) and building with latest SDK 21.


问:
How to set screen size for chrome headless system test in rails 5.1?
In order to work with and test a new responsive frontend for my site, I'm trying to use Rails' new system tests (specs) with javascript and Chrome headless. I cannot figure out a way to set the screen size of the browser in the spec, though.

Here's my setup in spec/rails_helper.rb

```<code>config.before(:each, type: :system, js: true) do
  driven_by :selenium_chrome_headless, screen_size: [1900, 800]
end
</code>```

I then create the screenshot with:

```<code>page.driver.save_screenshot(the_uri)
</code>```

But the size of the rendered screenshot still is the default, which is much smaller. Ideally, I'd like to see the entire rendered page, but at this point, I'd be happy with just using the dimensions I've provided.

Ideas on what I'm missing here?

答:
You simply need to redefine the driver which passes the headless and screen size arguments.</p>

```<code>Capybara.register_driver :selenium_chrome_headless do |app|
  options = Selenium::WebDriver::Chrome::Options.new

  [
    "headless",
    "window-size=1280x1280",
    "disable-gpu" # https://developers.google.com/web/updates/2017/04/headless-chrome
  ].each { |arg| options.add_argument(arg) }

  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

RSpec.configure do |config|
  config.before(:each, type: :system, js: true) do
    driven_by :selenium_chrome_headless
  end
end
</code>```

Body:
In order to work with and test a new responsive frontend for my site, I'm trying to use Rails' new system tests (specs) with javascript and Chrome headless. I cannot figure out a way to set the screen size of the browser in the spec, though.

Here's my setup in spec/rails_helper.rb

config.before(:each, type: :system, js: true) do
  driven_by :selenium_chrome_headless, screen_size: [1900, 800]
end

I then create the screenshot with:

page.driver.save_screenshot(the_uri)

But the size of the rendered screenshot still is the default, which is much smaller. Ideally, I'd like to see the entire rendered page, but at this point, I'd be happy with just using the dimensions I've provided.

Ideas on what I'm missing here?

Body:
You simply need to redefine the driver which passes the headless and screen size arguments.

Capybara.register_driver :selenium_chrome_headless do |app|
  options = Selenium::WebDriver::Chrome::Options.new

  [
    "headless",
    "window-size=1280x1280",
    "disable-gpu" # https://developers.google.com/web/updates/2017/04/headless-chrome
  ].each { |arg| options.add_argument(arg) }

  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

RSpec.configure do |config|
  config.before(:each, type: :system, js: true) do
    driven_by :selenium_chrome_headless
  end
end


问:
Android: Camera Preview Orientation on HTC EVO (Android 2.1 or 2.2)
I am developing an Android application that relies on the camera API, using an HTC EVO as my testing device. No matter what I've tried so far, the only time the camera preview looks right is in landscape mode (90 degrees rotation, to be specific). It seems as though there is no way to orient the preview correctly when in portrait mode (0 degrees rotation).

The default camera application on the device (for HTC Sense) allows for any kind of rotation without any problem, so I know that there is no hardware limitation. I even downloaded some source code from HTC's developer site, but it's all in C - kernel stuff, apparently.

Can anyone point me in the right direction for solving this problem? Is there a way to rotate the preview correctly in Android 2.1 or 2.2?

Thank you.

P.S. Here is the code I'm using, in case it helps...

```<code>package spikes.cameraSpike03;

import java.util.List;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity implements SurfaceHolder.Callback {
 private static final String LOG_TAG = "spikes.cameraSpike03 - MainActivity";

 private Camera _camera;
 private boolean _previewIsRunning = false;

 private SurfaceView _svCameraView;
 private SurfaceHolder _surfaceHolder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        _svCameraView = (SurfaceView)findViewById(R.id.svCameraView);

        _surfaceHolder = _svCameraView.getHolder();
        _surfaceHolder.addCallback(this);
        _surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

 @Override
 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  if(_previewIsRunning){
   _camera.stopPreview();
  }

  try{
   Camera.Parameters parameters = _camera.getParameters();

   //Get the optimal preview size so we don't get an exception when setting the parameters
   List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
   Size optimalPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, width, height);
   parameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);

   _camera.setParameters(parameters);

   _camera.setPreviewDisplay(holder);
  }
  catch(Exception ex){
   ex.printStackTrace();
   Log.e(LOG_TAG, ex.toString());
  }

  _camera.startPreview();
  _previewIsRunning = true;
 }

 @Override
 public void surfaceCreated(SurfaceHolder holder) {
  _camera = Camera.open();
 }

 @Override
 public void surfaceDestroyed(SurfaceHolder holder) {
  _camera.stopPreview();
  _previewIsRunning = false;
  _camera.release();
 }

 private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.05;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

}
</code>```

答:
Try locking the orientation of the Activity in horizontal if that fits with your design, or have a play with these:

```<code>private android.hardware.Camera mCamera;
</code>```

...

```<code>mCamera.setDisplayOrientation(90);
params.setRotation(90);
mCamera.setParameters(params);
</code>```

But I think setDisplayOrientation might be 2.2 only...

ContentLicense: CC BY-SA 2.5

Body:
I am developing an Android application that relies on the camera API, using an HTC EVO as my testing device. No matter what I've tried so far, the only time the camera preview looks right is in landscape mode (90 degrees rotation, to be specific). It seems as though there is no way to orient the preview correctly when in portrait mode (0 degrees rotation).

The default camera application on the device (for HTC Sense) allows for any kind of rotation without any problem, so I know that there is no hardware limitation. I even downloaded some source code from HTC's developer site, but it's all in C - kernel stuff, apparently.

Can anyone point me in the right direction for solving this problem? Is there a way to rotate the preview correctly in Android 2.1 or 2.2?

Thank you.

P.S. Here is the code I'm using, in case it helps...

package spikes.cameraSpike03;

import java.util.List;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity implements SurfaceHolder.Callback {
 private static final String LOG_TAG = "spikes.cameraSpike03 - MainActivity";

 private Camera _camera;
 private boolean _previewIsRunning = false;

 private SurfaceView _svCameraView;
 private SurfaceHolder _surfaceHolder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        _svCameraView = (SurfaceView)findViewById(R.id.svCameraView);

        _surfaceHolder = _svCameraView.getHolder();
        _surfaceHolder.addCallback(this);
        _surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

 @Override
 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  if(_previewIsRunning){
   _camera.stopPreview();
  }

  try{
   Camera.Parameters parameters = _camera.getParameters();

   //Get the optimal preview size so we don't get an exception when setting the parameters
   List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
   Size optimalPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, width, height);
   parameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);

   _camera.setParameters(parameters);

   _camera.setPreviewDisplay(holder);
  }
  catch(Exception ex){
   ex.printStackTrace();
   Log.e(LOG_TAG, ex.toString());
  }

  _camera.startPreview();
  _previewIsRunning = true;
 }

 @Override
 public void surfaceCreated(SurfaceHolder holder) {
  _camera = Camera.open();
 }

 @Override
 public void surfaceDestroyed(SurfaceHolder holder) {
  _camera.stopPreview();
  _previewIsRunning = false;
  _camera.release();
 }

 private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.05;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

}

Body:
Try locking the orientation of the Activity in horizontal if that fits with your design, or have a play with these:

private android.hardware.Camera mCamera;

...

mCamera.setDisplayOrientation(90);
params.setRotation(90);
mCamera.setParameters(params);

But I think setDisplayOrientation might be 2.2 only...


问:
How to open rabbitmq in browser using docker container?
This was probably asked already, but so far I can't find any detailed explanation at all, and the existing documentation seems as if it was written for some kind on psychic who supposed to know everything.

As per this manual, I added the container

```<code>docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:latest
</code>```

Then I checked it to receive the container ip

```<code>docker inspect some-rabbit
</code>```

Checked ports with

```<code>docker ps
</code>```

And tried to connect in the browser with this formula

```<code>https://{container-ip}:{port}
</code>```

It did't work.

Am I'm doing something wrong, or maybe I am supposed to add something additional, like a container for apache or other stuff?

EDIT

As I understand, after creating some-rabbit container, now I need to run Dockerfile to create image? (This whole thing is confusing to me). How am I supposed to do that? I mean, I saw command docker build -f /path/to/a/Dockerfile but if for example I placed the Dockerfile in second path D:\Docker\rabbitmq, how I supposed to get there? (the path doesn't seems to be recognized)

答:
You are using the wrong image which doesn't have the rabbitmq_management plugin enabled. Change rabbitmq:latest to rabbitmq:management.

On dockerhub they are using the command:

```<code>docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3-management
</code>```

If you want to go to the UI on localhost:15672 make sure to expose the port by adding -p 15672:15672 to the above command.

The management image is just the rabbitmq latest image with the management plugin enabled. Here is the dockerfile for rabbitmq:management

```<code>FROM rabbitmq

RUN rabbitmq-plugins enable --offline rabbitmq_management

EXPOSE 15671 15672
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This was probably asked already, but so far I can't find any detailed explanation at all, and the existing documentation seems as if it was written for some kind on psychic who supposed to know everything.

As per this manual, I added the container

docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:latest

Then I checked it to receive the container ip

docker inspect some-rabbit

Checked ports with

docker ps

And tried to connect in the browser with this formula

https://{container-ip}:{port}

It did't work.

Am I'm doing something wrong, or maybe I am supposed to add something additional, like a container for apache or other stuff?

EDIT

As I understand, after creating some-rabbit container, now I need to run Dockerfile to create image? (This whole thing is confusing to me). How am I supposed to do that? I mean, I saw command docker build -f /path/to/a/Dockerfile but if for example I placed the Dockerfile in second path D:\Docker\rabbitmq, how I supposed to get there? (the path doesn't seems to be recognized)

Body:
You are using the wrong image which doesn't have the rabbitmq_management plugin enabled. Change rabbitmq:latest to rabbitmq:management.

On dockerhub they are using the command:

docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3-management

If you want to go to the UI on localhost:15672 make sure to expose the port by adding -p 15672:15672 to the above command.

The management image is just the rabbitmq latest image with the management plugin enabled. Here is the dockerfile for rabbitmq:management

FROM rabbitmq

RUN rabbitmq-plugins enable --offline rabbitmq_management

EXPOSE 15671 15672


问:
Quill editor not firing (change) event in Angular
I'm using Quill editor with the ngx-quill NPM package. Everything is working great except that I just can't get the (change) event to fire. Here's the HTML:

```<code><quill-editor (change)="validateChange(field)" [formControlName]="field.id" [id]="field.id"></quill-editor>
</code>```

The (change)="validateChange(field)" is having no effect.

Thanks for any ideas!!

答:
In model driven form you could use valueChanges Observable on your form.

```<code>this.formName.valueChanges.subscribe(data => {
   console.log('Changed Values', data)
})
</code>```

Body:
I'm using Quill editor with the ngx-quill NPM package. Everything is working great except that I just can't get the (change) event to fire. Here's the HTML:

<quill-editor (change)="validateChange(field)" [formControlName]="field.id" [id]="field.id"></quill-editor>

The (change)="validateChange(field)" is having no effect.

Thanks for any ideas!!

Body:
In model driven form you could use valueChanges Observable on your form.

this.formName.valueChanges.subscribe(data => {
   console.log('Changed Values', data)
})


问:
SPServices Unique choice field not giving list entry
This one may sound weird but any help would be greatly appreciated.

I'm using GetListItems of SPServices and one of the fields is a Choice field that has to be unique (which I believe is causing the issue). Here is the code:

```<code>$().SPServices({
      operation: method,
      async: false,
      listName: "Content",
      CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Section' /><FieldRef Name='Content' /><FieldRef Name='Order' /></ViewFields>",
      CAMLQuery: "<Query><OrderBy><FieldRef Name='Order' Ascending='True'/></OrderBy><Where><Neq><FieldRef Name='ID' /><Value Type='Number'>0</Value></Neq></Where></Query>",
      completefunc: function (xData, Status) {
           $(xData.responseXML).SPFilterNode("z:row").each(function() {
                var cont = $(this).attr('ows_Content')==undefined?cont = "": cont = $(this).attr('ows_Content');
                var object={
                     title:$(this).attr('ows_Title'),
                     content:cont,
                     order:$(this).attr('ows_Order')
                }
                pages.push(object);
                console.log(object.order)
           });
      }
 });
</code>```

The console log details the object.order as:

```<code>"100.000000000000"
"200.000000000000"
"300.000000000000"
etc...
</code>```

At first I thought It was just pulling through a float error but I could get around that until I noticed that the order choice in the list does not match the selection.

For Example, the list item which order is 1 (in the List View), on the page pulls through as order 200.000000000000

Im not sure why this is, can anyone help?

答: Okay so found the value I wanted, as it turns out there was a secondary attr called ows_Order0 which had the selected value in it.

Body:
This one may sound weird but any help would be greatly appreciated.

I'm using GetListItems of SPServices and one of the fields is a Choice field that has to be unique (which I believe is causing the issue). Here is the code:

$().SPServices({
      operation: method,
      async: false,
      listName: "Content",
      CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Section' /><FieldRef Name='Content' /><FieldRef Name='Order' /></ViewFields>",
      CAMLQuery: "<Query><OrderBy><FieldRef Name='Order' Ascending='True'/></OrderBy><Where><Neq><FieldRef Name='ID' /><Value Type='Number'>0</Value></Neq></Where></Query>",
      completefunc: function (xData, Status) {
           $(xData.responseXML).SPFilterNode("z:row").each(function() {
                var cont = $(this).attr('ows_Content')==undefined?cont = "": cont = $(this).attr('ows_Content');
                var object={
                     title:$(this).attr('ows_Title'),
                     content:cont,
                     order:$(this).attr('ows_Order')
                }
                pages.push(object);
                console.log(object.order)
           });
      }
 });

The console log details the object.order as:

"100.000000000000"
"200.000000000000"
"300.000000000000"
etc...

At first I thought It was just pulling through a float error but I could get around that until I noticed that the order choice in the list does not match the selection.

For Example, the list item which order is 1 (in the List View), on the page pulls through as order 200.000000000000

Im not sure why this is, can anyone help?


问:
Hadoop on EC2 error: could only be replicated to 0 nodes, instead of 1
I'm running a very small Hadoop cluster on EC2.

I'm starting a cluster using whirr (version: whirr-0.2.0-incubating)  with 1 (jobtracker + namenode) and 4 (datanodes + tasktracker) :

```<code>    whirr.hardware-id=c1.medium
    whirr.instance-templates=1 jt+nn,4 dn+tt
    whirr.provider=ec2
</code>```

When I run my job I'm getting the following error , not right away but after a while :

```<code>.....
11/01/17 17:31:47 INFO mapred.JobClient:  map 100% reduce 66%
11/01/17 17:31:49 INFO mapred.JobClient:  map 100% reduce 68%
11/01/17 17:31:52 INFO mapred.JobClient:  map 100% reduce 70%
11/01/17 17:31:56 INFO mapred.JobClient:  map 100% reduce 73%
11/01/17 17:32:01 INFO mapred.JobClient: Task Id : attempt_201101172141_0002_r_000000_0, Status : FAILED
org.apache.hadoop.ipc.RemoteException: java.io.IOException: File /user/root/test/test2/test3/_temporary/_attempt_201101172141_0002_r_000000_0/parts/81/part-00000 could only be replicated to 0 nodes, instead of 1
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1271)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:422)
        at sun.reflect.GeneratedMethodAccessor13.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:508)
....
</code>```

I found the same error in the tasktracker log file :

```<code>....
2011-01-17 22:31:36,968 INFO org.apache.hadoop.mapred.JobTracker: Adding task (cleanup)'attempt_201101172141_0002_m_000004_1' to tip task_201101172141_0002_m_000004, for tracker 'tracker_ip-11-222-333-444.ec2.internal:localhost/127.0.0.1:44840'
2011-01-17 22:31:39,972 INFO org.apache.hadoop.mapred.JobTracker: Removed completed task 'attempt_201101172141_0002_m_000004_1' from 'tracker_ip-11-222-333-444.ec2.internal:localhost/127.0.0.1:44840'
2011-01-17 22:31:57,985 INFO org.apache.hadoop.mapred.TaskInProgress: Error from attempt_201101172141_0002_r_000000_0: org.apache.hadoop.ipc.RemoteException: java.io.IOException: File /user/root/dsp-test/test1/test2/_temporary/_attempt_201101172141_0002_r_000000_0/parts/81/part-00000 could only be replicated to 0 nodes, instead of 1
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1271)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:422)
    at sun.reflect.GeneratedMethodAccessor13.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
</code>```

In job's configuration I have:

```<code>dfs.replication=2
mapred.child.java.opts=-server -Xmx180m -XX:ErrorFile=/mnt/hadoop/logs/logs/java/java_error.log
</code>```

Does anyone have an idea why I'm getting this error?

答: Did you run out of disk space?  Sometimes if you run out of disk space it will complain in this way.</p>

Body:
I'm running a very small Hadoop cluster on EC2.

I'm starting a cluster using whirr (version: whirr-0.2.0-incubating)  with 1 (jobtracker + namenode) and 4 (datanodes + tasktracker) :

    whirr.hardware-id=c1.medium
    whirr.instance-templates=1 jt+nn,4 dn+tt
    whirr.provider=ec2

When I run my job I'm getting the following error , not right away but after a while :

.....
11/01/17 17:31:47 INFO mapred.JobClient:  map 100% reduce 66%
11/01/17 17:31:49 INFO mapred.JobClient:  map 100% reduce 68%
11/01/17 17:31:52 INFO mapred.JobClient:  map 100% reduce 70%
11/01/17 17:31:56 INFO mapred.JobClient:  map 100% reduce 73%
11/01/17 17:32:01 INFO mapred.JobClient: Task Id : attempt_201101172141_0002_r_000000_0, Status : FAILED
org.apache.hadoop.ipc.RemoteException: java.io.IOException: File /user/root/test/test2/test3/_temporary/_attempt_201101172141_0002_r_000000_0/parts/81/part-00000 could only be replicated to 0 nodes, instead of 1
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1271)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:422)
        at sun.reflect.GeneratedMethodAccessor13.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:508)
....

I found the same error in the tasktracker log file :

....
2011-01-17 22:31:36,968 INFO org.apache.hadoop.mapred.JobTracker: Adding task (cleanup)'attempt_201101172141_0002_m_000004_1' to tip task_201101172141_0002_m_000004, for tracker 'tracker_ip-11-222-333-444.ec2.internal:localhost/127.0.0.1:44840'
2011-01-17 22:31:39,972 INFO org.apache.hadoop.mapred.JobTracker: Removed completed task 'attempt_201101172141_0002_m_000004_1' from 'tracker_ip-11-222-333-444.ec2.internal:localhost/127.0.0.1:44840'
2011-01-17 22:31:57,985 INFO org.apache.hadoop.mapred.TaskInProgress: Error from attempt_201101172141_0002_r_000000_0: org.apache.hadoop.ipc.RemoteException: java.io.IOException: File /user/root/dsp-test/test1/test2/_temporary/_attempt_201101172141_0002_r_000000_0/parts/81/part-00000 could only be replicated to 0 nodes, instead of 1
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1271)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:422)
    at sun.reflect.GeneratedMethodAccessor13.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

In job's configuration I have:

dfs.replication=2
mapred.child.java.opts=-server -Xmx180m -XX:ErrorFile=/mnt/hadoop/logs/logs/java/java_error.log

Does anyone have an idea why I'm getting this error?


问:
Vector2i doesn't want to cooperate:D
My problem is that in the:

```<code>if(Keyboard::isKeyPressed(Keyboard::D))
    {
        source.y=right;
        source.x++;
    }
</code>```

fragment of my simple code, the source.y doesn't want to take the value of 0. What's causing this?
Full code:

```<code>#include <SFML/Graphics.hpp>
#include <iostream>
#include <conio.h>
#include <windows.h>

#define CW 64//cell width

using namespace std;
using namespace sf;

int main()
{
    RenderWindow win(VideoMode(1200,800),"lol");
    win.setFramerateLimit(30);

    Texture t;
    t.loadFromFile("char.png");

    Sprite char_;
    char_.setTexture(t);

    enum dir{right,left,idle};
    Vector2i source(1,idle);

while(win.isOpen())
{
    win.clear();

    if(Keyboard::isKeyPressed(Keyboard::D))
    {
        source.y=right;
        source.x++;
    }
    if(Keyboard::isKeyPressed(Keyboard::A))
    {
        source.y=left;
        source.x++;
    }
    else
    {
        source.y=idle;
    }

    char_.setTextureRect(IntRect(source.x*CW,source.y*CW,CW,CW));

    if(source.x==3 || source.x>3)
    {
        source.x=0;
    }

    cout<<"source.x: "<<source.x<<endl;
    cout<<"source.y: "<<source.y<<endl;

    win.draw(char_);
    win.display();

    system("cls");

}
}
</code>```

答:
You are missing an else after your first if:

```<code>if(Keyboard::isKeyPressed(Keyboard::D))
{
    source.y=right;
    source.x++;
}

if(Keyboard::isKeyPressed(Keyboard::A))
{
    source.y=left;
    source.x++;
}
else
{
    source.y=idle;
}
</code>```

Even if D is pressed, you will end up in the final else clause, because it's not A. So source.y will take the value of right, but will immediately be overwritten by the line source.y=idle;

What you probably want (check the else in front of the second if) is:

```<code>if(Keyboard::isKeyPressed(Keyboard::D))
{
    source.y=right;
    source.x++;
}
else if(Keyboard::isKeyPressed(Keyboard::A))
{
    source.y=left;
    source.x++;
}
else
{
    source.y=idle;
}
</code>```

Title: Vector2i doesn't want to cooperate:D

Body:
My problem is that in the:

if(Keyboard::isKeyPressed(Keyboard::D))
    {
        source.y=right;
        source.x++;
    }

fragment of my simple code, the source.y doesn't want to take the value of 0. What's causing this?
Full code:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <conio.h>
#include <windows.h>

#define CW 64//cell width

using namespace std;
using namespace sf;

int main()
{
    RenderWindow win(VideoMode(1200,800),"lol");
    win.setFramerateLimit(30);

    Texture t;
    t.loadFromFile("char.png");

    Sprite char_;
    char_.setTexture(t);

    enum dir{right,left,idle};
    Vector2i source(1,idle);

while(win.isOpen())
{
    win.clear();

    if(Keyboard::isKeyPressed(Keyboard::D))
    {
        source.y=right;
        source.x++;
    }
    if(Keyboard::isKeyPressed(Keyboard::A))
    {
        source.y=left;
        source.x++;
    }
    else
    {
        source.y=idle;
    }

    char_.setTextureRect(IntRect(source.x*CW,source.y*CW,CW,CW));

    if(source.x==3 || source.x>3)
    {
        source.x=0;
    }

    cout<<"source.x: "<<source.x<<endl;
    cout<<"source.y: "<<source.y<<endl;

    win.draw(char_);
    win.display();

    system("cls");

}
}

Body:
You are missing an else after your first if:

if(Keyboard::isKeyPressed(Keyboard::D))
{
    source.y=right;
    source.x++;
}

if(Keyboard::isKeyPressed(Keyboard::A))
{
    source.y=left;
    source.x++;
}
else
{
    source.y=idle;
}

Even if D is pressed, you will end up in the final else clause, because it's not A. So source.y will take the value of right, but will immediately be overwritten by the line source.y=idle;

What you probably want (check the else in front of the second if) is:

if(Keyboard::isKeyPressed(Keyboard::D))
{
    source.y=right;
    source.x++;
}
else if(Keyboard::isKeyPressed(Keyboard::A))
{
    source.y=left;
    source.x++;
}
else
{
    source.y=idle;
}


问:
"Allow access to Azure services" turn off by default from ARM template
Does anybody know how to setup ARM Template to keep "Allow access to Azure services" switch be turned OFF by default?

Here is what I currently have

```<code> "resources": [
{
  "name": "[parameters('serverName')]",
  "type": "Microsoft.Sql/servers",
  "location": "[parameters('location')]",
  "apiVersion": "2014-04-01-preview",
  "properties": {
    "administratorLogin": "[parameters('administratorLogin')]",
    "administratorLoginPassword": "[parameters('administratorLoginPassword')]",
    "version": "[parameters('serverVersion')]"
  },
  "tags": {
    "deploymentVersion": "[parameters('deploymentVersion')]",
    "deploymentType": "[parameters('deploymentType')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01-preview",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
      ],
      "location": "[parameters('location')]",
      "name": "AllowAllWindowsAzureIps",
      "properties": {
        "endIpAddress": "0.0.0.0",
        "startIpAddress": "0.0.0.0"
      },
      "type": "firewallrules"
    }
  ]
}  ]
</code>```

答: Just remove the nested resources section. Then the sql will deploy without that checkmark. Redeploying won't remove the rule, but deploying a new sql will work.

Body:
Does anybody know how to setup ARM Template to keep "Allow access to Azure services" switch be turned OFF by default?

Here is what I currently have

 "resources": [
{
  "name": "[parameters('serverName')]",
  "type": "Microsoft.Sql/servers",
  "location": "[parameters('location')]",
  "apiVersion": "2014-04-01-preview",
  "properties": {
    "administratorLogin": "[parameters('administratorLogin')]",
    "administratorLoginPassword": "[parameters('administratorLoginPassword')]",
    "version": "[parameters('serverVersion')]"
  },
  "tags": {
    "deploymentVersion": "[parameters('deploymentVersion')]",
    "deploymentType": "[parameters('deploymentType')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01-preview",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
      ],
      "location": "[parameters('location')]",
      "name": "AllowAllWindowsAzureIps",
      "properties": {
        "endIpAddress": "0.0.0.0",
        "startIpAddress": "0.0.0.0"
      },
      "type": "firewallrules"
    }
  ]
}  ]


问:
Filtering inside the List
Firstly,i fill in the list with some objects with different propetries and afterwards I'd like to remove all inappropriate objects from this list.
For sure, it throws an exception, saying that the list has been modified and it leads to problems with enumeration. How to manage this and remove all inappropriate objects without using another List, for example, ListFiltred, where I can add all appropriate objects?    </p>

```<code>MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "01" });
MyList.Add(new Houses() { Number = "02" });
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "04" });
foreach (var item in MyList)
{
    if (item.Number != "04")
    {
        MyList.Remove(item);
    }
}
</code>```

答:
List<T> has a RemoveAll method that takes a predicate. You can use it like this:

```<code>MyList.RemoveAll(x=>x.Number != "04");
</code>```

Title: Filtering inside the List

Body:
Firstly,i fill in the list with some objects with different propetries and afterwards I'd like to remove all inappropriate objects from this list.
For sure, it throws an exception, saying that the list has been modified and it leads to problems with enumeration. How to manage this and remove all inappropriate objects without using another List, for example, ListFiltred, where I can add all appropriate objects?

MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "01" });
MyList.Add(new Houses() { Number = "02" });
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "04" });
foreach (var item in MyList)
{
    if (item.Number != "04")
    {
        MyList.Remove(item);
    }
}

Body:
List<T> has a RemoveAll method that takes a predicate. You can use it like this:

MyList.RemoveAll(x=>x.Number != "04");


问:
React, Redux, Chai How do I wait for the payload of my test?
I think I have to reword my question. How do trigger the action and wait for a response. I am using firebase to save my data and redux thunk.

```<code>import {myAction} from "../../src/js/actions/index";

describe('My Description', () => {
    it('has correct payload', () => {

        const action = myAction();

        expect(action.payload).log(); //this doesn't work
        expect(action.payload).to.equal({some:"json"});
        //this fails but I want to see what was returned so I can fix it
    })
})
</code>```

//my action

```<code>export function myAction(data){

return dispatch => {
    //firebase
    const sectionKey =  agendaRef.push().key;
    agendaRef.child(   sectionKey  ).set(data);
    dispatch({
        type: ADD_ITEM_SAVE_SUCCESS,
        //payload: true
    })

  }
}
</code>```

答:
I had updated your code to print the payload value in the console log statement.</p>

```<code>import {myAction} from "../../src/js/actions/index";
//note my action is using a dispatch method from Redux Thunk

describe('My Description', () => {
    it('has correct payload', () => {

        const action = myAction();

        console.log(action.payload); //MODIFIED line
        expect(action.payload).to.equal({some:"json"});
        //this fails but I want to see what was returned so I can fix it
    })
})
</code>```

Body:
I think I have to reword my question. How do trigger the action and wait for a response. I am using firebase to save my data and redux thunk.

import {myAction} from "../../src/js/actions/index";

describe('My Description', () => {
    it('has correct payload', () => {

        const action = myAction();

        expect(action.payload).log(); //this doesn't work
        expect(action.payload).to.equal({some:"json"});
        //this fails but I want to see what was returned so I can fix it
    })
})

//my action

export function myAction(data){

return dispatch => {
    //firebase
    const sectionKey =  agendaRef.push().key;
    agendaRef.child(   sectionKey  ).set(data);
    dispatch({
        type: ADD_ITEM_SAVE_SUCCESS,
        //payload: true
    })

  }
}

Body:
I had updated your code to print the payload value in the console log statement.

import {myAction} from "../../src/js/actions/index";
//note my action is using a dispatch method from Redux Thunk

describe('My Description', () => {
    it('has correct payload', () => {

        const action = myAction();

        console.log(action.payload); //MODIFIED line
        expect(action.payload).to.equal({some:"json"});
        //this fails but I want to see what was returned so I can fix it
    })
})


问:
Parsing through Maps Javascript
I have a map returned by performing certain operations on a json data retrieved from a server. The map structure looks like follows when i print the key and values

```<code>action = [object Map]
comedy = [object Map]
thriller = [object Map]
</code>```

And with in a object Map (i.e when i just print the values) they have counts which i expect.

```<code>Map {
 'spanish' => 3
 'english' => 4
}
Map {
 'spanish' => 1
 'english' => 2
}
</code>```

I want to convert the nested map inside an array based something like this. is there already existing libraries i can leverage off?

```<code>var comedy[] = ['spanish_1', 'english_2']
var action[] =['spanish_3', 'english_4']
</code>```

Please suggest if this is the ideal way to handle this data as i am finding it difficult to get the data out of the nested map.

答:
Get the items in your map using Map.entries and iterate over it using Array.from to create a new Array having your desired values.

```<code>const myNewArray = Array.from(myMap.entries(), ([
  key,
  value,
]) => `${key}_${value}`);
</code>```

EDIT

To get the following result :

```<code>{
   actions: [
     'spanish_3',
     ...
   ],

   comedy: [
    'spanish_3',
     ...
   ],
}
</code>```

I loop on the first map level to feed a new json object that I fill with second level map data.

```<code>    Array.from(myMap.entries()).reduce((tmp, [
      xKey,
      xValue,
    ]) => ({
      ...tmp,

      [xKey]: Array.from(xValue.entries(), ([
        yKey,
        yValue,
      ]) => `${yKey}_${yValue}`),
    }), {});
</code>```

To get the following output

```<code>[
   [
     'spanish_3',
     ...
   ],

   [
    'spanish_3',
     ...
   ],

   ...
]
</code>```

Here I create a 2 dimensional array, that I use along with destructuration (the destructuration will work if you already know the data that's comming).

```<code>    const [
      action,
      comedy,
      thriller,
    ] = Array.from(myMap.entries(), ([
      xKey,
      xValue,
    ]) => Array.from(xValue.entries(), ([
      yKey,
      yValue,
    ]) => `${yKey}_${yValue}`));
</code>```

There is plenty of use case, depends what info you have and what you want to do with it. Hope all examples will give you enough help to figure your specific use case out. :)

Title: Parsing through Maps Javascript

Body:
I have a map returned by performing certain operations on a json data retrieved from a server. The map structure looks like follows when i print the key and values

action = [object Map]
comedy = [object Map]
thriller = [object Map]

And with in a object Map (i.e when i just print the values) they have counts which i expect.

Map {
 'spanish' => 3
 'english' => 4
}
Map {
 'spanish' => 1
 'english' => 2
}

I want to convert the nested map inside an array based something like this. is there already existing libraries i can leverage off?

var comedy[] = ['spanish_1', 'english_2']
var action[] =['spanish_3', 'english_4']

Please suggest if this is the ideal way to handle this data as i am finding it difficult to get the data out of the nested map.

Body:
Get the items in your map using Map.entries and iterate over it using Array.from to create a new Array having your desired values.

const myNewArray = Array.from(myMap.entries(), ([
  key,
  value,
]) => `${key}_${value}`);

EDIT

To get the following result :

{
   actions: [
     'spanish_3',
     ...
   ],

   comedy: [
    'spanish_3',
     ...
   ],
}

I loop on the first map level to feed a new json object that I fill with second level map data.

    Array.from(myMap.entries()).reduce((tmp, [
      xKey,
      xValue,
    ]) => ({
      ...tmp,

      [xKey]: Array.from(xValue.entries(), ([
        yKey,
        yValue,
      ]) => `${yKey}_${yValue}`),
    }), {});

To get the following output

[
   [
     'spanish_3',
     ...
   ],

   [
    'spanish_3',
     ...
   ],

   ...
]

Here I create a 2 dimensional array, that I use along with destructuration (the destructuration will work if you already know the data that's comming).

    const [
      action,
      comedy,
      thriller,
    ] = Array.from(myMap.entries(), ([
      xKey,
      xValue,
    ]) => Array.from(xValue.entries(), ([
      yKey,
      yValue,
    ]) => `${yKey}_${yValue}`));

There is plenty of use case, depends what info you have and what you want to do with it. Hope all examples will give you enough help to figure your specific use case out. :)


问:
Collection was modified in a foreach loop
I'm trying to get notifications from a bluetooth device sending records, and periodically update the UI to display the records.  The while loop below sits in its own thread to handle UI updates while the rest of the module takes care of other tasks.  gattCallback is an instance of a BluetoothGattCallback class that adds to a list of received records and returns that list when getHistory() is called.

My problem is that when I hit the foreach line, after so many iterations I get an error:

```<code>System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
</code>```

As far as I can tell, history isn't being updated here or anywhere else in my code so I'm confused by the error.  I specifically retrieve a copy of the record history through getHistory() to avoid modifying it during the foreach. Can anyone suggest what might be causing it or any tips to find out?

It might be relevant that this has only caused issues since switching to a Moto E4 on Android 7.1.1 from a Moto G Play on Android 6.0.1.

```<code>        // Periodically check to see what needs updating
        while (!finishedDisplayThread)
        {
            // See if there are any new records to display
            int count;

            List<Record> history = gattCallback.getHistory();

            if (history == null)
            {
                count = 0;
            }
            else
            {
                count = history.Count;
            }

            // Only update the display if it has changed
            if(count != prevCount)
            {
                prevCount = count;
                List<string> recordList = new List<string>();
                if (history == null)
                {
                    recordList = new List<string>();
                    recordList.Add("No history.");
                }
                else
                {
                    foreach (Record record in history)
                    {
                        recordList.Add(record.ToRow());
                    }
                }

                //Update the display
                RunOnUiThread(() =>
                {
                    ListAdapter = new ArrayAdapter<string>(this,
                                                           Resource.Layout.ListItemLayout,
                                                           recordList);
                    recordCountText.Text = "" + count;
                });
            }

            Thread.Sleep(100);
        }
</code>```

答:
I specifically retrieve a copy of the record history through getHistory() to avoid modifying it during the foreach.

Are you certain that you're getting a copy? Imagine this implementation:

```<code>public List<Record> getHistory() {
    return history;
}
</code>```

This will not return a copy of history, but a reference directly to history itself. If two different places call this method, any changes to one of the returned values will affect the other returned value.

If you want a copy, you have to do something like this:

```<code>public List<Record> getHistory() {
    return new ArrayList<>(history);
}
</code>```

Body:
I'm trying to get notifications from a bluetooth device sending records, and periodically update the UI to display the records.  The while loop below sits in its own thread to handle UI updates while the rest of the module takes care of other tasks.  gattCallback is an instance of a BluetoothGattCallback class that adds to a list of received records and returns that list when getHistory() is called.

My problem is that when I hit the foreach line, after so many iterations I get an error:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

As far as I can tell, history isn't being updated here or anywhere else in my code so I'm confused by the error.  I specifically retrieve a copy of the record history through getHistory() to avoid modifying it during the foreach. Can anyone suggest what might be causing it or any tips to find out?

It might be relevant that this has only caused issues since switching to a Moto E4 on Android 7.1.1 from a Moto G Play on Android 6.0.1.

        // Periodically check to see what needs updating
        while (!finishedDisplayThread)
        {
            // See if there are any new records to display
            int count;

            List<Record> history = gattCallback.getHistory();

            if (history == null)
            {
                count = 0;
            }
            else
            {
                count = history.Count;
            }

            // Only update the display if it has changed
            if(count != prevCount)
            {
                prevCount = count;
                List<string> recordList = new List<string>();
                if (history == null)
                {
                    recordList = new List<string>();
                    recordList.Add("No history.");
                }
                else
                {
                    foreach (Record record in history)
                    {
                        recordList.Add(record.ToRow());
                    }
                }

                //Update the display
                RunOnUiThread(() =>
                {
                    ListAdapter = new ArrayAdapter<string>(this,
                                                           Resource.Layout.ListItemLayout,
                                                           recordList);
                    recordCountText.Text = "" + count;
                });
            }

            Thread.Sleep(100);
        }

Body:
I specifically retrieve a copy of the record history through getHistory() to avoid modifying it during the foreach.

Are you certain that you're getting a copy? Imagine this implementation:

public List<Record> getHistory() {
    return history;
}

This will not return a copy of history, but a reference directly to history itself. If two different places call this method, any changes to one of the returned values will affect the other returned value.

If you want a copy, you have to do something like this:

public List<Record> getHistory() {
    return new ArrayList<>(history);
}


问:
networkX node_connected_component not implemented for directed type
I use networkX to build a directed graph, and I need to find the sub-graph that containing a special node. I try node_connected_component, but it can't implemented for directed graph, is there other function that can implement for directed graph in networkX?</p>

答:
As someone mentioned it depends what you call a connected component in a directed graph:

Strongly connected components:

There is a directed path between node A to node B and another from node B to node A.

Weakly connected components:

There is a directed path from node A to node B but not necessarily from node B to node A.

What you can do:

```<code>def get_strongly_cc(G, node):
    """ get storngly connected component of node"""
    for cc in nx.strongly_connected_components(G):
        if node in cc:
            return cc
    else:
        return set()

def get_weakly_cc(G, node):
    """ get weakly connected component of node"""
    for cc in nx.weakly_connected_components(G):
        if node in cc:
            return cc
    else:
        return set()

weak_component = get_weakly_cc(G, node)  # Weakly connected component of node in G
strong_component = get_strongly_cc(G, node)  # Strongly connected component of node in G
</code>```

Body:
As someone mentioned it depends what you call a connected component in a directed graph:

Strongly connected components:

There is a directed path between node A to node B and another from node B to node A.

Weakly connected components:

There is a directed path from node A to node B but not necessarily from node B to node A.

What you can do:

def get_strongly_cc(G, node):
    """ get storngly connected component of node"""
    for cc in nx.strongly_connected_components(G):
        if node in cc:
            return cc
    else:
        return set()

def get_weakly_cc(G, node):
    """ get weakly connected component of node"""
    for cc in nx.weakly_connected_components(G):
        if node in cc:
            return cc
    else:
        return set()

weak_component = get_weakly_cc(G, node)  # Weakly connected component of node in G
strong_component = get_strongly_cc(G, node)  # Strongly connected component of node in G


问:
Thread.sleep(1) stuck as seen in thread dump
I am using JRocket1.6. In thread dump, I am seeing

```<code>"Thread-174" id=994 idx=0xb54 tid=1012 prio=10 alive, sleeping, native_waiting
    at java/lang/Thread.sleep(J)V(Native Method)
    at com/test/EraserThread.run(EraserThread.java:50)
    at java/lang/Thread.run(Thread.java:662)
    at jrockit/vm/RNI.c2java(JJJJJ)V(Native Method)
    -- end of trace
</code>```

This thread is being stuck and never gets released.

Code :

```<code>public static String readAndMaskPassword( BufferedReader reader, PrintWriter writer){
         //Starting the masking thread for the password entered
           EraserThread et = new EraserThread(writer);
           Thread mask = new Thread(et);
           mask.start();

           String password = "";

           try {
              password = reader.readLine();
           } catch (IOException ioe) {
             ioe.printStackTrace();
           }
           // stop masking
           et.stopMasking();
           // return the password entered by the user
           return password;
       }
</code>```

readAndMaskPassword method return entered password and its returning from this method correctly.

EraserThread.java :

```<code>public void run() {
        int priority = Thread.currentThread().getPriority();
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        try{
            while (start) {
                writer.print("\b ");
                writer.flush();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ie) {
                    _logger.error(ie.getMessage(),ie);
                }
            }
        }finally{
            //Restore the original priority
            Thread.currentThread().setPriority(priority);
        }
    }

    public void stopMasking() {
        this.start = false;
    }
</code>```

stopMasking method is being called and start is set to false. I am confused why EraserThread is getting stuck at Thread.sleep(1) as per thread dump.

Requesting your help.

答:
It’s not actually stuck.  It’s just that any time you examine the thread’s stack trace, it is far more likely to be executing the sleep call.

A call to writer.print or writer.flush takes a fraction of a millisecond, on average.  So, if we pretend for the sake of illustration that each of those methods takes 0.01 milliseconds, your loop execution’s time allocation looks like this:

```<code>writer.print    0.01 ms
writer.flush    0.01 ms
Thread.sleep    1.00 ms
</code>```

As you can see, any time you ask for a thread dump, the odds are much greater that it will be executing sleep than the other methods.

An additional note:  Your try/catch should be outside the while loop.  As your loop is written now, it ignores interrupts, which makes it a rogue thread—a thread which cannot be halted.  Threads cannot be “killed”;  they can only be interrupted, and it is each Thread’s responsibility to properly clean up and exit in response to an interrupt.

The easy solution is to move your while loop inside your try/catch:

```<code>try {
    while (start) {
        writer.print("\b ");
        writer.flush();
        Thread.sleep(1);
    }
} catch (InterruptedException ie) {
    _logger.error(ie.getMessage(), ie);
}
</code>```

What this implies is that you could, if you wanted, do away with the start variable (and use while (true) instead), and do away with the stopMasking method, and instead simply interrupt the thread to stop it:

```<code>mask.interrupt();
</code>```

(I repeat that as your code is currently written, calling mask.interrupt() effectively does nothing.)

Body:
I am using JRocket1.6. In thread dump, I am seeing

"Thread-174" id=994 idx=0xb54 tid=1012 prio=10 alive, sleeping, native_waiting
    at java/lang/Thread.sleep(J)V(Native Method)
    at com/test/EraserThread.run(EraserThread.java:50)
    at java/lang/Thread.run(Thread.java:662)
    at jrockit/vm/RNI.c2java(JJJJJ)V(Native Method)
    -- end of trace

This thread is being stuck and never gets released.

Code :

public static String readAndMaskPassword( BufferedReader reader, PrintWriter writer){
         //Starting the masking thread for the password entered
           EraserThread et = new EraserThread(writer);
           Thread mask = new Thread(et);
           mask.start();

           String password = "";

           try {
              password = reader.readLine();
           } catch (IOException ioe) {
             ioe.printStackTrace();
           }
           // stop masking
           et.stopMasking();
           // return the password entered by the user
           return password;
       }

readAndMaskPassword method return entered password and its returning from this method correctly.

EraserThread.java :

public void run() {
        int priority = Thread.currentThread().getPriority();
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        try{
            while (start) {
                writer.print("\b ");
                writer.flush();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ie) {
                    _logger.error(ie.getMessage(),ie);
                }
            }
        }finally{
            //Restore the original priority
            Thread.currentThread().setPriority(priority);
        }
    }

    public void stopMasking() {
        this.start = false;
    }

stopMasking method is being called and start is set to false. I am confused why EraserThread is getting stuck at Thread.sleep(1) as per thread dump.

Requesting your help.

Body:
It’s not actually stuck.  It’s just that any time you examine the thread’s stack trace, it is far more likely to be executing the sleep call.

A call to writer.print or writer.flush takes a fraction of a millisecond, on average.  So, if we pretend for the sake of illustration that each of those methods takes 0.01 milliseconds, your loop execution’s time allocation looks like this:

writer.print    0.01 ms
writer.flush    0.01 ms
Thread.sleep    1.00 ms

As you can see, any time you ask for a thread dump, the odds are much greater that it will be executing sleep than the other methods.

An additional note:  Your try/catch should be outside the while loop.  As your loop is written now, it ignores interrupts, which makes it a rogue thread—a thread which cannot be halted.  Threads cannot be “killed”;  they can only be interrupted, and it is each Thread’s responsibility to properly clean up and exit in response to an interrupt.

The easy solution is to move your while loop inside your try/catch:

try {
    while (start) {
        writer.print("\b ");
        writer.flush();
        Thread.sleep(1);
    }
} catch (InterruptedException ie) {
    _logger.error(ie.getMessage(), ie);
}

What this implies is that you could, if you wanted, do away with the start variable (and use while (true) instead), and do away with the stopMasking method, and instead simply interrupt the thread to stop it:

mask.interrupt();

(I repeat that as your code is currently written, calling mask.interrupt() effectively does nothing.)


问:
How to use proc format with the number of lines?
I have a table like this :

```<code> |Num |  Label
-----------------------
1|1   |  a thing
2|2   |  another thing
3|3   |  something else
4|4   |  whatever
</code>```

I want to replace my values of my label column by something more generic for example the first two lines : label One, the two next ones label Two ...

```<code> |Num |  Label
-----------------------
1|1   |  label One
2|2   |  label One
3|3   |  label Two
4|4   |  label Two
</code>```

How can I do that using proc format procedure ? I was wondering if I can use either the number of lines or another column like Num.

I need to do something like this :

```<code>proc format;
value label_f
low-2 = "label One"
3-high = "label Two"
;
run;
</code>```

But I want to specify the number of the line or the value of the Num column.

答:
You could do what you are describing using the words format. You could swap out num for _N_ in the ceil function below in order to use the observation number instead of the value of num (if they are not always equal):

```<code>data have;
length num 8 label $20;
infile datalines dlm='|';
input num label $;
datalines;
1|a thing
2|another thing
3|something else
4|whatever
5|whatever else
6|so many things
;
run;

data want;
set have;
label=catx(' ','label',propcase(put(ceil(num/2),words.)));
run;
</code>```

Although this answer is probably a bit too specific to your example and it may not apply in your actual context.

Body:
I have a table like this :

 |Num |  Label
-----------------------
1|1   |  a thing
2|2   |  another thing
3|3   |  something else
4|4   |  whatever

I want to replace my values of my label column by something more generic for example the first two lines : label One, the two next ones label Two ...

 |Num |  Label
-----------------------
1|1   |  label One
2|2   |  label One
3|3   |  label Two
4|4   |  label Two

How can I do that using proc format procedure ? I was wondering if I can use either the number of lines or another column like Num.

I need to do something like this :

proc format;
value label_f
low-2 = "label One"
3-high = "label Two"
;
run;

But I want to specify the number of the line or the value of the Num column.

Body:
You could do what you are describing using the words format. You could swap out num for _N_ in the ceil function below in order to use the observation number instead of the value of num (if they are not always equal):

data have;
length num 8 label $20;
infile datalines dlm='|';
input num label $;
datalines;
1|a thing
2|another thing
3|something else
4|whatever
5|whatever else
6|so many things
;
run;

data want;
set have;
label=catx(' ','label',propcase(put(ceil(num/2),words.)));
run;

Although this answer is probably a bit too specific to your example and it may not apply in your actual context.


问:
Monodroid Linking Sdk Assemblies causing SIGSEGV in Mono Library
I have C# Android code that works fine when using either Shared Runtime (Mono) or Linking Sdk Assemblies, but when both are present, it stops working.  I can build with No linking, without using shared runtime and it runs flawlessly, but when I am trying to package for deployment (Sdk Linking and No Shared Runtime) I get a SIGSEGV:

```<code>03-22 08:23:56.486 E/mono-rt ( 2526): Stacktrace:
03-22 08:23:56.486 E/mono-rt ( 2526):
03-22 08:23:56.496 E/mono-rt ( 2526):   at <unknown> <0xffffffff>
03-22 08:23:56.496 E/mono-rt ( 2526):   at (wrapper managed-to-native) System.Net.Sockets.Socket.SetSocketOption_internal (intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&) <IL 0x0002a, 0xffffffff>
03-22 08:23:56.496 E/mono-rt ( 2526):   at System.Net.Sockets.Socket.SetSocketOption (System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object) <IL 0x000c2, 0x004cf>
03-22 08:23:56.496 E/mono-rt ( 2526):   at Keiser.Plugin.Socket.NetSocket.CreateListeningSocket () [0x00041] in d:\Development\Keiser.MPM.Screen\Keiser.Plugin.Socket.Droid\NetSocket.cs:73
03-22 08:23:56.496 E/mono-rt ( 2526):   at Keiser.Plugin.Socket.NetSocket.StartListener (System.AsyncCallback) [0x00012] in d:\Development\Keiser.MPM.Screen\Keiser.Plugin.Socket.Droid\NetSocket.cs:92
The program 'Mono' has exited with code 0 (0x0).
</code>```

The last method in my code is this:

```<code>    protected virtual void CreateListeningSocket()
    {
        lock (Locker)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _port);
            _socket.Bind(ipEndPoint);
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(_ipAddress)));
            _endPointSender = new IPEndPoint(IPAddress.Any, 0);
        }
    }
</code>```

Is there any way for me to solve this?  I've tried refactoring using UDPClient, but it gives the same error on the line where I call the JoinMulticastGroup on the UDPClient object.  Is this an error inside of the monodroid assembly?

** Note: This code is inside a MvvmCross plugin which is reference by the Core PCL for the project, which is itself reference by the Android project.

答: Now I know how to reproduce it, sent it to Xamarin. It happens when calling JoinMulticastGroup and also starting another socket operation in background. https://bugzilla.xamarin.com/show_bug.cgi?id=22183 Reproducible in Mono 5.4. Workaround is to JoinMulticastGroup before performing any other socket operations.</p>

Body:
I have C# Android code that works fine when using either Shared Runtime (Mono) or Linking Sdk Assemblies, but when both are present, it stops working.  I can build with No linking, without using shared runtime and it runs flawlessly, but when I am trying to package for deployment (Sdk Linking and No Shared Runtime) I get a SIGSEGV:

03-22 08:23:56.486 E/mono-rt ( 2526): Stacktrace:
03-22 08:23:56.486 E/mono-rt ( 2526):
03-22 08:23:56.496 E/mono-rt ( 2526):   at <unknown> <0xffffffff>
03-22 08:23:56.496 E/mono-rt ( 2526):   at (wrapper managed-to-native) System.Net.Sockets.Socket.SetSocketOption_internal (intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&) <IL 0x0002a, 0xffffffff>
03-22 08:23:56.496 E/mono-rt ( 2526):   at System.Net.Sockets.Socket.SetSocketOption (System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object) <IL 0x000c2, 0x004cf>
03-22 08:23:56.496 E/mono-rt ( 2526):   at Keiser.Plugin.Socket.NetSocket.CreateListeningSocket () [0x00041] in d:\Development\Keiser.MPM.Screen\Keiser.Plugin.Socket.Droid\NetSocket.cs:73
03-22 08:23:56.496 E/mono-rt ( 2526):   at Keiser.Plugin.Socket.NetSocket.StartListener (System.AsyncCallback) [0x00012] in d:\Development\Keiser.MPM.Screen\Keiser.Plugin.Socket.Droid\NetSocket.cs:92
The program 'Mono' has exited with code 0 (0x0).

The last method in my code is this:

    protected virtual void CreateListeningSocket()
    {
        lock (Locker)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _port);
            _socket.Bind(ipEndPoint);
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(_ipAddress)));
            _endPointSender = new IPEndPoint(IPAddress.Any, 0);
        }
    }

Is there any way for me to solve this?  I've tried refactoring using UDPClient, but it gives the same error on the line where I call the JoinMulticastGroup on the UDPClient object.  Is this an error inside of the monodroid assembly?

** Note: This code is inside a MvvmCross plugin which is reference by the Core PCL for the project, which is itself reference by the Android project.


问:
How do I configure full URLs in xcconfig files
I have an xcconfig file which contains a configuration for which server my app should hit. In debug mode, this will be a different server than for release builds.

The problem I have is that a URL of the form http://www.stackoverflow.com is treated as a comment after the double slash. So the string I get in code is 'http:'

I have read that I can put a -traditional build flag on Info.plist, I was wondering if someone else has had a similar issue and has solved it?

Thanks.

答:
```<code>SLASH=/

API_URL=http:$(SLASH)/endpoint.com
</code>```


问:
Puppeteer screenshot stop in random URL
I have a service nodejs working in Ubuntu, using puppeteer to take screenshots of pages, but in some pages the method page.screenshot({fullPage: true, type: 'jpeg'}) doesn't works in some random URLs and no errors are displayed in the log. The code is:

```<code>async takeScreenshot() {
        console.log('trying take Screenshot [...]');
        let image = await this.page.screenshot({fullPage: true, type: 'jpeg'});
        console.log('Completed!');
        return image;
    }
</code>```

An example of page that I had this problem is: https://nuevo.jumbo.cl/mayonesa-hellmanns-751-g-supreme-light/p

答:
You did not explain how it did not work, or how you expected it to show, but I'm assuming it captured something like the following image.

When you first load the page, it'll load something like this, which is not related to puppeteer, since you are not telling the code to wait for certain amount, if you are doing so, I don't see it specified anywhere.

For me, just normal screenshot worked, except the region settings. I used version 0.13 and the following code,

```<code>await page.goto("https://nuevo.jumbo.cl/mayonesa-hellmanns-751-g-supreme-light/p", {waitUntil: "networkidle0"});
    await page.screenshot({
        path: "test_google.png",
        fullPage: true
    });
});
</code>```

Title: Puppeteer screenshot stop in random URL

Body:
I have a service nodejs working in Ubuntu, using puppeteer to take screenshots of pages, but in some pages the method page.screenshot({fullPage: true, type: 'jpeg'}) doesn't works in some random URLs and no errors are displayed in the log. The code is:

async takeScreenshot() {
        console.log('trying take Screenshot [...]');
        let image = await this.page.screenshot({fullPage: true, type: 'jpeg'});
        console.log('Completed!');
        return image;
    }

An example of page that I had this problem is: https://nuevo.jumbo.cl/mayonesa-hellmanns-751-g-supreme-light/p

Body:
You did not explain how it did not work, or how you expected it to show, but I'm assuming it captured something like the following image.

When you first load the page, it'll load something like this, which is not related to puppeteer, since you are not telling the code to wait for certain amount, if you are doing so, I don't see it specified anywhere.

For me, just normal screenshot worked, except the region settings. I used version 0.13 and the following code,

await page.goto("https://nuevo.jumbo.cl/mayonesa-hellmanns-751-g-supreme-light/p", {waitUntil: "networkidle0"});
    await page.screenshot({
        path: "test_google.png",
        fullPage: true
    });
});


问:
IIS Application Pool reverted to v2.0 .NET Framework
Ok, so I'm not really sure where to put this.

I support a plant that runs a webpage to make changes to the process.

It runs on .net framework 4.0

For some reason (they claim they have done nothing) it reverted everything in IIS to v2.0 (this has happened twice)

What could possibly do this / how could I find out what did this...

答:
When you run the command using only -i parameter and you have both framework (2 and 4) applications on the server, it will reset all to framework 2.0. Use -iru will solve the problem.

Source: https://msdn.microsoft.com/en-Us/library/k6h9cz8h(v=vs.100).aspx


答:
You can convert it to an array and map the data to your desired format:

const map = new Map()
map.set('spanish', 3)
map.set('english', 4)

const result = Array.from(map).map(([key, value]) => `${key}_${value}`)

console.log(result) // ["spanish_3", "english_4"]```

Title: Parsing through Maps Javascript


问:
Scala nested Lists
I’m trying to fetch a value from a nested list in Scala but somehow I’m not able to find a solution.

I’ve created a list as:

```<code>var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))
</code>```

I require 7 as the output.

In Python, for the same thing, I’m creating list as

```<code>list3 = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]
</code>```

To get the output as 7, I’m using

```<code>list3[len(list3) -2][len(list3) -4]
</code>```

Please suggest me how to achieve the same in Scala.

Thanks in advance.

答:
You can use productElement as below

```<code>scala> var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))
list3: List[Product with Serializable] = List((1,2,3), (4,5,6), (7,8), (9,10,11,12))

scala> list3(list3.length -2).productElement(list3.length-4)
res0: Any = 7
</code>```

Title: Scala nested Lists

Body:
I’m trying to fetch a value from a nested list in Scala but somehow I’m not able to find a solution.

I’ve created a list as:

var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))

I require 7 as the output.

In Python, for the same thing, I’m creating list as

list3 = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]

To get the output as 7, I’m using

list3[len(list3) -2][len(list3) -4]

Please suggest me how to achieve the same in Scala.

Thanks in advance.

Body:
You can use productElement as below

scala> var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))
list3: List[Product with Serializable] = List((1,2,3), (4,5,6), (7,8), (9,10,11,12))

scala> list3(list3.length -2).productElement(list3.length-4)
res0: Any = 7


问:
R interactive plot?
How can a user interactively change one aspect (e.g., orientation or length of a line) on a 2D plot?</p>

答:
The tkexamp function in the TeachingDemos package helps you to create a graph with controls to change various options in the plot, there are several examples on the help page that can be run to see how it works.

The TkIdentify function in the same package allows you to drag labels (along with lines pointing from points to labels) to a desired position, you could start with the code from that function (all R, nothing compiled) as a basis for your own dynamic plot that would allow dragging a line.

Title: R interactive plot?


问:
Best practice when rolling back to the last commit in a branch
So, I made a bad commit, and merged it into my test-branch, and found out it didn't work.

The appropriate action, in my opinion, would be to roll back the test-branch, and deploy it again. But how I do that, without loosing the rest of my work?

I usually work with TFS (newest version), but it could also be just on my local machine it happened.

Edit: This is what I fear might happen (see below).
A coworker makes a commit, and merges it in, and his code breaks because mine didn't work.
And it could take hours, days, weeks before I make the last commit.
So I need to roll it back to not break other's work as well.

Git Flow is not a magic word I'm after, since we just share the Developer-branch.

答:
Since you are asking for best practice, here's an advice:

Do not rewrite history.

Fix the issue and merge it instead.

If it is important for you that a given branch only ever contains a known-to-work copy of your code, you really should look into Continuous Integration, and only ever allow merges into your precious "Test" branch if the CI-build succeeds.

(there's a number of git-based project management systems, like GitLab or GitHub that either have CI-support built-in or have a tight integration with 3rd party CI-providers).