问:
How to always get a zipcode record from ggmap/googleway package in R?
Two questions related to this topic. First, with the sample address '方桥社区居委会', I first checked it directly from Google Map, and I get both its location and its English translation 'Fangqiao Community Residents' Committee'.
However, when I try to run the code

```<code>library(googleway)
key <- 'APIkey'
google_geocode(address = "方桥社区居委会", language = "CN", key = key)
</code>```

The result I got from above Chinese address is

```<code>$results

address_components
1 Xinhai Avenue, Yaohai Qu, Hefei Shi, Anhui Sheng, China, Xinhai Ave, Yaohai
Qu, Hefei Shi, Anhui Sheng, CN, route, political, sublocality,
sublocality_level_1, locality, political, administrative_area_level_1,
political, country, political
                                 formatted_address geometry.location.lat
1 Xinhai Ave, Yaohai Qu, Hefei Shi, Anhui Sheng, China              31.89561
  geometry.location.lng geometry.location_type
geometry.viewport.northeast.lat
1              117.3393            APPROXIMATE
31.89696
  geometry.viewport.northeast.lng geometry.viewport.southwest.lat
1                        117.3407                        31.89426
  geometry.viewport.southwest.lng                    place_id
1                         117.338 ChIJ2attw2plyzUR782Meh0Xnvs
                         types
1 establishment, point_of_interest

$status
[1] "OK"
</code>```

I can not get its postal_code information. When I use the following codes

```<code>google_geocode(address = "Fangqiao Community Residents' Committee", language = "CN", key = key)
</code>```

I can get its postal_code information.

```<code>$results

address_components
1 Jiangdu Road, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, China, 225009,
Jiangdu Rd, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, CN, 225009, route,
political, sublocality, sublocality_level_1, locality, political,
administrative_area_level_1, political, country, political, postal_code
                                                 formatted_address
1 Jiangdu Rd, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, China, 225009
  geometry.location.lat geometry.location.lng geometry.location_type
1              32.39118              119.4622            APPROXIMATE
  geometry.viewport.northeast.lat geometry.viewport.northeast.lng
1                        32.39253                        119.4635
  geometry.viewport.southwest.lat geometry.viewport.southwest.lng
partial_match
1                        32.38983                        119.4608
TRUE
                 place_id                            types
1 ChIJcQhNY82HtjURw8QwBzgCGgA establishment, point_of_interest

$status
[1] "OK"
</code>```

Why is there a difference?
May I know how this package works or how Google Map works, and in which way I can get the zip code of a location of China for sure?

答:
You can consider using the geocode() function from the ggmap package.

```<code>library(ggmap)

result <- geocode("方桥社区居委会", output = 'more', source = 'google')

## components in the 'result' variable
 lon      lat          type          loctype
1 117.3393 31.89561 establishment geometric_center
                                                       address
1 xinhai ave, yaohai qu, hefei shi, anhui sheng, china, 230000
     north    south     east    west         route political
1 31.89696 31.89426 117.3407 117.338 Xinhai Avenue Yaohai Qu
   locality administrative_area_level_1 country postal_code
1 Hefei Shi                 Anhui Sheng   China      230000
</code>```

To obtain the zip code / postal code:

```<code>> result$postal_code
[1] 230000
</code>```

Body:
Two questions related to this topic. First, with the sample address '方桥社区居委会', I first checked it directly from Google Map, and I get both its location and its English translation 'Fangqiao Community Residents' Committee'.
However, when I try to run the code

library(googleway)
key <- 'APIkey'
google_geocode(address = "方桥社区居委会", language = "CN", key = key)

The result I got from above Chinese address is

$results

address_components
1 Xinhai Avenue, Yaohai Qu, Hefei Shi, Anhui Sheng, China, Xinhai Ave, Yaohai
Qu, Hefei Shi, Anhui Sheng, CN, route, political, sublocality,
sublocality_level_1, locality, political, administrative_area_level_1,
political, country, political
                                 formatted_address geometry.location.lat
1 Xinhai Ave, Yaohai Qu, Hefei Shi, Anhui Sheng, China              31.89561
  geometry.location.lng geometry.location_type
geometry.viewport.northeast.lat
1              117.3393            APPROXIMATE
31.89696
  geometry.viewport.northeast.lng geometry.viewport.southwest.lat
1                        117.3407                        31.89426
  geometry.viewport.southwest.lng                    place_id
1                         117.338 ChIJ2attw2plyzUR782Meh0Xnvs
                         types
1 establishment, point_of_interest

$status
[1] "OK"

I can not get its postal_code information. When I use the following codes

google_geocode(address = "Fangqiao Community Residents' Committee", language = "CN", key = key)

I can get its postal_code information.

$results

address_components
1 Jiangdu Road, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, China, 225009,
Jiangdu Rd, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, CN, 225009, route,
political, sublocality, sublocality_level_1, locality, political,
administrative_area_level_1, political, country, political, postal_code
                                                 formatted_address
1 Jiangdu Rd, Guangling Qu, Yangzhou Shi, Jiangsu Sheng, China, 225009
  geometry.location.lat geometry.location.lng geometry.location_type
1              32.39118              119.4622            APPROXIMATE
  geometry.viewport.northeast.lat geometry.viewport.northeast.lng
1                        32.39253                        119.4635
  geometry.viewport.southwest.lat geometry.viewport.southwest.lng
partial_match
1                        32.38983                        119.4608
TRUE
                 place_id                            types
1 ChIJcQhNY82HtjURw8QwBzgCGgA establishment, point_of_interest

$status
[1] "OK"

Why is there a difference?
May I know how this package works or how Google Map works, and in which way I can get the zip code of a location of China for sure?

Body:
You can consider using the geocode() function from the ggmap package.

library(ggmap)

result <- geocode("方桥社区居委会", output = 'more', source = 'google')

## components in the 'result' variable
 lon      lat          type          loctype
1 117.3393 31.89561 establishment geometric_center
                                                       address
1 xinhai ave, yaohai qu, hefei shi, anhui sheng, china, 230000
     north    south     east    west         route political
1 31.89696 31.89426 117.3407 117.338 Xinhai Avenue Yaohai Qu
   locality administrative_area_level_1 country postal_code
1 Hefei Shi                 Anhui Sheng   China      230000

To obtain the zip code / postal code:

> result$postal_code
[1] 230000


来源: stackexchange

问:
1 second delay to inverse the value of PORTB in MicroC with PIC16F887
Micro controller PIC16F887
//
The task says:
Write program who will invert PORTB and will make it output port and in every SECOND it will make inverse ON/OFF on the Led Diods

Here is my Code
:

```<code>unsigned cnt ;

void interrupt(){
     if(TMR0IF_bit){ //if there is interrupt in timer0
      cnt++;         //increase the counter
      TMR0IF_bit=0;  //reset the timer
      TMR0 = 96;     //set the TMR0 to its default value
     }
}

void main() {
ANSEL = 0;
ANSELH = 0;
OPTION_REG = 0b00000100; //1:32 prescalar (last 3 bits are 100)
INTCON = 0xA0;          //enable interrupt generated by TMR0
TRISB = 0x00;           //make PORTB output port
PORTB = 0xFF;           //set PORTB to 1s
cnt =0;                 //initialize counter
TMR0 = 96;              //starting value of TMR0

do{
if(cnt==391){
 PORTB = ~PORTB;       //invert PORTB
 cnt=0;                //reset the timer
}
cnt++;                 //increase counter if its not 391
}while(1);
}
</code>```

IMPORTANT
TMR0 = 96 is starting value and 256-96 = 160
OPTION_REG = 1:32 so prescalar is 32
we need to make close value to 2M cause 2M instructions are nearly 1 second as they say

2 000 000 / 32 (prescalar) * 160 (256-96) = ~ 391
so one second delay should be 2M / 32 * 160 when the counter reaches 391
but when i start it on 8Mhz simulation the LED DIODS inverse in much faster time than 1 second.

So can you help me figure out what's the problem and how to make it to invert on every second. Thank you

答:
Suggest you to go through the datasheet of the PIC16F series. It is really important to understand each registers and its significance before start using it

You have mentioned that, if you remove the increment of cnt from while loop, it takes more than 10sec which clearly indicate that , clock, TMR0 value and loop value is out of sync.

For Simple timer implementation explained in below link, which may help you

http://www.microcontrollerboard.com/pic-timer0-tutorial.html

Sudhee

ContentLicense: CC BY-SA 3.0

Body:
Micro controller PIC16F887
//
The task says:
Write program who will invert PORTB and will make it output port and in every SECOND it will make inverse ON/OFF on the Led Diods

Here is my Code
:

unsigned cnt ;

void interrupt(){
     if(TMR0IF_bit){ //if there is interrupt in timer0
      cnt++;         //increase the counter
      TMR0IF_bit=0;  //reset the timer
      TMR0 = 96;     //set the TMR0 to its default value
     }
}

void main() {
ANSEL = 0;
ANSELH = 0;
OPTION_REG = 0b00000100; //1:32 prescalar (last 3 bits are 100)
INTCON = 0xA0;          //enable interrupt generated by TMR0
TRISB = 0x00;           //make PORTB output port
PORTB = 0xFF;           //set PORTB to 1s
cnt =0;                 //initialize counter
TMR0 = 96;              //starting value of TMR0

do{
if(cnt==391){
 PORTB = ~PORTB;       //invert PORTB
 cnt=0;                //reset the timer
}
cnt++;                 //increase counter if its not 391
}while(1);
}

IMPORTANT
TMR0 = 96 is starting value and 256-96 = 160
OPTION_REG = 1:32 so prescalar is 32
we need to make close value to 2M cause 2M instructions are nearly 1 second as they say

2 000 000 / 32 (prescalar) * 160 (256-96) = ~ 391
so one second delay should be 2M / 32 * 160 when the counter reaches 391
but when i start it on 8Mhz simulation the LED DIODS inverse in much faster time than 1 second.

So can you help me figure out what's the problem and how to make it to invert on every second. Thank you


问:
How to map JSON Data in Javascript ES6
I would like to get the JSON data from Coinmarket.

I get the data but can't map the Data.

below my Code

```<code>    const p = document.querySelector('p');
    let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
    let coinsdata = [];
    fetch(endpoint)
    .then(blob => blob.json()
    .then(data => coinsdata.push(...data)));

    console.log(coinsdata);
    coinsdata.map(coindata => {
        return p.innerHTML = coindata.id;
    });
</code>```

答:
The issue is you are printing the list straight away, even before the data comes back from the API. You need to set the HTML inside the callback.</p>

```<code>const p = document.querySelector('p');
let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
  .then(blob => blob.json().then(data => {
    console.log(data);
    coinsdata.map(data => {
      return p.innerHTML = coindata.id;
    });
  })
);
</code>```

Title: How to map JSON Data in Javascript ES6

Body:
I would like to get the JSON data from Coinmarket.

I get the data but can't map the Data.

below my Code

    const p = document.querySelector('p');
    let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
    let coinsdata = [];
    fetch(endpoint)
    .then(blob => blob.json()
    .then(data => coinsdata.push(...data)));

    console.log(coinsdata);
    coinsdata.map(coindata => {
        return p.innerHTML = coindata.id;
    });

Body:
The issue is you are printing the list straight away, even before the data comes back from the API. You need to set the HTML inside the callback.

const p = document.querySelector('p');
let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
  .then(blob => blob.json().then(data => {
    console.log(data);
    coinsdata.map(data => {
      return p.innerHTML = coindata.id;
    });
  })
);


答:
The problem is that the first and last rows of ones you are appending to the matrix are in fact aliases for the same list, therefore you are appending twice to it. You need to modify your code, maybe like this:</p>

```<code>addrow1 = list(map(lambda x: 1, range(len(matrix[0]))))
addrow2 = list(map(lambda x: 1, range(len(matrix[0]))))
matrix_new.insert(0, addrow1)
matrix_new.append(addrow2)
</code>```

Title: something went wrong when I try add a layer on a matrix of data (python)

Body:
So assume I have a matrix here, a tuple containing tuples of 0:

matrix = ((0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),
          (0, 0, 0, 0, 0, 0),)

I want to add a layer of int(1) on the outside of it, so that it will look like:

[[1, 1, 1, 1, 1, 1, 1, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 1],
 [1, 1, 1, 1, 1, 1, 1, 1],]

first of all, I want to turn this matrix to list, since tuples are not changable:

matrix_new = list(map(lambda x: list(x), matrix))

Then I would like to add a row at the beginning and end of it.

addrow = list(map(lambda x: 1, range(len(matrix[0]))))
matrix_new.insert(0, addrow)
matrix_new.append(addrow)

so now, if I:

for i in matrix_new:
    print(i)
>>>
[1, 1, 1, 1, 1, 1]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1]

looking good so far.
Now I want to add a int(1) in each row of the matrix_new at the beginning and the end:

for i in matrix_new:
    i.insert(0, 1)
    i.append(1)
    print(i)

somehow it now looks like:

>>>
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

It seems that the last row is having 2 additional int(1)??????
And now, if I:

for i in matrix_new:
    print(i)

I got:

>>>
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Now I got the first row also with 2 additional int(1).

What could be wrong? I don't understand why this is happening.

Body:
The problem is that the first and last rows of ones you are appending to the matrix are in fact aliases for the same list, therefore you are appending twice to it. You need to modify your code, maybe like this:

addrow1 = list(map(lambda x: 1, range(len(matrix[0]))))
addrow2 = list(map(lambda x: 1, range(len(matrix[0]))))
matrix_new.insert(0, addrow1)
matrix_new.append(addrow2)


问:
How to show marker on google map when clicked on list item from hamburger menu
I am working on google maps. I want to link markers to items in menu. If I click the the name, it should show respective marker only. But my code is pointing to only last marker in the map.

All my links are pointing to last marker. Please help me solving this problem.

```<code><div class="menu">
     <div data-bind="foreach: visible">
        <p class="clicked" data-bind="text: location, click"></p>
     </div>
</div>
</code>```

javaScript:

```<code>var bounds = new google.maps.LatLngBounds();

for (var i = 0; i < markersData.length; i++) {

    var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
    var loc = markersData[i].locationId;
    var name = markersData[i].location;

    $('.clicked').on('click', function() {

        if ($('.clicked').location = name) {
            console.log(location);
            createMarker(latlng, loc);

        }
    });
</code>```

I changed the code but this one is displaying all the markers at a time on clicking single link.

```<code>function displayMarkers() {

     var bounds = new google.maps.LatLngBounds();

     for (var i = 0; i < markersData.length; i++) {

     var latlng = new google.maps.LatLng(markersData[i].lat,markersData[i].lng);
         var loc = markersData[i].locationId;
         var name = markersData[i].location;

         checkLinkClicked(latlng, loc, name);
         createMarker(latlng, loc);

         bounds.extend(latlng);
     }

     map.fitBounds(bounds);
 }

 function checkLinkClicked(latlng, loc, name) {

     $(’.clicked’).on(‘click’, function() {

         if ((’.clicked’).location = name) {
             createMarker(latlng, loc);

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

Please help.

答:
Please check this working sample. http://jsbin.com/tayope/edit?html,js,output

This is just a basic demo that demonstrates the functionality you need. Ignore the layout/design.

Here's a sample item in the menu with an onClick event:

```<code><li><a href="#" onClick="showMarker(1)">Marker 1</a></li>
</code>```

When the user clicks an item in the menu, it will basically show the specific marker in the map.

```<code>function showMarker(index) {
  hideAllMarkers();
  markers[index - 1].setMap(map);
}
</code>```

You can either pass the index or add it as a data attribute of the menu item.

Here is the code snippet as well: (try to open it in full screen)

var map;
var coordinates = [
  {
    lat: 14.534472,
    lng: 121.052367
  },
  {
    lat: 14.532709,
    lng: 121.05333
  },
  {
    lat: 14.533593,
    lng: 121.053128
  }
]
var markers = []

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 14.533593, lng: 121.053128},
    zoom: 15,
  });

  for(var i = 0; i < coordinates.length; i++) {
      var marker = new google.maps.Marker({
        position: coordinates[i],
        map: map
      });
      marker.setMap(null);
      markers.push(marker);
  }
}

function showMarker(index) {
  hideAllMarkers();
  markers[index - 1].setMap(map);
}

function hideAllMarkers() {
  for(var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
    height: 500px !important;
  margin: auto;
    background: gray;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Markers</title>

Menu

Marker 1

Marker 2

Marker 3

```

Body:
I am working on google maps. I want to link markers to items in menu. If I click the the name, it should show respective marker only. But my code is pointing to only last marker in the map.

All my links are pointing to last marker. Please help me solving this problem.

javaScript:

var bounds = new google.maps.LatLngBounds();

for (var i = 0; i < markersData.length; i++) {

    var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
    var loc = markersData[i].locationId;
    var name = markersData[i].location;

    $('.clicked').on('click', function() {

        if ($('.clicked').location = name) {
            console.log(location);
            createMarker(latlng, loc);

        }
    });

I changed the code but this one is displaying all the markers at a time on clicking single link.

function displayMarkers() {

     var bounds = new google.maps.LatLngBounds();

     for (var i = 0; i < markersData.length; i++) {

     var latlng = new google.maps.LatLng(markersData[i].lat,markersData[i].lng);
         var loc = markersData[i].locationId;
         var name = markersData[i].location;

         checkLinkClicked(latlng, loc, name);
         createMarker(latlng, loc);

         bounds.extend(latlng);
     }

     map.fitBounds(bounds);
 }

 function checkLinkClicked(latlng, loc, name) {

     $(’.clicked’).on(‘click’, function() {

         if ((’.clicked’).location = name) {
             createMarker(latlng, loc);

         }
     });
 }

Please help.

Body:
Please check this working sample. http://jsbin.com/tayope/edit?html,js,output

This is just a basic demo that demonstrates the functionality you need. Ignore the layout/design.

Here's a sample item in the menu with an onClick event:

<li><a href="#" onClick="showMarker(1)">Marker 1</a></li>

When the user clicks an item in the menu, it will basically show the specific marker in the map.

function showMarker(index) {
  hideAllMarkers();
  markers[index - 1].setMap(map);
}

You can either pass the index or add it as a data attribute of the menu item.

Here is the code snippet as well: (try to open it in full screen)

var map;
var coordinates = [
  {
    lat: 14.534472,
    lng: 121.052367
  },
  {
    lat: 14.532709,
    lng: 121.05333
  },
  {
    lat: 14.533593,
    lng: 121.053128
  }
]
var markers = []

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 14.533593, lng: 121.053128},
    zoom: 15,
  });

  for(var i = 0; i < coordinates.length; i++) {
      var marker = new google.maps.Marker({
        position: coordinates[i],
        map: map
      });
      marker.setMap(null);
      markers.push(marker);
  }
}

function showMarker(index) {
  hideAllMarkers();
  markers[index - 1].setMap(map);
}

function hideAllMarkers() {
  for(var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
  }
}

#map {
    height: 500px !important;
  margin: auto;
    background: gray;
}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Markers</title>
  </head>
  <body>
    <div>
      <h3>Menu</h3>
      <ul>
        <li><a href="#" onClick="showMarker(1)">Marker 1</a></li>
        <li><a href="#" onClick="showMarker(2)">Marker 2</a></li>
        <li><a href="#" onClick="showMarker(3)">Marker 3</a></li>
      </ul>
    </div>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8" async defer></script>
  </body>
</html>


问:
what are the reasons for virtualising these instructions?
why is it the below instructions has to be virtualised. How is failing to virtualise this can cause problem.

sgdt,sldt,sidt,smsw

fcall,longjump,srt

lar,verr,verw,lsl

pushf, popf, iret

答:
Modifying the machine state (segment bases / limits, disabling interrupts, etc.) obviously can't be allowed, or the guest could break out of the VM or at least hang it.  (E.g. by running an infinite loop with interrupts disabled.)

pushf/popf are slightly subtle: remember that IF (the interrupts-enabled bit which cli/sti  flip) is one of the bits in EFLAGS.

You want the physical machine to have interrupts enabled while the guest disables interrupts.  But you also want the guest to see IF=0 when it has interrupts disabled on the virtual x86 that it's running on.  So you need to virtualize pushf as well as popf.


问:
MimeMessage change the sendData on existing Mail
```<code>try (
            FileInputStream input = new FileInputStream(source);
            FileOutputStream output = new FileOutputStream(target);
    ) {
        byte[] emlBytes = IOUtils.toByteArray(input);
        Message mimeMessage = createMimeMessage(emlBytes);

        String date = "Wed, 16 Oct 2013 11:25:07 +0200";
        mimeMessage.setHeader("Date", date);
        System.out.println(mimeMessage.getSentDate());
        output.write(emlBytes);

    } catch (MessagingException e) {
        e.printStackTrace();
</code>```

}

I have to change the send date on existing email file. But after the execution the file have the same date as before. It doesnt get the new send date. I think it is because mimeMessage creates a new instance but doesnt change the emlBytes but I have to pass a emlBytes in output.write() I dont know how to pass the emlBytes which was customed by mimeMessage. What can I do?

答:
MimeMessage isn't going to change the original source of the data since it comes from an InputStream.  But you can use the MimeMessage.writeTo method to write the updated message to an OutputStream, e.g.,

```<code>mimeMessage.writeTo(output);
</code>```

Body:
try (
            FileInputStream input = new FileInputStream(source);
            FileOutputStream output = new FileOutputStream(target);
    ) {
        byte[] emlBytes = IOUtils.toByteArray(input);
        Message mimeMessage = createMimeMessage(emlBytes);

        String date = "Wed, 16 Oct 2013 11:25:07 +0200";
        mimeMessage.setHeader("Date", date);
        System.out.println(mimeMessage.getSentDate());
        output.write(emlBytes);

    } catch (MessagingException e) {
        e.printStackTrace();

}

I have to change the send date on existing email file. But after the execution the file have the same date as before. It doesnt get the new send date. I think it is because mimeMessage creates a new instance but doesnt change the emlBytes but I have to pass a emlBytes in output.write() I dont know how to pass the emlBytes which was customed by mimeMessage. What can I do?

Body:
MimeMessage isn't going to change the original source of the data since it comes from an InputStream.  But you can use the MimeMessage.writeTo method to write the updated message to an OutputStream, e.g.,

mimeMessage.writeTo(output);


问:
Android studio build failing because of dependencies
I get this message Error in Android studio and I don't know why I added card view and recycler and this came threw

if you know something please help me?

答:
The error probably because you have mix version of support library.

Use the same version of all support library. Don't use alpha version, something like this:

```<code>dependencies {
  ...

  compile 'com.android.support:appcompat-v7:25.3.0'
  compile 'com.android.support:design:25.3.0'
  compile 'com.android.support:recyclerview-v7:25.3.0'
  compile 'com.android.support:cardview-v7:25.3.0'
}
</code>```

And make sure your compileSdkVersion, buildToolsVersion, and targetSdkVersion is the same version which is 25.

Body:
The error probably because you have mix version of support library.

Use the same version of all support library. Don't use alpha version, something like this:

dependencies {
  ...

  compile 'com.android.support:appcompat-v7:25.3.0'
  compile 'com.android.support:design:25.3.0'
  compile 'com.android.support:recyclerview-v7:25.3.0'
  compile 'com.android.support:cardview-v7:25.3.0'
}

And make sure your compileSdkVersion, buildToolsVersion, and targetSdkVersion is the same version which is 25.


问:
Trackbar has obvious unfixed bug?
When I add a trackbar to a form and set

```<code>    Me.TrackBar1.Minimum = 0
    Me.TrackBar1.Maximum = 100
    Me.TrackBar1.LargeChange = 10
    Me.TrackBar1.SmallChange = 10
    Me.TrackBar1.TickFrequency = 10
</code>```

... the trackbar goes berzerk:

I can choose any small value by dragging the bar.
The trackbar no longer sticks to values of 10, 20, 30, etc.
I can manually choose any small value.

I confirmed this by adding the following code:

```<code>Private Sub TrackBar1_ValueChanged(sender As Object, e As EventArgs) Handles TrackBar1.ValueChanged

    Me.Text = Me.TrackBar1.Value

End Sub
</code>```

Did I overlook anything in the docs, or is that bug in Framework 4.6.1?

答:
I had no idea what you were asking in your question but after giving it some thought I finally figured out what it is you are asking. This is your question:

I can choose any small value by dragging the bar. The trackbar no longer sticks to values of 10, 20, 30, etc. I can manually choose any small value.

The documentation for SmallChange says:

When the user presses one of the arrow keys, the Value property changes according to the value set in the SmallChange property.

And the documentation for LargeChange says:

When the user presses the PAGE UP or PAGE DOWN key or clicks the track bar on either side of the scroll box, the Value property changes according to the value set in the LargeChange property.

Your Question Clarified

You are asking that instead of using the keyboard, if you are using the mouse, then the trackbar's value does not change as per the small and large change specified, which is 10 in your case. It actually steps up/down by 1's so it goes 1, 2, 3 and so on. But you want it to go 10, 20, 30 and so on.

Solution

You can handle the Scroll event and check if the value is a multiple of 10, if it is then do nothing. If not, change it by a multiple of 10.

VB.NET

```<code>Private Sub trackBar1_Scroll(ByVal sender As Object, ByVal e As EventArgs)
    Dim bar = CType(sender, TrackBar)
    Dim isMultipleOfTen As Boolean = bar.Value Mod bar.SmallChange = 0
    If isMultipleOfTen Then
        Return
    End If

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange)
End Sub
</code>```

C#

```<code>private void trackBar1_Scroll(object sender, EventArgs e)
{
    var bar = (TrackBar)sender;
    bool isMultipleOfTen = bar.Value % bar.SmallChange == 0;
    if (isMultipleOfTen)
    {
        return;
    }

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange);
}
</code>```

Title: Trackbar has obvious unfixed bug?

Body:
When I add a trackbar to a form and set

    Me.TrackBar1.Minimum = 0
    Me.TrackBar1.Maximum = 100
    Me.TrackBar1.LargeChange = 10
    Me.TrackBar1.SmallChange = 10
    Me.TrackBar1.TickFrequency = 10

... the trackbar goes berzerk:

I can choose any small value by dragging the bar.
The trackbar no longer sticks to values of 10, 20, 30, etc.
I can manually choose any small value.

I confirmed this by adding the following code:

Private Sub TrackBar1_ValueChanged(sender As Object, e As EventArgs) Handles TrackBar1.ValueChanged

    Me.Text = Me.TrackBar1.Value

End Sub

Did I overlook anything in the docs, or is that bug in Framework 4.6.1?

Body:
I had no idea what you were asking in your question but after giving it some thought I finally figured out what it is you are asking. This is your question:

I can choose any small value by dragging the bar. The trackbar no longer sticks to values of 10, 20, 30, etc. I can manually choose any small value.

The documentation for SmallChange says:

When the user presses one of the arrow keys, the Value property changes according to the value set in the SmallChange property.

And the documentation for LargeChange says:

When the user presses the PAGE UP or PAGE DOWN key or clicks the track bar on either side of the scroll box, the Value property changes according to the value set in the LargeChange property.

Your Question Clarified

You are asking that instead of using the keyboard, if you are using the mouse, then the trackbar's value does not change as per the small and large change specified, which is 10 in your case. It actually steps up/down by 1's so it goes 1, 2, 3 and so on. But you want it to go 10, 20, 30 and so on.

Solution

You can handle the Scroll event and check if the value is a multiple of 10, if it is then do nothing. If not, change it by a multiple of 10.

VB.NET

Private Sub trackBar1_Scroll(ByVal sender As Object, ByVal e As EventArgs)
    Dim bar = CType(sender, TrackBar)
    Dim isMultipleOfTen As Boolean = bar.Value Mod bar.SmallChange = 0
    If isMultipleOfTen Then
        Return
    End If

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange)
End Sub

C#

private void trackBar1_Scroll(object sender, EventArgs e)
{
    var bar = (TrackBar)sender;
    bool isMultipleOfTen = bar.Value % bar.SmallChange == 0;
    if (isMultipleOfTen)
    {
        return;
    }

    bar.Value = bar.SmallChange * ((bar.Value + bar.SmallChange / 2) / bar.SmallChange);
}


问:
data integration practice key field handling
Seeking thoughts and advice in addressing a customer request.  We're working in an existing database that contains primary keys but no foreign keys, which won't change.

The request is for us to integrate data from outside sources which
may contain duplicate values in the data.

The data is from a records-management system, so key id values will
increase with each record collected.

The key fields, for the most part, are decimal(22,0).

This is a daily ETL load of a relatively small amount of data, so
performance isn't the most important concern.

Is it better to prefix, suffix, or use some other strategy to create unique key values that can be traced back to the source?

For instance, if the max existing value were 123456789, is it a good idea to prefix 100000 for external site A, 110000 for external site B, etc?   We've batted a few ideas about as a team and there seems to be pro's and con's with everything we can think of.  Not seeing much guidance on the web.

Thanks in advance for any ideas!

答:
IMHO that's a design anti-pattern. You're ascribing special meaning to internal database keys. Bad idea. Also if you ever did hit the 10,000 limit you're completely stuffed. I know you think you won't... but you might and it will be a catastrophe.

The normal pattern (again in my experience and opinion) is to add a SRC_System and a SRC_Key field with a unique index/constraint on them. These are used to track where the record came from.

In addition to these two new fields, you also have your original primary key in this table which is an internal key used by the system.

This design allows any number of additional systems with any range of keys to be added to your system.

The only challenge then is working out

How to merge - i.e. if two systems have records representing the same thing

How to add additional reference data if required


问:
Color in status bar with React Native and react-navigation
I am using react-navigation in React Native and I have changed the header color with

```<code>const MyScreenNavigator = StackNavigator({
  ...
}, {
  navigationOptions: {
    headerStyle: {
      backgroundColor: 'blue',
    },
    headerTintColor: 'white'
  }
});
</code>```

It does change the background color of both header and status bar, but the font color is still black in the status bar.

How can I customise the font color of the status bar?

答:
I use StatusBar

```<code>const RootNavigator = StackNavigator({
...
}, {
  initialRouteName: 'Home',
  navigationOptions: {
    header: <Header />
  }
});
</code>```

header.js

```<code>import { StatusBar } from 'react-native';
export default class Header extends Component<{}> {
  <View>
    <StatusBar backgroundColor="#fff" />
    ...
  </View>
}
</code>```

Body:
I am using react-navigation in React Native and I have changed the header color with

const MyScreenNavigator = StackNavigator({
  ...
}, {
  navigationOptions: {
    headerStyle: {
      backgroundColor: 'blue',
    },
    headerTintColor: 'white'
  }
});

It does change the background color of both header and status bar, but the font color is still black in the status bar.

How can I customise the font color of the status bar?

Body:
I use StatusBar

const RootNavigator = StackNavigator({
...
}, {
  initialRouteName: 'Home',
  navigationOptions: {
    header: <Header />
  }
});

header.js

import { StatusBar } from 'react-native';
export default class Header extends Component<{}> {
  <View>
    <StatusBar backgroundColor="#fff" />
    ...
  </View>
}


问:
How to insert characters in between in jquery?
I have this data from the database 12345123412 but in my page I need to display it as 12345-1234-12. Any ideas on how to handle this? I'm trying to do the .split()

答:
Assuming the string is always going to be formatted the exact same way, there's no reason to use jQuery for this:</p>

```<code>var str = '12345123412';

var formatted = str.slice(0, 5) + '-' + str.slice(5, 9) + '-' + str.slice(9);
  //=> 12345-1234-12
</code>```

Body:
Assuming the string is always going to be formatted the exact same way, there's no reason to use jQuery for this:

var str = '12345123412';

var formatted = str.slice(0, 5) + '-' + str.slice(5, 9) + '-' + str.slice(9);
  //=> 12345-1234-12


问:
How to mask an EditText to show the dd/mm/yyyy date format
How can I format an EditText to follow the "dd/mm/yyyy" format the same way that we can format using a TextWatcher to mask the user input to look like "0.05€". I'm not talking about limiting the characters, or validating a date, just masking to the previous format.

答:
This answer does not apply a full mask for the remaining untyped digits. However, it is related and is the solution I needed. It works similar to how PhoneNumberFormattingTextWatcher works.

As you type it adds slashes to separate a date formatted like mm/dd/yyyy. It does not do any validation - just formatting.

No need for an EditText reference.
Just set the listener and it works.
myEditText.addTextChangedListener(new DateTextWatcher());

```<code>import android.text.Editable;
import android.text.TextWatcher;

import java.util.Locale;

/**
 * Adds slashes to a date so that it matches mm/dd/yyyy.
 *
 * Created by Mark Miller on 12/4/17.
 */
public class DateTextWatcher implements TextWatcher {

    public static final int MAX_FORMAT_LENGTH = 8;
    public static final int MIN_FORMAT_LENGTH = 3;

    private String updatedText;
    private boolean editing;

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {

    }

    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        if (text.toString().equals(updatedText) || editing) return;

        String digitsOnly = text.toString().replaceAll("\\D", "");
        int digitLen = digitsOnly.length();

        if (digitLen < MIN_FORMAT_LENGTH || digitLen > MAX_FORMAT_LENGTH) {
            updatedText = digitsOnly;
            return;
        }

        if (digitLen <= 4) {
            String month = digitsOnly.substring(0, 2);
            String day = digitsOnly.substring(2);

            updatedText = String.format(Locale.US, "%s/%s", month, day);
        }
        else {
            String month = digitsOnly.substring(0, 2);
            String day = digitsOnly.substring(2, 4);
            String year = digitsOnly.substring(4);

            updatedText = String.format(Locale.US, "%s/%s/%s", month, day, year);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

        if (editing) return;

        editing = true;

        editable.clear();
        editable.insert(0, updatedText);

        editing = false;
    }
}
</code>```

Body:
This answer does not apply a full mask for the remaining untyped digits. However, it is related and is the solution I needed. It works similar to how PhoneNumberFormattingTextWatcher works.

As you type it adds slashes to separate a date formatted like mm/dd/yyyy. It does not do any validation - just formatting.

No need for an EditText reference.
Just set the listener and it works.
myEditText.addTextChangedListener(new DateTextWatcher());

import android.text.Editable;
import android.text.TextWatcher;

import java.util.Locale;

/**
 * Adds slashes to a date so that it matches mm/dd/yyyy.
 *
 * Created by Mark Miller on 12/4/17.
 */
public class DateTextWatcher implements TextWatcher {

    public static final int MAX_FORMAT_LENGTH = 8;
    public static final int MIN_FORMAT_LENGTH = 3;

    private String updatedText;
    private boolean editing;

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {

    }

    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        if (text.toString().equals(updatedText) || editing) return;

        String digitsOnly = text.toString().replaceAll("\\D", "");
        int digitLen = digitsOnly.length();

        if (digitLen < MIN_FORMAT_LENGTH || digitLen > MAX_FORMAT_LENGTH) {
            updatedText = digitsOnly;
            return;
        }

        if (digitLen <= 4) {
            String month = digitsOnly.substring(0, 2);
            String day = digitsOnly.substring(2);

            updatedText = String.format(Locale.US, "%s/%s", month, day);
        }
        else {
            String month = digitsOnly.substring(0, 2);
            String day = digitsOnly.substring(2, 4);
            String year = digitsOnly.substring(4);

            updatedText = String.format(Locale.US, "%s/%s/%s", month, day, year);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

        if (editing) return;

        editing = true;

        editable.clear();
        editable.insert(0, updatedText);

        editing = false;
    }
}


问:
Errors in command-line while running Java programs
I have a complete Java program, but the way that my professor is going to check to make sure that the program is working correctly is through CMD using the command

 "java Caesar input.txt output.txt"

But the issues I am running into are that when I compile using "javac Caesar.java" it will compile and create a Caesar.class file in the folder, but when I try run it as "java caesar input.txt output.txt" it says Error: Could not find or load main class caesar.

What am I doing wrong here?

I can provide additional information as needed.

```<code>package caaesar;

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

/**
 *
 * @author Connorbboggs
 * Version 12.03.2017
 */
public class Caaesar
{

private static Scanner sc;
private static FileWriter fw;
private static BufferedWriter bw;
private Scanner inp;
private Scanner outp;
//DecodeChar class provided by you
public static char decodeChar(int n, char ch)
{
    int ord;
    if (ch >= 'A' && ch <= 'Z')
    {
        ord = ch - 'A';
        ord += n;
        ord %= 26;
        return (char)(ord + 'A');
    }
    else if (ch >= 'a' && ch <= 'z')
    {
        ord = ch - 'a';
        ord += n;
        ord %= 26;
        return (char)(ord + 'a');
    }
    else
    {
        return ch;
    }
}

public static void main(String[] args)
{
    //File input for decode.txt with the encrypted text
    File inputFile = new File(args[0]);
    //Output for the decrypted text
    File outputFile = new File(args[1]);
    try
    {
        //input from inputFile
        sc = new Scanner(inputFile);
        int shift = sc.nextInt();
        String decoded = "";
        //while lines are available text is fed to inputFile
        while( sc.hasNextLine())
        {
            //Lines being fed into string line
            String line = sc.nextLine();
            //for loop to feed into decoded using decodeChar
            for(int i=0; i<line.length(); i++)
            {
                decoded += decodeChar(shift, line.charAt(i));
            }
            decoded += '\n';
        }
        //Just to verify that the text is decrypted
        System.out.println(decoded);
        try
        {
            //create a fileWriter for outputFile
            fw = new FileWriter(outputFile);
            //write "decoded" to the file
            fw.write(decoded);
            //close the file
            fw.close();
        }
        //exception catching
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    //more exception
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}
</code>```

答:
If your professor intends to run

```<code>java Caesar input.txt output.txt
</code>```

then you need all of the following.  Spelling is important, and so is whether each letter is upper or lower case.

Your code file must be called Caesar.java,

The class in your code file must be called Caesar,

The class in your code file must contain a method that starts with public static void main(String[].

There must be no package declaration at the top of the file.

Please try to meet all these conditions, and be fastidious about the details.

Body:
I have a complete Java program, but the way that my professor is going to check to make sure that the program is working correctly is through CMD using the command

 "java Caesar input.txt output.txt"

But the issues I am running into are that when I compile using "javac Caesar.java" it will compile and create a Caesar.class file in the folder, but when I try run it as "java caesar input.txt output.txt" it says Error: Could not find or load main class caesar.

What am I doing wrong here?

I can provide additional information as needed.

package caaesar;

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

/**
 *
 * @author Connorbboggs
 * Version 12.03.2017
 */
public class Caaesar
{

private static Scanner sc;
private static FileWriter fw;
private static BufferedWriter bw;
private Scanner inp;
private Scanner outp;
//DecodeChar class provided by you
public static char decodeChar(int n, char ch)
{
    int ord;
    if (ch >= 'A' && ch <= 'Z')
    {
        ord = ch - 'A';
        ord += n;
        ord %= 26;
        return (char)(ord + 'A');
    }
    else if (ch >= 'a' && ch <= 'z')
    {
        ord = ch - 'a';
        ord += n;
        ord %= 26;
        return (char)(ord + 'a');
    }
    else
    {
        return ch;
    }
}

public static void main(String[] args)
{
    //File input for decode.txt with the encrypted text
    File inputFile = new File(args[0]);
    //Output for the decrypted text
    File outputFile = new File(args[1]);
    try
    {
        //input from inputFile
        sc = new Scanner(inputFile);
        int shift = sc.nextInt();
        String decoded = "";
        //while lines are available text is fed to inputFile
        while( sc.hasNextLine())
        {
            //Lines being fed into string line
            String line = sc.nextLine();
            //for loop to feed into decoded using decodeChar
            for(int i=0; i<line.length(); i++)
            {
                decoded += decodeChar(shift, line.charAt(i));
            }
            decoded += '\n';
        }
        //Just to verify that the text is decrypted
        System.out.println(decoded);
        try
        {
            //create a fileWriter for outputFile
            fw = new FileWriter(outputFile);
            //write "decoded" to the file
            fw.write(decoded);
            //close the file
            fw.close();
        }
        //exception catching
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    //more exception
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}

Body:
If your professor intends to run

java Caesar input.txt output.txt

then you need all of the following.  Spelling is important, and so is whether each letter is upper or lower case.

Your code file must be called Caesar.java,

The class in your code file must be called Caesar,

The class in your code file must contain a method that starts with public static void main(String[].

There must be no package declaration at the top of the file.

Please try to meet all these conditions, and be fastidious about the details.


问:
Java print multiple lines after reading multiple lines
(It's my homework task. So I can't make any changes to the task like changing the rules of input.)

I need to calculate

```<code>a^m mod n
</code>```

and print out the result. (I've already figured out how to code the calculation.)

But the question said there'll be multiple lines of input:

```<code>IN:

12 5 47
2 4 89
29 5 54
</code>```

and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)

```<code>OUT:

14
16
5
</code>```

The code I've tried so far:

```<code>import java.util.Scanner;

public class mod {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int count = 0;
        while (input.hasNextLine()){
            count++;
        }
        int[] array = new int[count];
        for (int i = 0; i < count; i ++){
            int a = input.nextInt();
            int m = input.nextInt();
            int n = input.nextInt();
            int result = (int)((Math.pow(a, m)) % n);
            array[i] = result;
        }
        for (int x : array){
             System.out.println(x);
        }
    }
}
</code>```

I tried to count the lines of input and build an array of that size to store the results.

But it seems my code fail to detect the end of input and keep looping.

答:
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,

```<code>Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
    String line = input.nextLine();
    if (line.isEmpty()) {
        break;
    } else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
        lines.add(line);
    }
}
int count = lines.size();
for (int i = 0; i < count; i++) {
    String[] tokens = lines.get(i).split("\\s+");
    int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
            n = Integer.parseInt(tokens[2]);
    int result = (int) ((Math.pow(a, m)) % n);
    System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
</code>```

I tested with your provided input,

```<code>12 5 47
2 4 89
29 5 54

(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5
</code>```

Body:
(It's my homework task. So I can't make any changes to the task like changing the rules of input.)

I need to calculate

a^m mod n

and print out the result. (I've already figured out how to code the calculation.)

But the question said there'll be multiple lines of input:

IN:

12 5 47
2 4 89
29 5 54

and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)

OUT:

14
16
5

The code I've tried so far:

import java.util.Scanner;

public class mod {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int count = 0;
        while (input.hasNextLine()){
            count++;
        }
        int[] array = new int[count];
        for (int i = 0; i < count; i ++){
            int a = input.nextInt();
            int m = input.nextInt();
            int n = input.nextInt();
            int result = (int)((Math.pow(a, m)) % n);
            array[i] = result;
        }
        for (int x : array){
             System.out.println(x);
        }
    }
}

I tried to count the lines of input and build an array of that size to store the results.

But it seems my code fail to detect the end of input and keep looping.

Body:
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,

Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
    String line = input.nextLine();
    if (line.isEmpty()) {
        break;
    } else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
        lines.add(line);
    }
}
int count = lines.size();
for (int i = 0; i < count; i++) {
    String[] tokens = lines.get(i).split("\\s+");
    int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
            n = Integer.parseInt(tokens[2]);
    int result = (int) ((Math.pow(a, m)) % n);
    System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}

I tested with your provided input,

12 5 47
2 4 89
29 5 54

(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5


问:
What's the POS framework call corresponding to StartSoftwareTriggerAsync application API call?
I am working on barcode scanner project on windows 10 and we are going to use software triggering. I got the mentioned APIs from application to implement software triggering but couldn't get information on the driver side handler for these calls?

Can someone suggest what would be the corresponding POS framework call for this software trigger API?

Thanks in advance.

Regards,
Tajpeer

答:
It is difficult to answer in your question contents.

Please describe what you want to do and what you are going to do concretely.

For example, I guessed what you want to do as follows.

Acquire images in real time from the camera connected to the PC and keep displaying it in the window of the PC screen.

Hold the barcode in the reading area of the camera, human confirms that it was displayed cleanly in the window, and performs barcode recognition by software trigger via POS application.

When the program can recognize the bar code, notify it to the POS application.

There are no such functions or APIs in the existing POS framework (UnifiedPOS (OPOS / POS for .NET / JavaPOS), Windows.Devices.PointOfService).

As an alternative, the closest one is to implement UnifiedPOS ImageScanner and Scanner (Bar Code Reader) as a Hydra device on one camera.
The software trigger function is implemented as a vendor specific extension function by the DirectIO method.


问:
JQuery datepicker language
I'm using the jQuery datepicker from jqueryui.com and I have a problem changing the calendar to Swedish, I have this code:

```<code>    <script type="text/javascript">
    $(function() {
        $.datepicker.setDefaults($.datepicker.regional['sv']);
        $("#StartDate").datepicker();
        $('#StartDate').datepicker('option', 'dateFormat', 'yy-mm-dd');
    });
</script>
</code>```

Still it shows as an English calendar.

What might be missing?

答:
Include language file source in your head script of the HTML body.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
</code>```

Example on JSFiddle

Title: JQuery datepicker language

Body:
I'm using the jQuery datepicker from jqueryui.com and I have a problem changing the calendar to Swedish, I have this code:

Still it shows as an English calendar.

What might be missing?

Body:
Include language file source in your head script of the HTML body.

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

Example on JSFiddle


问:
A way to restrict Git branch access?
I have four branches in my git repository, which is managed using GitHub:

Production

Staging

Master

[person's name]-development

Is there a way to restrict write access to only a single branch ([person's name]-development)? How would I do this?

For reference, a similar question: How to write a git hook to restrict writing to branch?.

答:
In Bitbucket version (Bitbucket v4.9.1) You can restrict changes by:

Branch name

Branch name pattern

Branch name modelling

Following actions can by restricted:

Prevent all changes

Prevent deletion

Prevent rewirting history

Prevent changes without a pull request

Enter user that is an exception;

Title: A way to restrict Git branch access?


问:
Android C++ Development with Visual Studio
I am trying to figure out how to setup android development with Visual Studio. I plan on using C++ (targeting 2.3 and above), but I see very little on the subject. Does anyone know how to do this?

I know that Android development suggests Java/Eclipse, however, I want to do C++/VS.

答:
The Android NDK (Native Developmemt Kit) uses the GCC toolchain, so Visual Studio won't be any good unless you are willing to use it just for editing your source files and using some other external mechanism (Makefile from the Command Prompt?) to compile your program.

You should be able to use eclipse/CDT however, and this provides a very rich C/C++ programming environment (I use it everyday for Linux development).  See here.

ContentLicense: CC BY-SA 2.5


问:
jQuery destroy and create timer function. How to destroy?
I have put together some code to reset and restart a timer every time the user closes a modal window after pressing Save Changes.

The problem I'm having is when I open the Modal for the second time and press Save Changes for a second time, it closes but it starts a second timer on top of the first one. This effect stacks indefinitely..

How can I change my code to destroy the first timer and create a second timer and so on, as needed, throughout the day?

Thanks for any help.

Modal JavaScript Code

```<code>$(document).on('click', '#btn-modal1-save-changes', function (e) {
//$(this.form).submit();
    alert('btn-modal1-save-changes Click for #modal1 Event fired.');
//$('#modal1').modal('hide');
    $('#total-clock').timer();
});
</code>```

Timer JQuery Custom functions

```<code>// Timer Custom function
jQuery.prototype.timer = function() {

    // Timer variable for setInterval.
    var timer;

    // Target html tag for timer
    var htmlTag = (this);

    // Integer increment
    var i = 0;

    // Activate Timer
    timer = setInterval(function() {

        // Always increment by 1;
        i++;

        // Output...
        htmlTag.text(i.toHHMMSS());

    }, 1000); // ..every 1 second(s)
};

// Format String Custom function
// Input type MUST BE INTERGER.
Number.prototype.toHHMMSS = function () {

    var seconds = Math.floor(this),
    hours = Math.floor(seconds / 3600);
    seconds -= hours*3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes*60;

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}

    return hours+':'+minutes+':'+seconds;

}
</code>```

答:
use jquery's clearInterval() inside function then call the function to stop.

sample

```<code>function stopInterval(){
   clearInterval(timer);
}
</code>```

Body:
I have put together some code to reset and restart a timer every time the user closes a modal window after pressing Save Changes.

The problem I'm having is when I open the Modal for the second time and press Save Changes for a second time, it closes but it starts a second timer on top of the first one. This effect stacks indefinitely..

How can I change my code to destroy the first timer and create a second timer and so on, as needed, throughout the day?

Thanks for any help.

Modal JavaScript Code

$(document).on('click', '#btn-modal1-save-changes', function (e) {
//$(this.form).submit();
    alert('btn-modal1-save-changes Click for #modal1 Event fired.');
//$('#modal1').modal('hide');
    $('#total-clock').timer();
});

Timer JQuery Custom functions

// Timer Custom function
jQuery.prototype.timer = function() {

    // Timer variable for setInterval.
    var timer;

    // Target html tag for timer
    var htmlTag = (this);

    // Integer increment
    var i = 0;

    // Activate Timer
    timer = setInterval(function() {

        // Always increment by 1;
        i++;

        // Output...
        htmlTag.text(i.toHHMMSS());

    }, 1000); // ..every 1 second(s)
};

// Format String Custom function
// Input type MUST BE INTERGER.
Number.prototype.toHHMMSS = function () {

    var seconds = Math.floor(this),
    hours = Math.floor(seconds / 3600);
    seconds -= hours*3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes*60;

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}

    return hours+':'+minutes+':'+seconds;

}

Body:
use jquery's clearInterval() inside function then call the function to stop.

sample

function stopInterval(){
   clearInterval(timer);
}


问:
Clone Azure Linux VM
I need to clone a Linux VM currently in production in Azure (it is a database server that is being used in a live environment).

I did a little research and it seems like you need to run a deprovisioning command to essentially remove things like SSH keys and other stuff which looks kinda scary to me; I saw language in other articles describing things like "after you backup, your existing VM is deleted, etc" and other things that I'm not sure about but don't seem like what I want.

Is there a safe way to just clone a box and bring it back up? In AWS it's very easy you just create an image, the box goes down for a min, and then you create a new instance from there.

Could someone just give me the steps in Azure? Do I want to click 'capture' at the top for the linux instance?

Thank you!

答:
Is there a safe way to just clone a box and bring it back up?

According to your description, I think you are looking for Recovery services vault.

We can use recovery services vault to backup Azure VM and restore Azure VM, more information about step by step to setup recovery services vault, please refer to this link.

Do I want to click 'capture' at the top for the linux instance?

Capture used for create VM image, after captured, we can use that image to create multiple VMs. Not a backup.

it seems like you need to run a deprovisioning command to essentially
  remove things like SSH keys and other stuff which looks kinda scary to
  me; I saw language in other articles describing things like "after you
  backup, your existing VM is deleted, etc"

You are right, that is prepare a new image, not a backup.

If you just want to backup that VM once, maybe we can copy that VHD to storage account with different name.

Title: Clone Azure Linux VM


问:
How to put redshift query in function?
It is very hard to me to remember query for listing all tables in redshift:

```<code>SELECT DISTINCT tablename
FROM pg_table_def
WHERE schemaname = 'public'
ORDER BY tablename;
</code>```

So I decided to create function that does it to me. But it turns out redshift does not understand "RETURNS TABLE" statement:

```<code>ERROR:  syntax error at or near "TABLE"
LINE 2: RETURNS TABLE (tablename varchar)
            ^
</code>```

I tried with other return types

```<code>CREATE FUNCTION show_tables()
RETURNS ANYELEMENT VOLATILE
AS 'SELECT DISTINCT tablename
    FROM pg_table_def
    WHERE schemaname = public
    ORDER BY tablename;'
LANGUAGE SQL;
</code>```

But I get error ERROR:  anyelement is not a supported sql UDF return type.

So, my question: "Is there any way to create show_tables() function in redhsift?"

答:
If your return type is anyelement, atleast one of your input parameters must be anyelement.

For reference, visit the relevant section (towards the bottom of the page) at Amazon Redshift Documentation

Title: How to put redshift query in function?

Body:
It is very hard to me to remember query for listing all tables in redshift:

SELECT DISTINCT tablename
FROM pg_table_def
WHERE schemaname = 'public'
ORDER BY tablename;

So I decided to create function that does it to me. But it turns out redshift does not understand "RETURNS TABLE" statement:

ERROR:  syntax error at or near "TABLE"
LINE 2: RETURNS TABLE (tablename varchar)
            ^

I tried with other return types

CREATE FUNCTION show_tables()
RETURNS ANYELEMENT VOLATILE
AS 'SELECT DISTINCT tablename
    FROM pg_table_def
    WHERE schemaname = public
    ORDER BY tablename;'
LANGUAGE SQL;

But I get error ERROR:  anyelement is not a supported sql UDF return type.

So, my question: "Is there any way to create show_tables() function in redhsift?"


问:
Ajax Call from React to a PHP file - don't know location
Im creating a very basic login page and i'm trying to use php to verify the user login. Here is the code I'm using to access the php file.

```<code> axios.post("login.php", {
    user: 'Fred',
    pass: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

The PHP file is located within the src folder of the react app.

```<code>  ── src
    │   ├── components
    │   │   ├── BrowsePage
    │   │   │   ├── BrowsePage.css
    │   │   │   ├── BrowsePage.js
    │   │   │   └── default.jpg
    │   │   ├── CreatePage
    │   │   │   ├── CreatePage.css
    │   │   │   └── CreatePage.js
    │   │   ├── Header
    │   │   │   ├── Header.css
    │   │   │   └── Header.js
    │   │   ├── LoginPage
    │   │   │   ├── LoginPage.css
    │   │   │   ├── LoginPage.js
    │   │   │   └── logo.svg
    │   │   ├── ProfilePage
    │   │   │   ├── ProfilePage.css
    │   │   │   └── ProfilePage.js
    │   │   └── RecPage
    │   │       ├── default.jpg
    │   │       ├── RecPage.css
    │   │       └── RecPage.js
    │   ├── index.css
    │   ├── index.js
    │   ├── login.php
    │   └── registerServiceWorker.js
</code>```

When I make the call it logs

```<code>xhr.js:178 POST http://localhost:3000/login.php 404 (Not Found)
</code>```

The current path to the php document does not work, and none of the others I've tried work. What is the path to make an axios call to this php document?

答:
You'll need to setup a server locally that your React application can proxy certain http requests to. This server will run your login.php script and authenticate the username/password. create-react-app looks for a proxy value in your package.json and tells webpack-dev-server to forward any calls to api/foobar to wherever you have declared that your back-end will be running.

In your package.json add:

```<code>"proxy": "http://localhost:8000"
</code>```

This tells React to forward requests made to http://localhost:3000/api/login to http://localhost:8000/api/login

Then modify your axios call to look like this

```<code>axios.post("/api/login", ..., ...).then()
</code>```

Next, you have to get your PHP server running on http://localhost:8000 and set up your server application to handle POST requests made to /api/login.

I'm not a PHP guy but I've heard Laravel is nice to work with. It would be easier if your PHP backend was in its own directory completely.

Body:
Im creating a very basic login page and i'm trying to use php to verify the user login. Here is the code I'm using to access the php file.

 axios.post("login.php", {
    user: 'Fred',
    pass: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

The PHP file is located within the src folder of the react app.

  ── src
    │   ├── components
    │   │   ├── BrowsePage
    │   │   │   ├── BrowsePage.css
    │   │   │   ├── BrowsePage.js
    │   │   │   └── default.jpg
    │   │   ├── CreatePage
    │   │   │   ├── CreatePage.css
    │   │   │   └── CreatePage.js
    │   │   ├── Header
    │   │   │   ├── Header.css
    │   │   │   └── Header.js
    │   │   ├── LoginPage
    │   │   │   ├── LoginPage.css
    │   │   │   ├── LoginPage.js
    │   │   │   └── logo.svg
    │   │   ├── ProfilePage
    │   │   │   ├── ProfilePage.css
    │   │   │   └── ProfilePage.js
    │   │   └── RecPage
    │   │       ├── default.jpg
    │   │       ├── RecPage.css
    │   │       └── RecPage.js
    │   ├── index.css
    │   ├── index.js
    │   ├── login.php
    │   └── registerServiceWorker.js

When I make the call it logs

xhr.js:178 POST http://localhost:3000/login.php 404 (Not Found)

The current path to the php document does not work, and none of the others I've tried work. What is the path to make an axios call to this php document?

Body:
You'll need to setup a server locally that your React application can proxy certain http requests to. This server will run your login.php script and authenticate the username/password. create-react-app looks for a proxy value in your package.json and tells webpack-dev-server to forward any calls to api/foobar to wherever you have declared that your back-end will be running.

In your package.json add:

"proxy": "http://localhost:8000"

This tells React to forward requests made to http://localhost:3000/api/login to http://localhost:8000/api/login

Then modify your axios call to look like this

axios.post("/api/login", ..., ...).then()

Next, you have to get your PHP server running on http://localhost:8000 and set up your server application to handle POST requests made to /api/login.

I'm not a PHP guy but I've heard Laravel is nice to work with. It would be easier if your PHP backend was in its own directory completely.


问:
Add dict file in json with python
i hv same code like this

```<code>import json

param1 = "xxxxxx"
param2 = "anaaaahhhhhhhhhj"
param3 = "333333333"

with open('data/'+param1+'.json','a') as f:
    data = param2,
    json.dump(data, f, sort_keys=True, indent=1,ensure_ascii=False)
</code>```

when i executed this, the output like this, not real dictionary

```<code>[
 "anaaaahhhhhhhhhj"
][
 "anaaaahhhhhhhhhj"
]
</code>```

i want

```<code>[
 "anaaaahhhhhhhhhj"
][
 "anaaaahhhhhhhhhj"
]
</code>```

to

```<code>[
 "anaaaahhhhhhhhhj",
 "blablablabal"
]
</code>```

anyone can help me?

ps: i new in python

答:
Assuming you're dealing with a list and trying to append to it each time you run the script: Load the list first, perform an append operation, and dump it back out.

This assumes you have an existing file named "mydata.json" with [] in it.

First method (more understandable):

```<code>import json

fileName = 'mydata.json'

# Load the list first
with open(fileName, 'r') as f:
    data = json.load(f)

# Perform an append operation
data.append('New Value')

# Dump it back out
with open(fileName, 'w') as f:
    json.dump(data, f, sort_keys=True, indent=1, ensure_ascii=False)
</code>```

Second method (using seek):

```<code>import json

fileName = 'mydata.json'

with open(fileName, 'r+') as f:
    # Load the list first
    data = json.load(f)

    # Perform an append operation
    data.append('New Value')

    # Dump it back out
    f.seek(0)
    json.dump(data, f, sort_keys=True, indent=1, ensure_ascii=False)
    f.truncate()
</code>```

Running either of these programs 3 times will result in "mydata.json" containing:

```<code>[
 "New Value",
 "New Value",
 "New Value"
]
</code>```

Title: Add dict file in json with python

Body:
i hv same code like this

import json

param1 = "xxxxxx"
param2 = "anaaaahhhhhhhhhj"
param3 = "333333333"

with open('data/'+param1+'.json','a') as f:
    data = param2,
    json.dump(data, f, sort_keys=True, indent=1,ensure_ascii=False)

when i executed this, the output like this, not real dictionary

[
 "anaaaahhhhhhhhhj"
][
 "anaaaahhhhhhhhhj"
]

i want

[
 "anaaaahhhhhhhhhj"
][
 "anaaaahhhhhhhhhj"
]

to

[
 "anaaaahhhhhhhhhj",
 "blablablabal"
]

anyone can help me?

ps: i new in python

Body:
Assuming you're dealing with a list and trying to append to it each time you run the script: Load the list first, perform an append operation, and dump it back out.

This assumes you have an existing file named "mydata.json" with [] in it.

First method (more understandable):

import json

fileName = 'mydata.json'

# Load the list first
with open(fileName, 'r') as f:
    data = json.load(f)

# Perform an append operation
data.append('New Value')

# Dump it back out
with open(fileName, 'w') as f:
    json.dump(data, f, sort_keys=True, indent=1, ensure_ascii=False)

Second method (using seek):

import json

fileName = 'mydata.json'

with open(fileName, 'r+') as f:
    # Load the list first
    data = json.load(f)

    # Perform an append operation
    data.append('New Value')

    # Dump it back out
    f.seek(0)
    json.dump(data, f, sort_keys=True, indent=1, ensure_ascii=False)
    f.truncate()

Running either of these programs 3 times will result in "mydata.json" containing:

[
 "New Value",
 "New Value",
 "New Value"
]


问:
Android altbeacon sensibility and new beacons
I've seen a lot of discussions on battery for altbeacon, specially if beacons are inside a region for a long time. This post was actually very clarifying.

I am currently working in a solution that requires a good sensibility (which I define as being a small detection time for a new beacon in a region).

As some beacons may be anonymous (which I define as presenting unexpected MAC addresses but share a same matching byte sequence) to the scanner in this particular solution, I would like to achieve good sensibility to new beacons but also a balanced battery impact to the user.

What concerns me is if a first beacon is found and the region triggers based on the matching sequence, how could I get a notification once another beacon approaches (or leaves) ?

A guess I was going to try was to keep monitoring for a generic matching sequence and once a beacon is found for that general sequence, range it to get its address and them create a particular region for the mac I've taken. The only problem with this approach was how could I prevent the first beacon to keep triggering the generic region?

And just out of curiosity. Is the ScanFilter class related to those hardware filters introduced on android 5?

Thank you,

答:
If you need to quickly  find new beacons with the same byte patterns as ones that already exist in the vicinity, you really have no choice but to keep ranging.

In such a situation, there is no distinction between ranging and monitoring in terms of battery consumption.  Both will require constant Bluetooth scans and decoding of all beacons in the vicinity.  Scan filters (yes, the hardware filters introduced in Android 5,) will not help because you expect the byte patterns to be the same.  There is no such thing as a packet "does not match" scan filter that could be used to find only new MAC addresses.

You may need to accept the battery drain of constant scans and just try to limit how long they last, if your use case allows.  Short scans of 30 minutes or less might be acceptable.

You could possibly save some battery by writing your own BLE scanning parsing code tailored to this use case.  You could first look for unique MAC addresses, and only do further processing and parsing if the MAC address has never been seen before.  This will not reduce battery usage from the constant scan, but it would cut down on battery usage from CPU expended on  parsing packets.  This might save 10-30% depending on the number of beacons in the vicinity.

Bottom line: you are right to be concerned about battery usage with this use case.


问:
Any tips for making Hive run faster on Hadoop?
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

```<code>0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)
</code>```

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>
</code>```

hdfs.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>
</code>```

core-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>
</code>```

mapred-site.xml

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>
</code>```

yarn-site.xml

```<code><?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>
</code>```

答: Use beeline shell, hive is deprecated.</p>

Body:
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>

hdfs.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>

core-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>

mapred-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>

yarn-site.xml

<?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>

Body: Use beeline shell, hive is deprecated.


答:
You need to store the timer as a variable which can be accessed even after jQuery.prototype.timer has finished executing.
A good way to do this, is store it as a key in the jQuery object as jQuery.customTimer.

I've modified your jQuery.prototype.timer function to make use of this as shown below.

```<code>// Timer Custom function
jQuery.prototype.timer = function() {
    // Target html tag for timer
    var htmlTag = (this);

    // Integer increment
    var i = 0;

    // Clear old timer if exists
    if (jQuery.customTimer)
        clearInterval(jQuery.customTimer);

    // Create timer
    jQuery.customTimer = setInterval(function() {
        // Always increment by 1;
        i++;

        // Output...
        htmlTag.text(i.toHHMMSS());
    }, 1000); // ..every 1 second(s)
};
</code>```

Title: jQuery destroy and create timer function. How to destroy?

Body:
You need to store the timer as a variable which can be accessed even after jQuery.prototype.timer has finished executing.
A good way to do this, is store it as a key in the jQuery object as jQuery.customTimer.

I've modified your jQuery.prototype.timer function to make use of this as shown below.

// Timer Custom function
jQuery.prototype.timer = function() {
    // Target html tag for timer
    var htmlTag = (this);

    // Integer increment
    var i = 0;

    // Clear old timer if exists
    if (jQuery.customTimer)
        clearInterval(jQuery.customTimer);

    // Create timer
    jQuery.customTimer = setInterval(function() {
        // Always increment by 1;
        i++;

        // Output...
        htmlTag.text(i.toHHMMSS());
    }, 1000); // ..every 1 second(s)
};


答:
There so many ways to do this but you can use a simple function to convert a number to a dass separated number as follows.</p>

```<code> //This function returns the result as per your question.
 function commaSeparateNumber(val){
    var regex =new  RegExp("(\\d{5})(\\d+)");
    var valEdit = val.toString().replace(regex, '$1'+'-');
    var valleft = val.toString().replace(regex, '$2');
    var regex =new  RegExp("(\\d{4})(\\d+)");
    val = valleft.toString().replace(regex, '$1'+'-'+'$2');
    return valEdit+val;
 }
 console.log(commaSeparateNumber(12345123412));

//This function work for change at every 4 digit insertion
function commaSeparateNumber(val){
    while (/(\d{4})(\d+)/.test(val.toString())){
      val = val.toString().replace(/(\d{4})(\d+)/, '$1'+'-'+'$2');
    }
    return val;
  }
  console.log(commaSeparateNumber(12345123412));
</code>```

Title: How to insert characters in between in jquery?

Body: I have this data from the database 12345123412 but in my page I need to display it as 12345-1234-12. Any ideas on how to handle this? I'm trying to do the .split()

Body:
There so many ways to do this but you can use a simple function to convert a number to a dass separated number as follows.

 //This function returns the result as per your question.
 function commaSeparateNumber(val){
    var regex =new  RegExp("(\\d{5})(\\d+)");
    var valEdit = val.toString().replace(regex, '$1'+'-');
    var valleft = val.toString().replace(regex, '$2');
    var regex =new  RegExp("(\\d{4})(\\d+)");
    val = valleft.toString().replace(regex, '$1'+'-'+'$2');
    return valEdit+val;
 }
 console.log(commaSeparateNumber(12345123412));

//This function work for change at every 4 digit insertion
function commaSeparateNumber(val){
    while (/(\d{4})(\d+)/.test(val.toString())){
      val = val.toString().replace(/(\d{4})(\d+)/, '$1'+'-'+'$2');
    }
    return val;
  }
  console.log(commaSeparateNumber(12345123412));


问:
How can I find a link between 2 separate SQL tables without knowing the foreign keys?
I'm relatively new to the SQL game and I'm having a rough time finding a link between tables.

Say I have 4 tables: A, B, C, D.

Table A has a foreign key to table B.

Table B has a foreign key to Table C.

Table C has a foreign key to table D.

There isn't any direct link / relationship between table A and table C, or between B and D or between A and D.

Is there an SQL command or a method of finding the 'path' from table A to table D without knowing anything about table B and C and their respective foreign keys?

Edit: I didn't realize that it may be specific to the type of database but I'm using an Oracle database and connecting to it with SQL Developer.

答:
Not in standard sql.

Some DB servers have tools that would help you visualize how to connect the dots. Microsoft Sql server for example has Microsoft Sql Server Management Studio that will allow you to select a table, show tables that references it or tables that the table references. I’m pretty sure that other DBMS  will have something similar.


问:
How can I open the default system browser from a java fx application?
I'm trying to open a web url in the default system browser from javafx. I didn't find any official documentation regard this. Any clue?

EDIT:
I've found a tutorial but it doesn't work.
I'm using MacOsX and I tried launching

```<code>java.awt.Desktop.getDesktop().browse(new URI(url));
</code>```

but I get an HeadlessExcelption

答:
Try This:</p>

```<code>try {
    Desktop.getDesktop().browse(new URL("https://google.com").toURI());
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
</code>```

Body:
I'm trying to open a web url in the default system browser from javafx. I didn't find any official documentation regard this. Any clue?

EDIT:
I've found a tutorial but it doesn't work.
I'm using MacOsX and I tried launching

java.awt.Desktop.getDesktop().browse(new URI(url));

but I get an HeadlessExcelption

Body:
Try This:

try {
    Desktop.getDesktop().browse(new URL("https://google.com").toURI());
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}


问:
How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?
How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p>

答:
The commercial solution, SpreadsheetGear for .NET will do it.

You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.

Disclaimer: I own SpreadsheetGear LLC

OwnerDisplayName: mistrmark

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: mistrmark

OwnerDisplayName: Joe Erickson


问:
If an object is passed as an argument in a function, does it create a new instance?
In this code:

```<code>function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);
</code>```

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

答:
It should be the same object you defined, and it will continue to the same object no matter how many times you pass it.  Why? Are you seeing something to indicate this is not the case?

You might be getting confused because primitive values are passed by value, while objects are passed by reference.

This is a pretty decent description of the difference : http://snook.ca/archives/javascript/javascript_pass

The punch line can is his code examples :

Here is a an example that handles a primitive value, an integer in this case. With primitive values,
Primitive values are passed by value meaning a new copy of the value is place on stack with function call. It also means that any changes made to a value within a function are local to that function.

```<code>function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4
</code>```

This is an example that shows how pass by reference works.  In this case a reference to an object is provided to the function and any changes to that object are seen by everyone who has the reference.

```<code>function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6
</code>```

One final thing, if you replace the reference passed into a function with a new reference this change is not reflected outside the function. Building off the previous example:

```<code>function myobject()
{
    this.value = 5;
}
var o = new myobject();

function objectchanger2(fnc)
{
  function myObject2()
     {
        this.value = 10
     }
   fnc = new myObject2()
}

objectchanger(o);
alert(o.value); // o.value is still  5
</code>```

Body:
In this code:

function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

Body:
It should be the same object you defined, and it will continue to the same object no matter how many times you pass it.  Why? Are you seeing something to indicate this is not the case?

You might be getting confused because primitive values are passed by value, while objects are passed by reference.

This is a pretty decent description of the difference : http://snook.ca/archives/javascript/javascript_pass

The punch line can is his code examples :

Here is a an example that handles a primitive value, an integer in this case. With primitive values,
Primitive values are passed by value meaning a new copy of the value is place on stack with function call. It also means that any changes made to a value within a function are local to that function.

function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4

This is an example that shows how pass by reference works.  In this case a reference to an object is provided to the function and any changes to that object are seen by everyone who has the reference.

function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

One final thing, if you replace the reference passed into a function with a new reference this change is not reflected outside the function. Building off the previous example:

function myobject()
{
    this.value = 5;
}
var o = new myobject();

function objectchanger2(fnc)
{
  function myObject2()
     {
        this.value = 10
     }
   fnc = new myObject2()
}

objectchanger(o);
alert(o.value); // o.value is still  5


问:
Filtering the duplicates in subset sum combinations
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

```<code>subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()
</code>```

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

答:
This is not a direct answer to your question, but a better algorithm. If you're only looking for one example of a list of maximal length which satisfies your sum criterion, you should be looking at longer lists first. This code uses itertools for the combinatorial bits and will stop when the longest list is found.

```<code>numbers = [1, 2, 2, 2]
taget = 5

for size in reversed(range(1, 1 + len(numbers))):
    for c in itertools.combinations(numbers, size):
        if sum(c) == target:
            break
    else:
        continue
    break
</code>```

c now contains the longest subset as a tuple (1, 2, 2)

Body:
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

Body:
This is not a direct answer to your question, but a better algorithm. If you're only looking for one example of a list of maximal length which satisfies your sum criterion, you should be looking at longer lists first. This code uses itertools for the combinatorial bits and will stop when the longest list is found.

numbers = [1, 2, 2, 2]
taget = 5

for size in reversed(range(1, 1 + len(numbers))):
    for c in itertools.combinations(numbers, size):
        if sum(c) == target:
            break
    else:
        continue
    break

c now contains the longest subset as a tuple (1, 2, 2)


问:
Django scheduled (template) modules
What I am trying to do is to architect "dynamic" modules on my website.

Assume I have a blog, with two columns.

Left column contains a post, right column contains "modules" ("Most popular posts", "Tags" etc).

Some of the modules will be unrelated to the post (ex. "Tags"), and some will be independent (ex.Blog Roll).

On the template level - what is the best way to "include" these modules? (each will have a different markup/different model).

On the back-end level - how can I add a schedule to the "unrelated" modules so they are displayed during particular days/hours?

答:
use include and block tags
http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance

to display something based on some variable. you can do something like this
in views

```<code>def foo(request):
    if day=="monday":
       show_tags=True
    else:
       show_tags=False
    return render_to_response('template.html', {'show_tags': show_tags})
</code>```

and in template.html

```<code>{% if show_tags %}
   {% include 'tags_template.html' %}
{% endif %}
</code>```

Title: Django scheduled (template) modules

Body:
use include and block tags
http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance

to display something based on some variable. you can do something like this
in views

def foo(request):
    if day=="monday":
       show_tags=True
    else:
       show_tags=False
    return render_to_response('template.html', {'show_tags': show_tags})

and in template.html

{% if show_tags %}
   {% include 'tags_template.html' %}
{% endif %}