问:
Pass longitude and latitude from CLLocationManager to URL?
i'm trying to pass my latitude and longitude to my url params but is returning Nil, but when i print within the delegate it returns the longitude and latitude and i can't seem to find the issue, i've tried many different ways and nothing seems to work

this are the variable where i store my latitude and longitude

var lat: Double!
 var long: Double!

this is my delegate

```<code>func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    currentLocation = manager.location!.coordinate

    let locValue:CLLocationCoordinate2D = currentLocation!

    self.long = locValue.longitude
    self.lat = locValue.latitude

    print(lat)
    print(long)

}
</code>```

and here pass them to variables i'm using in my URL parameters but they return nil and i don't understand why

```<code>let userLat = String(describing: lat)
let userLong = String(describing: long)
</code>```

Thank You

答:
I think the Joseph K's answer is not correct. It rounds off the values of the latitude and longitude. It will be something like the code below.

```<code>let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 35.6535425)!, longitude: CLLocationDegrees(exactly: 139.7047917)!)

let latitude = coordinate.latitude // 35.6535425
let longitude = coordinate.longitude // 139.7047917

let latitudeString = NSString(format: "%f", latitude) as String // "35.653543"
let longitudeString = NSString(format: "%f", longitude) as String // "139.704792"
</code>```

So the correct and simpler code is:

Swift 3

```<code>    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let coordinate = locations.last?.coordinate else { return }

        let latitude = "\(coordinate.latitude)"
        let longitude = "\(coordinate.longitude)"

        // Do whatever you want to make a URL.
    }
</code>```

Body:
i'm trying to pass my latitude and longitude to my url params but is returning Nil, but when i print within the delegate it returns the longitude and latitude and i can't seem to find the issue, i've tried many different ways and nothing seems to work

this are the variable where i store my latitude and longitude

var lat: Double!
 var long: Double!

this is my delegate

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    currentLocation = manager.location!.coordinate

    let locValue:CLLocationCoordinate2D = currentLocation!

    self.long = locValue.longitude
    self.lat = locValue.latitude

    print(lat)
    print(long)

}

and here pass them to variables i'm using in my URL parameters but they return nil and i don't understand why

let userLat = String(describing: lat)
let userLong = String(describing: long)

Thank You

Body:
I think the Joseph K's answer is not correct. It rounds off the values of the latitude and longitude. It will be something like the code below.

let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 35.6535425)!, longitude: CLLocationDegrees(exactly: 139.7047917)!)

let latitude = coordinate.latitude // 35.6535425
let longitude = coordinate.longitude // 139.7047917

let latitudeString = NSString(format: "%f", latitude) as String // "35.653543"
let longitudeString = NSString(format: "%f", longitude) as String // "139.704792"

So the correct and simpler code is:

Swift 3

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let coordinate = locations.last?.coordinate else { return }

        let latitude = "\(coordinate.latitude)"
        let longitude = "\(coordinate.longitude)"

        // Do whatever you want to make a URL.
    }


来源: stackexchange

问:
Three.js reverse raycasting
I'm setting up a world map on a curved plane that the user can rotate and highlight countries. When a country is clicked, I determine what exactly was clicked and then show a tooltip with some information about the selected country, like on the screenshot below:

The map itself is generated in three, but the tooltip is a regular old div. The thing is, I'd like the tooltip to stay glued to that particular point of the texture, even if the plane is rotated. The original positioning of the tooltip is based on the information from the raycaster. As such, I'd want the app to return the current position of that precise point, relative to the container (or window) - based on uv coordinate for instance. How can I achieve that?

答:
Basing on the link provided by @prisoner849, I've implemented the following solution:

a) on mouseup event I set a new tooltip 3D origin point (only if there was no significant delta in mouse position, to discern between clicking and dragging the camera)

b) every frame, the following function is fired, which converts the 3D coords to 2D and calculates the position of the tooltip:

```<code>function setTooltipOrigin( camera, renderer, tooltip, lastClickPoint ) {
  var canvas = renderer.domElement,
  point = new THREE.Vector3();

  point.x = lastClickPoint.x,
  point.y = lastClickPoint.y,
  point.z = lastClickPoint.z,

  point.project( camera );

  point.x = Math.round(( 0.5 + point.x / 2 ) * ( canvas.width / window.devicePixelRatio ));
  point.y = Math.round(( 0.5 - point.y / 2 ) * ( canvas.height / window.devicePixelRatio ));

  point.x -= 14; //small adjustment to the position, so the line points to the click point
  point.y -= (tooltip.scrollHeight * 0.7); //same for y

  tooltip.style.transform = 'translate(' + point.x + 'px, ' + point.y + 'px)';
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Three.js reverse raycasting

Body:
Basing on the link provided by @prisoner849, I've implemented the following solution:

a) on mouseup event I set a new tooltip 3D origin point (only if there was no significant delta in mouse position, to discern between clicking and dragging the camera)

b) every frame, the following function is fired, which converts the 3D coords to 2D and calculates the position of the tooltip:

function setTooltipOrigin( camera, renderer, tooltip, lastClickPoint ) {
  var canvas = renderer.domElement,
  point = new THREE.Vector3();

  point.x = lastClickPoint.x,
  point.y = lastClickPoint.y,
  point.z = lastClickPoint.z,

  point.project( camera );

  point.x = Math.round(( 0.5 + point.x / 2 ) * ( canvas.width / window.devicePixelRatio ));
  point.y = Math.round(( 0.5 - point.y / 2 ) * ( canvas.height / window.devicePixelRatio ));

  point.x -= 14; //small adjustment to the position, so the line points to the click point
  point.y -= (tooltip.scrollHeight * 0.7); //same for y

  tooltip.style.transform = 'translate(' + point.x + 'px, ' + point.y + 'px)';
}


问:
Golang: Selecting DB on a RedisPool in Redigo
using redigo, I create a pool, something like so:

```<code>&redis.Pool{
    MaxIdle:   80,
    MaxActive: 12000, // max number of connections
    Dial: func() (redis.Conn, error) {
        c, err := redis.Dial("tcp", host+":"+port)
        if err != nil {
            panic(err.Error())
        }
        return c, err
    }
</code>```

the problem I have is that for each time I get a new connection, I need to set the db, as I use different db's of redis since I host a number of sites on the VPS.

So, something like this:

```<code>conn := pool.Get()
defer conn.Close()

conn.Do("SELECT", dbNumber)  //this is the call I want to avoid
</code>```

Having to select the db each time I work with redis seems redundant and also poses a problem since I use it for sessions i.e. having code that is not mine working with my redis connection from my pool makes it "impossible" to set the correct db for it.

What I would like to do is to set the dbno for the pool so that whenever somebody asks for a new connection from the pool, it comes with the correct db already set i.e. not setting it explicitly each time.

How did you solve this in your applications?

Thanks.

答:
You can use redis.DialOption: redis.DialDatabase, redis.DialPassword

```<code>conn, err := redis.Dial("tcp", "127.0.0.1:6379", redis.DialDatabase(1))
if err != nil {
    panic(err)
}
defer conn.Close()
</code>```

Body:
using redigo, I create a pool, something like so:

&redis.Pool{
    MaxIdle:   80,
    MaxActive: 12000, // max number of connections
    Dial: func() (redis.Conn, error) {
        c, err := redis.Dial("tcp", host+":"+port)
        if err != nil {
            panic(err.Error())
        }
        return c, err
    }

the problem I have is that for each time I get a new connection, I need to set the db, as I use different db's of redis since I host a number of sites on the VPS.

So, something like this:

conn := pool.Get()
defer conn.Close()

conn.Do("SELECT", dbNumber)  //this is the call I want to avoid

Having to select the db each time I work with redis seems redundant and also poses a problem since I use it for sessions i.e. having code that is not mine working with my redis connection from my pool makes it "impossible" to set the correct db for it.

What I would like to do is to set the dbno for the pool so that whenever somebody asks for a new connection from the pool, it comes with the correct db already set i.e. not setting it explicitly each time.

How did you solve this in your applications?

Thanks.

Body:
You can use redis.DialOption: redis.DialDatabase, redis.DialPassword

conn, err := redis.Dial("tcp", "127.0.0.1:6379", redis.DialDatabase(1))
if err != nil {
    panic(err)
}
defer conn.Close()


问:
Code migration from Swift 2.x to Swift 4
We have big enough project which is built up with Swift 2.x and now Apple has just released Swift 4 so to move forward for latest version of Swift which path we can choose...

Do we need to migrate our code to Swift 3 first? Or we can directly migrate our code to Swift 4 using Xcode 9?

答:
Yes, you first need to migrate your code from Swift 2 to Swift 3, using Xcode 8.

Xcode 8 is the last version to support Swift 2.

Starting with Xcode 9, the supported Swift versions are 3.2 and 4


问:
Angular 4: Infinite scroll not working
I have tried using ngx-infinite-scroll (https://www.npmjs.com/package/angular2-infinite-scroll) and also some other directives but none seem to work.

package.json

```<code>"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.2",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/platform-server": "^4.0.2",
"@angular/router": "^4.0.0",
"absurd": "^0.3.8",
"angular2-masonry": "^0.4.0",
"animate.css": "^3.5.2",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"metismenu": "^2.7.0",
"ng2-bs3-modal": "^0.10.4",
"ngx-infinite-scroll": "^0.5.1",
"rxjs": "^5.1.0"
}
</code>```

user.component.html

```<code><div class="row" infiniteScroll [infiniteScrollDistance]="0"
  [infiniteScrollThrottle]="300" (scrolled)="loadMore()">
   <div class="col-md-3 col-sm-4" *ngFor="let user of userList">
     <span>{{user.name}} ({{user.email}})</span>
   </div>
</div>
</code>```

user.module.ts

The import is done

```<code>import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    InfiniteScrollModule
  ],
  declarations: [UserComponent],
  providers: [],
  exports: [],
})
export class UserModule { }
</code>```

user.component.ts

```<code>export class UserComponent {

  constructor() {}

  loadMore() {
    console.log('method begins');
  }
}
</code>```

Tried using host listener as well but the scroll event just doesn't seem to occur.
Has it got anything to do with the class i'm using on which the infinite scroll is applied?

答:
You have to set height of your container div</p>

```<code><div class="row" style="height: 90%"
  infiniteScroll [infiniteScrollDistance]="0"
  [infiniteScrollThrottle]="300" (scrolled)="loadMore()">
   <div class="col-md-3 col-sm-4" *ngFor="let user of userList">
     <span>{{user.name}} ({{user.email}})</span>
   </div>
</div>
</code>```

Title: Angular 4: Infinite scroll not working

Body:
I have tried using ngx-infinite-scroll (https://www.npmjs.com/package/angular2-infinite-scroll) and also some other directives but none seem to work.

package.json

"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.2",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/platform-server": "^4.0.2",
"@angular/router": "^4.0.0",
"absurd": "^0.3.8",
"angular2-masonry": "^0.4.0",
"animate.css": "^3.5.2",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"metismenu": "^2.7.0",
"ng2-bs3-modal": "^0.10.4",
"ngx-infinite-scroll": "^0.5.1",
"rxjs": "^5.1.0"
}

user.component.html

     {{user.name}} ({{user.email}})

user.module.ts

The import is done

import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    InfiniteScrollModule
  ],
  declarations: [UserComponent],
  providers: [],
  exports: [],
})
export class UserModule { }

user.component.ts

export class UserComponent {

  constructor() {}

  loadMore() {
    console.log('method begins');
  }
}

Tried using host listener as well but the scroll event just doesn't seem to occur.
Has it got anything to do with the class i'm using on which the infinite scroll is applied?

Body:
You have to set height of your container div

<div class="row" style="height: 90%"
  infiniteScroll [infiniteScrollDistance]="0"
  [infiniteScrollThrottle]="300" (scrolled)="loadMore()">
   <div class="col-md-3 col-sm-4" *ngFor="let user of userList">
     <span>{{user.name}} ({{user.email}})</span>
   </div>
</div>


问:
Is is possible to calibrate fish eye camera using standard openCV?
I try to calibrate camera with ultra wide angle lens > 180 degrees. I use OpenCV 3.2 and camera calibration code from opencv/samples/cpp/tutorial_code/calib3d/camera_calibration, as a result I get image similar to this one from this post. I found numerous movies on youtube.com on which people show how they calibrate fisheye cameras, for example this video.

I know that calibration of ultra wide lenses cameras could be tricky. I also found that there are another then standard model for fisheye camera calibrations in openCV contrib

Is it possible to use camera calibration model from standard OpenCV to calibrate such a wide angle camera or should I use another model e.g., from openCV contrib?

答:
I was working on the same problem a few weeks ago, what I found was that the standard model did not work with my fisheye images ( >180 FOV). Having said that, I did find a pull request on Github which addresses just this issue - https://github.com/opencv/opencv/pull/6801.

I eventually gave up on the standard model and just used the Omnidirectional model - http://docs.opencv.org/trunk/dd/d12/tutorial_omnidir_calib_main.html which worked like a charm.

Just as a side note, whilst I was researching the topic of distortion correction I came across a common misconception that fisheye images resulting from fisheye lenses are "distorted", indeed they might be distorted but the resulting images are simply a projection. A fisheye like other projections is one of many ways of mapping a 3D world onto a 2D plane. It doesn't help that majority of the related literature refer to it as "distortion". Fisheye lenses are deliberately designed to produce images with bent lines, when these lines would have been straight with standard (i.e. rectilinear) lenses. The word "distortion" is reserved solely for geometric aberrations that negatively affect standard (i.e. rectilinear) lenses.

In my case, even though I was looking into distortion correction I didn't end up correcting for any distortion, I just simply did a fisheye to perspective projection - you can find more on this on here http://paulbourke.net/dome/fish2/

Also, in regards to capturing checkerboard images follow these recommendations - How to verify the correctness of calibration of a webcam?


问:
How can I add a class to select2 selectbox?
I want to add the class pink to my select2 selectbox. It works with the option but not with the box:

$("select").select2({
  templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>```

The result I need:

答:
if you want the background-color of all options to be pink, you need to remove the standard color from the select2.css file . you can do that by using

.select2-container--default .select2-selection--single { background:none}

EDIT : JQ code explanation

store the original classes of the .select2-container

add class pink to the .select2-container

in the on change function , ' bring ' also the previous stored classes ( changeMeClass )

get the selected options class in optClass variable

find the select2-container corresponding to the selected option

remove all classes from the container

using a setTimeout function, add classes to the container ( original classes  + the selected option class )

let me know if this what you were looking for

see snippet below

$("select").select2({
  templateResult: function(data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }

    return data.text;
  }
});
var changeMeClass = $(".pink + .select2-container").attr("class")
$(".pink + .select2-container").addClass("pink")

$(".pink").on("change changeMeClass", function() {
  var optClass = $(this).children("option:selected").attr("class"),
    changeMe = $(this).next(".select2-container")

  $(changeMe).removeClass()

  setTimeout(function() {
    $(changeMe).attr("class", changeMeClass + " " + optClass)
  }, 10);

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }
.select2-container--default .select2-selection--single { background:none!important}</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>```

Body:
I want to add the class pink to my select2 selectbox. It works with the option but not with the box:

$("select").select2({
  templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});

.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>

The result I need:

Body:
if you want the background-color of all options to be pink, you need to remove the standard color from the select2.css file . you can do that by using

.select2-container--default .select2-selection--single { background:none}

EDIT : JQ code explanation

store the original classes of the .select2-container

add class pink to the .select2-container

in the on change function , ' bring ' also the previous stored classes ( changeMeClass )

get the selected options class in optClass variable

find the select2-container corresponding to the selected option

remove all classes from the container

using a setTimeout function, add classes to the container ( original classes  + the selected option class )

let me know if this what you were looking for

see snippet below

$("select").select2({
  templateResult: function(data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }

    return data.text;
  }
});
var changeMeClass = $(".pink + .select2-container").attr("class")
$(".pink + .select2-container").addClass("pink")

$(".pink").on("change changeMeClass", function() {
  var optClass = $(this).children("option:selected").attr("class"),
    changeMe = $(this).next(".select2-container")

  $(changeMe).removeClass()

  setTimeout(function() {
    $(changeMe).attr("class", changeMeClass + " " + optClass)
  }, 10);

})

.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }
.select2-container--default .select2-selection--single { background:none!important}

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.js"></script>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>


问:
VS2015 compile errors with Win API GetIscsiSessionList of Iscsidsc.h
I want to user a Windows API called GetIscsiSessionList to get the information of session list.

I came across with a compile problem, VS2015 complains as follows:

VS complians of GetIscsiSessionList:

VS complians in header file Iscsidsc.h:

Iscsidsc.h is in C:\Program Files (x86)\Windows Kits\8.1\Include\um
. Since Iscsidsc.h is a Windows provided file, I don't understand why VS compiler will complain.

答:
The order of include header files should be as follows:

iscsierr.h should be in front of iscsidsc.h


问:
Django rest framework: how to turn off/on pagination in ModelViewSet
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

```<code>class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"
</code>```

Thanks.

答:
if you just want to turn on or off pagination by client dynamically,you can custom Pagination class as:

```<code>class Pagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_page_size(self, request):
        if self.page_size_query_param:
            page_size = min(int(request.query_params.get(self.page_size_query_param, self.page_size)),
                        self.max_page_size)
            if page_size > 0:
                return page_size
            elif page_size == 0:
                return None
            else:
                pass
        return self.page_size
</code>```

use this class as your pagination_class and you can turn off pagination by request url "http://www.example.com/some_object/?page_size=0", ?page_size=0 will disable pagination.
if you just want disable pagination when request format is CVS,you can try what danilke said.

Body:
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"

Thanks.

Body:
if you just want to turn on or off pagination by client dynamically,you can custom Pagination class as:

class Pagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_page_size(self, request):
        if self.page_size_query_param:
            page_size = min(int(request.query_params.get(self.page_size_query_param, self.page_size)),
                        self.max_page_size)
            if page_size > 0:
                return page_size
            elif page_size == 0:
                return None
            else:
                pass
        return self.page_size

use this class as your pagination_class and you can turn off pagination by request url "http://www.example.com/some_object/?page_size=0", ?page_size=0 will disable pagination.
if you just want disable pagination when request format is CVS,you can try what danilke said.


问:
Scale tiny low-resolution app to larger screen size
I am creating a retro arcade game in Java. The screen resolution for the game is 304 x 256, which I want to keep to preserve the retro characteristics of the game (visuals, animations, font blockiness, etc.).

But when I render this on a large desktop display, it is too small, as one would expect.

I'd like to be able to scale the window up say by a constant factor, without having to code the various paint(Graphics) methods to be knowledgeable about the fact that there's a scale-up. That is, I'd like the rendering code believe that the screen is 304 x 256. I also don't want to have to change my desktop resolution or go into full screen exclusive mode. Just want a big window with scaled up pixels, essentially.

I'd be looking for something along the following lines:

```<code>scale(myJFrame, 4);
</code>```

and have all the contents automatically scale up.

UPDATE: Regarding input, my game happens to use keyboard input, so I don't myself need the inverse transform that trashgod describes. Still I can imagine that others would need that, so I think it's an appropriate suggestion.

答:
Thanks to trashgod for pointing me in the right direction with his two answers. I was able to combine elements of both answers to arrive at something that works for what I need to do.

So first, my goal was to scale up an entire UI rather than scaling up a single icon or other simple component. By "an entire UI" I specifically mean a JPanel containing multiple custom child components laid out using a BorderLayout. There are no JButtons or any other interactive Swing components, and no mouse input (it's all keyboard-based input), so really I just need to scale a 304 x 256 JPanel up by a factor of 3 or 4.

Here's what I did:

```<code>package bb.view;

import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import static bb.BBConfig.SCREEN_WIDTH_PX;   // 304
import static bb.BBConfig.SCREEN_HEIGHT_PX;  // 256

public class Resizer extends JPanel {
    private static final int K = 3;
    private static final Dimension PREF_SIZE =
        new Dimension(K * SCREEN_WIDTH_PX, K * SCREEN_HEIGHT_PX);
    private static final AffineTransform SCALE_XFORM =
        AffineTransform.getScaleInstance(K, K);

    public Resizer(JComponent component) {
        setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        add(component);
    }

    @Override
    public Dimension getPreferredSize() {
        return PREF_SIZE;
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setTransform(SCALE_XFORM);
        super.paint(g2);
    }
}
</code>```

Some important elements of the solution:

Using a FlowLayout here shrinkwraps the child component, which is what I want. (Thanks trashgod for that.) That is, I don't want the child to expand to fill the Resizer preferred size, because that wrecks the child component's layout. Specifically it was creating this huge gap between the child component's CENTER and SOUTH regions.

I configured the FlowLayout with left alignment and hgap, vgap = 0. That way my scale transform would have the scaled up version anchored in the upper left corner too.

I used an AffineTransform to accomplish the scaling. (Again thanks trashgod.)

I used paint() instead of paintComponent() because the Resizer is simply a wrapper. I don't want to paint a border. I basically want to intercept the paint() call, inserting the scale transform and then letting the JPanel.paint() do whatever it would normally do.

I didn't end up needing to render anything in a separate BufferedImage.

The end result is that the UI is large, but the all the code other than this Resizer thinks the UI is 304 x 256.

Body:
I am creating a retro arcade game in Java. The screen resolution for the game is 304 x 256, which I want to keep to preserve the retro characteristics of the game (visuals, animations, font blockiness, etc.).

But when I render this on a large desktop display, it is too small, as one would expect.

I'd like to be able to scale the window up say by a constant factor, without having to code the various paint(Graphics) methods to be knowledgeable about the fact that there's a scale-up. That is, I'd like the rendering code believe that the screen is 304 x 256. I also don't want to have to change my desktop resolution or go into full screen exclusive mode. Just want a big window with scaled up pixels, essentially.

I'd be looking for something along the following lines:

scale(myJFrame, 4);

and have all the contents automatically scale up.

UPDATE: Regarding input, my game happens to use keyboard input, so I don't myself need the inverse transform that trashgod describes. Still I can imagine that others would need that, so I think it's an appropriate suggestion.

Body:
Thanks to trashgod for pointing me in the right direction with his two answers. I was able to combine elements of both answers to arrive at something that works for what I need to do.

So first, my goal was to scale up an entire UI rather than scaling up a single icon or other simple component. By "an entire UI" I specifically mean a JPanel containing multiple custom child components laid out using a BorderLayout. There are no JButtons or any other interactive Swing components, and no mouse input (it's all keyboard-based input), so really I just need to scale a 304 x 256 JPanel up by a factor of 3 or 4.

Here's what I did:

package bb.view;

import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import static bb.BBConfig.SCREEN_WIDTH_PX;   // 304
import static bb.BBConfig.SCREEN_HEIGHT_PX;  // 256

public class Resizer extends JPanel {
    private static final int K = 3;
    private static final Dimension PREF_SIZE =
        new Dimension(K * SCREEN_WIDTH_PX, K * SCREEN_HEIGHT_PX);
    private static final AffineTransform SCALE_XFORM =
        AffineTransform.getScaleInstance(K, K);

    public Resizer(JComponent component) {
        setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        add(component);
    }

    @Override
    public Dimension getPreferredSize() {
        return PREF_SIZE;
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setTransform(SCALE_XFORM);
        super.paint(g2);
    }
}

Some important elements of the solution:

Using a FlowLayout here shrinkwraps the child component, which is what I want. (Thanks trashgod for that.) That is, I don't want the child to expand to fill the Resizer preferred size, because that wrecks the child component's layout. Specifically it was creating this huge gap between the child component's CENTER and SOUTH regions.

I configured the FlowLayout with left alignment and hgap, vgap = 0. That way my scale transform would have the scaled up version anchored in the upper left corner too.

I used an AffineTransform to accomplish the scaling. (Again thanks trashgod.)

I used paint() instead of paintComponent() because the Resizer is simply a wrapper. I don't want to paint a border. I basically want to intercept the paint() call, inserting the scale transform and then letting the JPanel.paint() do whatever it would normally do.

I didn't end up needing to render anything in a separate BufferedImage.

The end result is that the UI is large, but the all the code other than this Resizer thinks the UI is 304 x 256.


问:
A suitable PC for Visual Studio 2010 programming
I'm planning on buying a new PC for programming under Visual Studio 2010. My main other usages are:

Programming under Microsoft Visual Studio.

Running VMWare Virtual Machines.

Probably multi-monitor (if my budget lets me buy an extra one)

Here are my questions:

Do I need to purchase a high performance display adapter considering my usage described above? or a medium-range one will suffice? In general, I'd like to know how much a display adapter could affect my usages?

Which CPU could perform better? Core i7, Core 2 Quad, AMD?  I have a limited budget but I really need a good performance and buying a good CPU/MB/RAM is my first priority.

答: If you can afford it, go for a solid state drive.</p>

ContentLicense: CC BY-SA 2.5


问:
Which HTTP status codes should we consider for dead links
We are executing below curl call from PHP.

```<code>$url = $fullurl;

if (isset($url)) {
    $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);

$check_url_status =  $headers['http_code'];
if ($check_url_status == '200')
    $ress = "Link Works";
else
    $ress =  "Broken Link";

}
</code>```

What other HTTP status codes should we consider to check if the URL is not a broken /dead link.

答:
Remember the 5 HTTP Status code classes : 1xx Continue (protocol switching), 2xx OK, 3xx Redirect, 4xx client error, 5xx server error.

If your Curl client follow the redirections (3xx), I think you can just test that status code <= 299. All other status code will make a "broken link".

Depending on how deep is your test, you can also think of theses cases :

401 Unauthorized/ 403 Forbidden : the ressource need authentification. It does not mean the link is broken, but that authorized client may see it, and other will not.

204 No Content : the ressource is accessible but does not return any content. Some analytics ressources returns 204. But the visual result will be a broken image or a link to an empty page.

If your goal is to change the display of a broken link you can use Javascript to manage it client-side, but it can be limited to your domain. See this question

ContentLicense: CC BY-SA 4.0

Body:
We are executing below curl call from PHP.

$url = $fullurl;

if (isset($url)) {
    $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);

$check_url_status =  $headers['http_code'];
if ($check_url_status == '200')
    $ress = "Link Works";
else
    $ress =  "Broken Link";

}

What other HTTP status codes should we consider to check if the URL is not a broken /dead link.


问:
How to handle inconsistence state using Spring Batch?
in my spring batch application, CustomItemWriter has to update value in two separate tables(DynamoDB). If one table update is successful and some exception occur in updating the second table then the update from the first table should also be rollbacked(that either both update should be successful or none).

I am using following spring batch configuration

```<code><bean id="jobRepository"
    class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager" />
    </bean>

    <bean id="transactionManager"
    class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

    <bean id="jobLauncher"
    class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
    </bean>
</code>```

How can I achieve this. Is there any support provided by spring batch. Does we should use something else other then MapJobRepositoryFactoryBean?

答:
All the operations in DynamoDB are atomic. So, multiple operations can't be clubbed together to manage in a transaction. DynamoDB doesn't provide this feature natively like RDBMS.

However, AWS has a wrapper library for this.

Other alternative solution would be to use DynamoDB stream to update the second table.

1) Create a DynamoDB stream on table 1
2) Once the item is updated successfully, it produces a stream
3) You can consume the stream record to update the table 2

Dynamodb stream example

Body:
in my spring batch application, CustomItemWriter has to update value in two separate tables(DynamoDB). If one table update is successful and some exception occur in updating the second table then the update from the first table should also be rollbacked(that either both update should be successful or none).

I am using following spring batch configuration

<bean id="jobRepository"
    class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager" />
    </bean>

    <bean id="transactionManager"
    class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

    <bean id="jobLauncher"
    class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
    </bean>

How can I achieve this. Is there any support provided by spring batch. Does we should use something else other then MapJobRepositoryFactoryBean?


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答:
Computers use pseudorandom number generators. Essentially, they work by start with a seed number and iterating it through an algorithm each time a new pseudorandom number is required.

The process is of course entirely deterministic, so a given seed will generate exactly the same sequence of numbers every time it is used, but the numbers generated form a statistically uniform distribution (approximately), and this is fine, since in most scenarios all you need is stochastic randomness.

The usual practice is to use the current system time as a seed, though if more security is required, "entropy" may be gathered from a physical source such as disk latency in order to generate a seed that is more difficult to predict. In this case, you'd also want to use a cryptographically strong random number generator such as this.

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?


问:
How to debug Liferay portlet using IntelliJ idea?
I deploy my application using Maven on Liferay 7 (on Tomcat 8). But I need to debug it. How to configure my debug? Because, when I start maven with debug mode, it builds and stops. I have no ideas how to deal with it</p>

答:
Quick generic answer (someone with actual IntelliJ experience can probably give more details):

You start tomcat, that has Liferay deployed. Follow the advice you have for "how to debug tomcat applications". The caveat is that you might need to point IntelliJ to the source files for some (all) of the modules in Liferay - which is a huge task (being composed out of 500 modules. For eclipse I'm aware of a fix, for IntelliJ I'm not aware. I'm pretty sure such a beast exists though.

It will be easier (e.g. quick) if you only need your own modules' source.


问:
Is possible deploy c++ web server on OpenShift3?
I am trying to deploy a c++ Http web server on OepnShift3 then I referred this.

The problem is:

Shall I put the source code on OpenShift or compile it first then put the executable file on OpenShift?

Is possible to access the OpenShift3 server via Xshell or Ftp?

Any way to get the OepnShift2 account?

答:
It is no longer possible to get accounts on OpenShift 2.

For OpenShift 3, if you wanted to use a custom HTTP server you would need to be able to build a Docker image which includes it and any other files you need. If you can get the Docker image built, then you can deploy it to OpenShift 3.

Although you can get an interactive terminal in the container which runs your application, it doesn't work like traditional web hosting. That is, it isn't a shell access account where you would upload files using FTP or some other means.

Can you explain more about what it is you want to host? Depending on what you are doing there may be builder images already supported by OpenShift which can pull down files from a Git repository and build an image for you.

If OpenShift is new to you, I would suggest you try out:

https://learn.openshift.com

so you understand some of what it can do and how you interact with it.

Also grab down the free eBook and read it:

https://www.openshift.com/promotions/for-developers.html


问:
Oracle: How to find date of last Friday of the month
Is there any way, we can write a query in sql or pl/sql to find date of last friday of current month ?
Thanks in advance !!!</p>

答:
You can use LAST_DAY( SYSDATE ) to get the last day of the month. If you subtract 7 days from that then you can use the NEXT_DAY() function to find the last Friday of the month:

```<code>SELECT NEXT_DAY(
         LAST_DAY( SYSDATE ) - INTERVAL '7' DAY,
         'FRIDAY'
       )
FROM   DUAL;
</code>```

Wrap it in TRUNC() if you want to truncate the date to midnight of that day.

Body:
You can use LAST_DAY( SYSDATE ) to get the last day of the month. If you subtract 7 days from that then you can use the NEXT_DAY() function to find the last Friday of the month:

SELECT NEXT_DAY(
         LAST_DAY( SYSDATE ) - INTERVAL '7' DAY,
         'FRIDAY'
       )
FROM   DUAL;

Wrap it in TRUNC() if you want to truncate the date to midnight of that day.


问:
IIS Rewrite Rule - Redirect from one domain binding to another domain binding
I have multiple bindings on my IIS site and I want to catch all requests to

any of the following - domainA.co.uk, www.domainA.co.uk, domainA.com, www.domainA.com

and redirect to a page on one of the other bindings on the site

www.domainB.com/my-folder/

Is this possible with URL Rewrite?

答:
It is possible with url rewrite, you need to use this rule:

```<code><rule name="all domains to www.domainB.com/my-folder" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^domainA.co.uk$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.domainA.co.uk$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^domainA.com$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.domainA.com$" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="http://www.domainB.com/my-folder/{R:1}" />
</rule>
</code>```

It will redirect urls:

domainA.co.uk to www.domainB.com/my-folder/

www.domainA.co.uk to www.domainB.com/my-folder/

domainA.com to www.domainB.com/my-folder/

www.domainA.com to  www.domainB.com/my-folder/

www.domainA.com/something to  www.domainB.com/my-folder/something (in case if you dont want that, just remove {R:1} form rule)

Body:
It is possible with url rewrite, you need to use this rule:

<rule name="all domains to www.domainB.com/my-folder" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^domainA.co.uk$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.domainA.co.uk$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^domainA.com$" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.domainA.com$" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="http://www.domainB.com/my-folder/{R:1}" />
</rule>

It will redirect urls:

domainA.co.uk to www.domainB.com/my-folder/

www.domainA.co.uk to www.domainB.com/my-folder/

domainA.com to www.domainB.com/my-folder/

www.domainA.com to  www.domainB.com/my-folder/

www.domainA.com/something to  www.domainB.com/my-folder/something (in case if you dont want that, just remove {R:1} form rule)


问:
Add custom package source to Visual Studio Code
Does anybody know how to add custom package source to Visual Studio Code?

E.g. I'd like to add https://www.myget.org/F/aspnet-contrib/api/v3/index.json as a package source and drive these packages through project.json.

答:
Adding a nuget.config in the project solves it for the project. Adding to the root is ok. The config could look like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="MyGet" value="https://www.myget.org/F/aspnet-contrib/api/v3/index.json" />
  </packageSources>
</configuration>
</code>```

Body:
Adding a nuget.config in the project solves it for the project. Adding to the root is ok. The config could look like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="MyGet" value="https://www.myget.org/F/aspnet-contrib/api/v3/index.json" />
  </packageSources>
</configuration>


问:
Show Tutorial View on first time only
I'm trying to create an tutorial screen that displays only during the first opening of an app. i know i should use user defaults but how and where ? in method viewDidLoad or on app delegate class ? </p>

答:
Try this one</p>

```<code>- (BOOL)isAppAlreadyLaunchedOnce {
    BOOL isRememberMe = [[NSUserDefaults standardUserDefaults]boolForKey:@"isAppAlreadyLaunchedOnce"];
    if (isRememberMe) {
        return YES;
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAppAlreadyLaunchedOnce"];
        return NO;
    }
}
</code>```

Title: Show Tutorial View on first time only

Body:
Try this one

- (BOOL)isAppAlreadyLaunchedOnce {
    BOOL isRememberMe = [[NSUserDefaults standardUserDefaults]boolForKey:@"isAppAlreadyLaunchedOnce"];
    if (isRememberMe) {
        return YES;
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAppAlreadyLaunchedOnce"];
        return NO;
    }
}


问:
Why is there no Z80 like LDIR functionality in C/C++/rtl?
In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks.   So a chunk of code might look something like this.

```<code>LD HL, DESTINATION             ; point to the source
LD DE, DESTINATION + 1         ; point to the destination
LD BC, DESTINATION_SIZE - 1    ; copying this many bytes
LD (HL), 0X20                  ; put a seed space in the first position
LDIR                           ; move 1 to 2, 2 to 3...
</code>```

The result being that the chunk of memory at DESTINATION is completely blank filled.
I have experimented with memmove, and memcpy, and can't replicate this behavior.  I expected memmove to be able to do it correctly.

Why do memmove and memcpy behave this way?

Is there any reasonable way to do this sort of array initialization?

I am already aware of char array[size] = {0} for array initialization

I am already aware that memset will do the job for single characters.

What other approaches are there to this issue?

答: If you're on the PowerPC, _dcbz().</p>

OwnerDisplayName: EvilTeach

Body:
In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks.   So a chunk of code might look something like this.

LD HL, DESTINATION             ; point to the source
LD DE, DESTINATION + 1         ; point to the destination
LD BC, DESTINATION_SIZE - 1    ; copying this many bytes
LD (HL), 0X20                  ; put a seed space in the first position
LDIR                           ; move 1 to 2, 2 to 3...

The result being that the chunk of memory at DESTINATION is completely blank filled.
I have experimented with memmove, and memcpy, and can't replicate this behavior.  I expected memmove to be able to do it correctly.

Why do memmove and memcpy behave this way?

Is there any reasonable way to do this sort of array initialization?

I am already aware of char array[size] = {0} for array initialization

I am already aware that memset will do the job for single characters.

What other approaches are there to this issue?

Body: If you're on the PowerPC, _dcbz().

OwnerDisplayName: Crashworks


问:
Differences between xp_instance_RegRead and xp_RegRead
Whats the difference between XP_REGREAD and XP_INSTANCE_REGREAD.
How to use them, is there any docs on these?</p>

答:
Gabriel, The Service account does not have to be dbo. As long as the user is a user in the master database, you can grant execute permissions on system objects in the master db.
```<code>GRANT EXEC ON OBJECT::master.dbo.xp_instance_regread TO ServiceAccountUserName
```</code></p>

Body:
Gabriel, The Service account does not have to be dbo. As long as the user is a user in the master database, you can grant execute permissions on system objects in the master db.

GRANT EXEC ON OBJECT::master.dbo.xp_instance_regread TO ServiceAccountUserName


问:
vba add text box by clicking button
In vba, I need to add textbox by clicking 'Add' button. Is it possible in VBA?
If it is, could you possible to share source code?
Click here to see more description
In the image, after fill in first textbox, which is A, and then click 'Add button', below textbox which is marked as 'B' should appear.
I know that this kind of thing is possible in web using jquery, but I am new to vba, so I don't know if it is possible or not.
Any comments would be greatly helpful</p>

答:
You could use code similar to this in your click event of the button:

```<code>Me!TextBoxB.Visible = Not IsNull(Me!TextBoxA.Value)
</code>```

Title: vba add text box by clicking button

Body:
You could use code similar to this in your click event of the button:

Me!TextBoxB.Visible = Not IsNull(Me!TextBoxA.Value)


问:
post time don't change in loop - wordpress
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           " class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>```

答:
Thanks "Aron" for answer 1 :

echo get_the_time('', $recent["ID"]);```
</div>
</div>
</p>

<p>And Thanks "WizardCoder" for the other loop solution:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$args = array( 'posts_per_page' => '5', 'orderby' => 'most_recent' );
$recent_posts = new WP_Query( $args );
if ( $recent_posts->have_posts() ) : while ( $recent_posts->have_posts() ) : $recent_posts->the_post(); ?>
  <li class="orbit-slide">
    <div>
      " class="ticker-a">
        <span><?php the_time("g:i a"); ?>   </span>
        <?php the_title(); ?>

    </div>
  </li>
<?php
endwhile; endif;
wp_reset_query();
?></code>```

Body:
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           <a href="<?php echo get_permalink($recent["ID"]); ?>" class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>

Body:
Thanks "Aron" for answer 1 :

echo get_the_time('', $recent["ID"]);

And Thanks "WizardCoder" for the other loop solution:

<?php
$args = array( 'posts_per_page' => '5', 'orderby' => 'most_recent' );
$recent_posts = new WP_Query( $args );
if ( $recent_posts->have_posts() ) : while ( $recent_posts->have_posts() ) : $recent_posts->the_post(); ?>
  <li class="orbit-slide">
    <div>
      <a href="<?php the_permalink(); ?>" class="ticker-a">
        <span><?php the_time("g:i a"); ?>  &nbsp;</span>
        <?php the_title(); ?>
      </a>
    </div>
  </li>
<?php
endwhile; endif;
wp_reset_query();
?>


问:
Keras Python Multi Image Input shape error
I am trying to teach myself to build a CNN that takes more than one image as an input. Since the dataset I created to test this is large and in the long run I hope to solve a problem involving a very large dataset, I am using a generator to read images into arrays which I am passing to Keras Model's fit_generator function.

When I run my generator in isolation it works fine, and produces outputs of the appropriate shape. It yields a tuple containing two entries, the first of which has shape (4, 100, 100, 1) and the second of which has shape (4, ).

Reading about multiple input Keras CNNs has given me the impression that this is the right format for a generator for a 4 input CNN that is identifying which of the 4 inputs contains an image.

However, when I run the code I get:

```<code>"ValueError: Error when checking input: expected input_121 to have 4 dimensions, but got array with shape (100, 100, 1)"
</code>```

I've been searching for a solution for some time now and I suspect that the problem lies in getting my (100, 100, 1) shape arrays to be sent to the Inputs as (None, 100, 100, 1) shape arrays.

But when I tried to modify the output of my generator I get an error about having dimension 5, which makes sense as an error because the output of the generator should have the form X, y = [X1, X2, X3, X4], [a, b, c, d], where Xn has shape (100, 100, 1), and a/b/c/d are numbers.

Here is the code:

https://gist.github.com/anonymous/d283494aee982fbc30f3b52f2a6f422c

Thanks in advance!

答:
You are creating a list of arrays in your generator with the wrong dimensions.

If you want the correct shape, reshape individual images to have the 4 dimensions: (n_samples, x_size, y_size, n_bands) your model will work. In your case you should reshape your images to (1, 100, 100, 1).

At the end stack them with np.vstack. The generator will yield an array of shape (4, 100, 100, 1).

Check if this adapted code works

```<code>def input_generator(folder, directories):

    Streams = []
    for i in range(len(directories)):
        Streams.append(os.listdir(folder + "/" + directories[i]))
        for j in range(len(Streams[i])):
            Streams[i][j] = "Stream" + str(i + 1) + "/" + Streams[i][j]
        Streams[i].sort()

    length = len(Streams[0])
    index = 0
    while True:
        X = []
        y = np.zeros(4)
        for Stream in Streams:
            image = load_img(folder + '/' + Stream[index], grayscale = True)
            array = img_to_array(image).reshape((1,100,100,1))
            X.append(array)
        y[int(Stream[index][15]) - 1] = 1
        index += 1
        index = index % length
        yield np.vstack(X), y
</code>```

Body:
I am trying to teach myself to build a CNN that takes more than one image as an input. Since the dataset I created to test this is large and in the long run I hope to solve a problem involving a very large dataset, I am using a generator to read images into arrays which I am passing to Keras Model's fit_generator function.

When I run my generator in isolation it works fine, and produces outputs of the appropriate shape. It yields a tuple containing two entries, the first of which has shape (4, 100, 100, 1) and the second of which has shape (4, ).

Reading about multiple input Keras CNNs has given me the impression that this is the right format for a generator for a 4 input CNN that is identifying which of the 4 inputs contains an image.

However, when I run the code I get:

"ValueError: Error when checking input: expected input_121 to have 4 dimensions, but got array with shape (100, 100, 1)"

I've been searching for a solution for some time now and I suspect that the problem lies in getting my (100, 100, 1) shape arrays to be sent to the Inputs as (None, 100, 100, 1) shape arrays.

But when I tried to modify the output of my generator I get an error about having dimension 5, which makes sense as an error because the output of the generator should have the form X, y = [X1, X2, X3, X4], [a, b, c, d], where Xn has shape (100, 100, 1), and a/b/c/d are numbers.

Here is the code:

https://gist.github.com/anonymous/d283494aee982fbc30f3b52f2a6f422c

Thanks in advance!

Body:
You are creating a list of arrays in your generator with the wrong dimensions.

If you want the correct shape, reshape individual images to have the 4 dimensions: (n_samples, x_size, y_size, n_bands) your model will work. In your case you should reshape your images to (1, 100, 100, 1).

At the end stack them with np.vstack. The generator will yield an array of shape (4, 100, 100, 1).

Check if this adapted code works

def input_generator(folder, directories):

    Streams = []
    for i in range(len(directories)):
        Streams.append(os.listdir(folder + "/" + directories[i]))
        for j in range(len(Streams[i])):
            Streams[i][j] = "Stream" + str(i + 1) + "/" + Streams[i][j]
        Streams[i].sort()

    length = len(Streams[0])
    index = 0
    while True:
        X = []
        y = np.zeros(4)
        for Stream in Streams:
            image = load_img(folder + '/' + Stream[index], grayscale = True)
            array = img_to_array(image).reshape((1,100,100,1))
            X.append(array)
        y[int(Stream[index][15]) - 1] = 1
        index += 1
        index = index % length
        yield np.vstack(X), y


问:
TextIO. Read multiple files from GCS using pattern {}
I tried using the following

```<code>TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

That pattern didn't work, as I get

```<code>java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}
</code>```

Even though those 2 files do exist. And I tried with a local file using a similar expression

```<code>TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?

答:
Did you try Apache Beam TextIO.Read from function? Here, it says that it is possible with gcs as well:

public TextIO.Read from(java.lang.String filepattern)

Reads text files that reads from the file(s) with the given filename or filename pattern. This can be a local path (if running locally), or a Google Cloud Storage filename or filename pattern of the form "gs://<bucket>/<filepath>" (if running locally or using remote execution service).

Standard Java Filesystem glob patterns ("*", "?", "[..]") are supported.

Body:
I tried using the following

TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")

That pattern didn't work, as I get

java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}

Even though those 2 files do exist. And I tried with a local file using a similar expression

TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?


问:
How to implement authenticated routes in React Router 4?
I was trying to implement authenticated routes but found that React Router 4 now prevents this from working:

```<code><Route exact path="/" component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>
</code>```

The error is:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

In that case, what's the correct way to implement this?

It appears in react-router (v4) docs, it suggests something like

```<code><Router>
    <div>
    <AuthButton/>
    <ul>
        <li><Link to="/public">Public Page</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
    </ul>
    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>
    </div>
</Router>
</code>```

But is it possible to achieve this while grouping a bunch of routes together?

After some research, I came up with this:

```<code>import React, {PropTypes} from "react"
import {Route} from "react-router-dom"

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}
</code>```

Is it correct to dispatch an action in render()? It feels wrong. It doesn't really seem correct with componentDidMount or some other hook, either.

答:
install react-router-dom

then create two components one for valid users and other for invalid users.

try this on app.js

```<code>import React from 'react';

import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';

import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;

class App extends React.Component {
 render() {
    return (
      <Router>
      <div>
        <Route exact path="/" render={() =>(
          loggedin ? ( <Route  component={ValidUser} />)
          : (<Route component={InValidUser} />)
        )} />

        </div>
      </Router>
    )
  }
}
export default App;
</code>```

Body:
I was trying to implement authenticated routes but found that React Router 4 now prevents this from working:

<Route exact path="/" component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>

The error is:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

In that case, what's the correct way to implement this?

It appears in react-router (v4) docs, it suggests something like

<Router>

    <AuthButton/>

<Link to="/public">Public Page</Link>

<Link to="/protected">Protected Page</Link>

    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>

</Router>

But is it possible to achieve this while grouping a bunch of routes together?

After some research, I came up with this:

import React, {PropTypes} from "react"
import {Route} from "react-router-dom"

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}

Is it correct to dispatch an action in render()? It feels wrong. It doesn't really seem correct with componentDidMount or some other hook, either.

Body:
install react-router-dom

then create two components one for valid users and other for invalid users.

try this on app.js

import React from 'react';

import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';

import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;

class App extends React.Component {
 render() {
    return (
      <Router>
      <div>
        <Route exact path="/" render={() =>(
          loggedin ? ( <Route  component={ValidUser} />)
          : (<Route component={InValidUser} />)
        )} />

        </div>
      </Router>
    )
  }
}
export default App;


问:
Set a scheduling task (Windows Hosting) in Parallels Plesk Panel
I need to set a scheduling task (Windows Hosting). I configured like below

```<code>Path to executable file = C:\Program Files (x86)\Parallels\Plesk\Additional\PleskPHP5\php.exe

Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php
</code>```

Accompalive is the root folder name and aspiresoftwareconsultancy is the domain name. I tried with example.com also as domine name but schedular is not running. I set each 2 minutes every hour, day, week, month, year as timing. I also set one notification email address. But I am getting email with an error file having message "Could not open input file: C:\Inetpub\vhosts\aspiresoftwareconsultancy.tld\httpdocs\accompalive\Scheduler.php". Did I set it correctly or need some changes? thank you.

答:
I used your code and it is working for me.

```<code>Path to executable file = C:\Program Files (x86)\Parallels\Plesk\Additional\PleskPHP4\php.exe
Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php
</code>```

If you have validation on scheduler.php or wrong code then it can not work.

When I send some data using get method (like Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php?id=12) then I also got text file(utility output) in email where they said that "Could not open input file".

Body:
I need to set a scheduling task (Windows Hosting). I configured like below

Path to executable file = C:\Program Files (x86)\Parallels\Plesk\Additional\PleskPHP5\php.exe

Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php

Accompalive is the root folder name and aspiresoftwareconsultancy is the domain name. I tried with example.com also as domine name but schedular is not running. I set each 2 minutes every hour, day, week, month, year as timing. I also set one notification email address. But I am getting email with an error file having message "Could not open input file: C:\Inetpub\vhosts\aspiresoftwareconsultancy.tld\httpdocs\accompalive\Scheduler.php". Did I set it correctly or need some changes? thank you.

Body:
I used your code and it is working for me.

Path to executable file = C:\Program Files (x86)\Parallels\Plesk\Additional\PleskPHP4\php.exe
Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php

If you have validation on scheduler.php or wrong code then it can not work.

When I send some data using get method (like Arguments = C:\Inetpub\vhosts\example.com\httpdocs\accompalive\Scheduler.php?id=12) then I also got text file(utility output) in email where they said that "Could not open input file".


问:
Collapsing/Expanding view coordinated with Sliding RecyclerView
I am trying to achieve the following affect (also see image below):

the app opens with a view (map) partially visible and the RecyclerView at a default anchor point (center image)

user scrolls the RecyclerView up, the map collapses and the list continues scrolling (right image)

user scrolls the RecyclerView down, the map expands to a maximum point (note the list should not slide completely off screen but to some anchored point) (left image)

答:
I Found Solution for Tabs in CoordinatorLayout

```<code> <?xml version="1.0" encoding="utf-8"?>

        <android.support.design.widget.CoordinatorLayout                                                                          xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/htab_maincontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/htab_appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/htab_collapse_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                app:layout_scrollFlags="scroll|enterAlways|snap"
                app:statusBarScrim="@null"
                app:titleEnabled="false">

                <LinearLayout
                    android:id="@+id/isprofile"
                    android:layout_width="match_parent"
                    android:layout_height="180dp"
                    android:background="@drawable/profile_cover"
                    android:gravity="center"
                    app:layout_collapseMode="parallax">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginBottom="10dp"
                        android:gravity="center"
                        android:orientation="vertical">

                        <com.root.findagame.utills.CircleImageView
                            android:id="@+id/profile_pic"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:background="@drawable/profile_pic" />

                        <TextView
                            android:id="@+id/txtUserName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_medium_size"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/txtAge"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"

                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_small_size" />

                        <TextView
                            android:id="@+id/txtName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_small_size"
                            android:visibility="gone" />

                    </LinearLayout>
                </LinearLayout>

                <android.support.v7.widget.Toolbar
                    android:id="@+id/htab_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:visibility="gone"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
                    app:popupTheme="@style/AppTheme.PopupOverlay" />

            </android.support.design.widget.CollapsingToolbarLayout>
            <android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_gravity="bottom"
                android:background="@color/cpb_white"
                app:layout_collapseMode="pin"
                app:tabIndicatorColor="#7CC142"
                app:tabSelectedTextColor="#7CC142"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
                app:tabTextColor="@color/lightGrayColor" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/htab_viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>

*Fragment*
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dummyfrag_bg"
    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dummyfrag_scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />

</FrameLayout>
</code>```

Body:
I Found Solution for Tabs in CoordinatorLayout

 <?xml version="1.0" encoding="utf-8"?>

        <android.support.design.widget.CoordinatorLayout                                                                          xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/htab_maincontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/htab_appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/htab_collapse_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                app:layout_scrollFlags="scroll|enterAlways|snap"
                app:statusBarScrim="@null"
                app:titleEnabled="false">

                <LinearLayout
                    android:id="@+id/isprofile"
                    android:layout_width="match_parent"
                    android:layout_height="180dp"
                    android:background="@drawable/profile_cover"
                    android:gravity="center"
                    app:layout_collapseMode="parallax">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginBottom="10dp"
                        android:gravity="center"
                        android:orientation="vertical">

                        <com.root.findagame.utills.CircleImageView
                            android:id="@+id/profile_pic"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:background="@drawable/profile_pic" />

                        <TextView
                            android:id="@+id/txtUserName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_medium_size"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/txtAge"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"

                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_small_size" />

                        <TextView
                            android:id="@+id/txtName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text=""
                            android:textColor="@color/cpb_white"
                            android:textSize="@dimen/text_small_size"
                            android:visibility="gone" />

                    </LinearLayout>
                </LinearLayout>

                <android.support.v7.widget.Toolbar
                    android:id="@+id/htab_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:visibility="gone"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
                    app:popupTheme="@style/AppTheme.PopupOverlay" />

            </android.support.design.widget.CollapsingToolbarLayout>
            <android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_gravity="bottom"
                android:background="@color/cpb_white"
                app:layout_collapseMode="pin"
                app:tabIndicatorColor="#7CC142"
                app:tabSelectedTextColor="#7CC142"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
                app:tabTextColor="@color/lightGrayColor" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/htab_viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>

*Fragment*
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dummyfrag_bg"
    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dummyfrag_scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />

</FrameLayout>


问:
ggplot2: Leave one of the margins as default
```<code>library(ggplot2)

#default
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()

#modify margins
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,1),"cm"))
</code>```

Now I am trying to control some margins while others are left as default.

```<code>#doesn't work
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,NULL),"cm"))
</code>```

Using NA or NULL doesn't seem to work.

答:
try this:</p>

```<code>add_margin = function(...)  grid::convertUnit(theme_get()[["plot.margin"]] + margin(...), "cm")

 ggplot(iris,aes(Sepal.Length,Sepal.Width))+
   geom_point()+ theme(plot.margin = add_margin(l=2, unit="cm"))
</code>```

Body:
library(ggplot2)

#default
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()

#modify margins
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,1),"cm"))

Now I am trying to control some margins while others are left as default.

#doesn't work
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,NULL),"cm"))

Using NA or NULL doesn't seem to work.

Body:
try this:

add_margin = function(...)  grid::convertUnit(theme_get()[["plot.margin"]] + margin(...), "cm")

 ggplot(iris,aes(Sepal.Length,Sepal.Width))+
   geom_point()+ theme(plot.margin = add_margin(l=2, unit="cm"))


问:
Start GitLog with Java Process Builder
I try to start a GitLog command via Processbuilder in Java.

GitLog Command :

git --git-dir=C:/Users/User/Code/code1/git/.git log
  --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short

This is my code. The Path is the path to the git dir.
I hardcoded the gitpath to the git dir for testing.

```<code>public void createGitLog( Path path ) {
            try
            {
                String gitpath = "--git-dir=C:/Users/User/Code/code1/git/.git";
                String options = "--pretty=format:\"%H \\\"%an\\\" %ad \\\"%s\\\"\" --numstat --date=short";

                ProcessBuilder builder = new ProcessBuilder("git", gitpath, "log", options );
                Process process = builder.start();

                builder.redirectOutput(ProcessBuilder.Redirect.to( path.resolve("gitlog.dat").toFile() ) );

                int exitValue = process.waitFor();

                if ( exitValue != 0 )
                {
                    // throw
                }
            }
            catch (IOException e) {

            }
}
</code>```

If i try this command in the cmd it works, but in Java I get always the exitcode 128.

What is the Problem with this process ?

答:
That what works in my case to run commands in terminal:

"/bin/bash" - path to your bash

"-c" - states that next param is command

"command" - full command you want to execute from terminal (like git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short)

```<code>String command = "git " + gitpath + " log " + options;
ProcessBuilder builder = new ProcessBuilder("/bin/bash" , "-c" , command);
</code>```

you can also use on ProcessBuilder directory() if you want to start process from specific dir;

```<code> .directory(new File("C:/Users/User/Code/code1/git/"))
</code>```

Title: Start GitLog with Java Process Builder

Body:
I try to start a GitLog command via Processbuilder in Java.

GitLog Command :

git --git-dir=C:/Users/User/Code/code1/git/.git log
  --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short

This is my code. The Path is the path to the git dir.
I hardcoded the gitpath to the git dir for testing.

public void createGitLog( Path path ) {
            try
            {
                String gitpath = "--git-dir=C:/Users/User/Code/code1/git/.git";
                String options = "--pretty=format:\"%H \\\"%an\\\" %ad \\\"%s\\\"\" --numstat --date=short";

                ProcessBuilder builder = new ProcessBuilder("git", gitpath, "log", options );
                Process process = builder.start();

                builder.redirectOutput(ProcessBuilder.Redirect.to( path.resolve("gitlog.dat").toFile() ) );

                int exitValue = process.waitFor();

                if ( exitValue != 0 )
                {
                    // throw
                }
            }
            catch (IOException e) {

            }
}

If i try this command in the cmd it works, but in Java I get always the exitcode 128.

What is the Problem with this process ?

Body:
That what works in my case to run commands in terminal:

"/bin/bash" - path to your bash

"-c" - states that next param is command

"command" - full command you want to execute from terminal (like git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short)

String command = "git " + gitpath + " log " + options;
ProcessBuilder builder = new ProcessBuilder("/bin/bash" , "-c" , command);

you can also use on ProcessBuilder directory() if you want to start process from specific dir;

 .directory(new File("C:/Users/User/Code/code1/git/"))


问:
Is it possible to load an instance of a VSTO addin from a network drive?
I've got a VSTO 3.0 Word Addin. Around here, they do all work off network drives (for backup reasons, etc etc).

Anyway, when I'm in the IDE, I can run my project, it automatically starts Word, i can debug, break, etc, just fine.

HOWEVER... If I compile the project, then run Word OUTSIDE of the ide, the Addin registry entry is, of course, still pointing to the NETWORK copy of the VSTO dll, not a local machine (C Drive) copy, and the addin always fails to load.

I can copy the DLL down to the local machine, update the registry to point to the C: location, and then run word and it loads fine.

But I was wondering if there's any way to config VSTO to be able to load an addin from a network share directly.

I've tried setting the "TRUSTED LOCATIONS" in Word 2010 to point to my network location, but it didn't help.

The only oddity in doing so is that the error message I get back from Word when I have VSTO_SUPPRESSDISPLAYALERTS=0, contains a path of file://j:/path/path/path, ie a mapped drive letter.

BUT, when I try to add the j:\path location to my "trusted locations" in word, it always converts it to a full pathspec, ie \domain\dfs\path\path.

I'm wondering if that mismatch is what's screwing it up, but I can't find anyway around it.

答:
Well, as far as I can tell, it's just not possible to load addins on a network drive without running them in the IDE. If someone comes along and knows otherwise, I'd love to know, but I'll go ahead and mark this question closed for now.

Essentially, what I've done is create a little REG script that reregisters the add in to point to the local drive, then, when I need to run as a release (ie NOT in the VS IDE), I compile, copy the dll down locally, and run the regscript. Not great, but not too bad either.


问:
How to compare MDS and Cluster analysis in R
This is my first post on here so I hope I don't break any rules! I have a set of 30snps sampled from 450 individuals. I have performed an MDS on my dataset and a cluster analysis. In both cases I have obtained two distinct groups. I would like to see if the individuals in the two groups are the same both for the MDS and the cluster analysis. Do you have any suggestions on how I could solve this?

Thanks for your help!

答:
If you've got two vectors, you can see how they differ using setdiff():

```<code>set1 <- c(1, 2, 3, 4, 5)
set2 <- c(2, 3, 4, 5, 6)

# what elements are in set1 but not in set2?
setdiff(set1, set2)
[1] 1
</code>```

Body:
If you've got two vectors, you can see how they differ using setdiff():

set1 <- c(1, 2, 3, 4, 5)
set2 <- c(2, 3, 4, 5, 6)

# what elements are in set1 but not in set2?
setdiff(set1, set2)
[1] 1


问:
Appengine search API doesn't work for deploys in flex environment
I have been trying to deploy a service that uses the appengine golang search APIs. It works fine if I deploy it with vm: true option, but it's getting deprecated. When I deploy it with env: flex, I get this error:

service bridge HTTP failed: Post http://appengine.googleapis.internal:10001/rpc_http: dial tcp: lookup appengine.googleapis.internal on 127.0.0.11:53: no such host

How can I get around this issue?

答:
Sadly Search API is not available on AppEngine Flex anymore.It was available on AppEngine Flex using the compat runtime, but as you said, this is deprecated and will stop working on October 27th, 2017.

I guess you have two options:

use something like ElasticSearch (either SaaS or using Compute Engine to create your own cluster),

use an AppEngine Standard service to handle the search part of your application.


问:
Remove option to choose between the three pages in Settings Page
I am develop an UWP app, and I am using Template10 (Hamburguer Menu). In Settings Page, there is, by default, 3 pages: Settings, About and Privacy statement.

I want only one page - Settings

How do I remove that option to choose between the three pages? I already managed to remove it, but it always remains there.

答:
Please try to find the relative Pivot control in Views->SettingsPage.xaml of your project and delete or commented out the following two PivotItems, the "About and Privacy statement" will gone.

```<code><!--  privacy  -->
<PivotItem
    Padding="0"
    DataContext="{Binding SettingsPartViewModel}"
    Header="Privacy statement">
    <ScrollViewer Margin="0,0,-12,0" VerticalScrollBarVisibility="Auto">
        ...
    </ScrollViewer>
</PivotItem>
<!--  about  -->
<PivotItem Header="About">
    <RelativePanel DataContext="{Binding AboutPartViewModel}">
        ...
    </RelativePanel>
</PivotItem>
</code>```

Body:
Please try to find the relative Pivot control in Views->SettingsPage.xaml of your project and delete or commented out the following two PivotItems, the "About and Privacy statement" will gone.

<!--  privacy  -->
<PivotItem
    Padding="0"
    DataContext="{Binding SettingsPartViewModel}"
    Header="Privacy statement">
    <ScrollViewer Margin="0,0,-12,0" VerticalScrollBarVisibility="Auto">
        ...
    </ScrollViewer>
</PivotItem>
<!--  about  -->
<PivotItem Header="About">
    <RelativePanel DataContext="{Binding AboutPartViewModel}">
        ...
    </RelativePanel>
</PivotItem>


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
You can use a CTE with the ranking functions in SQL Server 2005 and up:

```<code>;WITH TopValues AS
(
   SELECT
     YEAR(some_date) AS 'Year',
     MONTH(some_date) AS 'Month',
     Some_Value,
     ROW_NUMBER() OVER(PARTITION BY YEAR(some_date),MONTH(some_date)
                       ORDER BY Some_Value DESC) AS 'RowNumber'
  FROM
     dbo.some_table
)
SELECT
    Year, Month, Some_Value
FROM
    TopValues
WHERE
    RowNumber <= 2
</code>```

This will "partition" (i.e. group) your data by month/year, order inside each group by Some_Value descending (largest first), and then you can select the first two of each group from that CTE.

RANK() works as well (I most often use ROW_NUMBER) - it produces slightly different results, though - really depends on what your needs are.

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

Body:
You can use a CTE with the ranking functions in SQL Server 2005 and up:

;WITH TopValues AS
(
   SELECT
     YEAR(some_date) AS 'Year',
     MONTH(some_date) AS 'Month',
     Some_Value,
     ROW_NUMBER() OVER(PARTITION BY YEAR(some_date),MONTH(some_date)
                       ORDER BY Some_Value DESC) AS 'RowNumber'
  FROM
     dbo.some_table
)
SELECT
    Year, Month, Some_Value
FROM
    TopValues
WHERE
    RowNumber <= 2

This will "partition" (i.e. group) your data by month/year, order inside each group by Some_Value descending (largest first), and then you can select the first two of each group from that CTE.

RANK() works as well (I most often use ROW_NUMBER) - it produces slightly different results, though - really depends on what your needs are.


问:
MySQL query to show results
My query is...

```<code>SELECT
    tbl1.FeeName,
    SUM(tbl1.FeeAmount) AS TotAmt
FROM
    tbl1
WHERE
    tbl1.DateTaken BETWEEN '2017-06-02' AND '2017-06-06'
GROUP BY
    tbl1.FeeId
</code>```

The output is...

The table has other Fees that are not taken (transaction) between the above dates therefore not showing in the query result.

I want to show those FeeNames and the value should be 0. Just like below (The yellow colored results).

What should I do ?

答:
Try this : this will only perform sum operations of fees which are in given date range, for remaining fees this will put 0

```<code>SELECT
tbl1.FeeName,
SUM(CASE WHEN tbl1.DateTaken BETWEEN '2017-06-02' AND '2017-06-06'
         THEN tbl1.FeeAmount
         ELSE 0
    END) AS TotAmt
FROM tbl1
GROUP BY  tbl1.FeeId
</code>```

Title: MySQL query to show results

Body:
My query is...

SELECT
    tbl1.FeeName,
    SUM(tbl1.FeeAmount) AS TotAmt
FROM
    tbl1
WHERE
    tbl1.DateTaken BETWEEN '2017-06-02' AND '2017-06-06'
GROUP BY
    tbl1.FeeId

The output is...

The table has other Fees that are not taken (transaction) between the above dates therefore not showing in the query result.

I want to show those FeeNames and the value should be 0. Just like below (The yellow colored results).

What should I do ?

Body:
Try this : this will only perform sum operations of fees which are in given date range, for remaining fees this will put 0

SELECT
tbl1.FeeName,
SUM(CASE WHEN tbl1.DateTaken BETWEEN '2017-06-02' AND '2017-06-06'
         THEN tbl1.FeeAmount
         ELSE 0
    END) AS TotAmt
FROM tbl1
GROUP BY  tbl1.FeeId