问:
Broken image in ng-repeat that will not go away
I tried ng-hide and ng-if and no matter what I do, the console log shows a broken image with empty values like this:

```<code>%7B%7B%20bookings.country%20%7D%7D.png:1
GET http://localhost:8080/img/flagNations/%7B%7B%20bookings.country%20%7D%7D.png
404 (Not Found)
</code>```

And here is the code that causes this:

```<code><table class="start-table" ng-if="vm.doubleBookings.length > 0">
<tbody>
    <tr ng-repeat="bookings in vm.doubleBookings" class="start-text">
        <td class="start-left">
            <img src="./img/flagNations/{{ bookings.country }}.png" class="start-flag">
            <b class="start-country">{{ bookings.country | uppercase }}</b>
            {{ bookings.name }}
        </td>
    </tr>
</tbody>
</table>
</code>```

Looks like it still tries to render the image even thou there is no data, and it totally ignores the ng-if="vm.doubleBookings.length > 0"

Just to confirm, here is from my controller

```<code>    }).then(function successCallback(result) {
        console.log('from getDoubleBooking: ' + JSON.stringify(result.data.res, null, 4))
        var res = result.data.res;
        console.log("LENGTH RES: " + res.doubleBooking.length)
        vm.doubleBookings = res.doubleBooking;
        console.log("LENGTH VM: " + vm.doubleBookings.length)
</code>```

Which gives the result

```<code>from getDoubleBooking: {
    "doubleBooking": [],
    "sameDayBooking": []
}
LENGTH RES: 0
LENGTH VM: 0
</code>```

I seriously cannot figure this one out - it makes no sense why it should render the image?!?

I even tried this:

 0" src="./img/flagNations/{{ bookings.country }}.png" class="start-flag">

same result.

Here is a bigger part of the controller:

```<code>//
// Find Double Bookings and Same Day Bookings
//
var findDoubleBooking = () => {
    return new Promise((resolve, reject) => {
    $http({
        method: 'POST',
        url: globalSetting.serverURL + 'manager/getDoubleBooking',
        headers: { 'Content-Type': 'application/json' },
        data: {"checkout" : 5299014799}
    }).then(function successCallback(result) {
        console.log('from getDoubleBooking: ' + JSON.stringify(result.data.res, null, 4))
        var res = result.data.res;
        console.log("LENGTH RES: " + res.doubleBooking.length)
        vm.doubleBookings = res.doubleBooking;
        console.log("LENGTH VM: " + vm.doubleBookings.length)
        vm.sameDayBookings = res.sameDayBooking;
        console.log("LENGTH VM: " + vm.sameDayBookings.length)

        resolve();
    }, function errorCallback(err) {
        reject(new Error('getDoubleBooking ERROR : ' + err));
    });
})};
</code>```

And here is the whole HTML segment

```<code><!--Double Bookings Table-->
<table border="0" cellspacing="0" cellpadding="0" class="start-table start-double-table" ng-if="vm.doubleBookings.length > 0">
<tbody>
    <tr class="start-header start-bold start-double-bg">
        <td colspan="5" class="start-padding overflow">
            DOUBLE BOOKINGS - FIX THEM NOW!
        </td>
    </tr>
    <tr class="start-header start-head start-double-bg">
        <td class="start-left nowrap" style="min-width:76px;">Property</td>
        <td class="start-center overflow" style="width:13%">Checkin</td>
        <td class="start-center overflow" style="width:13%">Checkout</td>
        <td class="start-left overflow" style="width:44%">Tenant</td>
        <td class="start-right overflow" style="width:10%">Paid</td>
    </tr>

    <tr ng-repeat="bookings in vm.doubleBookings" class="start-text">
        <td class="start-left start-border nowrap" ng-class="{'start-double': !$last && bookings.property !== vm.doubleBookings[$index + 1].property}">
            <span class="chan-{{ bookings.source }}">{{ bookings.source }}</span> {{ bookings.property }}
        </td>
        <td class="start-center start-border overflow" ng-class="{'start-double': !$last && bookings.property !== vm.doubleBookings[$index + 1].property}">{{bookings.checkin*1000 | date : 'dd MMM' }}</td>
        <td class="start-center start-border overflow" ng-class="{'start-double': !$last && bookings.property !== vm.doubleBookings[$index + 1].property}">{{bookings.checkout*1000 | date : 'dd MMM' }}</td>
        <td class="start-left start-border overflow" ng-class="{'start-double': !$last && bookings.property !== vm.doubleBookings[$index + 1].property}">
            <img ng-if="vm.doubleBookings.length > 0" src="./img/flagNations/{{ bookings.country }}.png" class="start-flag">
            <b class="start-country">{{ bookings.country | uppercase }}</b>
            {{ bookings.name }}
        </td>
        <td class="start-right start-border overflow" ng-class="{'start-double': !$last && bookings.property !== vm.doubleBookings[$index + 1].property}">{{ bookings.paidAlready }}</td>
    </tr>
</tbody>
</table>
<div class="spacer" ng-if="vm.doubleBookings.length > 0"></div>
</code>```

答:
Instead of

```<code><img src="./img/flagNations/{{ bookings.country }}.png">
</code>```

I changed src= to ng-src=

```<code><img ng-src="./img/flagNations/{{ bookings.country }}.png">
</code>```

And the problem is gone!!

Body:
I tried ng-hide and ng-if and no matter what I do, the console log shows a broken image with empty values like this:

%7B%7B%20bookings.country%20%7D%7D.png:1
GET http://localhost:8080/img/flagNations/%7B%7B%20bookings.country%20%7D%7D.png
404 (Not Found)

And here is the code that causes this:

 0">

            {{ bookings.country | uppercase }}
            {{ bookings.name }}

Looks like it still tries to render the image even thou there is no data, and it totally ignores the ng-if="vm.doubleBookings.length > 0"

Just to confirm, here is from my controller

    }).then(function successCallback(result) {
        console.log('from getDoubleBooking: ' + JSON.stringify(result.data.res, null, 4))
        var res = result.data.res;
        console.log("LENGTH RES: " + res.doubleBooking.length)
        vm.doubleBookings = res.doubleBooking;
        console.log("LENGTH VM: " + vm.doubleBookings.length)

Which gives the result

from getDoubleBooking: {
    "doubleBooking": [],
    "sameDayBooking": []
}
LENGTH RES: 0
LENGTH VM: 0

I seriously cannot figure this one out - it makes no sense why it should render the image?!?

I even tried this:

 0" src="./img/flagNations/{{ bookings.country }}.png" class="start-flag">

same result.

Here is a bigger part of the controller:

//
// Find Double Bookings and Same Day Bookings
//
var findDoubleBooking = () => {
    return new Promise((resolve, reject) => {
    $http({
        method: 'POST',
        url: globalSetting.serverURL + 'manager/getDoubleBooking',
        headers: { 'Content-Type': 'application/json' },
        data: {"checkout" : 5299014799}
    }).then(function successCallback(result) {
        console.log('from getDoubleBooking: ' + JSON.stringify(result.data.res, null, 4))
        var res = result.data.res;
        console.log("LENGTH RES: " + res.doubleBooking.length)
        vm.doubleBookings = res.doubleBooking;
        console.log("LENGTH VM: " + vm.doubleBookings.length)
        vm.sameDayBookings = res.sameDayBooking;
        console.log("LENGTH VM: " + vm.sameDayBookings.length)

        resolve();
    }, function errorCallback(err) {
        reject(new Error('getDoubleBooking ERROR : ' + err));
    });
})};

And here is the whole HTML segment

 0">

            DOUBLE BOOKINGS - FIX THEM NOW!

        Property
        Checkin
        Checkout
        Tenant
        Paid

            {{ bookings.source }} {{ bookings.property }}

        {{bookings.checkin*1000 | date : 'dd MMM' }}
        {{bookings.checkout*1000 | date : 'dd MMM' }}

             0" src="./img/flagNations/{{ bookings.country }}.png" class="start-flag">
            {{ bookings.country | uppercase }}
            {{ bookings.name }}

        {{ bookings.paidAlready }}

 0">

Body:
Instead of

<img src="./img/flagNations/{{ bookings.country }}.png">

I changed src= to ng-src=

<img ng-src="./img/flagNations/{{ bookings.country }}.png">

And the problem is gone!!


来源: stackexchange

问:
How to check if an element in a string array is empty?
How can I check if an element in a string array is empty? This is my example array:

```<code>private static String correct[] = new String[5];
    static {
        correct[1] = "some texT";
        correct[2] = "some texT3";
        correct[4] = "some texT2";
}
</code>```

I can assign null to rest of elements, but I want to find another, better way to do this.
I found isEmpty, but it is available only on API 9 and above.

if(correct[0].length() > 0)
gives me a NPE.
if(correct[0] != null also.

答:
Had similar version where number of arguments could be bigger</p>

```<code>if (Arrays.asList(new String[] {productId, productTitle, imageName, productPrice}).contains(null)) {
        return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I check if an element in a string array is empty? This is my example array:

private static String correct[] = new String[5];
    static {
        correct[1] = "some texT";
        correct[2] = "some texT3";
        correct[4] = "some texT2";
}

I can assign null to rest of elements, but I want to find another, better way to do this.
I found isEmpty, but it is available only on API 9 and above.

if(correct[0].length() > 0)
gives me a NPE.
if(correct[0] != null also.

Body:
Had similar version where number of arguments could be bigger

if (Arrays.asList(new String[] {productId, productTitle, imageName, productPrice}).contains(null)) {
        return null;
}


问:
Appium error : [XCUITest] Error: Could not initialize ios-deploy make sure it is installed (npm install -g ios-deploy) and works on your system
I got an error in Appium : [XCUITest] Error: Could not initialize ios-deploy make sure it is installed (npm install -g ios-deploy) and works on your system.

I try to run my test automation on the real device, not on simulator.

I am using Mac v10.12.5
Appium v1.6.5
Xcode v8.3.3

Can anyone help what could cause it please?

答:
I had to manually add environment variables when launching Appium Server programmatically. Maybe same in your case.
Try follows if you are launching server by AppiumServiceBuilder class in java.</p>

```<code>AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder.withEnvironment(new HashMap<String, String>() {
    { put("PATH", "/usr/local/bin:/usr/bin: and any...") }
});
</code>```

Body:
I had to manually add environment variables when launching Appium Server programmatically. Maybe same in your case.
Try follows if you are launching server by AppiumServiceBuilder class in java.

AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder.withEnvironment(new HashMap<String, String>() {
    { put("PATH", "/usr/local/bin:/usr/bin: and any...") }
});


问:
What the HTML 5 alternative to using the rules attribute for table element?
When using the rules attribute on this table element

I get the following warning:

Attribute (rules) is obsolete. Its use is discouraged in HTML5 documents.

What is the HTML 5 alternative for this?

答:
From here

What does
 do?

Was used to specify the display of internal borders between rows and colums. This attribute has been deprecated. Use CSS to style table borders instead.

So there is no HTML5 alternative, just CSS alternative:

table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 15px;
}

table td {
  text-align: center;
}

.frame-box {
  border: 1px solid black;
}

.frame-void {
  border: none;
}

.rules-none td {
  border: none;
}

.rules-all td {
  border: 1px solid black;
}

.rules-all td:first-child {
  border-left: none;
}

.rules-all td:last-child {
  border-right: none;
}

.rules-all tr:first-child td {
  border-top: none;
}

.rules-all tr:last-child td {
  border-bottom: none;
}

.rules-cols td {
  border-left: 1px solid black;
  border-right: 1px solid black;
}

.rules-rows td {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}

.border-2,
.border-2 td {
  border-width: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>"<TABLE BORDER=2 RULES=NONE FRAME=BOX>"

<table class="rules-none border-2 frame-box">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"<TABLE BORDER=2 FRAME=VOID RULES=ALL>"
<table class="border-2 frame-void rules-all">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"<TABLE BORDER=2 RULES=COLS FRAME=BOX>"
<table class="border-2 frame-box rules-cols">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"<TABLE BORDER=2 RULES=ROWS FRAME=BOX>"
<table class="border-2 frame-box rules-rows">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table></code>```

Body:
From here

What does <table rules=""> do?

Was used to specify the display of internal borders between rows and colums. This attribute has been deprecated. Use CSS to style table borders instead.

So there is no HTML5 alternative, just CSS alternative:

table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 15px;
}

table td {
  text-align: center;
}

.frame-box {
  border: 1px solid black;
}

.frame-void {
  border: none;
}

.rules-none td {
  border: none;
}

.rules-all td {
  border: 1px solid black;
}

.rules-all td:first-child {
  border-left: none;
}

.rules-all td:last-child {
  border-right: none;
}

.rules-all tr:first-child td {
  border-top: none;
}

.rules-all tr:last-child td {
  border-bottom: none;
}

.rules-cols td {
  border-left: 1px solid black;
  border-right: 1px solid black;
}

.rules-rows td {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}

.border-2,
.border-2 td {
  border-width: 2px;
}

"&lt;TABLE BORDER=2 RULES=NONE FRAME=BOX&gt;"

<table class="rules-none border-2 frame-box">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"&lt;TABLE BORDER=2 FRAME=VOID RULES=ALL&gt;"
<table class="border-2 frame-void rules-all">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"&lt;TABLE BORDER=2 RULES=COLS FRAME=BOX&gt;"
<table class="border-2 frame-box rules-cols">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>

"&lt;TABLE BORDER=2 RULES=ROWS FRAME=BOX&gt;"
<table class="border-2 frame-box rules-rows">
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td>4</td><td>5</td><td>6</td></tr>
  <tr><td>7</td><td>8</td><td>9</td></tr>
</table>


问:
Flex performance hit?
I looked at this demo:
http://bubblemark.com/

Flex seems very slow compared to silverlight 3. Unfortunately can't see pure flash but should flex be forbidden if performance is top requirements compared to Flash ?

答:
I wouldn't take that test as a benchmark.

If you try the same test on different browsers, it might give you a different result. (I got better fps on flex then on silverlight using firefox, also when going to the back button of the browser and waiting a bit would slow down silverlight.)

As Kelsey Rider said, do some tests for your particular app and try use the average setup of your target group.

ContentLicense: CC BY-SA 2.5

Title: Flex performance hit?


问:
Leaflet map won't render in browser
I have a map using Leaflet which works in the html output of r markdown, but the map won't render when I open the html in Google or IE. Ggmap works fine, but I'd prefer an interactive map. Any ideas?</p>

```<code>```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = FALSE,
  warning = FALSE,
  message = FALSE,
  comment=NA,
  fig.height=7,
  fig.width = 9)
```

```{r Libraries}
library(leaflet)
library(ggmap)
```

Plot map with leaflet package.
```{r Leaflet}
#using leaflet
Pin <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))

Bne2 <- leaflet() %>%
  addTiles()  %>%
  addMarkers(data=Pin)
Bne2

```

Plot map with ggmap package.
```{r Ggmap}
#using ggmap
Sa2 <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))
Brisbane <- get_map("Brisbane,Australia",zoom=11)

BNE <- ggmap(Brisbane)+
  geom_point(data=Sa2,aes(x=Lng,y=Lat),color="black",size=3)

plot(BNE)

```
</code>```

答:
I'm seeing the same issue, and it appears to be related to the default tiles not rendering in the browser. But, I have no idea why that's the case.

So a couple of options are

Change the tile layer (https://leaflet-extras.github.io/leaflet-providers/preview/)

Use a different mapping package. Here I'm demonstrating my googleway package for plotting interactive Google Maps

```<code>```{r Libraries}
library(leaflet)
library(ggmap)
library(googleway)
```

Plot map with leaflet package.
```{r Leaflet}
#using leaflet
Pin <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))

Bne2 <- leaflet() %>%
  addTiles(urlTemplate = 'http://{s}.tile.opentopomap.org/{z}/{x}/{y}.png')  %>%
  addMarkers(data=Pin)
Bne2

```

Plot map with ggmap package.
```{r Ggmap}
#using ggmap
Sa2 <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))
Brisbane <- get_map("Brisbane,Australia",zoom=11)

BNE <- ggmap(Brisbane)+
  geom_point(data=Sa2,aes(x=Lng,y=Lat),color="black",size=3)

plot(BNE)

```

Plot map with googleway
```{r googleway}
## you need an api key to use google maps
mapKey <- 'your_api_key'

google_map(key = mapKey) %>%
    add_markers(data = Pin)

```
</code>```

Here are all three working in Chrome

Title: Leaflet map won't render in browser

Body:
I have a map using Leaflet which works in the html output of r markdown, but the map won't render when I open the html in Google or IE. Ggmap works fine, but I'd prefer an interactive map. Any ideas?

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = FALSE,
  warning = FALSE,
  message = FALSE,
  comment=NA,
  fig.height=7,
  fig.width = 9)
```

```{r Libraries}
library(leaflet)
library(ggmap)
```

Plot map with leaflet package.
```{r Leaflet}
#using leaflet
Pin <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))

Bne2 <- leaflet() %>%
  addTiles()  %>%
  addMarkers(data=Pin)
Bne2

```

Plot map with ggmap package.
```{r Ggmap}
#using ggmap
Sa2 <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))
Brisbane <- get_map("Brisbane,Australia",zoom=11)

BNE <- ggmap(Brisbane)+
  geom_point(data=Sa2,aes(x=Lng,y=Lat),color="black",size=3)

plot(BNE)

```

Body:
I'm seeing the same issue, and it appears to be related to the default tiles not rendering in the browser. But, I have no idea why that's the case.

So a couple of options are

Change the tile layer (https://leaflet-extras.github.io/leaflet-providers/preview/)

Use a different mapping package. Here I'm demonstrating my googleway package for plotting interactive Google Maps

```{r Libraries}
library(leaflet)
library(ggmap)
library(googleway)
```

Plot map with leaflet package.
```{r Leaflet}
#using leaflet
Pin <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))

Bne2 <- leaflet() %>%
  addTiles(urlTemplate = 'http://{s}.tile.opentopomap.org/{z}/{x}/{y}.png')  %>%
  addMarkers(data=Pin)
Bne2

```

Plot map with ggmap package.
```{r Ggmap}
#using ggmap
Sa2 <- data.frame(t(c(ID=1,Lat=-27.474176,Lng=153.024901)))
Brisbane <- get_map("Brisbane,Australia",zoom=11)

BNE <- ggmap(Brisbane)+
  geom_point(data=Sa2,aes(x=Lng,y=Lat),color="black",size=3)

plot(BNE)

```

Plot map with googleway
```{r googleway}
## you need an api key to use google maps
mapKey <- 'your_api_key'

google_map(key = mapKey) %>%
    add_markers(data = Pin)

```

Here are all three working in Chrome


问:
Bootstrap Modal not closing on data dismiss (Rails)
I have a rails application with an edit modal. The submit functionality works, but the close buttons do not do anything.

Edit.js.erb:

```<code>$("#modal-window").html("<%= escape_javascript(render 'users/edit') %>");
</code>```

_edit.html.erb

```<code><div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
 <%= form_for @user,url: root_path,:method => :GET do |f|%>
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>
     <%= f.submit "Save changes", class: "btn btn-primary" %>
     <%# submit_tag 'Cancel', :type => :reset, :class => "btn btn-danger", "data-dismiss" => "modal", "aria-hidden" => "true" %>
<% end %>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
</code>```

The lines from the view that opens and houses the modal

```<code><%= link_to 'Edit Password', edit_path(user.id),  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}

......

<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
</code>```

I have the gems set up. //= require bootstrap/modal and //= require jqueryare in my application.js

Edit: Full application.js

```<code>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require bootstrap/modal
//= require jquery
</code>```

答:
As the bootstrap-modal-rails gem would work with a Rails 4 application version, you could consider just using the Bootstrap modals to ge it work.

You can create a modal div, then add the button which will make a request to a certain method in the controller, which will respond with a js file, that then will render the partial which will fill the modal div.

In your index.html.erb you can set the link_to helper:

```<code><%= link_to 'Edit Password', edit_path(user), remote: true, data: { toggle: 'modal', 'target': '#modal-window' } %>
...
<!-- Modal -->
<div class="modal fade " id="modal-window" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
</code>```

This specifies the path, in this case the one that responds to the edit method in the UsersController, add the remote: true option to start an asynchronous request to such method, and specifiy as data attributes the data-toggle and data-target.

Then, in the bottom if you prefer, you can create the #modal-window div, setted to work as a bootstrap modal, and which most match in id and data-target with the link_to helper to be "opened".

The route that's defined in the link_to expects an id, and use the alias option to create a short version:

```<code>get 'users/edit/:id', to: 'users#edit', as: 'edit'
</code>```

Your controller just needs the method, edit, which will respond in Javascript, it just receives the id param that's sent:

```<code>def edit
  @user = User.find(params[:id])
end
</code>```

As edit responds in json format, then you need to create a file with the same name of your method plus the extension js and erb, this is edit.js.erb, and contains the code to render the _edit partial, and show the modal:

```<code>$("#modal-window").html("<%= j render 'users/edit' %>");
$('#modal-window').modal('show')
</code>```

Finally the _edit partial will contain the content that will be added to the div modal created before, this can be easily tweaked, in the .modal-body div, so you can add the form:

```<code><div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      <h4 class="modal-title" id="myModalLabel">Modal title</h4>
    </div>

    <div class="modal-body">
      <%= form_for @user, url: edit_path do |f|%>
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %><br>
        <%= f.submit "Save changes", class: "btn btn-primary" %>
      <% end %>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div>
</div>
</code>```

Note this depends on Bootstrap, so you need to add the gem to your Gemfile file, and configure both js and css application files:

```<code># Gemfile
gem 'bootstrap-sass'

# application.js
//= require jquery
//= require bootstrap-sprockets

# application.scss
@import "bootstrap-sprockets";
@import "bootstrap";
</code>```

In the application.js, as bootstrap depends on jQuery, this must be added before the bootstrap one, and for the css configuration, the file must be scss in order to make the proper import's.

Body:
I have a rails application with an edit modal. The submit functionality works, but the close buttons do not do anything.

Edit.js.erb:

$("#modal-window").html("<%= escape_javascript(render 'users/edit') %>");

_edit.html.erb

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

 <%= form_for @user,url: root_path,:method => :GET do |f|%>
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>
     <%= f.submit "Save changes", class: "btn btn-primary" %>
     <%# submit_tag 'Cancel', :type => :reset, :class => "btn btn-danger", "data-dismiss" => "modal", "aria-hidden" => "true" %>
<% end %>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

The lines from the view that opens and houses the modal

<%= link_to 'Edit Password', edit_path(user.id),  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}

......

I have the gems set up. //= require bootstrap/modal and //= require jqueryare in my application.js

Edit: Full application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require bootstrap/modal
//= require jquery

Body:
As the bootstrap-modal-rails gem would work with a Rails 4 application version, you could consider just using the Bootstrap modals to ge it work.

You can create a modal div, then add the button which will make a request to a certain method in the controller, which will respond with a js file, that then will render the partial which will fill the modal div.

In your index.html.erb you can set the link_to helper:

<%= link_to 'Edit Password', edit_path(user), remote: true, data: { toggle: 'modal', 'target': '#modal-window' } %>
...
<!-- Modal -->
<div class="modal fade " id="modal-window" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

This specifies the path, in this case the one that responds to the edit method in the UsersController, add the remote: true option to start an asynchronous request to such method, and specifiy as data attributes the data-toggle and data-target.

Then, in the bottom if you prefer, you can create the #modal-window div, setted to work as a bootstrap modal, and which most match in id and data-target with the link_to helper to be "opened".

The route that's defined in the link_to expects an id, and use the alias option to create a short version:

get 'users/edit/:id', to: 'users#edit', as: 'edit'

Your controller just needs the method, edit, which will respond in Javascript, it just receives the id param that's sent:

def edit
  @user = User.find(params[:id])
end

As edit responds in json format, then you need to create a file with the same name of your method plus the extension js and erb, this is edit.js.erb, and contains the code to render the _edit partial, and show the modal:

$("#modal-window").html("<%= j render 'users/edit' %>");
$('#modal-window').modal('show')

Finally the _edit partial will contain the content that will be added to the div modal created before, this can be easily tweaked, in the .modal-body div, so you can add the form:

<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">Modal title</h4>
    </div>

    <div class="modal-body">
      <%= form_for @user, url: edit_path do |f|%>
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %><br>
        <%= f.submit "Save changes", class: "btn btn-primary" %>
      <% end %>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div>
</div>

Note this depends on Bootstrap, so you need to add the gem to your Gemfile file, and configure both js and css application files:

# Gemfile
gem 'bootstrap-sass'

# application.js
//= require jquery
//= require bootstrap-sprockets

# application.scss
@import "bootstrap-sprockets";
@import "bootstrap";

In the application.js, as bootstrap depends on jQuery, this must be added before the bootstrap one, and for the css configuration, the file must be scss in order to make the proper import's.


问:
Datashader has snappy error
I was using python's datashader 0.5.0 package to plot population density information, generally following the tutorial https://www.continuum.io/blog/developer-blog/analyzing-and-visualizing-big-data-interactively-your-laptop-datashading-2010-us . I installed datashader using conda install -c bokeh datashader=0.5.0.

All was fine. Though perhaps unrelated, things seemed to break as soon as I installed the haloviews and geoviews packages. After installing these additional packages, I can no longer import datashader and my once working code no longer runs. When importing datashader, I get the following error:
AttributeError: module 'snappy' has no attribute 'compress'

I am running on windows 10, anaconda python 3.5.3.

Perhaps I'm going down the wrong rabbit hole, but I thought perhaps it was the snappy package. I ran "conda install -c conda-forge snappy=1.1.4". conda list reveals that snappy is installed. Snappy does import. The snappy.compress object is not found. My issue seems related to the following SO post as I also had a fastparquet error when trying geoviews: error with snappy while importing fastparquet in python

When running import snappy, print(snappy.__filename__) gives the following error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-b8565733b383> in <module>()
----> 1 import snappy; print(snappy.__file__)

AttributeError: module 'snappy' has no attribute '__file__'
</code>```

I also tried uninstalling through both conda and pip just in case. Still no joy.

Running "pip install python-snappy" results in a "failed building wheel for python-snappy" error preceded with " error: Microsoft Visual C++ 14.0 is required..." So I went and got the "Microsoft Visual C++ Redistributable for Visual Studio 2017" and ran it, but had no change.

Any thoughts on how to resolve this? For reference, the full error on datashader import is as follows:

```<code>--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-3d7b1ff9e530> in <module>()
----> 1 import datashader

C:\Python\lib\site-packages\datashader\__init__.py in <module>()
      3 __version__ = '0.5.0'
      4
----> 5 from .core import Canvas
      6 from .reductions import (count, any, sum, min, max, mean, std, var, count_cat,
      7                          summary)

C:\Python\lib\site-packages\datashader\core.py in <module>()
      3 import numpy as np
      4 from datashape.predicates import istabular
----> 5 from odo import discover
      6 from xarray import DataArray
      7

C:\Python\lib\site-packages\odo\__init__.py in <module>()
     63     from .backends.url import URL
     64 with ignoring(ImportError):
---> 65     from .backends.dask import dask
     66
     67

C:\Python\lib\site-packages\odo\backends\dask.py in <module>()
      8
      9 from dask.array.core import Array, from_array
---> 10 from dask.bag.core import Bag
     11 import dask.bag as db
     12 from dask.compatibility import long

C:\Python\lib\site-packages\dask\bag\__init__.py in <module>()
      1 from __future__ import absolute_import, division, print_function
      2
----> 3 from .core import (Bag, Item, from_sequence, from_url, to_textfiles, concat,
      4                    from_delayed, map_partitions, bag_range as range,
      5                    bag_zip as zip, bag_map as map)

C:\Python\lib\site-packages\dask\bag\core.py in <module>()
     30
     31 from ..base import Base, normalize_token, tokenize
---> 32 from ..bytes.core import write_bytes
     33 from ..compatibility import apply, urlopen
     34 from ..context import _globals, defer_to_globals

C:\Python\lib\site-packages\dask\bytes\__init__.py in <module>()
      2
      3 from ..utils import ignoring
----> 4 from .core import read_bytes, open_files, open_text_files
      5
      6 from . import local

C:\Python\lib\site-packages\dask\bytes\core.py in <module>()
      7 from warnings import warn
      8
----> 9 from .compression import seekable_files, files as compress_files
     10 from .utils import (SeekableFile, read_block, infer_compression,
     11                     infer_storage_options, build_name_function)

C:\Python\lib\site-packages\dask\bytes\compression.py in <module>()
     30 with ignoring(ImportError):
     31     import snappy
---> 32     compress['snappy'] = snappy.compress
     33     decompress['snappy'] = snappy.decompress
     34

AttributeError: module 'snappy' has no attribute 'compress'
</code>```

答:
It turns out that in adding packages, something messed up the snappy install. I followed this solution: How to install snappy C libraries on Windows 10 for use with python-snappy in Anaconda?
It was a snappy error, not a datashader issue, but I'll leave the post in case anyone has the same series of issues.</p>

Title: Datashader has snappy error

Body:
I was using python's datashader 0.5.0 package to plot population density information, generally following the tutorial https://www.continuum.io/blog/developer-blog/analyzing-and-visualizing-big-data-interactively-your-laptop-datashading-2010-us . I installed datashader using conda install -c bokeh datashader=0.5.0.

All was fine. Though perhaps unrelated, things seemed to break as soon as I installed the haloviews and geoviews packages. After installing these additional packages, I can no longer import datashader and my once working code no longer runs. When importing datashader, I get the following error:
AttributeError: module 'snappy' has no attribute 'compress'

I am running on windows 10, anaconda python 3.5.3.

Perhaps I'm going down the wrong rabbit hole, but I thought perhaps it was the snappy package. I ran "conda install -c conda-forge snappy=1.1.4". conda list reveals that snappy is installed. Snappy does import. The snappy.compress object is not found. My issue seems related to the following SO post as I also had a fastparquet error when trying geoviews: error with snappy while importing fastparquet in python

When running import snappy, print(snappy.__filename__) gives the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-b8565733b383> in <module>()
----> 1 import snappy; print(snappy.__file__)

AttributeError: module 'snappy' has no attribute '__file__'

I also tried uninstalling through both conda and pip just in case. Still no joy.

Running "pip install python-snappy" results in a "failed building wheel for python-snappy" error preceded with " error: Microsoft Visual C++ 14.0 is required..." So I went and got the "Microsoft Visual C++ Redistributable for Visual Studio 2017" and ran it, but had no change.

Any thoughts on how to resolve this? For reference, the full error on datashader import is as follows:

--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-3d7b1ff9e530> in <module>()
----> 1 import datashader

C:\Python\lib\site-packages\datashader\__init__.py in <module>()
      3 __version__ = '0.5.0'
      4
----> 5 from .core import Canvas
      6 from .reductions import (count, any, sum, min, max, mean, std, var, count_cat,
      7                          summary)

C:\Python\lib\site-packages\datashader\core.py in <module>()
      3 import numpy as np
      4 from datashape.predicates import istabular
----> 5 from odo import discover
      6 from xarray import DataArray
      7

C:\Python\lib\site-packages\odo\__init__.py in <module>()
     63     from .backends.url import URL
     64 with ignoring(ImportError):
---> 65     from .backends.dask import dask
     66
     67

C:\Python\lib\site-packages\odo\backends\dask.py in <module>()
      8
      9 from dask.array.core import Array, from_array
---> 10 from dask.bag.core import Bag
     11 import dask.bag as db
     12 from dask.compatibility import long

C:\Python\lib\site-packages\dask\bag\__init__.py in <module>()
      1 from __future__ import absolute_import, division, print_function
      2
----> 3 from .core import (Bag, Item, from_sequence, from_url, to_textfiles, concat,
      4                    from_delayed, map_partitions, bag_range as range,
      5                    bag_zip as zip, bag_map as map)

C:\Python\lib\site-packages\dask\bag\core.py in <module>()
     30
     31 from ..base import Base, normalize_token, tokenize
---> 32 from ..bytes.core import write_bytes
     33 from ..compatibility import apply, urlopen
     34 from ..context import _globals, defer_to_globals

C:\Python\lib\site-packages\dask\bytes\__init__.py in <module>()
      2
      3 from ..utils import ignoring
----> 4 from .core import read_bytes, open_files, open_text_files
      5
      6 from . import local

C:\Python\lib\site-packages\dask\bytes\core.py in <module>()
      7 from warnings import warn
      8
----> 9 from .compression import seekable_files, files as compress_files
     10 from .utils import (SeekableFile, read_block, infer_compression,
     11                     infer_storage_options, build_name_function)

C:\Python\lib\site-packages\dask\bytes\compression.py in <module>()
     30 with ignoring(ImportError):
     31     import snappy
---> 32     compress['snappy'] = snappy.compress
     33     decompress['snappy'] = snappy.decompress
     34

AttributeError: module 'snappy' has no attribute 'compress'


问:
Get videos from a facebook page and their length using field expansion using Graph API
I have been looking at the field expansion functionality of graph API from facebook. I tried this approach to get the duration of videos on a facebook page but it does not return my required fields. I have made following attempts to retrieve the required information

```<code>https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=videos.fields(id,length)
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=videos{id,length}
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=data{id,length}
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=posts{id,length}
</code>```

At best, I am able to get back the required fields from facebook i.e description, id, last_updated. Any ideas how I can use this nesting to save some requests.

答:
If you're already sending a call to /videos you shouldn't need to use field expansion to get the length. Try this:

```<code>https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=length,description,id
</code>```

Body:
I have been looking at the field expansion functionality of graph API from facebook. I tried this approach to get the duration of videos on a facebook page but it does not return my required fields. I have made following attempts to retrieve the required information

https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=videos.fields(id,length)
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=videos{id,length}
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=data{id,length}
https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=posts{id,length}

At best, I am able to get back the required fields from facebook i.e description, id, last_updated. Any ideas how I can use this nesting to save some requests.

Body:
If you're already sending a call to /videos you shouldn't need to use field expansion to get the length. Try this:

https://graph.facebook.com/v2.9/575805779234615/videos?access_token=<my token>&fields=length,description,id


答:
HTML 5 demands that you replace the rules attribute with CSS attributes.
Source: https://www.w3schools.com/tags/att_table_rules.asp

Title: What the HTML 5 alternative to using the rules attribute for table element?

Body:
When using the rules attribute on this table element

I get the following warning:

Attribute (rules) is obsolete. Its use is discouraged in HTML5 documents.

What is the HTML 5 alternative for this?


问:
Django custom FileField attribute and property
I want to add a property to the FileField, so that I can specify when adding a field to the model.

```<code>class TestFile(models.Model):
    c206 = CategoryFileField(
        category='206'
    )
</code>```

And also get the same value from the model instance.

```<code>tf = TestFile.objects.latest('id')
tf.c206.category # 206
</code>```

I tried to extend FileFiled by analogy with ImageFileField:

```<code>class CategoryMetadataMixin(object):
    @property
    def category(self):
        return self.category

class CategoryFieldFile(CategoryMetadataMixin, FieldFile):
    pass

class CategoryFileField(FileField):
    attr_class = CategoryFieldFile
    descriptor_class = FileDescriptor
    description = _("File")

    def __init__(self, verbose_name=None, name=None, category='', **kwargs):
        self.attr_class.category = category
        super().__init__(verbose_name, name, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.category:
            kwargs['category'] = self.category
        return name, path, args, kwargs
</code>```

But in this case category always returns ''. Apparently I went the wrong way.

答:
Today with a clear mind I studied the sources more closely. In the end, it turned out:

```<code>class CategoryFieldFile(FieldFile):
    @property
    def category(self):
        return self.field.category

    @category.setter
    def category(self, value):
        self.field.category = value

class CategoryFileField(FileField):
    attr_class = CategoryFieldFile
    descriptor_class = FileDescriptor
    description = _("File")

    def __init__(self, verbose_name=None, name=None, category='', **kwargs):
        self.category = category
        super().__init__(verbose_name, name, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.category:
            kwargs['category'] = self.category
        return name, path, args, kwargs
</code>```

It works.

Body:
I want to add a property to the FileField, so that I can specify when adding a field to the model.

class TestFile(models.Model):
    c206 = CategoryFileField(
        category='206'
    )

And also get the same value from the model instance.

tf = TestFile.objects.latest('id')
tf.c206.category # 206

I tried to extend FileFiled by analogy with ImageFileField:

class CategoryMetadataMixin(object):
    @property
    def category(self):
        return self.category

class CategoryFieldFile(CategoryMetadataMixin, FieldFile):
    pass

class CategoryFileField(FileField):
    attr_class = CategoryFieldFile
    descriptor_class = FileDescriptor
    description = _("File")

    def __init__(self, verbose_name=None, name=None, category='', **kwargs):
        self.attr_class.category = category
        super().__init__(verbose_name, name, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.category:
            kwargs['category'] = self.category
        return name, path, args, kwargs

But in this case category always returns ''. Apparently I went the wrong way.

Body:
Today with a clear mind I studied the sources more closely. In the end, it turned out:

class CategoryFieldFile(FieldFile):
    @property
    def category(self):
        return self.field.category

    @category.setter
    def category(self, value):
        self.field.category = value

class CategoryFileField(FileField):
    attr_class = CategoryFieldFile
    descriptor_class = FileDescriptor
    description = _("File")

    def __init__(self, verbose_name=None, name=None, category='', **kwargs):
        self.category = category
        super().__init__(verbose_name, name, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.category:
            kwargs['category'] = self.category
        return name, path, args, kwargs

It works.

ContentLicense: CC BY-SA 4.0


问:
Woocommerce product listing by store location
The resources described below:

Wordpress website with woocommerce plugin activated.

Sample products are entered in the woocommerce store.

These Products are having categories such as (T-shirts, pants, hats and store name).

WP multi store locator plugin to get user location and showcase nearby stores based on location.

The problem is described below:
1. user should get option to select the nearby store and products gets sorted based on this store name.

P.S: The wp multi store locator plugin is not necessary, if there is any other alternative plugin which can solve this, it is good. tried numerous wordpress plugin to solve this but no plugin is connecting store locator to product category.

Note: This type of functionality is available on major store sites such as Walmart, Best Buy, Loblaws etc. They ask user their location and set it as main category to display the products available at that location in same city.

答:
Which plugin you have tried? I think WooCommerce Geolocation Based Products may meet your requirement.
https://wordpress.org/plugins/woocommerce-geolocation-based-products/</p>


问:
java.lang.ClassNotFoundException: org.apache.hive.service.cli.HiveSQLException
For connecting hive through spring application i have added below dependency in pom.xml.

```<code><dependency>
 <groupId>org.apache.hive</groupId>
 <artifactId>hive-jdbc</artifactId>
 <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.thrift</groupId>
  <artifactId>libfb303</artifactId>
  <version>0.9.3</version>
    <exclusions>
     <exclusion>
    <groupId>org.apache.hive</groupId>
        <artifactId>hive-common</artifactId>
     </exclusion>
    </exclusions>
</dependency>
<dependency>
  <groupId>org.apache.hive</groupId>
  <artifactId>hive-service-rpc</artifactId>
  <version>2.1.1</version>
</dependency>
</code>```

But still i am facing the below exception :: Caused by:
  java.lang.NoClassDefFoundError:
  org/apache/hive/service/cli/HiveSQLException at
  org.apache.hive.jdbc.HiveConnection.(HiveConnection.java:132) at
  org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107) at
  java.sql.DriverManager.getConnection(DriverManager.java:664) at
  java.sql.DriverManager.getConnection(DriverManager.java:208) at
  org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
  at
  org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
  at
  org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
  at
  org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
  at
  org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:71)
  at
  org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:113)
  at
  org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2836)
  at
  org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2832)
  at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
  at
  org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
  at
  org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
  at
  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
  at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
  ... 97 more Caused by: java.lang.ClassNotFoundException:
  org.apache.hive.service.cli.HiveSQLException at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
  at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
  ... 116 more

Any one please tell me if any jars i am missing or what is the issue.Using  the same url i am able to connect through beeline

```<code> $HIVE_HOME/bin/beeline -u jdbc:hive2://localhost:10000/TEST_DB
</code>```

I have refer below url but it contains no answer

org.apache.hive.service.cli.HiveSQLException: java.lang.NoClassDefFoundError: org/apache/hadoop/ipc/CallerContext$Builder

答:
finally able to connect hive through spring application.This type of exception which i have asked we got due to compatibility issue with jars i.e some version are not compatible to used with spring.Below i am attaching my pom.xml for more clarification.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-hadoop-samples-hive</artifactId>

    <name>Spring Hadoop Samples - Hive</name>

    <parent>
        <groupId>org.springframework.samples</groupId>
        <artifactId>spring-hadoop-samples</artifactId>
        <version>1.0.0.BUILD-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.hadoop.version>2.3.0.M1</spring.hadoop.version>
        <hadoop.version>2.7.1</hadoop.version>
        <hive.version>1.2.1</hive.version>
        <!-- <hive.version>2.1.1</hive.version> -->
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop</artifactId>
            <version>${spring.hadoop.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-metastore</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-service</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libfb303</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- runtime Hive deps start -->
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-common</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-shims</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-serde</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-contrib</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- runtime Hive deps end -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>1.8.5</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationSourceDirectory>src/main/config</configurationSourceDirectory>
                    <copyConfigurationDirectory>true</copyConfigurationDirectory>
                    <!-- Extra JVM arguments that will be included in the bin scripts -->
                    <extraJvmArguments>-Xms512m -Xmx1024m -Dhive.version=${hive.version}</extraJvmArguments>
                    <programs>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveApp</mainClass>
                            <name>hiveApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveClientApp</mainClass>
                            <name>hiveClientApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveAppWithApacheLogs</mainClass>
                            <name>hiveAppWithApacheLogs</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <id>package</id>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>config</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <copy todir="target/appassembler/data">
                                    <fileset dir="data"/>
                                </copy>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

After that you may encounter with authentication issue while running the appliation.Please run below command for that.

```<code>hadoop fs -mkdir /tmp
hadoop fs -chmod a+w /tmp
hadoop fs -mkdir -p /user/hive/warehouse
hadoop fs -chmod a+w /user/hive/warehouse
</code>```

If their is no folder structure then it will create and give the read,write permission to that.

Body:
For connecting hive through spring application i have added below dependency in pom.xml.

<dependency>
 <groupId>org.apache.hive</groupId>
 <artifactId>hive-jdbc</artifactId>
 <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.thrift</groupId>
  <artifactId>libfb303</artifactId>
  <version>0.9.3</version>
    <exclusions>
     <exclusion>
    <groupId>org.apache.hive</groupId>
        <artifactId>hive-common</artifactId>
     </exclusion>
    </exclusions>
</dependency>
<dependency>
  <groupId>org.apache.hive</groupId>
  <artifactId>hive-service-rpc</artifactId>
  <version>2.1.1</version>
</dependency>

But still i am facing the below exception :: Caused by:
  java.lang.NoClassDefFoundError:
  org/apache/hive/service/cli/HiveSQLException at
  org.apache.hive.jdbc.HiveConnection.(HiveConnection.java:132) at
  org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107) at
  java.sql.DriverManager.getConnection(DriverManager.java:664) at
  java.sql.DriverManager.getConnection(DriverManager.java:208) at
  org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
  at
  org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
  at
  org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
  at
  org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
  at
  org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:71)
  at
  org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:113)
  at
  org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2836)
  at
  org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2832)
  at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
  at
  org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
  at
  org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
  at
  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
  at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
  ... 97 more Caused by: java.lang.ClassNotFoundException:
  org.apache.hive.service.cli.HiveSQLException at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
  at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
  ... 116 more

Any one please tell me if any jars i am missing or what is the issue.Using  the same url i am able to connect through beeline

 $HIVE_HOME/bin/beeline -u jdbc:hive2://localhost:10000/TEST_DB

I have refer below url but it contains no answer

org.apache.hive.service.cli.HiveSQLException: java.lang.NoClassDefFoundError: org/apache/hadoop/ipc/CallerContext$Builder

Body:
finally able to connect hive through spring application.This type of exception which i have asked we got due to compatibility issue with jars i.e some version are not compatible to used with spring.Below i am attaching my pom.xml for more clarification.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-hadoop-samples-hive</artifactId>

    <name>Spring Hadoop Samples - Hive</name>

    <parent>
        <groupId>org.springframework.samples</groupId>
        <artifactId>spring-hadoop-samples</artifactId>
        <version>1.0.0.BUILD-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.hadoop.version>2.3.0.M1</spring.hadoop.version>
        <hadoop.version>2.7.1</hadoop.version>
        <hive.version>1.2.1</hive.version>
        <!-- <hive.version>2.1.1</hive.version> -->
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop</artifactId>
            <version>${spring.hadoop.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-metastore</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-service</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libfb303</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- runtime Hive deps start -->
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-common</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-shims</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-serde</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-contrib</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- runtime Hive deps end -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>1.8.5</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationSourceDirectory>src/main/config</configurationSourceDirectory>
                    <copyConfigurationDirectory>true</copyConfigurationDirectory>
                    <!-- Extra JVM arguments that will be included in the bin scripts -->
                    <extraJvmArguments>-Xms512m -Xmx1024m -Dhive.version=${hive.version}</extraJvmArguments>
                    <programs>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveApp</mainClass>
                            <name>hiveApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveClientApp</mainClass>
                            <name>hiveClientApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveAppWithApacheLogs</mainClass>
                            <name>hiveAppWithApacheLogs</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <id>package</id>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>config</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <copy todir="target/appassembler/data">
                                    <fileset dir="data"/>
                                </copy>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

After that you may encounter with authentication issue while running the appliation.Please run below command for that.

hadoop fs -mkdir /tmp
hadoop fs -chmod a+w /tmp
hadoop fs -mkdir -p /user/hive/warehouse
hadoop fs -chmod a+w /user/hive/warehouse

If their is no folder structure then it will create and give the read,write permission to that.


问:
Samba Share Not Writable (Linux)
I am currently running a fresh install of CentOS 7 (64-bit). This machine isn't used for anything except for storage via Samba. However, for some strange reason, I can't see to get the share to be writable through windows. With the drive mapped, I can read the file lists and browse (even accessing files), but I cannot write any new files.

The steps that I took was to install samba via yum. I added a system user, bdawson, and then added that same user as a Samba user. I then logged in as that user and make a directory called storage (path being /home/bdawson/Storage).

I then edited my Samba config and added the following:

```<code>[Storage]
valid users = bdawson,@bdawson
path = /home/bdawson/Storage
write list = bdawson,@bdawson
</code>```

/home/bdawson was chown -R'd to be owned by bdawson:bdawson. File permissions are set to 0755 for both /home/bdawson and /home/bdawson/Storage.

At this point, I am not sure what I'm doing wrong that is preventing me from being able to write. This same configuration worked just fine on a different machine, so I'm at a complete loss. (Side note: Samba logs aren't showing any issues and watching the Samba connections via Webmin does show that I am connecting and reading from the share, but attempts to write to it fail saying I need permission.)

答: After a lot of digging, I discovered this was due to a missing SELinux label. This was not an issue with my Ubuntu share, since Ubuntu doesn't use SELinux.</p>

Title: Samba Share Not Writable (Linux)

Body:
I am currently running a fresh install of CentOS 7 (64-bit). This machine isn't used for anything except for storage via Samba. However, for some strange reason, I can't see to get the share to be writable through windows. With the drive mapped, I can read the file lists and browse (even accessing files), but I cannot write any new files.

The steps that I took was to install samba via yum. I added a system user, bdawson, and then added that same user as a Samba user. I then logged in as that user and make a directory called storage (path being /home/bdawson/Storage).

I then edited my Samba config and added the following:

[Storage]
valid users = bdawson,@bdawson
path = /home/bdawson/Storage
write list = bdawson,@bdawson

/home/bdawson was chown -R'd to be owned by bdawson:bdawson. File permissions are set to 0755 for both /home/bdawson and /home/bdawson/Storage.

At this point, I am not sure what I'm doing wrong that is preventing me from being able to write. This same configuration worked just fine on a different machine, so I'm at a complete loss. (Side note: Samba logs aren't showing any issues and watching the Samba connections via Webmin does show that I am connecting and reading from the share, but attempts to write to it fail saying I need permission.)


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答: There is no portable way to do this, but select() might be a good way. See http://c-faq.com/osdep/readavail.html for more possible solutions.</p>

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

OwnerDisplayName: Nathan Stoddard


问:
Silverlight Memory Leaks
We have a rather large silverlight 4 application. We are in the process of finding memory leaks in the application and this has turned into a daunting task.

Things have changed completely with this one, for those of you that have seen the original post!

I realised that ANTS memory profiler wasn't showing me the right stuff. That was because the memory leak was not in the managed code, but in the native code. I did fix some issues with ANTS - it is a good tool for managed code memory leaks.

So I found this blog,

http://blogs.msdn.com/b/slperf/archive/2010/08/19/analyzing-silverlight-memory-usage-part-1-obtaining-measurements.aspx

Which was excellent. I used xPerf and xPerfViewer to view the native heap and see what I suspect is the actual memory leak.

So I can see a stack trace which looks like this,

```<code>CCoreServices::Draw
    CCoreServices::Tick
    CUElement::Render
        CUIElement::Render
        CUIElement::RenderWithTransform
        CUIElement::RenderVisual
        CUIElement::RenderChildren
            {Repeat of the above in a recursive fashion}
</code>```

So in this 'Render' method somewhere it allocates about 520 bytes of memory, and as far as I can tell it doesn't free it.

I can also see a method or class called

```<code>SDBitmapCreate
</code>```

is leaking memory too.

Interesting because it seems like I have found something, but I am not really sure what.

Any other suggestions?

Thanks.

答: If I were in your situation I would try to create a simple test application that demos the leak, just to double-check it is repeatable outside of your actual code.  This proves that it isn't a subtle bug in your code.  Then, I would post the test app to the MS Silverlight forums, which is monitored by MS folks.  If you have an MSDN subscription, or if your company has a support agreement with MS, I would also open up a "ticket" (forget what they actually call them) with MS as well.</p>

Title: Silverlight Memory Leaks

Body:
We have a rather large silverlight 4 application. We are in the process of finding memory leaks in the application and this has turned into a daunting task.

Things have changed completely with this one, for those of you that have seen the original post!

I realised that ANTS memory profiler wasn't showing me the right stuff. That was because the memory leak was not in the managed code, but in the native code. I did fix some issues with ANTS - it is a good tool for managed code memory leaks.

So I found this blog,

http://blogs.msdn.com/b/slperf/archive/2010/08/19/analyzing-silverlight-memory-usage-part-1-obtaining-measurements.aspx

Which was excellent. I used xPerf and xPerfViewer to view the native heap and see what I suspect is the actual memory leak.

So I can see a stack trace which looks like this,

CCoreServices::Draw
    CCoreServices::Tick
    CUElement::Render
        CUIElement::Render
        CUIElement::RenderWithTransform
        CUIElement::RenderVisual
        CUIElement::RenderChildren
            {Repeat of the above in a recursive fashion}

So in this 'Render' method somewhere it allocates about 520 bytes of memory, and as far as I can tell it doesn't free it.

I can also see a method or class called

SDBitmapCreate

is leaking memory too.

Interesting because it seems like I have found something, but I am not really sure what.

Any other suggestions?

Thanks.


问:
when i save that in database, field password is empty in database,

```<code>protected function create(array $data)
 {
     return Customer::create([
        'nama_customer' => $data['nama'],
        'password' =>bcrypt($data['password']),
        'kontak' => $data['kontak'],
        'email' => $data['email'],
      ])
  }
</code>```

I want to make a multi auth laravel, but when i save register data in database, field password is empty in database, can anyone help me to fix it ?

答: It could be any number of things. Maybe your password field is named differently in the database, maybe it has the wrong data type or data length. Check those things.</p>

Body:
protected function create(array $data)
 {
     return Customer::create([
        'nama_customer' => $data['nama'],
        'password' =>bcrypt($data['password']),
        'kontak' => $data['kontak'],
        'email' => $data['email'],
      ])
  }

I want to make a multi auth laravel, but when i save register data in database, field password is empty in database, can anyone help me to fix it ?


问:
arules subset not working in the new version (1.5-2) of arules package
I recently updated by Arules package to version 1.5-2, ever since I am not able to subset item list from Rule set, I get the following error when I try to subset
"Error in structure(seq(length(labels)), names = labels)[i] :
  invalid subscript type 'S4'" here is an example

```<code>library(arules)
data("Groceries")

#generate Rules without second record to create an itemset
rules <- apriori(Groceries[-2],parameter = list(supp = 0.05, conf = 0.2,target = "rules"))

#Create an itemlist with second record
enter code here`basket <- Groceries[2]
rulesMatchLHS <- is.subset(rules@lhs,basket)
suitableRules <- rulesMatchLHS & !(is.subset(rules@rhs,basket))
#output
inspect(rules[suitableRules])
</code>```

Thanks in advance

答:
Your subset vector looks like a sparse matrix, but a dense logical vector is needed:</p>

```<code>suitableRules

7 x 1 sparse Matrix of class "lgCMatrix"
                   {tropical fruit,yogurt,coffee}
{}                                              |
{yogurt}                                        |
{whole milk}                                    .
{rolls/buns}                                    .
{whole milk}                                    .
{other vegetables}                              .
{whole milk}                                    .

as.logical(suitableRules)
[1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE

inspect(rules[as.logical(suitableRules)])
    lhs         rhs          support   confidence lift     count
[1] {}       => {whole milk} 0.2555420 0.2555420  1.000000 2513
[2] {yogurt} => {whole milk} 0.0560301 0.4018964  1.572722  551
</code>```

Body:
I recently updated by Arules package to version 1.5-2, ever since I am not able to subset item list from Rule set, I get the following error when I try to subset
"Error in structure(seq(length(labels)), names = labels)[i] :
  invalid subscript type 'S4'" here is an example

library(arules)
data("Groceries")

#generate Rules without second record to create an itemset
rules <- apriori(Groceries[-2],parameter = list(supp = 0.05, conf = 0.2,target = "rules"))

#Create an itemlist with second record
enter code here`basket <- Groceries[2]
rulesMatchLHS <- is.subset(rules@lhs,basket)
suitableRules <- rulesMatchLHS & !(is.subset(rules@rhs,basket))
#output
inspect(rules[suitableRules])

Thanks in advance

Body:
Your subset vector looks like a sparse matrix, but a dense logical vector is needed:

suitableRules

7 x 1 sparse Matrix of class "lgCMatrix"
                   {tropical fruit,yogurt,coffee}
{}                                              |
{yogurt}                                        |
{whole milk}                                    .
{rolls/buns}                                    .
{whole milk}                                    .
{other vegetables}                              .
{whole milk}                                    .

as.logical(suitableRules)
[1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE

inspect(rules[as.logical(suitableRules)])
    lhs         rhs          support   confidence lift     count
[1] {}       => {whole milk} 0.2555420 0.2555420  1.000000 2513
[2] {yogurt} => {whole milk} 0.0560301 0.4018964  1.572722  551


问:
Convert mm/dd/yyyy to MMMM dd, yyyy in MySQL
I have seen a lot of sources in converting a date to any format except converting it to MMMM dd, yyyy. Is there any way in MySQL that the returned date will be converted to MMMM dd, yyyy format?

Sample Output:

January 1, 2017

答:
It's all available in the MySQL documentation:</p>

```<code>SELECT DATE_FORMAT('2017-07-03 22:00:00', '%M %d %Y');  -- July 03, 2017
</code>```

Body:
It's all available in the MySQL documentation:

SELECT DATE_FORMAT('2017-07-03 22:00:00', '%M %d %Y');  -- July 03, 2017


问:
Differnace between "delete p" and "p->~MyClass()"
```<code>class MyClass
{
    public:
        MyClass()
        {
            std::cout << "MyClass Constructor" << std::endl;
        }

        ~MyClass()
        {
            std::cout << "MyClass Destructor" << std::endl;
        }
};

int main()
{
    MyClass* p = new MyClass();
}
</code>```

What is the difference between
calling p->~MyClass();
OR
delete p;

Both call the destructor.

答:
Using the new operator will:

Allocate a chunk of memory.

Call the constructor for the class, with this pointing at that memory.

delete is just the undoing of what new does, so it will, by default:

Call the destructor with this pointing to its memory block.

Free the memory block.

You can overload these operators to behave differently, of course.

Body:
class MyClass
{
    public:
        MyClass()
        {
            std::cout << "MyClass Constructor" << std::endl;
        }

        ~MyClass()
        {
            std::cout << "MyClass Destructor" << std::endl;
        }
};

int main()
{
    MyClass* p = new MyClass();
}

What is the difference between
calling p->~MyClass();
OR
delete p;

Both call the destructor.


答:
The date_format() function can return the date pretty much however you want.

```<code>date_format(my_date_field, '%M %d, %Y')
</code>```

More info on the function can be found here

Title: Convert mm/dd/yyyy to MMMM dd, yyyy in MySQL

Body:
I have seen a lot of sources in converting a date to any format except converting it to MMMM dd, yyyy. Is there any way in MySQL that the returned date will be converted to MMMM dd, yyyy format?

Sample Output:

January 1, 2017

Body:
The date_format() function can return the date pretty much however you want.

date_format(my_date_field, '%M %d, %Y')

More info on the function can be found here


问:
Gridview error when fetching data from json. how to solve it?
I have a custom gridview in which I'm using : One image view and two text views. In one text view I'm putting data manually and in another text view i want to put data via json.
If in textview2 (json text) data is not there then gridview will give error..
How to do it?
Or
How to hide gridview items if textview2 is empty during loading of json data?</p>

答:
You can hide TextView element via property Visibility.
Like this:</p>

```<code> TextView tv2 = (TextView) getActivity().findViewById(R.id.tv2);
 JSONObject jo = result.getJSONObject(i);
        if (!jo.getString("text2").equals("null")) {
              tv2.setVisibility(View.INVISIBLE);
        }
</code>```

Body:
You can hide TextView element via property Visibility.
Like this:

 TextView tv2 = (TextView) getActivity().findViewById(R.id.tv2);
 JSONObject jo = result.getJSONObject(i);
        if (!jo.getString("text2").equals("null")) {
              tv2.setVisibility(View.INVISIBLE);
        }


问:
PHP big array performance?
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?</p>

```<code>  $pages=array(
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>');
  }
</code>```

答:
Defining an array with 500 items will probably go fast enough. If you're not doing anything interesting with the array other than printing out it's contents, you probably don't have to worry.

If you ever wondering something like this, just measure it.

Title: PHP big array performance?

Body:
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?

  $pages=array(
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

');
  }


问:
How to watch one gulp file that imports other?
My sass structure look like this.

```<code>    - /base
    -- _fonts.scss
    -- _all.scss
    - /components
    -- _all.scss
    -- _header.scss
    -- _footer.scss
    - main.scss
</code>```

Each _all.scss imports all files in the current folder, then the main.scss imports all _all files from each folder.

The problem I am facing is that I actually need to save main.scss in order for gulp to generate the .css file. If i watch all files it will then generate a lot of .css files which I don't need.

gulpfile.js

```<code>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  return gulp.src('./src/stylesheets/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./public/css/'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./src/stylesheets/main.scss', ['sass']);
});
</code>```

How do I make gulp watch all files and generate only one css file in the public folder?

答:
Here's how I do it.

Main.scss

```<code>@import "your/relative/path/of/your/_partial-file1";
@import "your/relative/path/of/your/_partial-file2";

/*Other scss stylings if needed*/
</code>```

In your gulpfile.js, add the sass task

```<code>gulp.task('css', ()=>{

 return gulp.src('src/scss/*.scss') //target all the .css files in the specified directory

   .pipe(sass()) //gulp-sass module to convert scss files into css file

   .pipe(minifyCSS()) //method to minify the final css file

   .pipe(gulp.dest('build/css')); //outputs final css file into the specified directory

   console.log('CSS build');

});

gulp.task('default', [ 'css','your', 'other','tasks' ],()=>{

console.log("All done. Watching files...");

 //watch the files in the specified directory.

 //if any changes are made to the files, the specified task will be executed in the watch method

gulp.watch('src/**/*.scss',['css']);

});
</code>```

Find the full article here: http://todarman.com/gulp-configuration-build-html-css-js/

Hope this helps.

Body:
My sass structure look like this.

    - /base
    -- _fonts.scss
    -- _all.scss
    - /components
    -- _all.scss
    -- _header.scss
    -- _footer.scss
    - main.scss

Each _all.scss imports all files in the current folder, then the main.scss imports all _all files from each folder.

The problem I am facing is that I actually need to save main.scss in order for gulp to generate the .css file. If i watch all files it will then generate a lot of .css files which I don't need.

gulpfile.js

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  return gulp.src('./src/stylesheets/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./public/css/'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./src/stylesheets/main.scss', ['sass']);
});

How do I make gulp watch all files and generate only one css file in the public folder?

Body:
Here's how I do it.

Main.scss

@import "your/relative/path/of/your/_partial-file1";
@import "your/relative/path/of/your/_partial-file2";

/*Other scss stylings if needed*/

In your gulpfile.js, add the sass task

gulp.task('css', ()=>{

 return gulp.src('src/scss/*.scss') //target all the .css files in the specified directory

   .pipe(sass()) //gulp-sass module to convert scss files into css file

   .pipe(minifyCSS()) //method to minify the final css file

   .pipe(gulp.dest('build/css')); //outputs final css file into the specified directory

   console.log('CSS build');

});

gulp.task('default', [ 'css','your', 'other','tasks' ],()=>{

console.log("All done. Watching files...");

 //watch the files in the specified directory.

 //if any changes are made to the files, the specified task will be executed in the watch method

gulp.watch('src/**/*.scss',['css']);

});

Find the full article here: http://todarman.com/gulp-configuration-build-html-css-js/

Hope this helps.


问:
Forloop Error on Powershell script
I'm having some problem with this sentences. The powershell script generated having error due to this for loop.

```<code>for ($i = 5; $i <=110 -le ; $i+=15)
</code>```

May I know the solutions for this loop please?

Thanks.

The output should be
5
20
35
50
65
80
95
110

答:
```<code>for ($i = 5; $i -le 110; $i += 15) {
  Write-Host $i
}
</code>```

Your syntax is mostly right, but PowerShell doesn't use the '<=' style operators at all. Use '-le' in it's place and you'll be good to go.

Read more about comparison operators here.

Title: Forloop Error on Powershell script

Body:
I'm having some problem with this sentences. The powershell script generated having error due to this for loop.

for ($i = 5; $i <=110 -le ; $i+=15)

May I know the solutions for this loop please?

Thanks.

The output should be
5
20
35
50
65
80
95
110

Body:
for ($i = 5; $i -le 110; $i += 15) {
  Write-Host $i
}

Your syntax is mostly right, but PowerShell doesn't use the '<=' style operators at all. Use '-le' in it's place and you'll be good to go.

Read more about comparison operators here.


问:
How to cut tube in half in SceneKit?
I have a SCNTube and wanted to see if there is a way to cut the tube in half?

答:
You'll have to use custom geometry, or your favorite 3D editing tool (Maya, SketchUp, Blender, Cheetah3D).

You could in theory extract and cut up the geometry created by the SCNTube, but that format is undocumented (therefore subject to change), and would be a lot of work.

Title: How to cut tube in half in SceneKit?


问:
How to center my buttons vertically?
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html>
    <head>
    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">
    </head>

    <body>

    <h3>make your choice.</h3>

    <div id="light"><button>Light</button></div>
    <div id="dark"><button>Dark</button></div>

    </body>
    </html></code>```

This is a screencap of what this thing is doing:

答:
Hope this would help:

body{
    background-color:black;
}
#light{
    position: absolute;
    top: 45%;
    left: 50%;
}
#dark{
    position: absolute;
    top: 55%;
    left: 50%;
}
h3{
    color:white;
    font-family:Courier New;
    font-size:24px;
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">
  </head>

  <body>

    <h3>make your choice.</h3>

    <div id="light"><button>Light</button></div>
    <div id="dark"><button>Dark</button></div>

  </body>
</html></code>```

Title: How to center my buttons vertically?

Body:
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }

    <!DOCTYPE html>

    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">

make your choice.

<button>Light</button>

<button>Dark</button>

This is a screencap of what this thing is doing:

Body:
Hope this would help:

body{
    background-color:black;
}
#light{
    position: absolute;
    top: 45%;
    left: 50%;
}
#dark{
    position: absolute;
    top: 55%;
    left: 50%;
}
h3{
    color:white;
    font-family:Courier New;
    font-size:24px;
    text-align: center;
}

<!DOCTYPE html>
<html>
  <head>
    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">
  </head>

  <body>

    <h3>make your choice.</h3>

    <div id="light"><button>Light</button></div>
    <div id="dark"><button>Dark</button></div>

  </body>
</html>