问:
Using Windows Phone 7 pinching in XNA
I'm trying to figure out how to implement pinch-to-zoom functionality. My problem is I'm not sure how to do it algorithmically.

I have the pinch positions of both fingers and the amount they've moved since the last frame. At first I tried making the pinch amount the delta of the distance between the two fingers however every way I've done it around this concept has been unyieldly.

Even if I manage to get the pinching working semi-decently I still have the problem of the zoom direction and how to make the image zoom in on the center of the pinch area...

Is there a proper way of implementing such functionality?

答:
What you want to do is use the built-in gesture API (specifically Pinch and PinchComplete). That way, you can take advantage of the heuristics that the xna/wp7 team has already built in. Your app will feel "more native" this way because it will react like the rest of the OS in reaction to a pinch gesture.

Nick Gravelyn has a great intro to the gesture API here:

http://blogs.msdn.com/b/nicgrave/archive/2010/07/12/touch-gestures-on-windows-phone-7.aspx

Title: Using Windows Phone 7 pinching in XNA


来源: stackexchange

问:
$q.all of AngularJS only works for one result
I am working on function that calculates a distance from a given object to a number of other places with the help of Google Distance Matrix which is of course async therefore I'm dealing with promises.

When the number of places is one, everything works great. But once I have more than one promise, $q.all doesn't do anything : it neither resolves in a success nor in error. Though I have checked in the console that the calls to the Google distance matrix do happen and return a correct result. Any clue what can be at play here?

I am using AngularJS 1.6.4. Let me know should you need any more details. Thanks!

```<code>var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var deferred = $q.defer();
    requests.push(deferred.promise);
    var destination = ctrl.places[i].latLng;
    service.getDistanceMatrix({
        origins: [ctrl.origin],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        }
    });
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});
</code>```

答:
Reason why it does not work

By the time the service call resolves and the callback handler is invoked, the deferred attribute is referring to the very last deferred object created by the for loop. So, in effect, you are always performing a resolve on the very last deferred object that was created.

Solution:

Create a new function:

```<code>function getDistanceMatrixForDestination (destination, origins) {
   var deferred = $q.defer();
   service.getDistanceMatrix({
        origins: [origins],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        } else {
            deferred.reject();
        }
    });
   return deferred.promise;
}
</code>```

Change your existing code to this:

```<code>var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var destination = ctrl.places[i].latLng;
    requests.push(getDistanceMatrixForDestination (destination, ctrl.origins));
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on function that calculates a distance from a given object to a number of other places with the help of Google Distance Matrix which is of course async therefore I'm dealing with promises.

When the number of places is one, everything works great. But once I have more than one promise, $q.all doesn't do anything : it neither resolves in a success nor in error. Though I have checked in the console that the calls to the Google distance matrix do happen and return a correct result. Any clue what can be at play here?

I am using AngularJS 1.6.4. Let me know should you need any more details. Thanks!

var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var deferred = $q.defer();
    requests.push(deferred.promise);
    var destination = ctrl.places[i].latLng;
    service.getDistanceMatrix({
        origins: [ctrl.origin],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        }
    });
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});

Body:
Reason why it does not work

By the time the service call resolves and the callback handler is invoked, the deferred attribute is referring to the very last deferred object created by the for loop. So, in effect, you are always performing a resolve on the very last deferred object that was created.

Solution:

Create a new function:

function getDistanceMatrixForDestination (destination, origins) {
   var deferred = $q.defer();
   service.getDistanceMatrix({
        origins: [origins],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        } else {
            deferred.reject();
        }
    });
   return deferred.promise;
}

Change your existing code to this:

var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var destination = ctrl.places[i].latLng;
    requests.push(getDistanceMatrixForDestination (destination, ctrl.origins));
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});


问:
OnClick: Passing String as Parameter
I would like to pass a string as a parameter of the following:

How would I make "hello" become a parameter. The integers pass without problem.

Thank you.

答:
Use single quotes around your string like so:</p>

```<code><div id="menubutton1" class="menubutton lightbox" onclick="lightbox(1000, 410, 'hello')">
</code>```

Title: OnClick: Passing String as Parameter

Body:
Use single quotes around your string like so:

<div id="menubutton1" class="menubutton lightbox" onclick="lightbox(1000, 410, 'hello')">


问:
Android + Firebase: how to make sure to have the minimum Google Play Services
I have this problem: I'm running an app with firebase in a Samsung tablet with Android 4.3 with Google Play Services at version 7.8.99 (should be minimum 9). So when I try to login with FireBase it gives me a "Can't connect to Google Play Services".

My question is: is there a way to make sure that the App will run on all devices with the minimum version of the SDK, in my case the minimum compatibility is 4.3.

I installed Firebase in the app using the assistant, and then checked if everything was there following the manual install guide. I also tried what is described in this post and is this post. So far nothing solved my issue.

My root level build.gradle:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And my App Level build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "xx.xx.xxxxxxxx"
        minSdkVersion 18
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.roughike:bottom-bar:2.3.1'
    compile 'com.android.support:support-v4:24.2.1'
    compile 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.2'
    compile 'com.github.clans:fab:1.6.4'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:10.2.6'
    compile 'com.google.firebase:firebase-auth:10.2.6'
    compile 'com.google.firebase:firebase-database:10.2.6'
    compile 'com.google.firebase:firebase-crash:10.2.6'
    compile 'com.estimote:sdk:1.0.3:release@aar'

}

apply plugin: 'com.google.gms.google-services'
</code>```

Is there anything I can do to make sure that I can work with firebase in every device?

答:
You need to check to see if google play services is available and the connection result of that check tells you what you need to do

```<code>switch (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)){
        case ConnectionResult.SERVICE_MISSING:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_MISSING,0).show();
            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED,0).show();
            break;
        case ConnectionResult.SERVICE_DISABLED:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_DISABLED,0).show();
            break;
    }
</code>```

The latest Google Play Services is compatible with all devices 4.1 and up.

There isn't a way to tie GPS to specific android versions, you have to just make sure the version you are using is compatible with your min Android API version you need to target.

Body:
I have this problem: I'm running an app with firebase in a Samsung tablet with Android 4.3 with Google Play Services at version 7.8.99 (should be minimum 9). So when I try to login with FireBase it gives me a "Can't connect to Google Play Services".

My question is: is there a way to make sure that the App will run on all devices with the minimum version of the SDK, in my case the minimum compatibility is 4.3.

I installed Firebase in the app using the assistant, and then checked if everything was there following the manual install guide. I also tried what is described in this post and is this post. So far nothing solved my issue.

My root level build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And my App Level build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "xx.xx.xxxxxxxx"
        minSdkVersion 18
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.roughike:bottom-bar:2.3.1'
    compile 'com.android.support:support-v4:24.2.1'
    compile 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.2'
    compile 'com.github.clans:fab:1.6.4'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:10.2.6'
    compile 'com.google.firebase:firebase-auth:10.2.6'
    compile 'com.google.firebase:firebase-database:10.2.6'
    compile 'com.google.firebase:firebase-crash:10.2.6'
    compile 'com.estimote:sdk:1.0.3:release@aar'

}

apply plugin: 'com.google.gms.google-services'

Is there anything I can do to make sure that I can work with firebase in every device?

Body:
You need to check to see if google play services is available and the connection result of that check tells you what you need to do

switch (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)){
        case ConnectionResult.SERVICE_MISSING:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_MISSING,0).show();
            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED,0).show();
            break;
        case ConnectionResult.SERVICE_DISABLED:
            GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_DISABLED,0).show();
            break;
    }

The latest Google Play Services is compatible with all devices 4.1 and up.

There isn't a way to tie GPS to specific android versions, you have to just make sure the version you are using is compatible with your min Android API version you need to target.


问:
Autodesk Forge API - How can I convert DWG files?
I am an App developer with no experience with AutoCAD at all, and for my current project I need to convert DWG files into Spatial Data - ESRI Shapefile / GeoJSON, etc.
Given that DWG is a proprietary format owned by Autodesk, the Autodesk Forge API becomes my only option to interpret such file. I have been evaluating the Model Derivative API for a week now, and what I found is that it won't work for my purposes. It has only 3 output formats (f2d, f3d, rvt) for DWG files and none of them fits my purpose.

For this reason, I started to look at others API's in the platform and ended up finding the Design Automation API which might be helpful, however it lacks documentation.

One of the examples in the API is the PlotToPdf activity that exports a DWG into a PDF. I wonder if there is a way to export other formats other than PDF.

I tried to find the possible "commands" in the interface by listing all the activities, workItems and AppPackages but none of these end-points returned me any useful information.

So here are my questions?

How can I can convert a DWG into a non Autodesk format? Being more specifically, the output must be an open format that I can interpret without using proprietary tools.

If the answer for the first question is Autodesk Forge API, which one should I use?

In case I should be using Design Automation API for that, where can I find complementary documentation once the one provided is lacking details?

答: Right now the derivativeApi is the way to go for this: You can convert any input format from this list (https://developer.autodesk.com/en/docs/model-derivative/v2/overview/supported-translations/) to the "intermediate format" svf and the convert the svf file to obj for example. This will also create a material file which can be downloaded seperately. I am evaluation the forge api right now and can produce obj from dwg files right now.</p>


答:
Add a ' before hello and a ' after hello:
onclick="lightbox(1000, 410, 'hello')"

Title: OnClick: Passing String as Parameter

Body:
I would like to pass a string as a parameter of the following:

How would I make "hello" become a parameter. The integers pass without problem.

Thank you.


问:
pick item from list at random, each has different chance
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

```<code>this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};
</code>```

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

```<code>this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];
</code>```

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

答:
This is how I'd implement the solution.
Step 1: accumulate all the possible chances
Step 2: pick a random value in proportion to total chance
Step 3: loop through the resources to see in which part it random value falls under.

var resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

function solution(resources) {
  let chanceTotal = resources.reduce((acc, val) => { acc += val.chance ; return acc;}, 0);
  let randomVal = parseInt(Math.random() * chanceTotal);
  let chanceAcc = 0;
  let ans;
  resources.forEach(r => {
    chanceAcc += r.chance;
    if (chanceAcc > randomVal && !ans) {
      ans = r;
    }
  });
  return ans;
}

console.log(solution(resources));```

Body:
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.


问:
Textual filter very slow
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

```<code>$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });
</code>```

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help

答:
This is how I would filter the data based on a data attribute so it runs quickly.

/* Just filling table with data */
var trs = $(Array.from({length: 1000}, () => Math.floor(Math.random() * 1000)).map( n => `<tr data-name="${n}"><td>${n}</td></tr>`).join(""))

var tbody = $("#tbod").append(trs)
/* end of filling table */

var lastFilter = "", //holds last typed search
    rows = tbody.find("tr");  // table rows

/* Normalize the data to start so you are not doing it on every check */
rows.attr("data-name", function (index, value) {
 return value.toLowerCase()
})

$("#filter").on("keyup", function () {
    var currentFilter = this.value.toLowerCase();  //get what was typed and normalize it
    //If the last filter does not match current than we need to reset table rows
    if (!lastFilter || currentFilter.substring(0,currentFilter.length-1) !== lastFilter) {
        rows.removeClass("hidden");
    }
    //store what the filter was for next iteration
    lastFilter = currentFilter;

    //If there is text, filter it
    if (currentFilter) {
      //Use CSS selector to find it ^ is start, use * for anywhere
      trs.not('tr[data-name^="' + currentFilter + '"]').addClass("hidden")
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden { display:none}</code>```

<input type="text" id="filter" />

```

Title: Textual filter very slow

Body:
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help

Body:
This is how I would filter the data based on a data attribute so it runs quickly.

/* Just filling table with data */
var trs = $(Array.from({length: 1000}, () => Math.floor(Math.random() * 1000)).map( n => `<tr data-name="${n}"><td>${n}</td></tr>`).join(""))

var tbody = $("#tbod").append(trs)
/* end of filling table */

var lastFilter = "", //holds last typed search
    rows = tbody.find("tr");  // table rows

/* Normalize the data to start so you are not doing it on every check */
rows.attr("data-name", function (index, value) {
 return value.toLowerCase()
})

$("#filter").on("keyup", function () {
    var currentFilter = this.value.toLowerCase();  //get what was typed and normalize it
    //If the last filter does not match current than we need to reset table rows
    if (!lastFilter || currentFilter.substring(0,currentFilter.length-1) !== lastFilter) {
        rows.removeClass("hidden");
    }
    //store what the filter was for next iteration
    lastFilter = currentFilter;

    //If there is text, filter it
    if (currentFilter) {
      //Use CSS selector to find it ^ is start, use * for anywhere
      trs.not('tr[data-name^="' + currentFilter + '"]').addClass("hidden")
    }
});

.hidden { display:none}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="filter" />
<table>
  <tbody id="tbod">
  </tbody>
</table>


问:
String startswith a particular text
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

```<code>inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)
</code>```

答:
if string.startswith(whateveritshouldstartwith):

This is the correct way to make this.

Title: String startswith a particular text

Body:
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)


问:
Cropping center square of UIImage
So here's where I've made it so far.  I am using a UIImage captured from the camera and can crop the center square when in landscape.  For some reason this doesn't translate to portrait mode as expected.  I'll post my code and logs just for reference.

Code:

```<code>CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];
</code>```

Portrait results (not square):

```<code>original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected
</code>```

Landscape results (square):

```<code>original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1
</code>```

Is this a bug within CGImageCreateWithImageInRect() or am I missing something here?

答:
This is based on @Alonzo's Swift 3 answer above, with the code simplified and streamlined to make it more understandable and concise. It also bails out if the image is already square.</p>

```<code>extension UIImage {
    func square() -> UIImage? {
        if size.width == size.height {
            return self
        }

        let cropWidth = min(size.width, size.height)

        let cropRect = CGRect(
            x: (size.width - cropWidth) * scale / 2.0,
            y: (size.height - cropWidth) * scale / 2.0,
            width: cropWidth * scale,
            height: cropWidth * scale
        )

        guard let imageRef = cgImage?.cropping(to: cropRect) else {
            return nil
        }

        return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
    }
}
</code>```

Title: Cropping center square of UIImage

Body:
So here's where I've made it so far.  I am using a UIImage captured from the camera and can crop the center square when in landscape.  For some reason this doesn't translate to portrait mode as expected.  I'll post my code and logs just for reference.

Code:

CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];

Portrait results (not square):

original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected

Landscape results (square):

original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1

Is this a bug within CGImageCreateWithImageInRect() or am I missing something here?

Body:
This is based on @Alonzo's Swift 3 answer above, with the code simplified and streamlined to make it more understandable and concise. It also bails out if the image is already square.

extension UIImage {
    func square() -> UIImage? {
        if size.width == size.height {
            return self
        }

        let cropWidth = min(size.width, size.height)

        let cropRect = CGRect(
            x: (size.width - cropWidth) * scale / 2.0,
            y: (size.height - cropWidth) * scale / 2.0,
            width: cropWidth * scale,
            height: cropWidth * scale
        )

        guard let imageRef = cgImage?.cropping(to: cropRect) else {
            return nil
        }

        return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
    }
}

ContentLicense: CC BY-SA 4.0


问:
How can I convert an int number from decimal to binary
how to convert an int array of length 8 to  an int array of length 32 each 4 indexes are the binary representation of an index of the first array is there such a method that do all overhead.

Edit, PST: I updated the title. However, this doesn't quite reflect with the notion of "binary", it's just decomposing integers into bytes. Correct and/or add examples if this is not accurate.

ok programers the main thing that i want is >> How can I convert an int number from decimal to binary

答:
You can use ByteBuffer from java.nio. While the NIO can be sometimes cumbersome to use, its ByteBuffers are very nice and easy to use. Also be careful with endianness, by default it is BigEndian, but you can change that.

EDIT

Disregard this, I misread the question. It says convert int array to another int array, not to a byte array. Sorry.

ContentLicense: CC BY-SA 2.5


问:
Deploy in IBM Bluemix
Preparing to start the job...
Downloading build artifacts...
Target: https://api.ng.bluemix.net
Creating service instance simple-rbs-cloudantNoSQLDB in org foodue / space dev as inopark95@gmail.com...
OK
Service simple-rbs-cloudantNoSQLDB already exists
Using manifest file /home/pipeline/f1a258a3-836b-4192-9f3d-c81f0e0448bf/manifest.yml

Creating app simple-rbs-foodue in org foodue / space dev as inopark95@gmail.com...
OK

Creating route simple-rbs.mybluemix.net...
OK

FAILED
Server error, status code: 400, error code: 210003, message: The host is taken: simple-rbs

Finished: FAILED

It says the host is already taken. Do you have any ideas how to fix this problem?

答:
The host is already taken error means that either you or another user are already using that hostname and it is not available for use.  To use a different hostname, modify your manifest.yml file to specify what host to use, or remove the host parameter to default to using <your-app-name>.mybluemix.net.

Example manifest.yml file specifying hostname of my-simple-rbs-hostname.mybluemix.net:

```<code>---
applications:
 - name: simple-rbs
   host: my-simple-rbs-hostname
   domain: mybluemix.net
</code>```

See the Deploying with Application Manifests for more information on options in the manifest.yml file.

Title: Deploy in IBM Bluemix

Body:
The host is already taken error means that either you or another user are already using that hostname and it is not available for use.  To use a different hostname, modify your manifest.yml file to specify what host to use, or remove the host parameter to default to using <your-app-name>.mybluemix.net.

Example manifest.yml file specifying hostname of my-simple-rbs-hostname.mybluemix.net:

---
applications:
 - name: simple-rbs
   host: my-simple-rbs-hostname
   domain: mybluemix.net

See the Deploying with Application Manifests for more information on options in the manifest.yml file.


问:
Pip only install cpu tensorflow of tensorflow 0.11
I previously installed tensorflow-gpu v 0.12 which worked fine, but for a code of a colleague I need v0.11. So I uninstalled tensorflow and tensorflow-gpu 0.12 and I tried to install v 0.11 with:

```<code>pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
</code>```

It successfully installs tensorflow, but not the gpu version, even though in the link above I took the gpu and not cpu version. Apparently, it doesn't matter if I choose cpu or gpu, it always only installs the cpu version.

Any idea how to fix this problem?

答:
For tensorflow versions 0.11.x and below there isn't any tensorflow-gpu package in pip. The wheel corresponding to https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl is the correct wheel with gpu support. If you install this wheel via pip, it'll say Installed tensorflow==0.11.0 but has support of CUDA-8. By downloading the individual wheels, for the cpu and gpu folder have a different md5 signature, hence they are different.

See here.

Body:
I previously installed tensorflow-gpu v 0.12 which worked fine, but for a code of a colleague I need v0.11. So I uninstalled tensorflow and tensorflow-gpu 0.12 and I tried to install v 0.11 with:

pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl

It successfully installs tensorflow, but not the gpu version, even though in the link above I took the gpu and not cpu version. Apparently, it doesn't matter if I choose cpu or gpu, it always only installs the cpu version.

Any idea how to fix this problem?


问:
Spring Rest template trying to parse JSON Response and model it in form of getters and setters
I have following json to parse in spring rest template.I could not see how I could do it.I have never seen such a json, but this is a valid json response.
THis is what I have tried :

```<code> @jsonignoreuknown(true)
class smsresponse {

    private String status;
    private String message;
    private Data data;
    getters/setters

    }

    class Data {

    private String group_id;
    private Map<String,SummaryPOJO> map;
    getters/setters

    }

    class SummaryPOJO {

    private String id;
    private String mobile;
    private String status;
    rest of fields
    getteers/setters

    }

restTemplate.exchange(url,method,null,some paramterhere)
</code>```

Is it right approach and what rest template API should I call to achieve this.

```<code> {
        "status": "OK",
        "data":
        {
            "group_id":zzz,
            "0":
            {
                "id": "wewew-1wewewew",
                "customid": "1",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
               "1":
                {
                "id": "2758-2",
                "customid": "2",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
              }
                ...
        }
        "message": "Campaign Submitted successfully"
    }
</code>```

答:
This answer might not be suitable for all,but it serves my purpose for time being.

```<code> public SmsResponse sendSMS(String recipient, String dynamicMessage) throws Exception {
    String message = URLEncoder.encode(dynamicMessage, "UTF-8");
    String requestUrl = MessageFormat.format(getApiEndPoint(), recipient, message);

    System.out.println("Printing request url from property message" + requestUrl);
    Map<String, Object> smsResponse = getRestTemplate().getForObject(requestUrl, Map.class);
    return createSMSResponseClass(smsResponse);

  }

  private SmsResponse createSMSResponseClass(Map<String, Object> map) {
    SmsResponse smsResponse = new SmsResponse();
    if (map.containsKey("status")) {
      smsResponse.setStatus((String) map.get("status"));
    }
    if (map.containsKey("message")) {
      smsResponse.setMessage((String) map.get("message"));
    }
    if (map.containsKey("data")) {
      Map<String, Object> data = (Map<String, Object>) map.get("data");
      if (data.containsKey("group_id")) {
        smsResponse.setGroupId((String) map.get("group_id"));
}
        if (data.containsKey("0")) {
          Map<String, Object> metaData = (Map<String, Object>) data.get("0");
          ObjectMapper mapper = new ObjectMapper();
          SMSMetaDataObject smsMetaDataObject =
              mapper.convertValue(metaData, SMSMetaDataObject.class);
          smsResponse.setSmsMetaDataObject(smsMetaDataObject);

        }

    }
    logger.info(String.format("Printing sms response object %s", smsResponse.toString()));
    return smsResponse;

  }
</code>```

Body:
I have following json to parse in spring rest template.I could not see how I could do it.I have never seen such a json, but this is a valid json response.
THis is what I have tried :

 @jsonignoreuknown(true)
class smsresponse {

    private String status;
    private String message;
    private Data data;
    getters/setters

    }

    class Data {

    private String group_id;
    private Map<String,SummaryPOJO> map;
    getters/setters

    }

    class SummaryPOJO {

    private String id;
    private String mobile;
    private String status;
    rest of fields
    getteers/setters

    }

restTemplate.exchange(url,method,null,some paramterhere)

Is it right approach and what rest template API should I call to achieve this.

 {
        "status": "OK",
        "data":
        {
            "group_id":zzz,
            "0":
            {
                "id": "wewew-1wewewew",
                "customid": "1",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
               "1":
                {
                "id": "2758-2",
                "customid": "2",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
              }
                ...
        }
        "message": "Campaign Submitted successfully"
    }

Body:
This answer might not be suitable for all,but it serves my purpose for time being.

 public SmsResponse sendSMS(String recipient, String dynamicMessage) throws Exception {
    String message = URLEncoder.encode(dynamicMessage, "UTF-8");
    String requestUrl = MessageFormat.format(getApiEndPoint(), recipient, message);

    System.out.println("Printing request url from property message" + requestUrl);
    Map<String, Object> smsResponse = getRestTemplate().getForObject(requestUrl, Map.class);
    return createSMSResponseClass(smsResponse);

  }

  private SmsResponse createSMSResponseClass(Map<String, Object> map) {
    SmsResponse smsResponse = new SmsResponse();
    if (map.containsKey("status")) {
      smsResponse.setStatus((String) map.get("status"));
    }
    if (map.containsKey("message")) {
      smsResponse.setMessage((String) map.get("message"));
    }
    if (map.containsKey("data")) {
      Map<String, Object> data = (Map<String, Object>) map.get("data");
      if (data.containsKey("group_id")) {
        smsResponse.setGroupId((String) map.get("group_id"));
}
        if (data.containsKey("0")) {
          Map<String, Object> metaData = (Map<String, Object>) data.get("0");
          ObjectMapper mapper = new ObjectMapper();
          SMSMetaDataObject smsMetaDataObject =
              mapper.convertValue(metaData, SMSMetaDataObject.class);
          smsResponse.setSmsMetaDataObject(smsMetaDataObject);

        }

    }
    logger.info(String.format("Printing sms response object %s", smsResponse.toString()));
    return smsResponse;

  }


问:
Replace gives different outcomes based on length of string
I use the following code to convert values entered in US format (0.8) to a propper format (0,8).

For row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(row, col), ".") > 0 Then
            wsg.Cells(row, col).Value = Replace(wsg.Cells(row, col), ".", ",")
        End If
    Next col
Next row

This usually works well, except for the case that there are 4 decimal places. In the case of 19.1991 it gets converted to 191991, instead of 19,1991. Whilst this is done the format of the cell also changes automatically to the numberformat, instead of the text format I set in my code. For values with 1 or 2 decimal places this doesn't happen.

答:
add single quote '

```<code>For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).Value = "'" & (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row
</code>```

Or

```<code>For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).NumberFormatLocal = "@"
            wsg.Cells(Row, col).Value = (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row
</code>```

Body:
add single quote '

For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).Value = "'" & (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row

Or

For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).NumberFormatLocal = "@"
            wsg.Cells(Row, col).Value = (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row


问:
Search many expressions in many documents using Python
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched).

So slow pseudo version of code is

```<code>for text in documents:
     for word in words:
             position = search(word, text)
             if position:
                  print word, position
</code>```

Is there any fast Python module for doing this? Or should I implement something myself?

答:
For fast exact-text, multi-keyword search, try acora - http://pypi.python.org/pypi/acora/1.4

If you want a few extras - result relevancy, near-matches, word-rooting etc, Whoosh might be better - http://pypi.python.org/pypi/Whoosh/1.4.1

I don't know how well either scales to millions of docs, but it wouldn't take long to find out!

Body:
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched).

So slow pseudo version of code is

for text in documents:
     for word in words:
             position = search(word, text)
             if position:
                  print word, position

Is there any fast Python module for doing this? Or should I implement something myself?


问:
Crypto JS: TripleDES not encrypting properly
When using crypto js tripleDES to encrypt, I noticed that all strings to encrypt which are of small length e.g "01", "111", "20" encrypt properly but with long strings like "5000021234567890000", the output isn't correct or is not the value I am expecting.
For example for this "5000021234567890000", I am expecting this: "HctDaKc/U9avOwZMSS5mEi62kfojDHA4" but I get this instead: HctDaKc/U9bNnFy6eZHqHj3SemorJxQM.

This is the code I found and using to encrypt

```<code>let key = CryptoJS.MD5(enckey);
key.words[4] = key.words[0];
key.words[5] = key.words[1];
let iv = CryptoJS.lib.WordArray.create(64/8);
CryptoJS.TripleDES.encrypt("5000021234567890000", key, {iv: iv});
</code>```

Your help would be very much appreciated.

答:
Looking at the encrypted data the first blocks match and the following two blocks do not.

```
    HctDaKc/U9avOwZMSS5mEi62kfojDHA4
    1DCB4368A73F53D6 AF3B064C492E6612 2EB691FA230C7038

    HctDaKc/U9bNnFy6eZHqHj3SemorJxQM
    1DCB4368A73F53D6 CD9C5CBA7991EA1E 3DD27A6A2B27140C
```

The IV is presumably all 0x00 bytes.

THis indicates one is using ECB m ode and the other is using CBC mode.

See Block cipher mode of operation, specifically ECB and CBC modes.

ECB mode encrypted each block independly, CBC mode xors the previous block with the data to be encrypted and for the first block the IV. Since the IV is all 0x00 values no change is made to the first block.

Options can be specified in the createion of the encryptor, you need to see the documentation page, good luck with that.

It would look something like:

```<code>encryptor = crypto.createCipheriv( mode, key, iv)
</code>```

where mode is one of: 'des-ede', 'des-ede-cbc', 'des-ede3', 'des-ede3-cbc', 'des3'

Body:
When using crypto js tripleDES to encrypt, I noticed that all strings to encrypt which are of small length e.g "01", "111", "20" encrypt properly but with long strings like "5000021234567890000", the output isn't correct or is not the value I am expecting.
For example for this "5000021234567890000", I am expecting this: "HctDaKc/U9avOwZMSS5mEi62kfojDHA4" but I get this instead: HctDaKc/U9bNnFy6eZHqHj3SemorJxQM.

This is the code I found and using to encrypt

let key = CryptoJS.MD5(enckey);
key.words[4] = key.words[0];
key.words[5] = key.words[1];
let iv = CryptoJS.lib.WordArray.create(64/8);
CryptoJS.TripleDES.encrypt("5000021234567890000", key, {iv: iv});

Your help would be very much appreciated.

Body:
Looking at the encrypted data the first blocks match and the following two blocks do not.

    HctDaKc/U9avOwZMSS5mEi62kfojDHA4
    1DCB4368A73F53D6 AF3B064C492E6612 2EB691FA230C7038

    HctDaKc/U9bNnFy6eZHqHj3SemorJxQM
    1DCB4368A73F53D6 CD9C5CBA7991EA1E 3DD27A6A2B27140C

The IV is presumably all 0x00 bytes.

THis indicates one is using ECB m ode and the other is using CBC mode.

See Block cipher mode of operation, specifically ECB and CBC modes.

ECB mode encrypted each block independly, CBC mode xors the previous block with the data to be encrypted and for the first block the IV. Since the IV is all 0x00 values no change is made to the first block.

Options can be specified in the createion of the encryptor, you need to see the documentation page, good luck with that.

It would look something like:

encryptor = crypto.createCipheriv( mode, key, iv)

where mode is one of: 'des-ede', 'des-ede-cbc', 'des-ede3', 'des-ede3-cbc', 'des3'


问:
How to convert from std::io::Bytes to &[u8]
I am trying to write the contents of an HTTP Response to a file.

```<code>extern crate reqwest;

use std::io::Write;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    f.write_all(resp.bytes());
}
</code>```

But I get the following compile error:

error[E0308]: mismatched types
  --> src/main.rs:12:17
   |
12 |     f.write_all(resp.bytes());
   |                 ^^^^^^^^^^^^ expected &[u8], found struct `std::io::Bytes`
   |
   = note: expected type `&[u8]`
              found type `std::io::Bytes<reqwest::Response>`
```

答:
You cannot. Checking the docs for io::Bytes, there are no appropriate methods. That's because io::Bytes is an iterator that returns things byte-by-byte so there may not even be a single underlying slice of data.

It you only had io::Bytes, you would need to collect the iterator into a Vec:

```<code>let data: Result<Vec<_>, _> = resp.bytes().collect();
let data = data.expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");
</code>```

However, in most cases you have access to the type that implements Read, so you could instead use Read::read_to_end:

```<code>let mut data = Vec::new();
resp.read_to_end(&mut data).expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");
</code>```

In this specific case, you can use io::copy to directly copy from the Request to the file because Request implements io::Read and File implements io::Write:

```<code>extern crate reqwest;

use std::io;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    io::copy(&mut resp, &mut f).expect("Unable to copy data");
}
</code>```

Body:
I am trying to write the contents of an HTTP Response to a file.

extern crate reqwest;

use std::io::Write;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    f.write_all(resp.bytes());
}

But I get the following compile error:

error[E0308]: mismatched types
  --> src/main.rs:12:17
   |
12 |     f.write_all(resp.bytes());
   |                 ^^^^^^^^^^^^ expected &[u8], found struct `std::io::Bytes`
   |
   = note: expected type `&[u8]`
              found type `std::io::Bytes<reqwest::Response>`

Body:
You cannot. Checking the docs for io::Bytes, there are no appropriate methods. That's because io::Bytes is an iterator that returns things byte-by-byte so there may not even be a single underlying slice of data.

It you only had io::Bytes, you would need to collect the iterator into a Vec:

let data: Result<Vec<_>, _> = resp.bytes().collect();
let data = data.expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

However, in most cases you have access to the type that implements Read, so you could instead use Read::read_to_end:

let mut data = Vec::new();
resp.read_to_end(&mut data).expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

In this specific case, you can use io::copy to directly copy from the Request to the file because Request implements io::Read and File implements io::Write:

extern crate reqwest;

use std::io;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    io::copy(&mut resp, &mut f).expect("Unable to copy data");
}


问:
Get specific part of a URL with JavaScript
I'm new to JavaScript, I need help solving a problem.

I have the following URL:

http://localhost/solo04/index.php?route=checkout/checkout#shipping-method

I would like to just get that part of the url (route =checkout/checkout) how to do this?

答:
I'd like to throw this out too cause I don't think it's been mentioned here.
You can use the new URL API too to avoid any regex or any string manipulation that I'm seeing on some of the answers here.

But this is relatively new so support for this in older browsers might be limited.

e.g:

```<code>var myURL = new URL('http://localhost/solo04/index.php?q=somequery');
console.log(myURL);
</code>```

That will give you an object which should have path, hostname, search etc.

Body:
I'd like to throw this out too cause I don't think it's been mentioned here.
You can use the new URL API too to avoid any regex or any string manipulation that I'm seeing on some of the answers here.

But this is relatively new so support for this in older browsers might be limited.

e.g:

var myURL = new URL('http://localhost/solo04/index.php?q=somequery');
console.log(myURL);

That will give you an object which should have path, hostname, search etc.


问:
How to detect mouse moving while left button down?
I would like to detect mouse movement while the left button is pressed.

I'm simply creating a drawing application. I can detect mouse movement without any mouse being pressed. But I want to detect it WITH left mouse pressed.

I don't think there's a listener for this. So, what is the idea to do that?

答: there is mouseDragged method in MouseMotionListener...check this out for more details...</p>


问:
Django 1.7 makemigrations - ValueError: Cannot serialize class
I'm running into an interesting issue with an upgrade from Django 1.6.11 to 1.7. It seems to be based on how I am currently splitting up files. Currently, model methods are stored in separate files from the models, due to the massive amount of methods.

For example it is split up as follows:

```<code>help
|_ modelmethods
|  |_ __init__.py
|  |_ thread_methods.py
|_ __init__.py
|_ models.py
</code>```

The __init__.py in the help app folder looks like so:

```<code>""" __init__.py for help app."""

from help.modelmethods.thread_methods import *
</code>```

And thread_methods.py looks like this:

```<code>"""Methods for the Thread model."""

from help.models import Thread

class ThreadMethods:

    """Adds methods on to the Thread model."""

    def do_the_thing(self):
        pass

Thread.__bases__ += (ThreadMethods,)
</code>```

The error that I'm seeing from this is as follows:

```<code>Migrations for 'help':
  0001_initial.py:
    - Create model Thread
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 124, in handle
    self.write_migration_files(changes)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
    migration_string = writer.as_string()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 129, in as_string
    operation_string, operation_imports = OperationWriter(operation).serialize()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 86, in serialize
    arg_string, arg_imports = MigrationWriter.serialize(arg_value)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 245, in serialize
    item_string, item_imports = cls.serialize(item)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 380, in serialize
    raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
ValueError: Cannot serialize: <class help.modelmethods.thread_methods.ThreadMethods at 0x1105c3870>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing
</code>```

I realize that it is attempting to serialize the class and choking on it. Is there a good way to fix this and keep the separation? Or would the only comparable way be to break up the models.py file into a models folder with the proper __init__.py setup and each file be dedicated to one model that also contains all the relevant methods (as well as making sure no circular imports were introduced).

答:
I was unable to migrate because of a custom validator. My problem was that I have not read the manual properly, where it says:

If a class-based validator is used in the validators model field
  option, you should make sure it is serializable by the migration
  framework by adding deconstruct() and __eq__() methods.

Which points to the migrations-docs which explain why you need the deconstruct() and __eq__() and how to write them.

Should also work for other classes and not just for validators.

Body:
I'm running into an interesting issue with an upgrade from Django 1.6.11 to 1.7. It seems to be based on how I am currently splitting up files. Currently, model methods are stored in separate files from the models, due to the massive amount of methods.

For example it is split up as follows:

help
|_ modelmethods
|  |_ __init__.py
|  |_ thread_methods.py
|_ __init__.py
|_ models.py

The __init__.py in the help app folder looks like so:

""" __init__.py for help app."""

from help.modelmethods.thread_methods import *

And thread_methods.py looks like this:

"""Methods for the Thread model."""

from help.models import Thread

class ThreadMethods:

    """Adds methods on to the Thread model."""

    def do_the_thing(self):
        pass

Thread.__bases__ += (ThreadMethods,)

The error that I'm seeing from this is as follows:

Migrations for 'help':
  0001_initial.py:
    - Create model Thread
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 124, in handle
    self.write_migration_files(changes)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
    migration_string = writer.as_string()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 129, in as_string
    operation_string, operation_imports = OperationWriter(operation).serialize()
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 86, in serialize
    arg_string, arg_imports = MigrationWriter.serialize(arg_value)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 245, in serialize
    item_string, item_imports = cls.serialize(item)
  File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 380, in serialize
    raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
ValueError: Cannot serialize: <class help.modelmethods.thread_methods.ThreadMethods at 0x1105c3870>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing

I realize that it is attempting to serialize the class and choking on it. Is there a good way to fix this and keep the separation? Or would the only comparable way be to break up the models.py file into a models folder with the proper __init__.py setup and each file be dedicated to one model that also contains all the relevant methods (as well as making sure no circular imports were introduced).


问:
C - Segmentation Fault when using malloc with large size paramater
I'm running into a segfault when allocating a dynamic array of large size.

As a specific example, the below code causes a segfault.

```<code>int max = 1399469912;
int *arr = (int*) malloc((max+1) * sizeof(int));
arr[0] = 1;
</code>```

However, if I replace max with something smaller like 5, then I get no segfault.

Why does this happen? Or, is there another solution to achieve the same effect? I need a dynamically allocated array of significant size.

Thanks

答:
Reed documentation of malloc (or malloc(3) from Linux man page)

It can fail, and then returns NULL; and your code should handle that case:

```<code>int *arr = malloc((max+1) * sizeof(int));
if (!arr) { perror("malloc arr"); exit(EXIT_FAILURE); };
</code>```

You could handle the failure in some other ways, but errno is giving the reason. In practice, recovering a malloc or calloc failure is quite tricky. In most cases, exiting abruptly like above is the simplest thing to do. In some cases (think of a server program which should run continuously) you can do otherwise (but that is difficult).

Read also about memory overcommitment (a whole system configurable thing or feature, that I personally dislike and disable, because it might make malloc apparently succeed when memory resources are exhausted; on Linux read about Out-of-memory killer)

See also this (a silly implementation of malloc)

BTW, you need to be sure that (max+1) * sizeof(int) is not overflowing, and you'll better define size_t max = 1399469912; (not int).

Notice that you are requesting (on systems having sizeof(int)==4 like my Linux/x86-64 desktop) more than five gigabytes. This is a significant amount of virtual address space.

Body:
I'm running into a segfault when allocating a dynamic array of large size.

As a specific example, the below code causes a segfault.

int max = 1399469912;
int *arr = (int*) malloc((max+1) * sizeof(int));
arr[0] = 1;

However, if I replace max with something smaller like 5, then I get no segfault.

Why does this happen? Or, is there another solution to achieve the same effect? I need a dynamically allocated array of significant size.

Thanks

Body:
Reed documentation of malloc (or malloc(3) from Linux man page)

It can fail, and then returns NULL; and your code should handle that case:

int *arr = malloc((max+1) * sizeof(int));
if (!arr) { perror("malloc arr"); exit(EXIT_FAILURE); };

You could handle the failure in some other ways, but errno is giving the reason. In practice, recovering a malloc or calloc failure is quite tricky. In most cases, exiting abruptly like above is the simplest thing to do. In some cases (think of a server program which should run continuously) you can do otherwise (but that is difficult).

Read also about memory overcommitment (a whole system configurable thing or feature, that I personally dislike and disable, because it might make malloc apparently succeed when memory resources are exhausted; on Linux read about Out-of-memory killer)

See also this (a silly implementation of malloc)

BTW, you need to be sure that (max+1) * sizeof(int) is not overflowing, and you'll better define size_t max = 1399469912; (not int).

Notice that you are requesting (on systems having sizeof(int)==4 like my Linux/x86-64 desktop) more than five gigabytes. This is a significant amount of virtual address space.


问:
How to set up cluster environment for Spark applications on Windows machines?
I have been developing in pyspark with spark standalone non-cluster mode. These days, I would like to explore more on the cluster mode of spark. I searched on the internet, and found I may need a cluster manager to run clusters in different machines using Apache Mesos or Spark Standalone. But, I couldn't easily find details of the picture. </p>

<p>How should I set up from system design point of view in order to run spark clusters in multiple windows machines (or multiple windows vms). </p>

答:
You may want to explore (from the simplest) Spark Standalone, through Hadoop YARN to Apache Mesos or DC/OS. See Cluster Mode Overview.

I'd recommend using Spark Standalone first (as the easiest option to submit Spark applications to). Spark Standalone is included in any Spark installation and works fine on Windows. The issue is that there are no scripts to start and stop the standalone Master and Workers (aka slaves) for Windows OS. You simply have to "code" them yourself.

Use the following to start a standalone Master on Windows:

```<code>// terminal 1
bin\spark-class org.apache.spark.deploy.master.Master
</code>```

Please note that after you start the standalone Master you get no input, but don't worry and head over to http://localhost:8080/ to see the web UI of the Spark Standalone cluster.

In a separate terminal start an instance of the standalone Worker.

```<code>// terminal 2
bin\spark-class org.apache.spark.deploy.worker.Worker spark://localhost:7077
</code>```

With one-worker Spark Standalone cluster up, you should be able to submit Spark applications as follows:

```<code>spark-submit --master spark://localhost:7077 ...
</code>```

Read Spark Standalone Mode in the official documentation of Spark.

As I just found out Mesos is not an option given its System Requirements:

Mesos runs on Linux (64 Bit) and Mac OS X (64 Bit).

You could however run any of the clusters using virtual machines using VirtualBox or similar. At least DC/OS has dcos-vagrant that should make it fairly easy:

dcos-vagrant Quickly provision a DC/OS cluster on a local machine for development, testing, or demonstration.

Deploying DC/OS Vagrant involves creating a local cluster of VirtualBox VMs using the dcos-vagrant-box base image and then installing DC/OS.

Body:
I have been developing in pyspark with spark standalone non-cluster mode. These days, I would like to explore more on the cluster mode of spark. I searched on the internet, and found I may need a cluster manager to run clusters in different machines using Apache Mesos or Spark Standalone. But, I couldn't easily find details of the picture.

How should I set up from system design point of view in order to run spark clusters in multiple windows machines (or multiple windows vms).

Body:
You may want to explore (from the simplest) Spark Standalone, through Hadoop YARN to Apache Mesos or DC/OS. See Cluster Mode Overview.

I'd recommend using Spark Standalone first (as the easiest option to submit Spark applications to). Spark Standalone is included in any Spark installation and works fine on Windows. The issue is that there are no scripts to start and stop the standalone Master and Workers (aka slaves) for Windows OS. You simply have to "code" them yourself.

Use the following to start a standalone Master on Windows:

// terminal 1
bin\spark-class org.apache.spark.deploy.master.Master

Please note that after you start the standalone Master you get no input, but don't worry and head over to http://localhost:8080/ to see the web UI of the Spark Standalone cluster.

In a separate terminal start an instance of the standalone Worker.

// terminal 2
bin\spark-class org.apache.spark.deploy.worker.Worker spark://localhost:7077

With one-worker Spark Standalone cluster up, you should be able to submit Spark applications as follows:

spark-submit --master spark://localhost:7077 ...

Read Spark Standalone Mode in the official documentation of Spark.

As I just found out Mesos is not an option given its System Requirements:

Mesos runs on Linux (64 Bit) and Mac OS X (64 Bit).

You could however run any of the clusters using virtual machines using VirtualBox or similar. At least DC/OS has dcos-vagrant that should make it fairly easy:

dcos-vagrant Quickly provision a DC/OS cluster on a local machine for development, testing, or demonstration.

Deploying DC/OS Vagrant involves creating a local cluster of VirtualBox VMs using the dcos-vagrant-box base image and then installing DC/OS.


问:
Angular2 - What folder for custom CSS / JS files?
I have to include a set of CSS and JS files in my angular2 application.

What is the correct folder in order to have them included when I do the build?

Should I have to put them inside SRC\Assets or under SRC\myFolder ?

Once defined it, how do I have to include them inside my app.component.html and how to configure <base href="/"> properly?

Thanks to support

答:
If your using the Angular CLI then you can put them anywhere, but I would suggest in a logical place that makes sense in your src/assets folder.

From there add entries for the js and css files in your angular.cli.json file.

there is a scripts array and a styles array under each object/app in the apps node.

look for something like ...

```<code>apps: [
 {
   ...
   "styles": [ "assets/styles/myCustomStyles.css" ],
   "scripts": [ "assets/js/dragevents.js" ]
 }
]
</code>```

If done correctly the cli will automatically add them to your index when it builds.

Body:
If your using the Angular CLI then you can put them anywhere, but I would suggest in a logical place that makes sense in your src/assets folder.

From there add entries for the js and css files in your angular.cli.json file.

there is a scripts array and a styles array under each object/app in the apps node.

look for something like ...

apps: [
 {
   ...
   "styles": [ "assets/styles/myCustomStyles.css" ],
   "scripts": [ "assets/js/dragevents.js" ]
 }
]

If done correctly the cli will automatically add them to your index when it builds.


问:
Generating XML reports using LINQ to XML in C#
I'm generating reports using LINQ to XML in C#.
For example, I want to generate a report formatted like:

```<code><report>
    <canada>
        <division_1>
            <power generated="22" dailygoal="25" />
            <resources used="15" available="50" />
        </division_1>
        <division_2>
            <power generated="36" dailygoal="40" />
            <resources used="28" available="85" />
        </division_2>
    </canada>
</report>
</code>```

How can I generate an XML file (with one root element) with this format in C# by using foreach loops and object methods to fill the data like so, since I'm getting the data from power and resources objects?:

```<code>foreach (var i in powerList)
{
    division_1.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
{
</code>```

Can I do this with an XDocument object, or do I need to initialize division_1 and division_2 as XElements, do .Add to add the info to the XElements, .Save the XElements as .xml docs, then merge and save them as one doc?

Update:

I've modified the code to look like this...:

```<code>namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {

        // list of power objects...

        List<Power> powerList = new List<Power>();

        Power canada = new Power("canada", 25, 50, 70, 100);
        Power usa = new Power("usa", 45, 60, 80, 150);
        Power sweden = new Power("sweden", 50, 60, 70, 80);
        Power germany = new Power("germany", 65, 75, 90, 125);

        powerList.Add(canada);
        powerList.Add(usa);
        powerList.Add(sweden);
        powerList.Add(germany);

        // create report var and element..

        var report = new XElement("report");

        // foreach...
        foreach (var x in powerList)
        {

            var country = new XElement(x.Country);
            report.Add(country);

            var n = 0;

            //foreach...
            foreach (var i in powerList)
            {
                ++n;

                var division = new XElement("division_" + n);

                division.Add(
                    new XElement("power",
                        new XAttribute("generated", i.powerGenerated),
                        new XAttribute("dailygoal", i.powerGoal)),
                    new XElement("resources",
                        new XAttribute("used", i.resourcesUsed),
                        new XAttribute("available", i.resourcesAvailable)));
                country.Add(division);
            }
        }

        // create xdocument from xelement and save to disk...

        XDocument xml = new XDocument();
        xml.Add(report);

        xml.Save(@".\report.xml");
    }
}
}
</code>```

... but it's generating, for example:

```<code><canada>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</canada>
<usa>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</usa>
</code>```

In the loop it's generating the same data for all objects each run through. Do you see what the issue is and how it could be fixed? I've tried multiple approaches and can't seem to get it.

答:
Yes you could use XElement:

```<code>  var root = new XElement("report");
  var canada=new XElement("canada");
  root.Add(canada);
  for(int i=0;i<powerList.Count();i++)
  {
        canada.Add(new XElement("division"+(i+1).ToString(),
        new XElement("power",
            new XAttribute("generated", powerList[i].powerGenerated),
            new XAttribute("dailygoal", powerList[i].powerGoal)),
        new XElement("resources",
            new XAttribute("used", powerList[i].resourcesUsed),
            new XAttribute("available", powerList[i].resourcesAvailable))));
  }
  root.Save("Root.xml");
</code>```

XElement has a Save method.

Body:
I'm generating reports using LINQ to XML in C#.
For example, I want to generate a report formatted like:

<report>
    <canada>
        <division_1>
            <power generated="22" dailygoal="25" />
            <resources used="15" available="50" />
        </division_1>
        <division_2>
            <power generated="36" dailygoal="40" />
            <resources used="28" available="85" />
        </division_2>
    </canada>
</report>

How can I generate an XML file (with one root element) with this format in C# by using foreach loops and object methods to fill the data like so, since I'm getting the data from power and resources objects?:

foreach (var i in powerList)
{
    division_1.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
{

Can I do this with an XDocument object, or do I need to initialize division_1 and division_2 as XElements, do .Add to add the info to the XElements, .Save the XElements as .xml docs, then merge and save them as one doc?

Update:

I've modified the code to look like this...:

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {

        // list of power objects...

        List<Power> powerList = new List<Power>();

        Power canada = new Power("canada", 25, 50, 70, 100);
        Power usa = new Power("usa", 45, 60, 80, 150);
        Power sweden = new Power("sweden", 50, 60, 70, 80);
        Power germany = new Power("germany", 65, 75, 90, 125);

        powerList.Add(canada);
        powerList.Add(usa);
        powerList.Add(sweden);
        powerList.Add(germany);

        // create report var and element..

        var report = new XElement("report");

        // foreach...
        foreach (var x in powerList)
        {

            var country = new XElement(x.Country);
            report.Add(country);

            var n = 0;

            //foreach...
            foreach (var i in powerList)
            {
                ++n;

                var division = new XElement("division_" + n);

                division.Add(
                    new XElement("power",
                        new XAttribute("generated", i.powerGenerated),
                        new XAttribute("dailygoal", i.powerGoal)),
                    new XElement("resources",
                        new XAttribute("used", i.resourcesUsed),
                        new XAttribute("available", i.resourcesAvailable)));
                country.Add(division);
            }
        }

        // create xdocument from xelement and save to disk...

        XDocument xml = new XDocument();
        xml.Add(report);

        xml.Save(@".\report.xml");
    }
}
}

... but it's generating, for example:

<canada>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</canada>
<usa>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</usa>

In the loop it's generating the same data for all objects each run through. Do you see what the issue is and how it could be fixed? I've tried multiple approaches and can't seem to get it.

Body:
Yes you could use XElement:

  var root = new XElement("report");
  var canada=new XElement("canada");
  root.Add(canada);
  for(int i=0;i<powerList.Count();i++)
  {
        canada.Add(new XElement("division"+(i+1).ToString(),
        new XElement("power",
            new XAttribute("generated", powerList[i].powerGenerated),
            new XAttribute("dailygoal", powerList[i].powerGoal)),
        new XElement("resources",
            new XAttribute("used", powerList[i].resourcesUsed),
            new XAttribute("available", powerList[i].resourcesAvailable))));
  }
  root.Save("Root.xml");

XElement has a Save method.


问:
Missing required gems when execute cron created by whenever gem in production environment
I've ruby on rails application running in production, this apps have STOCK model and it should be updated every 1 minute.

For updating this model i create simple rake task db:populate:stocks, when it contain only two operation :

truncate the STOCK model

fill STOCK model with latest data fetch from webservice

this rake task should be execute every 1 minute, for this purpose i use whenever gem. Here my schedule.rb :

```<code>env :PATH, ENV['PATH']
set :job_template, nil
set :output, {:standard => '/home/admin/shared/log/cron.log', :error => '/home/admin/shared/log/cron-error.log'}

job_type :rake, "cd :path && rake :task RAILS_ENV=:environment --trace :output"

every 1.minute do
  rake "db:populate:stocks"
end
</code>```

In production i'm using rvm running ruby 1.9.2-p180, rails 3.1.0 and capistrano, here my capistrano task for update cron tab :

```<code>after "deploy:update_code" do
 run "cd #{release_path} && whenever --clear-crontab RAILS_ENV=production"
 run "cd #{release_path} && whenever --update-crontab RAILS_ENV=production"
end
</code>```

And my schedule.rb create cron task like :

```<code># Begin Whenever generated tasks for: RAILS_ENV=production
PATH=/home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin:/home/admin/.rvm//gems/ruby-1.9.2-p180@global/bin:/home/admin/.rvm//rubies/ruby-1.9.2-p180/bin:/home/admin/.rvm//bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

* * * * * cd /home/admin/releases/20120904103658 && RAILS_ENV=production rake db:populate:stocks --trace >> /home/admin/shared/log/cron.log 2>> /home/admin/shared/log/cron-error.log
</code>```

THE PROBLEM is the cron task failed to execute the rake task, from cron-error.log :

```<code>/home/admin/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:314:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
from /home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin/rake:19:in `<main>'
</code>```

What i'm missing here, why the cron job failed to load my env ? Is there any problem with my  schedule.rb ?

答:
I have similar problem and I fix with

```<code>rvm cron setup
</code>```

in server. This add rvm env variables (PATH, GEM_HOME,GEM_PATH...) to my cronjob.

I have to delete the set command

```<code>env :PATH, ENV['PATH']
</code>```

Body:
I've ruby on rails application running in production, this apps have STOCK model and it should be updated every 1 minute.

For updating this model i create simple rake task db:populate:stocks, when it contain only two operation :

truncate the STOCK model

fill STOCK model with latest data fetch from webservice

this rake task should be execute every 1 minute, for this purpose i use whenever gem. Here my schedule.rb :

env :PATH, ENV['PATH']
set :job_template, nil
set :output, {:standard => '/home/admin/shared/log/cron.log', :error => '/home/admin/shared/log/cron-error.log'}

job_type :rake, "cd :path && rake :task RAILS_ENV=:environment --trace :output"

every 1.minute do
  rake "db:populate:stocks"
end

In production i'm using rvm running ruby 1.9.2-p180, rails 3.1.0 and capistrano, here my capistrano task for update cron tab :

after "deploy:update_code" do
 run "cd #{release_path} && whenever --clear-crontab RAILS_ENV=production"
 run "cd #{release_path} && whenever --update-crontab RAILS_ENV=production"
end

And my schedule.rb create cron task like :

# Begin Whenever generated tasks for: RAILS_ENV=production
PATH=/home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin:/home/admin/.rvm//gems/ruby-1.9.2-p180@global/bin:/home/admin/.rvm//rubies/ruby-1.9.2-p180/bin:/home/admin/.rvm//bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

* * * * * cd /home/admin/releases/20120904103658 && RAILS_ENV=production rake db:populate:stocks --trace >> /home/admin/shared/log/cron.log 2>> /home/admin/shared/log/cron-error.log

THE PROBLEM is the cron task failed to execute the rake task, from cron-error.log :

/home/admin/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:314:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
from /home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin/rake:19:in `'

What i'm missing here, why the cron job failed to load my env ? Is there any problem with my  schedule.rb ?

Body:
I have similar problem and I fix with

rvm cron setup

in server. This add rvm env variables (PATH, GEM_HOME,GEM_PATH...) to my cronjob.

I have to delete the set command

env :PATH, ENV['PATH']


问:
Is there a way to recreate an ODI package using ODI Scenario?
I mistakenly deleted an ODI package from my project which is very large in size. Is there a way to recreate the same package if I have a previously exported scenario for the same project?</p>

答:
Unfortunately there isn't any way to directly generate a deleted package from a scenario which you can see as a compiled version of the package.

Here are a couple of things to check to see if you can retrieve some information :

When promoting from one environment to another, it's recommended to export the base object along with the scenario. That way you keep track of what was the code behind that scenario (black box). Bonus points if it's all versioned in a version control system (VCS).

Starting with ODI 12.2.1, VCS can be directly integrated within ODI to version your code and create release archives. If that's the case you can restore a deleted object

Before 12.2.1 it was possible to use the internal versioning system of ODI that would store the objects in the Master Repository. You can restore it from the top menu.

If nothing of that is setup, you can still open the scenario export in any file editor and manually go through it to retrieve the logic. It's just an XML files that describes the different steps of your package. That would help you to rebuild it manually.

If you end up doing that last bullet point, now is probably a good time to improve your existing procedures and setup one of the three backup/versioning solutions mentioned above so it doesn't happen in the future.


问:
(Swift) pan & zoom constrained to a certain size image
I am trying to pan and zoom across an image background in spritekit, I have managed to get the zoom working ok and manually entered some restrictions on how far you can pan the image, however the problem is when you pan the screen right to the edge of the image and then zoom out the background shows.
I want the camera to restrict only to the image on screen and not any blank background. Any ideas on how I should do this or any better solutions?
Here is what I got so far</p>

```<code>class GameScene:SKScene{
 var cam: SKCameraNode!
 var scaleNum:CGFloat=1

 override func didMove(to view: SKView){
    cam=SKCameraNode()
    cam.setScale(CGFloat(scaleNum))
    self.camera=cam
    self.addChild(cam)
    let gesture=UIPinchGestureRecognizer(target: self, action: #selector(zoomIn(recognizer:)))
    self.view!.addGestureRecognizer(gesture)
}

func zoomIn(recognizer: UIPinchGestureRecognizer){
    if recognizer.state == .changed{
        cam.setScale(recognizer.scale)
        scaleNum=recognizer.scale
        if cam.xScale<1 || cam.yScale<1{
            cam.setScale(1)
        }
        if cam.xScale>3 || cam.yScale > 3{
            cam.setScale(3)
       }
       // recognizer.scale=1
       test()
    }
}

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
   let firstTouch=touches.first
        let location=(firstTouch?.location(in: self))!
        let previousLocation=firstTouch?.previousLocation(in: self)
        cam?.position.x -= location.x - (previousLocation?.x)!
        cam?.position.y -= location.y - (previousLocation?.y)!
        test()
}

func test(){
    if cam.position.x < 1000*scaleNum{
        cam.position.x=1000*scaleNum
    }
    if cam.position.x > 9200*scaleNum{
        cam.position.x=9200*scaleNum
    }
    if cam.position.y<617*scaleNum{
        cam.position.y=617*scaleNum
    }
    if cam.position.y>4476*scaleNum{
        cam.position.y=4476*scaleNum
    }
  }
}
</code>```

答:
First of all, I would change your zoomIn function to this:

```<code>func zoomIn(recognizer: UIPinchGestureRecognizer){
   if recognizer.state == .changed {
       scaleNum = recognizer.scale
       if scaleNum < 1 { scaleNum = 1 }
       if scaleNum > 3 { scaleNum = 3 }
       cam.setScale(scaleNum)
       test()
   }
}
</code>```

It is easier to understand, you're not setting the camera scale twice, and most importantly, when you clamp the camera scale, scaleNum reflects that clamped value.  This was not the case before, and in fact, that small change might be your entire problem.

Now I don't have much experience with UIPinchGestureRecognizer but I think the reason your zoom gesture works "ok" is because you are assigning directly from recognizer.scale to cam scale.  Correct me if I'm wrong, but I think UIGestureRecognizer always starts with a scale of 1 for each new gesture, but your camera scale maintains its last value.

As an example, imagine your camera is at a scale of 1. A user zooms in to a scale of 2, the scene zooms in perfectly.  The user lifts their fingers ending the gesture.  Then the user tries to zoom in more, so they begin a new gesture, starting with a scale of 1, but your scene is still at a scale of 2.  You can't assign the gesture scale directly or the image scale will 'jump' back to 1 for each new gesture.  You have to convert from the gesture scale space to the camera scale space.

How exactly you do this is a design and feel choice.  With no experience, my advice would be to change the line in my zoomIn function from

```<code>`scaleNum = recognizer.scale'
</code>```

to

```<code>`scaleNum *= recognizer.scale`
</code>```

Try both versions, and let me know how they work.  If there is still a problem, then it most likely resides in your test() function.  If so, I will try and help out with that as needed.

Body:
I am trying to pan and zoom across an image background in spritekit, I have managed to get the zoom working ok and manually entered some restrictions on how far you can pan the image, however the problem is when you pan the screen right to the edge of the image and then zoom out the background shows.
I want the camera to restrict only to the image on screen and not any blank background. Any ideas on how I should do this or any better solutions?
Here is what I got so far

class GameScene:SKScene{
 var cam: SKCameraNode!
 var scaleNum:CGFloat=1

 override func didMove(to view: SKView){
    cam=SKCameraNode()
    cam.setScale(CGFloat(scaleNum))
    self.camera=cam
    self.addChild(cam)
    let gesture=UIPinchGestureRecognizer(target: self, action: #selector(zoomIn(recognizer:)))
    self.view!.addGestureRecognizer(gesture)
}

func zoomIn(recognizer: UIPinchGestureRecognizer){
    if recognizer.state == .changed{
        cam.setScale(recognizer.scale)
        scaleNum=recognizer.scale
        if cam.xScale<1 || cam.yScale<1{
            cam.setScale(1)
        }
        if cam.xScale>3 || cam.yScale > 3{
            cam.setScale(3)
       }
       // recognizer.scale=1
       test()
    }
}

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
   let firstTouch=touches.first
        let location=(firstTouch?.location(in: self))!
        let previousLocation=firstTouch?.previousLocation(in: self)
        cam?.position.x -= location.x - (previousLocation?.x)!
        cam?.position.y -= location.y - (previousLocation?.y)!
        test()
}

func test(){
    if cam.position.x < 1000*scaleNum{
        cam.position.x=1000*scaleNum
    }
    if cam.position.x > 9200*scaleNum{
        cam.position.x=9200*scaleNum
    }
    if cam.position.y<617*scaleNum{
        cam.position.y=617*scaleNum
    }
    if cam.position.y>4476*scaleNum{
        cam.position.y=4476*scaleNum
    }
  }
}

Body:
First of all, I would change your zoomIn function to this:

func zoomIn(recognizer: UIPinchGestureRecognizer){
   if recognizer.state == .changed {
       scaleNum = recognizer.scale
       if scaleNum < 1 { scaleNum = 1 }
       if scaleNum > 3 { scaleNum = 3 }
       cam.setScale(scaleNum)
       test()
   }
}

It is easier to understand, you're not setting the camera scale twice, and most importantly, when you clamp the camera scale, scaleNum reflects that clamped value.  This was not the case before, and in fact, that small change might be your entire problem.

Now I don't have much experience with UIPinchGestureRecognizer but I think the reason your zoom gesture works "ok" is because you are assigning directly from recognizer.scale to cam scale.  Correct me if I'm wrong, but I think UIGestureRecognizer always starts with a scale of 1 for each new gesture, but your camera scale maintains its last value.

As an example, imagine your camera is at a scale of 1. A user zooms in to a scale of 2, the scene zooms in perfectly.  The user lifts their fingers ending the gesture.  Then the user tries to zoom in more, so they begin a new gesture, starting with a scale of 1, but your scene is still at a scale of 2.  You can't assign the gesture scale directly or the image scale will 'jump' back to 1 for each new gesture.  You have to convert from the gesture scale space to the camera scale space.

How exactly you do this is a design and feel choice.  With no experience, my advice would be to change the line in my zoomIn function from

`scaleNum = recognizer.scale'

to

`scaleNum *= recognizer.scale`

Try both versions, and let me know how they work.  If there is still a problem, then it most likely resides in your test() function.  If so, I will try and help out with that as needed.


问:
Make a placeholder div overlappable dynamically
I'm using a jQuery UI accordion as a menu on the right side of a page. However, there are occasions where the menu will be taller than the content on the left. Because of this, when expanding/contracting sections of the accordion, the scrollbar on the browser can grow/shrink when opening a section of the accordion. My thought was to have a div below the accordion which is the height that the accordion could possibly get to, and when the accordion expands it would just overlap it, thus not changing the scrollbar on the browser at all (hope that makes sense). Giving it a position: absolute and declaring the height and width seems to screw up the layout, placing it overlapping the footer but bleeding below it. Anyone have any ideas on how to make this work? If you need a more detailed example, I'll see what I can do to provide it, however, the site is locked down and I can't give out a username/password.</p>

答:
Min-height is easy to implement in IE 6.
The oldest hack from Dustin Diaz:

```<code>selector {
    min-height:500px;
    height:auto!important;
    height:500px;
}
</code>```

Or with expressions:

```<code>selector {
    height:expression( this.scrollHeight < 499 ? "500px" : "auto" );
}
</code>```

In fact for IE 6 height is like min-height.  Element will expand with the content in it, until there is overflow:hidden specified..

You can always apply rules for IE 6 only with "* html hack" or with Conditional Comments.

Body:
Min-height is easy to implement in IE 6.
The oldest hack from Dustin Diaz:

selector {
    min-height:500px;
    height:auto!important;
    height:500px;
}

Or with expressions:

selector {
    height:expression( this.scrollHeight < 499 ? "500px" : "auto" );
}

In fact for IE 6 height is like min-height.  Element will expand with the content in it, until there is overflow:hidden specified..

You can always apply rules for IE 6 only with "* html hack" or with Conditional Comments.


问:
Cannot read property from undefined
I have the following code, which works fine and does what it's supposed to do.

However my table has 2 rows at the top which doesn't interest me (they wouldn't match the if clause anyway so it doesn't affect me, just trying to figure this out) so I was trying to tailor my range to simply exclude them.

All I did was change the A1 to A3 inside the getRange and it's throwing the Cannot read property "1" from undefined (referring to the hardcoded 1 in the if statement).

The reason I don't understand why it's undefined is because changing the range like this shouldn't affect it at all, since I'm reducing my range from A1:B6 (6 rows in my sheet with the first 2 being either empty or not needed) to A3:B6, but the first value in the set (A3) should still end up at [0][0] inside 'data'.. unless getValues() messes something up that I don't know about..

```<code>var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:B" + lastRow);
var options = new Array();
var data = myRange.getValues();
for(var i = 0; i < lastRow; i++) {
    if(data[i][1] == region)
    {
     options.push(data[i][0]);
    }
}
</code>```

Thanks!

答:
Your bug stems from your for loop; it expects to iterate over 6 rows (i starts at 0 and increments by 1 up to 5), when what you really want is to iterate over 4 rows matching the range A3:B6. So the array only has 4 elements but your for loop tries to reference a 5th element that does not exist.

Simplest solution is to use the Array object's built in array methods (I'm using forEach in this case) to iterate over the items specifically in the range you defined as follows:

```<code>var range = sheet.getRange("A3:B"), // you automatically reference the last row with A3:B, no need for A3:B6
    options = [],
    region = '[some-region-value]';

range.getValues().forEach(function(row){
    row[1] == region && options.push(row[0]); // exploit short-circuit mechanism in logical AND operator (in this case the operand on the right, the push, only gets executed if the operand on the left is true)
});
</code>```

Title: Cannot read property from undefined

Body:
I have the following code, which works fine and does what it's supposed to do.

However my table has 2 rows at the top which doesn't interest me (they wouldn't match the if clause anyway so it doesn't affect me, just trying to figure this out) so I was trying to tailor my range to simply exclude them.

All I did was change the A1 to A3 inside the getRange and it's throwing the Cannot read property "1" from undefined (referring to the hardcoded 1 in the if statement).

The reason I don't understand why it's undefined is because changing the range like this shouldn't affect it at all, since I'm reducing my range from A1:B6 (6 rows in my sheet with the first 2 being either empty or not needed) to A3:B6, but the first value in the set (A3) should still end up at [0][0] inside 'data'.. unless getValues() messes something up that I don't know about..

var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:B" + lastRow);
var options = new Array();
var data = myRange.getValues();
for(var i = 0; i < lastRow; i++) {
    if(data[i][1] == region)
    {
     options.push(data[i][0]);
    }
}

Thanks!

Body:
Your bug stems from your for loop; it expects to iterate over 6 rows (i starts at 0 and increments by 1 up to 5), when what you really want is to iterate over 4 rows matching the range A3:B6. So the array only has 4 elements but your for loop tries to reference a 5th element that does not exist.

Simplest solution is to use the Array object's built in array methods (I'm using forEach in this case) to iterate over the items specifically in the range you defined as follows:

var range = sheet.getRange("A3:B"), // you automatically reference the last row with A3:B, no need for A3:B6
    options = [],
    region = '[some-region-value]';

range.getValues().forEach(function(row){
    row[1] == region && options.push(row[0]); // exploit short-circuit mechanism in logical AND operator (in this case the operand on the right, the push, only gets executed if the operand on the left is true)
});


答: malloc() returns NULL if it wasn't able to allocate the requested memory. You should check the value returned by malloc() against NULL.

Title: C - Segmentation Fault when using malloc with large size paramater