问:
How to construct 2d array from 2d arrays
I need to reconstruct 2d array(from image colour channel) of the specific shape from a number of smaller arrays:

```<code>import numpy as np
from PIL import Image

def blockshaped(arr, nrows, ncols):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size

If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.

"""
h, w = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))

pic = Image.open('testimage.bmp') # open image
(r, g, b) = pic.split()# split to channels

c = np.asarray(b) # channel b as array

ar = np.empty((0,256),int) # empty array for appending

n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays

for i in n_a2:
    ar = np.append(ar, i) # append array elements

ar = ar.reshape((16,16)) # reshaping
</code>```

This code produces following result:

It differs from the original array:

Which is understandable, since np.concatenate does not concatenate arrays in the order I need. The question is how do I merge arrays to restore them to the original state?

blockshaped function is from here

答:
Reshape to split the first axis into three axes of lengths 2,2,8, keeping the second axis as it is. Then, permute axes with rollaxis/swapaxes/transpose and a final reshape to have 16 x 16 shape -

```<code>n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)
</code>```

Sample run for verification -

```<code>In [46]: c = np.random.randint(11,99,(16,16))

In [47]: n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
    ...: n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays
    ...:

In [48]: out = n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)

In [49]: np.allclose(out, c)
Out[49]: True
</code>```

Body:
I need to reconstruct 2d array(from image colour channel) of the specific shape from a number of smaller arrays:

import numpy as np
from PIL import Image

def blockshaped(arr, nrows, ncols):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size

If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.

"""
h, w = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))

pic = Image.open('testimage.bmp') # open image
(r, g, b) = pic.split()# split to channels

c = np.asarray(b) # channel b as array

ar = np.empty((0,256),int) # empty array for appending

n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays

for i in n_a2:
    ar = np.append(ar, i) # append array elements

ar = ar.reshape((16,16)) # reshaping

This code produces following result:

It differs from the original array:

Which is understandable, since np.concatenate does not concatenate arrays in the order I need. The question is how do I merge arrays to restore them to the original state?

blockshaped function is from here

Body:
Reshape to split the first axis into three axes of lengths 2,2,8, keeping the second axis as it is. Then, permute axes with rollaxis/swapaxes/transpose and a final reshape to have 16 x 16 shape -

n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)

Sample run for verification -

In [46]: c = np.random.randint(11,99,(16,16))

In [47]: n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
    ...: n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays
    ...:

In [48]: out = n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)

In [49]: np.allclose(out, c)
Out[49]: True


来源: stackexchange

问:
How to convert an arbitrary dataset to the siamese network dataset format in caffe?
I have a dataset that I have created of gray scale images which i want to use with the siamese network example in caffe in which the documentation uses mnist dataset. I want to replace the mnist dataset with my own dataset

I see that for doing this I need my dataset to be in the format required by the siamese netwrk. This can be created using the 'create_mnist_siamese.sh' which loads the mnist dataset in the idx3-ubyte format and creates a dataset lmdb database with two images and a matching/non matching label in each location of the lmdb database.

So I figured for me to use the 'create_mnist_siamese.sh' script, my dataset also needs to be in the idx-ubyte format. I tried to convert my dataset to the idx-ubyte format using 'mnisten'. However i get the error 'error:total images are less than num_tests'. I guess the script is not identifying my images. The folder structure of the dataset is like this:

```<code>parent-directory
  - subfolder
  - subfolder
  .
  .
  .
  -txt file
</code>```

parent directory name - 'generated dataset'

subfolders - 1 ,2 ,3 ... (the subfolders are titled 1 - 30 as I want to label the data in each subfolder by the name of the subfolder)

The txt file contains image title on each row with the class label.

How do I work with my dataset on the siamese network in caffe? Is there a direct way to convert my dataset to the lmdb format for the siamese network? Or do I have to use mnisten? If I do then how do I fix my error ? Anu help will be much appreciated. Thanks.

答:
Generating pairs is the most important step in a Siamese network. However, there is a simple way to do that using caffe.

Load the data as separate lmdbs

Create 2 lmdbs data_1 and data_2 using the create_imagenet.sh or convert_imageset.cpp script. Use the same data for both the sets except data_2 containing one image less that data_1.

This will ensure that at each epoc, a different pair of images will be compared, thus allowing us to cover all nC2 combinations(n^2actually)

```<code>layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  data_param{
      source: "/home/subho/SSD2/data_1/"
      batch_size: 8
      backend: LMDB
     }
  }
layer {
name: "data_p"
type: "Data"
top: "data_p"
top: "label_p"
data_param {
    source: "/home/subho/SSD2/data_2/"
    batch_size: 8
    backend: LMDB
   }
}
</code>```

Introduce a Similarity layer in the prototxt

```<code>layer {
  name: "sim_check"
  type: "Similarity"
  bottom: "label"
  bottom: "label_p"
  top: "sim_check"
  propagate_down: false # for each bottom_blob
  propagate_down: false
  }
layer {
    name: "loss"
    type: "ContrastiveLoss"
    contrastive_loss_param {
    margin: 1.0
    }
    bottom: "feat"
    bottom: "feat_p"
    bottom: "sim_check"
    top: "loss"
  }
</code>```

Create files for Similarity layer

Download files for similarity layer

Place the similarity_layer.cpp in caffe/src/caffe/layers/ and similarity_layers.hpp in caffe/include/caffe/layers/ and rebuild caffe.

```<code>cd build
cmake ..
make -j12
</code>```

Note
If your network does not converge using the above technique, then you should have a look at the following :

Selection of image pairs using hard negatives

Ensuring balance of positive and negative pairs(dissimilar pairs)

ContentLicense: CC BY-SA 3.0

Body:
I have a dataset that I have created of gray scale images which i want to use with the siamese network example in caffe in which the documentation uses mnist dataset. I want to replace the mnist dataset with my own dataset

I see that for doing this I need my dataset to be in the format required by the siamese netwrk. This can be created using the 'create_mnist_siamese.sh' which loads the mnist dataset in the idx3-ubyte format and creates a dataset lmdb database with two images and a matching/non matching label in each location of the lmdb database.

So I figured for me to use the 'create_mnist_siamese.sh' script, my dataset also needs to be in the idx-ubyte format. I tried to convert my dataset to the idx-ubyte format using 'mnisten'. However i get the error 'error:total images are less than num_tests'. I guess the script is not identifying my images. The folder structure of the dataset is like this:

parent-directory
  - subfolder
  - subfolder
  .
  .
  .
  -txt file

parent directory name - 'generated dataset'

subfolders - 1 ,2 ,3 ... (the subfolders are titled 1 - 30 as I want to label the data in each subfolder by the name of the subfolder)

The txt file contains image title on each row with the class label.

How do I work with my dataset on the siamese network in caffe? Is there a direct way to convert my dataset to the lmdb format for the siamese network? Or do I have to use mnisten? If I do then how do I fix my error ? Anu help will be much appreciated. Thanks.

Body:
Generating pairs is the most important step in a Siamese network. However, there is a simple way to do that using caffe.

Load the data as separate lmdbs

Create 2 lmdbs data_1 and data_2 using the create_imagenet.sh or convert_imageset.cpp script. Use the same data for both the sets except data_2 containing one image less that data_1.

This will ensure that at each epoc, a different pair of images will be compared, thus allowing us to cover all nC2 combinations(n^2actually)

layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  data_param{
      source: "/home/subho/SSD2/data_1/"
      batch_size: 8
      backend: LMDB
     }
  }
layer {
name: "data_p"
type: "Data"
top: "data_p"
top: "label_p"
data_param {
    source: "/home/subho/SSD2/data_2/"
    batch_size: 8
    backend: LMDB
   }
}

Introduce a Similarity layer in the prototxt

layer {
  name: "sim_check"
  type: "Similarity"
  bottom: "label"
  bottom: "label_p"
  top: "sim_check"
  propagate_down: false # for each bottom_blob
  propagate_down: false
  }
layer {
    name: "loss"
    type: "ContrastiveLoss"
    contrastive_loss_param {
    margin: 1.0
    }
    bottom: "feat"
    bottom: "feat_p"
    bottom: "sim_check"
    top: "loss"
  }

Create files for Similarity layer

Download files for similarity layer

Place the similarity_layer.cpp in caffe/src/caffe/layers/ and similarity_layers.hpp in caffe/include/caffe/layers/ and rebuild caffe.

cd build
cmake ..
make -j12

Note
If your network does not converge using the above technique, then you should have a look at the following :

Selection of image pairs using hard negatives

Ensuring balance of positive and negative pairs(dissimilar pairs)


问:
Detecting Webview Error and Show Message
I'd like to show an error message when there is an error loading a webview page (No connection).  This is what I have so far, without the error handling code:

```<code>public class TrackerPage extends Activity {

    // @Override
    private WebView webview;
    private ProgressDialog progressDialog;

    private boolean error;

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

        // Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Set the XML layout
        setContentView(R.layout.tracker_page);

        // Bundle objectbundle = this.getIntent().getExtras();
        webview = (WebView) findViewById(R.id.tracker);

        final Activity activity = this;

        // Enable JavaScript and lets the browser go back
        webview.getSettings().setJavaScriptEnabled(true);
        webview.canGoBack();

        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onLoadResource(WebView view, String url) {
                // Check to see if there is a progress dialog
                if (progressDialog == null) {
                    // If no progress dialog, make one and set message
                    progressDialog = new ProgressDialog(activity);
                    progressDialog.setMessage("Loading please wait...");
                    progressDialog.show();

                    // Hide the webview while loading
                    webview.setEnabled(false);
                }
            }

            public void onPageFinished(WebView view, String url) {
                // Page is done loading;
                // hide the progress dialog and show the webview
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                    webview.setEnabled(true);
                }
            }

        });

        // The URL that webview is loading
        webview.loadUrl("http://url.org/");
    }
}
</code>```

How would I do this?

答:
```<code>public class WebClient extends WebViewClient {

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        final Uri uri = request.getUrl();
        handleError(view, error.getErrorCode(), error.getDescription().toString(), uri);
    }

    @SuppressWarnings("deprecation")
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        final Uri uri = Uri.parse(failingUrl);
        handleError(view, errorCode, description, uri);
    }

    private void handleError(WebView view, int errorCode, String description, final Uri uri) {
        final String host = uri.getHost();// e.g. "google.com"
        final String scheme = uri.getScheme();// e.g. "https"
        // TODO: logic
    }
}
</code>```

Body:
I'd like to show an error message when there is an error loading a webview page (No connection).  This is what I have so far, without the error handling code:

public class TrackerPage extends Activity {

    // @Override
    private WebView webview;
    private ProgressDialog progressDialog;

    private boolean error;

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

        // Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Set the XML layout
        setContentView(R.layout.tracker_page);

        // Bundle objectbundle = this.getIntent().getExtras();
        webview = (WebView) findViewById(R.id.tracker);

        final Activity activity = this;

        // Enable JavaScript and lets the browser go back
        webview.getSettings().setJavaScriptEnabled(true);
        webview.canGoBack();

        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onLoadResource(WebView view, String url) {
                // Check to see if there is a progress dialog
                if (progressDialog == null) {
                    // If no progress dialog, make one and set message
                    progressDialog = new ProgressDialog(activity);
                    progressDialog.setMessage("Loading please wait...");
                    progressDialog.show();

                    // Hide the webview while loading
                    webview.setEnabled(false);
                }
            }

            public void onPageFinished(WebView view, String url) {
                // Page is done loading;
                // hide the progress dialog and show the webview
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                    webview.setEnabled(true);
                }
            }

        });

        // The URL that webview is loading
        webview.loadUrl("http://url.org/");
    }
}

How would I do this?


问:
Using toCharArray to check if String has any non-digits
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

```<code>public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}
</code>```

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

答:
In addition to the other answers, in Java 8 there is a chars() method on interface CharSequence (which String) implements) which returns an IntStream of the codepoints of the characters in the string. You can use the allMatch method on the stream with a predicate to ensure that all the codepoints are digits as follows:

```<code>public void setMobile(String mobile) {
    boolean ok = mobile.chars().allMatch(Character::isDigit);

    if (ok) {
        this.mobile = mobile;
    }
}
</code>```

At this point the ok variable isn't really pulling its weight, and we could simply substitute the expression into the condition of the if statement. Or, if you want to get a little crazy (although this is arguably entering code-golf territory), you could rewrite it as a one-liner with a ternary operator:

```<code>public void setMobile(String mob) {
    mobile = mob.chars().allMatch(Character::isDigit)? mob : mobile;
}
</code>```

Body:
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

Body:
In addition to the other answers, in Java 8 there is a chars() method on interface CharSequence (which String) implements) which returns an IntStream of the codepoints of the characters in the string. You can use the allMatch method on the stream with a predicate to ensure that all the codepoints are digits as follows:

public void setMobile(String mobile) {
    boolean ok = mobile.chars().allMatch(Character::isDigit);

    if (ok) {
        this.mobile = mobile;
    }
}

At this point the ok variable isn't really pulling its weight, and we could simply substitute the expression into the condition of the if statement. Or, if you want to get a little crazy (although this is arguably entering code-golf territory), you could rewrite it as a one-liner with a ternary operator:

public void setMobile(String mob) {
    mobile = mob.chars().allMatch(Character::isDigit)? mob : mobile;
}


问:
Is a good convention using semicolon at the end of the line when using ES6 in babel
I saw several examples on the web of tutorials using redux and react where the code of omitting the semicolon when using es6 with babel.

Example semicolon at the end of import, export.

What is the reason?

What is a good practice?

Missing semicolon

```<code>import React, { PropTypes } from 'react'

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name} {country}
    </li>
)

export default Location
</code>```

vs with semicolon

```<code>import React, { PropTypes } from 'react';

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name} {country}
    </li>
);

export default Location;
</code>```

答: It depends on your coding style and your linting tool. For example, if you are using standard, you explicitly have to omit semi colons. Standard is a set of eslint rules that is meant to not to be configurable. It’s okay to not use semicolons in JS. It’s not slower or introduces bugs and it's okay to use them too. It doesn't matter.</p>

Body:
I saw several examples on the web of tutorials using redux and react where the code of omitting the semicolon when using es6 with babel.

Example semicolon at the end of import, export.

What is the reason?

What is a good practice?

Missing semicolon

import React, { PropTypes } from 'react'

const Location = ({ onClick, name, country}) => (

        {name} {country}

)

export default Location

vs with semicolon

import React, { PropTypes } from 'react';

const Location = ({ onClick, name, country}) => (

        {name} {country}

);

export default Location;


问:
OrientDB -Order by FIELD not working
I want to order the table by the id's given within "IN Clause"

SELECT * FROM mytable WHERE id IN [1,2,3,4] ORDER BY FIELD(id,3,2,1,4);

But i am getting error as response.

答: Sorry, OrientDB does not support this in current release. Please open an issue on the official issue tracker, we'll consider it for next releases.</p>

Title: OrientDB -Order by FIELD not working


问:
While validating today date with specific range of dates, shows inappropriate result in php
While selecting today's date as from_date, it shows "Not ok" message. Can anyone help me with this? I am using PHP.</p>

```<code>$today_date = date("d/m/y");
$from_date = 01/04/2017;
$to_date = 05/04/2017;

if(($today_date >= $from_date) && ($today_date <= $to_date))
{
  echo("ok");
}
else
{
  echo("Not ok");
}
</code>```

答:
Try below code:</p>

```<code>$today_date = date("d/m/y");
$from_date = "01/04/2017";
$to_date = "05/04/2017";

if((strtotime($today_date) >= strtotime($from_date)) && (strtotime($today_date) <= strtotime($to_date)))
{
    echo("ok");
} else {
    echo("Not ok");
}
</code>```

Body:
While selecting today's date as from_date, it shows "Not ok" message. Can anyone help me with this? I am using PHP.

$today_date = date("d/m/y");
$from_date = 01/04/2017;
$to_date = 05/04/2017;

if(($today_date >= $from_date) && ($today_date <= $to_date))
{
  echo("ok");
}
else
{
  echo("Not ok");
}

Body:
Try below code:

$today_date = date("d/m/y");
$from_date = "01/04/2017";
$to_date = "05/04/2017";

if((strtotime($today_date) >= strtotime($from_date)) && (strtotime($today_date) <= strtotime($to_date)))
{
    echo("ok");
} else {
    echo("Not ok");
}


问:
Porting a Visual C++ project to C#
I got my hands on some well documented C++ code that's about 1KLOC. It would take me a significant amount of time to port this line by line and debug the results, so I'm wondering if there are tools or ways to do it faster, and I have questions in case I have to do it fully manually.

Specific questions:

Does C# also support overriding operators like * and +?

What to do with the C++ memory management code like alloc() and free()?

How to identify functions used from <stdio.h>, <conio.h> and <math.h>?

How to find replacements to such system functions?

Does C# have any special/open source libraries that provide such functions?

No graphics libraries have been used, its purely command line based.

答:
You might want to try this tool and see if that works out for you.  There is a demo where you translate up to a 100 lines of code at a time:

http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_CSharp_Converter_Details.html

Try it out and let us know.  But it would prolly be more beneficial to port this yourself in c# so you can get a handle of the features that c# comes with.

ContentLicense: CC BY-SA 2.5

Title: Porting a Visual C++ project to C#


问:
Xcode quits unexpectedly every time I open my project
After opening xcode, when I open my current project, it's showing a warning like "xcode quit unexpectedly" with 3 options: "Ignore", "Report" and "Reopen". When I click "Reopen", it will open the xcode window and again automatically it will close and show the same warning.

Why this is happening? If I open any other projects, then it opens with no issues; the issue is with my current app.

versions:

xcode is 4.3.1

mac OS X version is 10.7.3

Please tell me why it's happening like this.

答:
I am using CocoaPods, and followed Rob's Instruction on the .xcworkspace file as indicated above by Allecto. After I "showed Package Contents" on the .xcworkspace file, the only thing I did was to rename the xcuserdata folder to xcuserdataCrashApril2. I was then able to open the project (workspace) with no problems. The only difference is xcode did not save the state of which .swift source code files were previously opened (which is not a big issue for me). </p>

<p>I suppose I can delete the xcuserdataCrashApril2 file, but I am keeping it out there as a reminder of what to do the next time this happens.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I am using CocoaPods, and followed Rob's Instruction on the .xcworkspace file as indicated above by Allecto. After I "showed Package Contents" on the .xcworkspace file, the only thing I did was to rename the xcuserdata folder to xcuserdataCrashApril2. I was then able to open the project (workspace) with no problems. The only difference is xcode did not save the state of which .swift source code files were previously opened (which is not a big issue for me).

I suppose I can delete the xcuserdataCrashApril2 file, but I am keeping it out there as a reminder of what to do the next time this happens.


问:
How to equalize two .ps files to get same md5 hash
I have to somehow equalize two pretty similar files to get the same md5 hashes. I take my inspiration from this work,
https://natmchugh.blogspot.co.at/2015/05/how-to-make-two-binaries-with-same-md5.html?m=1

But I have to work on Postscript files. My files looks like this:

In which block I have to add some data to get the same files, and get the same hashes.

答:
Two researchers, Magnus Daum and Stefan Lucks, demonstrated a pair of PostScript files with the same MD5 hash but different contents back in 2005. See Attacking Hash Functions by Poisoned Messages, "The Story of Alice and her Boss".

Their pair of PostScript language files are hand-crafted, and have the following form:

```<code>%!PS-Adobe-1.0
%%BoundingBox: 0 0 612 792
(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑ó
F~™¿T>±˚Em3¸S‡[Ô†É£xRÌZ3Œ6ô
únEZRÑyÎ/ΩïıWÂv:Ïø™Ÿ µsY»2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜÿk»ÙîÙNa|ÑÄ`œoîµê)(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑ó
F~™¿T>±˚Em3¸S‡[Ô†É£xRÌZ3Œ6ô
únEZRÑyÎ/ΩïıWÂv:Ïø™Ÿ µsY»2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜÿk»ÙîÙNa|ÑÄ`œoîµê)eq{
    % Code to print innocent document
}{
    % Code to print evil document
}ifelse
showpage
</code>```

Note that the code has two strings, delimited by parentheses (), and tests them for equality. If they are the same, the file prints the innocent document. Otherwise, it prints the evil document.

The PostScript language document which prints the evil document has a slightly different octet sequence in the first string:

```<code>(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑
F~™¿T>±˚Em3¸S‡[Ô†É#yRÌZ3Œ6ô
únE⁄RÑyÎ/ΩïıWÂv:Ïø™Ÿ µsYH2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜXk»ÙîÙNa|ÑÄ`œÔîµê)
</code>```

Both files have the same MD5 digest, a25f7f0b29ee0b3968c860738533a4b9.

Since your files include binary data and all manner of other content, the structure they used won't work well for you.   Instead, you can try inserting a string like this in the early part of your file. Put it after the Document Structuring Conventions (lines beginning with %) at the start of the file.

```<code>(0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789) pop
</code>```

Then use a hash-collision finding tool to identify which octets within the body of that string you need to replace, with which other octets, in order to make one of your PostScript language files match the md5 hash of the other.

Which tool will find hash collisions is not a PostScript-specific question, so is out of the scope of this answer.

Body:
Two researchers, Magnus Daum and Stefan Lucks, demonstrated a pair of PostScript files with the same MD5 hash but different contents back in 2005. See Attacking Hash Functions by Poisoned Messages, "The Story of Alice and her Boss".

Their pair of PostScript language files are hand-crafted, and have the following form:

%!PS-Adobe-1.0
%%BoundingBox: 0 0 612 792
(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑ó
F~™¿T>±˚Em3¸S‡[Ô†É£xRÌZ3Œ6ô
únEZRÑyÎ/ΩïıWÂv:Ïø™Ÿ µsY»2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜÿk»ÙîÙNa|ÑÄ`œoîµê)(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑ó
F~™¿T>±˚Em3¸S‡[Ô†É£xRÌZ3Œ6ô
únEZRÑyÎ/ΩïıWÂv:Ïø™Ÿ µsY»2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜÿk»ÙîÙNa|ÑÄ`œoîµê)eq{
    % Code to print innocent document
}{
    % Code to print evil document
}ifelse
showpage

Note that the code has two strings, delimited by parentheses (), and tests them for equality. If they are the same, the file prints the innocent document. Otherwise, it prints the evil document.

The PostScript language document which prints the evil document has a slightly different octet sequence in the first string:

(ËB¶jﬁM‡’â_¯Âú¡ß/ ∑
F~™¿T>±˚Em3¸S‡[Ô†É#yRÌZ3Œ6ô
únE⁄RÑyÎ/ΩïıWÂv:Ïø™Ÿ µsYH2Ù},π£v‘6 ˝Ô;É°Ú}Î 6SÜXk»ÙîÙNa|ÑÄ`œÔîµê)

Both files have the same MD5 digest, a25f7f0b29ee0b3968c860738533a4b9.

Since your files include binary data and all manner of other content, the structure they used won't work well for you.   Instead, you can try inserting a string like this in the early part of your file. Put it after the Document Structuring Conventions (lines beginning with %) at the start of the file.

(0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789) pop

Then use a hash-collision finding tool to identify which octets within the body of that string you need to replace, with which other octets, in order to make one of your PostScript language files match the md5 hash of the other.

Which tool will find hash collisions is not a PostScript-specific question, so is out of the scope of this answer.


问:
Selectively parse JSON in Java
I have a JSON file like this:

```<code>{"start":1489730400000,
"end":1489733999999,
"interval":1000,
"weight":1,
"augmented": true,
"profileName":"Selene/prod",
"prunedSamples":0,
"fleet":{"c4.2xlarge":14.313278698132972}, "costPerSecond":0.000008259246540496541,
"profileData":{
    "name":"ALL",
    "states":{"BLOCKED":2281, "NEW":0, "RUNNABLE":125833, "TERMINATED":0, "TIMED_WAITING":23170429, "WAITING":59901416},
    "location": "0",
    "hidden": [],
    "children":[{"name":"GarbageCollector.gc",
    "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":17069},
    "location": "0.0",
    "hidden": [],
    "children":[{"name":"ConcurrentMarkSweep.gc",
                "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":14977},
                "location": "0.0.0",
                "hidden": [],
                "level": 1},
                {"name":"ParNew.gc",
                 "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":2092},
                 "location": "0.0.1",
                 "hidden": [],
                 "level": 1}]
}}
</code>```

This is just a part of it. I get a much bigger file in GZip format which i decompress first and store the decompressed part in a string. I use the following code for that:

```<code>URL url = new URL("http://example.com/Selene%20Prod?start=1490234400000&end=1490237999999&maxDepth=200&minimumCountsThreshold=0.00");
URLConnection myUrlConnection = url.openConnection();
GZIPInputStream gZIPInputStream = new GZIPInputStream(myUrlConnection.getInputStream());
StringBuffer decompressedStringBuffer = new StringBuffer();
int bytes_read;
while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {
    String part = new String(buffer, 0 ,bytes_read, "UTF-8");
    decompressedStringBuffer.append(part);
}
gZIPInputStream.close();
String decompressedString = decompressedStringBuffer.toString();
JSONObject obj = new JSONObject(decompressedString);
JSONArray profileData = obj.getJSONObject("profileData").getJSONArray("children");
</code>```

My code gives Caused by: java.lang.OutOfMemoryError: Java heap space on decompressedStringBuffer.append(part);. Since the file gets too big to store in memory I thought about storing it in a file and then reading the file back to convert to JSON but then the JSON object I would create using the FileInputStream would give me a Caused by:java.lang.OutOfMemoryError: Java heap space.

The only useful data in the JSON I get is name and children under the profileData key.

Is there a way to only convert them to JSONObject while parsing the inputStream and ignore the others?

If there is a better way someone can think of i would appreciate that as well.

答:
I think that you need not go to the JACKSON library just try to find a way to parse your large JSON in GSON only.

Try This resource Which is the answer from the author of GSON.
On the same page you will find a working example for JACKSON too using streaming and tree model (in case you want to move on Jackson)

As well as refer the link below in case you want to increase your heap size:
How to increase Java heap size

Title: Selectively parse JSON in Java

Body:
I have a JSON file like this:

{"start":1489730400000,
"end":1489733999999,
"interval":1000,
"weight":1,
"augmented": true,
"profileName":"Selene/prod",
"prunedSamples":0,
"fleet":{"c4.2xlarge":14.313278698132972}, "costPerSecond":0.000008259246540496541,
"profileData":{
    "name":"ALL",
    "states":{"BLOCKED":2281, "NEW":0, "RUNNABLE":125833, "TERMINATED":0, "TIMED_WAITING":23170429, "WAITING":59901416},
    "location": "0",
    "hidden": [],
    "children":[{"name":"GarbageCollector.gc",
    "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":17069},
    "location": "0.0",
    "hidden": [],
    "children":[{"name":"ConcurrentMarkSweep.gc",
                "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":14977},
                "location": "0.0.0",
                "hidden": [],
                "level": 1},
                {"name":"ParNew.gc",
                 "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":2092},
                 "location": "0.0.1",
                 "hidden": [],
                 "level": 1}]
}}

This is just a part of it. I get a much bigger file in GZip format which i decompress first and store the decompressed part in a string. I use the following code for that:

URL url = new URL("http://example.com/Selene%20Prod?start=1490234400000&end=1490237999999&maxDepth=200&minimumCountsThreshold=0.00");
URLConnection myUrlConnection = url.openConnection();
GZIPInputStream gZIPInputStream = new GZIPInputStream(myUrlConnection.getInputStream());
StringBuffer decompressedStringBuffer = new StringBuffer();
int bytes_read;
while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {
    String part = new String(buffer, 0 ,bytes_read, "UTF-8");
    decompressedStringBuffer.append(part);
}
gZIPInputStream.close();
String decompressedString = decompressedStringBuffer.toString();
JSONObject obj = new JSONObject(decompressedString);
JSONArray profileData = obj.getJSONObject("profileData").getJSONArray("children");

My code gives Caused by: java.lang.OutOfMemoryError: Java heap space on decompressedStringBuffer.append(part);. Since the file gets too big to store in memory I thought about storing it in a file and then reading the file back to convert to JSON but then the JSON object I would create using the FileInputStream would give me a Caused by:java.lang.OutOfMemoryError: Java heap space.

The only useful data in the JSON I get is name and children under the profileData key.

Is there a way to only convert them to JSONObject while parsing the inputStream and ignore the others?

If there is a better way someone can think of i would appreciate that as well.


问:
How to receive Github WebHook in Google Apps Script web application?
I have Google Apps Script web application:

```<code>function doPost(request){
  request.postData;
  // operations based on received JSON
}
</code>```

and I have setup webhook in Github.

Why my GAS app is rejecting HTTP requests from GitHub WebHook? Every time I check WebHook log I see error messages:

```<code>Error 401 "Sorry, unable to open the file at this time.".
</code>```

答:
You can retrieve JSON data from WebHook of GitHub using e.parameters.payload for doPost(). About this parameter, you can see at https://developers.google.com/apps-script/guides/web

So you can write your function as follows.

```<code>function doPost(request){
  Logger.log(request.parameters.payload)

}
</code>```

payload is a JSON key from GitHub.

WebHook of GitHub doesn't support redirects. So although the WebHook log of GitHub will leave warnings, doPost() at GAS can retrieve data from the WebHook.

Body:
I have Google Apps Script web application:

function doPost(request){
  request.postData;
  // operations based on received JSON
}

and I have setup webhook in Github.

Why my GAS app is rejecting HTTP requests from GitHub WebHook? Every time I check WebHook log I see error messages:

Error 401 "Sorry, unable to open the file at this time.".

Body:
You can retrieve JSON data from WebHook of GitHub using e.parameters.payload for doPost(). About this parameter, you can see at https://developers.google.com/apps-script/guides/web

So you can write your function as follows.

function doPost(request){
  Logger.log(request.parameters.payload)

}

payload is a JSON key from GitHub.

WebHook of GitHub doesn't support redirects. So although the WebHook log of GitHub will leave warnings, doPost() at GAS can retrieve data from the WebHook.


问:
Passing a CLOB into a .net dll
I wanted to know if it were possible to pass a CLOB (8k String) to a .net dll?
Is there max limit on what a dll can receive? </p>

答:
I'm not 100% clear on what you mean by "pass to a dll".

If you mean calling a method where the parameter is a string then I think your bound by string length, which is Int32.MaxValue or 2,147,483,647 characters.

Title: Passing a CLOB into a .net dll


问:
jQuery on click event partially working
```<code>var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});
</code>```

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

答:
sideBarAndWrapper Is a collection. You can set both but PERHAPS not interrogate using hasClass - in v3.1.1 you can

Try this more elegant version

```<code>var $sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function () {
  var tgl = $(this).data("tgl") || false; // or true depending on state
  $sideBarAndWrapper.toggleClass("hide-sidebar",tgl);
  $(this).text(tgl?"Show Sidebar":"Hide Sidebar");
  $(this).data("tgl",!tgl);
});
</code>```

Title: jQuery on click event partially working

Body:
var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

Body:
sideBarAndWrapper Is a collection. You can set both but PERHAPS not interrogate using hasClass - in v3.1.1 you can

Try this more elegant version

var $sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function () {
  var tgl = $(this).data("tgl") || false; // or true depending on state
  $sideBarAndWrapper.toggleClass("hide-sidebar",tgl);
  $(this).text(tgl?"Show Sidebar":"Hide Sidebar");
  $(this).data("tgl",!tgl);
});


问:
cmd batch file ; assign different parameters from a text file
I have one text file (trimlist.txt) with a variable number of lines, but each line are similar with a variable file path and name and 2 numbers separated by coma:

```<code>E:\test\00037_20161001_100956.mov,3.6369666,1.2345666
</code>```

I need to get 3 different variables from each line: mov, 3.6369666 & 1.2345666 in this example.
I can get the 2 last variables like this

```<code>set prevfile=

for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if "!counter!"=="" (set counter=1) else (set /a counter+=1)
) else (
    set counter=
    set "prevfile=%%F"
        )
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed.mov"
</code>```

So with the above text file my final commmand will be

```<code>ffmpeg -ss 3.6369666 -i "E:\test\00037_20161001_100956.mov" -c copy -t 1.2345666 "E:\test\00037_20161001_100956 01 -trimmed.mov"
</code>```

I would like the "mov" of E:\test\00037_20161001_100956 01 -trimmed.movto be a variable taken from the textfile.

Any help will be greatly appreciated.

答:
Finally found how to do

```<code>setlocal enableDelayedExpansion
set prevfile=
for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
        if "!counter!"=="" (set counter=1) else (set /a counter+=1)
    ) else (
        set counter=
        set "prevfile=%%F"
    )
    ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed%%~xF"
)
</code>```

i only have to get the extension from the file with %%~xF

Body:
I have one text file (trimlist.txt) with a variable number of lines, but each line are similar with a variable file path and name and 2 numbers separated by coma:

E:\test\00037_20161001_100956.mov,3.6369666,1.2345666

I need to get 3 different variables from each line: mov, 3.6369666 & 1.2345666 in this example.
I can get the 2 last variables like this

set prevfile=

for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if "!counter!"=="" (set counter=1) else (set /a counter+=1)
) else (
    set counter=
    set "prevfile=%%F"
        )
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed.mov"

So with the above text file my final commmand will be

ffmpeg -ss 3.6369666 -i "E:\test\00037_20161001_100956.mov" -c copy -t 1.2345666 "E:\test\00037_20161001_100956 01 -trimmed.mov"

I would like the "mov" of E:\test\00037_20161001_100956 01 -trimmed.movto be a variable taken from the textfile.

Any help will be greatly appreciated.

Body:
Finally found how to do

setlocal enableDelayedExpansion
set prevfile=
for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
        if "!counter!"=="" (set counter=1) else (set /a counter+=1)
    ) else (
        set counter=
        set "prevfile=%%F"
    )
    ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed%%~xF"
)

i only have to get the extension from the file with %%~xF


问:
How do I add a backround image to each DetailViewControllers separately?
I want to build an app that has 5 cells in a UITableView. I assigned a background image to the main page of the table view; however, I want to assign different background images to each view that comes up after I tap on a cell. How do I achieve that?

Thanks!

答:
You can create an array which contains five different images that you want to set as a background. Then you can use didSelect function of UITableViewDelegate and get the selected index. With this index you can get the image and set as background.

```<code>// do not forget to set delegate for tableview inside your viewcontroller
tableView.delegate = self
</code>```

Swift

```<code>let images = [image1, image3, image3, image4, image5]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedIndex = indexPath.row
    let backgroundImage = images[selectedIndex]
    YOUR_IMAGE_VIEW.image = backgroundImage
}
</code>```

Objective-C

```<code>NSArray *images = [NSArray arrayWithObjects:image1, image2, image3, image4, image5, nil];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int selectedIndex = indexPath.row;
    UIImage *backgroundImage = images[selectedIndex];
    YOUR_IMAGE_VIEW.image = backgroundImage;
}
</code>```

Body:
You can create an array which contains five different images that you want to set as a background. Then you can use didSelect function of UITableViewDelegate and get the selected index. With this index you can get the image and set as background.

// do not forget to set delegate for tableview inside your viewcontroller
tableView.delegate = self

Swift

let images = [image1, image3, image3, image4, image5]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedIndex = indexPath.row
    let backgroundImage = images[selectedIndex]
    YOUR_IMAGE_VIEW.image = backgroundImage
}

Objective-C

NSArray *images = [NSArray arrayWithObjects:image1, image2, image3, image4, image5, nil];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int selectedIndex = indexPath.row;
    UIImage *backgroundImage = images[selectedIndex];
    YOUR_IMAGE_VIEW.image = backgroundImage;
}


问:
Getting Illegal invocation error while using Jquery
I am getting the below error while trying to use ajax call in Jquery. I am explaining my code below.

```<code>Error: Uncaught TypeError: Illegal invocation
    at e (http://oditek.in/fyndspace/js/jquery.js:4:23990)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23875)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23898)
    at Function.m.param (http://oditek.in/fyndspace/js/jquery.js:4:24236)
    at Function.ajax (http://oditek.in/fyndspace/js/jquery.js:4:20195)
    at Function.m.(anonymous function) [as post] (http://oditek.in/fyndspace/js/jquery.js:4:22297)
    at saveAllManageSpaceData (http://oditek.in/fyndspace/listyourspace:1418:6)
    at HTMLButtonElement.onclick (http://oditek.in/fyndspace/listyourspace:693:102)
</code>```

My working code is given below

```<code><button class="btn nextbtnbgdiv open6" type="button" onclick="saveAllManageSpaceData();">Save & Continue <span class="fa fa-arrow-right"></span></button>

var data={"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess};
console.log('hello',data);
var url="common.php?action=saveManageSpace";
$.post(url,data,function(data){
    console.log('res',data);
});
</code>```

Here I am getting the above  error while using ajax call. Please help me to resolve this issue.

答:
your data is an object - you might want to try as array </p>

```<code> var data=[{"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess}];
</code>```

Body:
I am getting the below error while trying to use ajax call in Jquery. I am explaining my code below.

Error: Uncaught TypeError: Illegal invocation
    at e (http://oditek.in/fyndspace/js/jquery.js:4:23990)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23875)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23898)
    at Function.m.param (http://oditek.in/fyndspace/js/jquery.js:4:24236)
    at Function.ajax (http://oditek.in/fyndspace/js/jquery.js:4:20195)
    at Function.m.(anonymous function) [as post] (http://oditek.in/fyndspace/js/jquery.js:4:22297)
    at saveAllManageSpaceData (http://oditek.in/fyndspace/listyourspace:1418:6)
    at HTMLButtonElement.onclick (http://oditek.in/fyndspace/listyourspace:693:102)

My working code is given below

<button class="btn nextbtnbgdiv open6" type="button" onclick="saveAllManageSpaceData();">Save & Continue </button>

var data={"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess};
console.log('hello',data);
var url="common.php?action=saveManageSpace";
$.post(url,data,function(data){
    console.log('res',data);
});

Here I am getting the above  error while using ajax call. Please help me to resolve this issue.

Body:
your data is an object - you might want to try as array

 var data=[{"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess}];


问:
vim create new file and insert text on first line
I have the following function which opens a new file in vim but I want to insert a line of text into the first line of the new file.

```<code>function journ(){
  datestring=`date +"%Y-%m-%d - %H%M%S - Rx2_Px -"`
  notev $datestring Journal
}
</code>```

notev calls this function:

```<code>function notev() {
    vim "$*.md"
}
</code>```

I want the first line of the file to read:

# name_of_file

答:
It seems that the easiest solution is to pipe the data to the file and then start vim.

```<code>function notev() {
    echo "# $*.md" >> "$*.md"
    vim "$*.md"
}
</code>```

Body:
I have the following function which opens a new file in vim but I want to insert a line of text into the first line of the new file.

function journ(){
  datestring=`date +"%Y-%m-%d - %H%M%S - Rx2_Px -"`
  notev $datestring Journal
}

notev calls this function:

function notev() {
    vim "$*.md"
}

I want the first line of the file to read:

# name_of_file

Body:
It seems that the easiest solution is to pipe the data to the file and then start vim.

function notev() {
    echo "# $*.md" >> "$*.md"
    vim "$*.md"
}


问:
Can't use delete method on Ruby on rails
I am a beginner of Ruby on rails, I failed when I try to delete the object that I  create. here is the code.
controller

```<code>class PuzzlesController < ApplicationController
  def index
    @puzzles = Puzzle.all
  end
  def show
    @puzzle=Puzzle.find(params[:id])
  end
  def new
    @puzzle = Puzzle.new

  end
  def create
      #render plain: params[:puzzle].inspect
    @puzzle = Puzzle.new(puzzle_params)
    if(@puzzle.save)
      redirect_to @puzzle
    else
      render 'new'
    end
  end
  def edit
    @puzzle=Puzzle.find(params[:id])
  end
  def update
    @puzzle=Puzzle.find(params[:id])
    if(@puzzle.update(puzzle_params))
      redirect_to @puzzle
    else
      render 'edit'
    end
  end
  def destroy
    @puzzle = Puzzle.find(params[:id])
    @puzzle.destroy

    redirect_to puzzle_path
  end
  private def puzzle_params
    params.require(:puzzle).permit(:title,:body,:category,:difficulty)
  end
end
</code>```

show

```<code><h2><%= @puzzle.title %></h2>
    <p><%= @puzzle.body %></p>
    <p><%= @puzzle.category %></p>
    <p><%= @puzzle.difficulty %></p>
<hr>
<%= link_to "Edit", edit_puzzle_path(@puzzle), :class => 'btn btn-default'%>
<%= link_to "Delete", puzzle_path(@puzzle),
            method: :delete,
            data: {confrim: 'are you sure? '},
             :class => 'btn btn-danger'%>
</code>```

when i click on delete, its like re-render the page. i searched a lot on internet and cant find a solution for it.

this is the information on rails server.

```<code>Started GET "/puzzles/1" for ::1 at 2017-04-02 18:51:18 +0930
Processing by PuzzlesController#show as HTML
  Parameters: {"id"=>"1"}
  Puzzle Load (0.5ms)  SELECT  "puzzles".* FROM "puzzles" WHERE "puzzles"."id" = ? LIM             IT ?  [["id", 1], ["LIMIT", 1]]
  Rendering puzzles/show.html.erb within layouts/application
  Rendered puzzles/show.html.erb within layouts/application (1.0ms)
Completed 200 OK in 63ms (Views: 46.2ms | ActiveRecord: 0.5ms)
</code>```

答:
There are several issues in your code:

1) There is a typo in the link_to parameter list (confirm, instead of confrim):

```<code><%= link_to 'Delete', puzzle_path(@puzzle),
      method: :delete,
      data: { confirm: 'are you sure? '},
      class: 'btn btn-danger' %>
</code>```

2) At the end of your destroy method you cannot redirect to a singular puzzle path, because you just deleted the puzzle. Redirect to the index page instead:

```<code>redirect_to puzzles_path
</code>```

3) But most important. Links with method: 'delete' only work with JavaScript and Rails 5.0 depends on jQuery. Because you wrote that the links just redirects to the show page, I guess you do not have included the Rails JavaScript files into your asset pipeline:

```<code># Add this to the head of your `views/layout/application.rb`:
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

# Ensure that your `assets/javascripts/application.js` include the following lines:
//= require jquery
//= require jquery_ujs
</code>```

Ensure in your browser's concole that the files are loaded without an error.

Body:
I am a beginner of Ruby on rails, I failed when I try to delete the object that I  create. here is the code.
controller

class PuzzlesController < ApplicationController
  def index
    @puzzles = Puzzle.all
  end
  def show
    @puzzle=Puzzle.find(params[:id])
  end
  def new
    @puzzle = Puzzle.new

  end
  def create
      #render plain: params[:puzzle].inspect
    @puzzle = Puzzle.new(puzzle_params)
    if(@puzzle.save)
      redirect_to @puzzle
    else
      render 'new'
    end
  end
  def edit
    @puzzle=Puzzle.find(params[:id])
  end
  def update
    @puzzle=Puzzle.find(params[:id])
    if(@puzzle.update(puzzle_params))
      redirect_to @puzzle
    else
      render 'edit'
    end
  end
  def destroy
    @puzzle = Puzzle.find(params[:id])
    @puzzle.destroy

    redirect_to puzzle_path
  end
  private def puzzle_params
    params.require(:puzzle).permit(:title,:body,:category,:difficulty)
  end
end

show

<%= @puzzle.title %>

<%= @puzzle.body %>

<%= @puzzle.category %>

<%= @puzzle.difficulty %>

<%= link_to "Edit", edit_puzzle_path(@puzzle), :class => 'btn btn-default'%>
<%= link_to "Delete", puzzle_path(@puzzle),
            method: :delete,
            data: {confrim: 'are you sure? '},
             :class => 'btn btn-danger'%>

when i click on delete, its like re-render the page. i searched a lot on internet and cant find a solution for it.

this is the information on rails server.

Started GET "/puzzles/1" for ::1 at 2017-04-02 18:51:18 +0930
Processing by PuzzlesController#show as HTML
  Parameters: {"id"=>"1"}
  Puzzle Load (0.5ms)  SELECT  "puzzles".* FROM "puzzles" WHERE "puzzles"."id" = ? LIM             IT ?  [["id", 1], ["LIMIT", 1]]
  Rendering puzzles/show.html.erb within layouts/application
  Rendered puzzles/show.html.erb within layouts/application (1.0ms)
Completed 200 OK in 63ms (Views: 46.2ms | ActiveRecord: 0.5ms)

Body:
There are several issues in your code:

1) There is a typo in the link_to parameter list (confirm, instead of confrim):

<%= link_to 'Delete', puzzle_path(@puzzle),
      method: :delete,
      data: { confirm: 'are you sure? '},
      class: 'btn btn-danger' %>

2) At the end of your destroy method you cannot redirect to a singular puzzle path, because you just deleted the puzzle. Redirect to the index page instead:

redirect_to puzzles_path

3) But most important. Links with method: 'delete' only work with JavaScript and Rails 5.0 depends on jQuery. Because you wrote that the links just redirects to the show page, I guess you do not have included the Rails JavaScript files into your asset pipeline:

# Add this to the head of your `views/layout/application.rb`:
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

# Ensure that your `assets/javascripts/application.js` include the following lines:
//= require jquery
//= require jquery_ujs

Ensure in your browser's concole that the files are loaded without an error.


问:
Complex List Comprehension slower than straight loop
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

```<code>def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
</code>```

Snippet 2

```<code>def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out
</code>```

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

答:
Yes, because in the comprehension all the instructions are being evaluated in each loop.

While in Snippet 2 atmost 1 if branch is evaluated. Thus, reducing the computation, and making it a faster alternative.

Body:
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]

Snippet 2

def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?


问:
How can I find the exact amount of physical memory on Windows x86-32bit using Perl or any other language?
I need to know how much physical memory a windows machine has, using Perl.

I've tried using Win32::SystemInfo. However this module states the following caveat:

On Intel x86 computers with more than 2 GB and less than 4 GB of memory, the MemoryStatus function will always return 2 GB for TotalPhys. Similarly, if the total available memory is between 2 and 4 GB, AvailPhys will be rounded down to 2 GB.

So on a machine which has 2-4 GB of physical memory, I get a false answer.

Is there a way to get the correct amount of physical memory? Perhaps another module? Or directly using Win32::API?

Edit: From the comments people gave here, it looks like the limitation is in the Win32 API , and not specific to Win32::SystemInfo. However, the OS does know exactly how much physical ram is available, so there must be a way to extract that information. If not in Perl then maybe in another language?

答:
This information can be pulled from WMI, or using SNMP if you choose to enable SNMP on the box it will be running on. For WMI, I don't have a Perl example offhand but for a VBScript example see below.

Ref:  http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx

```<code>strComputer = "."

Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
 objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

For Each objSWbemObject In colSWbemObjectSet
 Wscript.Echo "Total Physical Memory (kb): " & _
 objSWbemObject.TotalPhysicalMemory
Next
</code>```

Tested on my XP system and it retrieves the desired results (only 1.5GB RAM here, sorry). I'm quite sure there are WMI interfaces for Perl as well if you want to stick with Perl. If SNMP is an option, the total physical memory can be obtained from SNMP as well using one of the Perl SNMP libraries.

EDIT: Just noticed @Mr. Muskrat's comment regarding Microsoft KB http://support.microsoft.com/kb/274558 - evidently the behavior you're seeing with Perl is a limitation of the Win32 API call, so you might end up with the same results with WMI. Unfortunately I don't have a 2-4GB RAM machine to try this on to verify.

OwnerDisplayName: Bonzo

LastEditorDisplayName: casperOne

Body:
This information can be pulled from WMI, or using SNMP if you choose to enable SNMP on the box it will be running on. For WMI, I don't have a Perl example offhand but for a VBScript example see below.

Ref:  http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx

strComputer = "."

Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
 objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

For Each objSWbemObject In colSWbemObjectSet
 Wscript.Echo "Total Physical Memory (kb): " & _
 objSWbemObject.TotalPhysicalMemory
Next

Tested on my XP system and it retrieves the desired results (only 1.5GB RAM here, sorry). I'm quite sure there are WMI interfaces for Perl as well if you want to stick with Perl. If SNMP is an option, the total physical memory can be obtained from SNMP as well using one of the Perl SNMP libraries.

EDIT: Just noticed @Mr. Muskrat's comment regarding Microsoft KB http://support.microsoft.com/kb/274558 - evidently the behavior you're seeing with Perl is a limitation of the Win32 API call, so you might end up with the same results with WMI. Unfortunately I don't have a 2-4GB RAM machine to try this on to verify.

OwnerDisplayName: Jay

LastEditorDisplayName: Jay


问:
Goroutines with sync.WaitGroup end before last wg.Done()
I have an example code (you can find it on Go Playground):

```<code>package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()
    go func() {
        for i := range messages {
            fmt.Println(i)
        result = append(result, i)
        }

    }()

    wg.Wait()
    fmt.Println(result)
}
</code>```

I got this output:

```<code>2
1
[2 1]
</code>```

I think I know why is it happening, but I can't solve it. There is 3 item in the WaitGroup I mean the three goroutine, and the 4th groutine consume the data from the channel. When the last groutine say wg.Done() the program is over because of the wg.Wait() said every goroutine finished and the last goroutine result the 4th goroutine couldn't have consume, because the program ended. I tryed to add plus one with wg.Add(1) and the wg.Done() in the 4th function but in this case I got deadlock.

答:
The last goroutine you spawn—that one intended to collect the results—is not waited by main() so wg.Wait() in there returns, main() quits and reaps the remainin goroutines.
Supposedly just a single—collecting—goroutine remains by that time but it fails to update the slice.

Also note that due to the same reason you have a data race in your program: by the time main() reads the slice of results, it does not know whether it's safe to read it—that is, whether the writer is done writing to there.

An easy fix is to do add wg.Add(1) for that goroutine and defer wg.Done() in it, too.

A better solution is to close() the messages channel after wg.Wait()
and before reading from the slice.  This would make the collecting goroutine's range loop to terminate and this would also create a proper synchronization point between that goroutine and main().

Body:
I have an example code (you can find it on Go Playground):

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()
    go func() {
        for i := range messages {
            fmt.Println(i)
        result = append(result, i)
        }

    }()

    wg.Wait()
    fmt.Println(result)
}

I got this output:

2
1
[2 1]

I think I know why is it happening, but I can't solve it. There is 3 item in the WaitGroup I mean the three goroutine, and the 4th groutine consume the data from the channel. When the last groutine say wg.Done() the program is over because of the wg.Wait() said every goroutine finished and the last goroutine result the 4th goroutine couldn't have consume, because the program ended. I tryed to add plus one with wg.Add(1) and the wg.Done() in the 4th function but in this case I got deadlock.


问:
Add axis labels to tableGrob in R
When using the default table output, the default is to plot the "axis" labels using the parameter names (k1 and k2 in this case). This is useful particularly for comparing cluster membership and the most important thing to denote is which cluster is rows and which is columns.

```<code>table(
  k1=matrix(1:4, 2),
  k2=matrix(1:4, 2)
)

   k2
k1  1 2 3 4
  1 1 0 0 0
  2 0 1 0 0
  3 0 0 1 0
  4 0 0 0 1
</code>```

I am trying to make use of tableGrob to output some tables, composed with other ggplot components in grid.arrange. However, the axis labels are lost.

```<code>grid.arrange(tableGrob(
  table(
    k1=matrix(1:4, 2),
    k2=matrix(1:4, 2)
  )
))
</code>```

All I want to do is have those included or even include them manually after making the grob.

Thanks

Edit: Attempt with annotation_custom:

Code:

```<code>ggTableAxis2 <- function(t) {
  my_grob <- tableGrob(t)

  my_plot <- ggplot(mapping = aes(k2, k1)) +
    annotation_custom(my_grob) +
    scale_x_continuous(position = 'top') +
    theme(axis.title =  element_text(angle = 0, hjust = 0),
          axis.title.x.top =  element_text(hjust = 0))
  return(my_plot)
}

grid.arrange(
  ggTableAxis2(
    table(
      k1=matrix(1:4, 2),
      k2=matrix(1:4, 2)
    )
  ),
  ggTableAxis2(
    table(
      k1=matrix(1:4, 2),
      k2=matrix(1:4, 2)
    )
  ),
  nrow=1
)
</code>```

答:
You could use an empty ggplot with mapped aesthetics:

```<code>library(grid)
library(gridExtra)
library(ggplot2)

my_grob <- tableGrob(table(k1 = matrix(1:4, 2), k2 = matrix(1:4, 2)))

my_plot <- ggplot(mapping = aes(k2, k1)) +
  annotation_custom(my_grob) +
  scale_x_continuous(position = 'top') +
  theme(axis.title.y =  element_text(angle = 0),
        axis.title.x.top =  element_text(hjust = 0))

grid.arrange(my_plot, my_plot, my_plot, my_plot)
</code>```

Title: Add axis labels to tableGrob in R

Body:
When using the default table output, the default is to plot the "axis" labels using the parameter names (k1 and k2 in this case). This is useful particularly for comparing cluster membership and the most important thing to denote is which cluster is rows and which is columns.

table(
  k1=matrix(1:4, 2),
  k2=matrix(1:4, 2)
)

   k2
k1  1 2 3 4
  1 1 0 0 0
  2 0 1 0 0
  3 0 0 1 0
  4 0 0 0 1

I am trying to make use of tableGrob to output some tables, composed with other ggplot components in grid.arrange. However, the axis labels are lost.

grid.arrange(tableGrob(
  table(
    k1=matrix(1:4, 2),
    k2=matrix(1:4, 2)
  )
))

All I want to do is have those included or even include them manually after making the grob.

Thanks

Edit: Attempt with annotation_custom:

Code:

ggTableAxis2 <- function(t) {
  my_grob <- tableGrob(t)

  my_plot <- ggplot(mapping = aes(k2, k1)) +
    annotation_custom(my_grob) +
    scale_x_continuous(position = 'top') +
    theme(axis.title =  element_text(angle = 0, hjust = 0),
          axis.title.x.top =  element_text(hjust = 0))
  return(my_plot)
}

grid.arrange(
  ggTableAxis2(
    table(
      k1=matrix(1:4, 2),
      k2=matrix(1:4, 2)
    )
  ),
  ggTableAxis2(
    table(
      k1=matrix(1:4, 2),
      k2=matrix(1:4, 2)
    )
  ),
  nrow=1
)

Body:
You could use an empty ggplot with mapped aesthetics:

library(grid)
library(gridExtra)
library(ggplot2)

my_grob <- tableGrob(table(k1 = matrix(1:4, 2), k2 = matrix(1:4, 2)))

my_plot <- ggplot(mapping = aes(k2, k1)) +
  annotation_custom(my_grob) +
  scale_x_continuous(position = 'top') +
  theme(axis.title.y =  element_text(angle = 0),
        axis.title.x.top =  element_text(hjust = 0))

grid.arrange(my_plot, my_plot, my_plot, my_plot)


问:
Grails Mail Plugin Office365
I have a code that sends mail using the following config.
It works on development (windows, java 1.7, grails 2.3.7) but not in production (ubuntu, tomcat7, jdk 1.7)

Anyone has any idea why this works on dev but not in prod? anyway to fix this?

Sidenote: This code used to work, but suddenly it stop working. Don't know what changed.

Config:

```<code>grails {
   mail {
     host = "Outlook.office365.com"
     port = 587
     username = "username here"
     password = "password here"
     props = ["mail.smtp.starttls.enable":"true" ,
                "mail.smtp.port":"587",
                // "mail.debug":"true"
            ]
   }
}
</code>```

Edit1: Good point in the comments, forgot to include the error. Hope to see some suggestions as fast as the comments! :)

```<code>Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: Outlook.office365.com, 587; timeout -1; nested exception is: java.net.UnknownHostException: Outlook.office365.com. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: Outlook.office365.com, 587; timeout -1; nested exception is: java.net.UnknownHostException: Outlook.office365.com
</code>```

答:
Ok guys, after struggling for some time, I found out that the damn dns changed.....

After changing the dns and a restart it went back to normal again.

Thank you for your advice and following up the question.

(Tried to telnet with no response whatsoever. Check dns and tried to ping with no response whatsoever. Couldn't even ping stackoverflow. Changed to some other dns. Restart.)

Title: Grails Mail Plugin Office365

Body:
I have a code that sends mail using the following config.
It works on development (windows, java 1.7, grails 2.3.7) but not in production (ubuntu, tomcat7, jdk 1.7)

Anyone has any idea why this works on dev but not in prod? anyway to fix this?

Sidenote: This code used to work, but suddenly it stop working. Don't know what changed.

Config:

grails {
   mail {
     host = "Outlook.office365.com"
     port = 587
     username = "username here"
     password = "password here"
     props = ["mail.smtp.starttls.enable":"true" ,
                "mail.smtp.port":"587",
                // "mail.debug":"true"
            ]
   }
}

Edit1: Good point in the comments, forgot to include the error. Hope to see some suggestions as fast as the comments! :)

Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: Outlook.office365.com, 587; timeout -1; nested exception is: java.net.UnknownHostException: Outlook.office365.com. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: Outlook.office365.com, 587; timeout -1; nested exception is: java.net.UnknownHostException: Outlook.office365.com


问:
Design Issue - Creating aspx pages dynamically
I currently have a web application that serves a single dashboard page. The client would like multiple dashboards for different systems displayed on the same physical machine.  They would like to avoid installing many instances of the application as this would require opening up too many ports to view different dashboards.

They have suggested I alter my application to include multiple tabs/pages for each dashboard. Currently I have some C# classes which gather and process the data and feed it into the Default.aspx.cs file which then uses Web HTML controls to generate the html content and feed it into Default.aspx page via a placeholder.

At runtime I don't know how many Dashboards there will be or what they will be called (the C# classes read information from textfiles located in each dashboard directory on the drive, C:\Dashboard1*.txt C:\Dashboard2*.txt).

I am new to this and I'm struggling to see how to split the design out so that I can dynamically create the aspx.cs file and aspx file for each dashboard object.

Would a solution be to create a Dashboard.cs class that handles all the html generation (in place of default.aspx.cs) and creates an aspx page dynamically for each dashboard found on C:. Would all of the Web HTMLControls still work without a link between an aspx.cs file and a aspx file?

I realise this question is vague...more specifically I guess I am asking:

How do I create an aspx page dynamically from a C# class and then add web html controls to it?  E.g. create the aspx page from a template and then use controls like HTMLGenericControl RowDiv = new HTMLGenericControl('div').  I wouldn't know how to link my C# class to the newly created aspx page so that the HTML Web controls knew they were supposed to be added to that new aspx page.

答: I would create the dashboard as an user control, and add the controls you need dynamically. Doing it like this you also have the option to create different looking dashboards (if you need it).</p>


问:
Compatibility between Mac and Windows MATLAB Gui
I am quite familiar with MATLAB, although not so much with writing GUIs in it. Now my boss gave me a MATLAB program with GUI which was developed on a Windows machine and runs there without problems. I copied it to my mac (osx 10.6.5 with MATLAB R2009b) using a USB memory stick and tried to work on the files on my computer.

When starting the GUI, some of the callbacks are executed, some not. I was able to open the figure file containing the GUI in GUIDE, but there cannot click on the callback fields in the Property inspector. Also some components are not shown in GUIDE which are visible when running the GUI. First I suspected it might be corrupted by changed newline characters, but learned that .fig files are binary, so this should not be the case. I opened the binary .fig file with a text editor and found the following ASCII line followed by binary data:

```<code>MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Tue Aug 10 17:11:57 2010
</code>```

Are the GUIs created with MATLAB OS specific? Wouldn't this be really stupid?

I opened the files on the windows machine again and tried to export them or save them by specifying that I want them to be compatible with other operating systems but could not find an option like this.

Of course I researched this on google, and wondered that I did not really find something related. If an incompatibility exists, I think this would have been discussed, right?

Anyone knows about it or had the same problem before?

答:
Hmmm, ok. Well, the answer is quite embarrassing but still bears some potential to learn from it. The folder that my boss gave me contained a lot of files and figures with similar names, like:

bla1.fig

bla.fig

bla0.fig

the simple problem was, the first time I opened the figure with GUIDE I opened figure bla.fig instead of bla1.fig. After this I always used the reopen function of GUIDE and did not see that it was always the wrong file. this caused the problems.

==> so there is no incompatibility between Mac and PC, although I wonder why the platform is written in the file then

==> it could have been a problem with backwards-compatibility as the original figure was created with MATLAB 5

==> as @Adrian and @Mikhail pointed out: it would be very very useful to use a Version control system in order to prevent to have hundreds of files with different numbers where most of them are of no use anymore

Body:
I am quite familiar with MATLAB, although not so much with writing GUIs in it. Now my boss gave me a MATLAB program with GUI which was developed on a Windows machine and runs there without problems. I copied it to my mac (osx 10.6.5 with MATLAB R2009b) using a USB memory stick and tried to work on the files on my computer.

When starting the GUI, some of the callbacks are executed, some not. I was able to open the figure file containing the GUI in GUIDE, but there cannot click on the callback fields in the Property inspector. Also some components are not shown in GUIDE which are visible when running the GUI. First I suspected it might be corrupted by changed newline characters, but learned that .fig files are binary, so this should not be the case. I opened the binary .fig file with a text editor and found the following ASCII line followed by binary data:

MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Tue Aug 10 17:11:57 2010

Are the GUIs created with MATLAB OS specific? Wouldn't this be really stupid?

I opened the files on the windows machine again and tried to export them or save them by specifying that I want them to be compatible with other operating systems but could not find an option like this.

Of course I researched this on google, and wondered that I did not really find something related. If an incompatibility exists, I think this would have been discussed, right?

Anyone knows about it or had the same problem before?


答:
not sure where exactly you want the labels, but it's probably easiest to add grobs to the gtable,

```<code>tbl <- table(
  longlabel1=matrix(1:4, 2),
  longlabel2=matrix(1:4, 2)
)

nms <- names(dimnames(tbl))

library(gridExtra)
library(grid)
library(gtable)
grid.newpage()

tg <- textGrob(nms[1], x=0, hjust=0)
lg <- textGrob(nms[2], x=1, hjust=1)
g <- tableGrob(tbl)
g <- gtable_add_rows(g, unit(1,"line"), 0)
g <- gtable_add_cols(g, grobWidth(lg), 0)
g <- gtable_add_grob(g, tg, t = 1, l=3, r=ncol(g))
g <- gtable_add_grob(g, lg, l = 1, t=2)
grid.draw(g)
</code>```

Title: Add axis labels to tableGrob in R

Body:
not sure where exactly you want the labels, but it's probably easiest to add grobs to the gtable,

tbl <- table(
  longlabel1=matrix(1:4, 2),
  longlabel2=matrix(1:4, 2)
)

nms <- names(dimnames(tbl))

library(gridExtra)
library(grid)
library(gtable)
grid.newpage()

tg <- textGrob(nms[1], x=0, hjust=0)
lg <- textGrob(nms[2], x=1, hjust=1)
g <- tableGrob(tbl)
g <- gtable_add_rows(g, unit(1,"line"), 0)
g <- gtable_add_cols(g, grobWidth(lg), 0)
g <- gtable_add_grob(g, tg, t = 1, l=3, r=ncol(g))
g <- gtable_add_grob(g, lg, l = 1, t=2)
grid.draw(g)


问:
cannot not step into function while debugging
my simple test cpp is followed:

```<code>#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

void hello(string str) {
    cout << str << endl;
}

int main(int argc, const char **argv) {
    string str = "hello world!";
    hello(str);
    return 0;
}
</code>```

and I compile the cpp with command:

```<code>g++ hello.cpp -o hello -g
</code>```

and then run as debug mode:

```<code>cgdb hello
(gdb) b main
(gdb) r
(gdb) n
(gdb) s
</code>```

after I use step command in gdb, I got the following errors:

```<code>std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0x7fffffffe5c0, __str="hello world!") at /build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h:399
399     /build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h: No such file or directory.
</code>```

I found that this error only happen when the function has arguments with type of string. For example:

```<code>void hello(int i);
</code>```

I can step into the function hello without any problem.

I use the following command to find where allocator.h is:

```<code>sudo find / | grep allocator.h
</code>```

and I got the results as follow(only list part of the results):

```<code>/usr/include/c++/6.3.1/ext/bitmap_allocator.h
/usr/include/c++/6.3.1/ext/debug_allocator.h
/usr/include/c++/6.3.1/ext/new_allocator.h
/usr/include/c++/6.3.1/ext/extptr_allocator.h
/usr/include/c++/6.3.1/ext/throw_allocator.h
/usr/include/c++/6.3.1/ext/pool_allocator.h
/usr/include/c++/6.3.1/ext/array_allocator.h
/usr/include/c++/6.3.1/ext/malloc_allocator.h
/usr/include/c++/6.3.1/x86_64-pc-linux-gnu/bits/c++allocator.h
/usr/include/c++/6.3.1/bits/allocator.h
/usr/include/c++/6.3.1/bits/uses_allocator.h
/usr/include/gc/gc_allocator.h
</code>```

Why would this happen?
THX!!!

答:
Why would this happen?

You wanted to step into void hello() but stepped into std::string copy constructor. Now you can go out of std::string constructor using finish command and step into void hello():

```<code>(gdb) finish
(gdb) step
</code>```

Another option is to pass string argument to void hello() by reference to avoid unnecessary copying. That way you will step into desired function with only a single step:

```<code>void hello(const string& str) {
    cout << str << endl;
}
</code>```

Body:
my simple test cpp is followed:

#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

void hello(string str) {
    cout << str << endl;
}

int main(int argc, const char **argv) {
    string str = "hello world!";
    hello(str);
    return 0;
}

and I compile the cpp with command:

g++ hello.cpp -o hello -g

and then run as debug mode:

cgdb hello
(gdb) b main
(gdb) r
(gdb) n
(gdb) s

after I use step command in gdb, I got the following errors:

std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0x7fffffffe5c0, __str="hello world!") at /build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h:399
399     /build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h: No such file or directory.

I found that this error only happen when the function has arguments with type of string. For example:

void hello(int i);

I can step into the function hello without any problem.

I use the following command to find where allocator.h is:

sudo find / | grep allocator.h

and I got the results as follow(only list part of the results):

/usr/include/c++/6.3.1/ext/bitmap_allocator.h
/usr/include/c++/6.3.1/ext/debug_allocator.h
/usr/include/c++/6.3.1/ext/new_allocator.h
/usr/include/c++/6.3.1/ext/extptr_allocator.h
/usr/include/c++/6.3.1/ext/throw_allocator.h
/usr/include/c++/6.3.1/ext/pool_allocator.h
/usr/include/c++/6.3.1/ext/array_allocator.h
/usr/include/c++/6.3.1/ext/malloc_allocator.h
/usr/include/c++/6.3.1/x86_64-pc-linux-gnu/bits/c++allocator.h
/usr/include/c++/6.3.1/bits/allocator.h
/usr/include/c++/6.3.1/bits/uses_allocator.h
/usr/include/gc/gc_allocator.h

Why would this happen?
THX!!!

Body:
Why would this happen?

You wanted to step into void hello() but stepped into std::string copy constructor. Now you can go out of std::string constructor using finish command and step into void hello():

(gdb) finish
(gdb) step

Another option is to pass string argument to void hello() by reference to avoid unnecessary copying. That way you will step into desired function with only a single step:

void hello(const string& str) {
    cout << str << endl;
}


问:
Can I inject a service into CanActivate?
Unlike the other hooks, CanActivate is a function separated from the component.

```<code>import 'dart:async';
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';

@Component(selector: 'my-app', template: '<h1>Hello World!</h1>')
@CanActivate(someGuard)
class HelloComponent {}

FutureOr<bool> someGuard(ComponentInstruction next, ComponentInstruction prev) {
  return true;
}
</code>```

AFAIK, it is possible to intercept the root injector at bootstrap time and assign it to a global variable, so that I can access it anywhere. IMO, that sounds like a hack and I don't like it. Is there a proper way to inject a service in CanActivate hook?

答:
Angulars DI only supports constructor injection. @CanActivate() is an annotation and therefore doesn't support DI.

There is a workaround though.

Create a variable in a library and import it

```<code>Injector injector;
</code>```

assign the injector when the application is created

```<code>bootstrap(App, [
  Auth,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(LocationStrategy, useClass: HashLocationStrategy)
]).then((appRef: ComponentRef) => {
  // store a reference to the application injector
  injector = appRef.injector;
});
</code>```

then you can import the library with the injector and access it from code someGuard()

Body:
Unlike the other hooks, CanActivate is a function separated from the component.

import 'dart:async';
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';

@Component(selector: 'my-app', template: '
Hello World!
')
@CanActivate(someGuard)
class HelloComponent {}

FutureOr<bool> someGuard(ComponentInstruction next, ComponentInstruction prev) {
  return true;
}

AFAIK, it is possible to intercept the root injector at bootstrap time and assign it to a global variable, so that I can access it anywhere. IMO, that sounds like a hack and I don't like it. Is there a proper way to inject a service in CanActivate hook?

Body:
Angulars DI only supports constructor injection. @CanActivate() is an annotation and therefore doesn't support DI.

There is a workaround though.

Create a variable in a library and import it

Injector injector;

assign the injector when the application is created

bootstrap(App, [
  Auth,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(LocationStrategy, useClass: HashLocationStrategy)
]).then((appRef: ComponentRef) => {
  // store a reference to the application injector
  injector = appRef.injector;
});

then you can import the library with the injector and access it from code someGuard()


问:
Suggest an alternative for gets() function, using gcc compiler
Trying to input more than a single string in my program's strings array, for that used :

scanf("%80[^\r\n]", strings[i]);

fgets(string[i], MAXLEN, stdin);

a custom made function was also used:

```<code>int getString(char s[]) {

    char ch;
    int i=0;

    while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
        s[i] = ch;
        ++i;
    }

    s[i] = '\0';

    fflush(stdin);

    return i;
}
</code>```

but unable to get input with more than one string each including white spaces

function gets() used to work earlier for me but since it is deprecated no alternative can be found

This is where it was used :

```<code>int getString(char s[]) {

char ch;
int i=0;

while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
    s[i] = ch;
    ++i;
}

s[i] = '\0';

fflush(stdin);

return i;
}

struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
    double price;
} data[5];

int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");

int i=0;
while(i < 5) {
    printf("Input vechile Type : \n");
    fgets(data[i].vechileType, MAXLEN, stdin);

    printf("Input begin month : \n");
    scanf("%d", &data[i].begin_month);

    printf("Input end monhth : \n");
    scanf("%d", &data[i].end_month);

    printf("Input price : \n");
    scanf("%lf", &data[i].price);

    ++i;
}

printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);

i=0;
while(i < 5) {
    if (strcmp(vech,data[i].vechileType) == 0)
    {
        printf("vechileType: %s\n", data[i].vechileType);
        printf("Begin month: %d\n", data[i].begin_month);
        printf("End month: %d\n", data[i].end_month);
        printf("Price : %lf\n", data[i].price);
    }
    ++i;
}

return 0;
}
</code>```

It skips the next input to string statement during run time, "seems to"

答:
Actually, there you can use while((getchar())!='\n'); to avoid such type of problem and one thing there is no need to use of fflush(stdin) function.
Here's code you can use

```<code>#include<stdio.h>
#include<string.h>
#define MAXLEN 50
int getString(char s[])
{
    char ch;
    int i=0;
    while( (ch = getchar()) != '\n'   &&   ch != EOF )
    {
        s[i] = ch;
        ++i;
    }
    s[i] = '\0';
    return i;
}
struct vechileData
{
    char vechileType[MAXLEN];
    int begin_month;
    int end_month;
    double price;
}data[5];
int main(int argc, char const *argv[])
{
    printf("Input Vechile data: \n");
    int i=0;
    while(i < 2)
    {
        printf("Input vechile Type : \n");
        fgets(data[i].vechileType, MAXLEN, stdin);

        printf("Input begin month : \n");
        scanf("%d", &data[i].begin_month);

        printf("Input end monhth : \n");
        scanf("%d", &data[i].end_month);

        printf("Input price : \n");
        scanf("%lf", &data[i].price);
        while((getchar())!='\n');
        ++i;
    }
    printf("Input Vechile Type to display information about the vechile : \n");
    char vech[MAXLEN];
    fgets(vech, MAXLEN, stdin);
    i=0;
    while(i < 2)
    {
        if (strcmp(vech,data[i].vechileType) == 0)
        {
            printf("vechileType: %s\n", data[i].vechileType);
            printf("Begin month: %d\n", data[i].begin_month);
            printf("End month: %d\n", data[i].end_month);
            printf("Price : %lf\n", data[i].price);
        }
        ++i;
    }
    return 0;
}
</code>```

I hope this will help you.....

Body:
Trying to input more than a single string in my program's strings array, for that used :

scanf("%80[^\r\n]", strings[i]);

fgets(string[i], MAXLEN, stdin);

a custom made function was also used:

int getString(char s[]) {

    char ch;
    int i=0;

    while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
        s[i] = ch;
        ++i;
    }

    s[i] = '\0';

    fflush(stdin);

    return i;
}

but unable to get input with more than one string each including white spaces

function gets() used to work earlier for me but since it is deprecated no alternative can be found

This is where it was used :

int getString(char s[]) {

char ch;
int i=0;

while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
    s[i] = ch;
    ++i;
}

s[i] = '\0';

fflush(stdin);

return i;
}

struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
    double price;
} data[5];

int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");

int i=0;
while(i < 5) {
    printf("Input vechile Type : \n");
    fgets(data[i].vechileType, MAXLEN, stdin);

    printf("Input begin month : \n");
    scanf("%d", &data[i].begin_month);

    printf("Input end monhth : \n");
    scanf("%d", &data[i].end_month);

    printf("Input price : \n");
    scanf("%lf", &data[i].price);

    ++i;
}

printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);

i=0;
while(i < 5) {
    if (strcmp(vech,data[i].vechileType) == 0)
    {
        printf("vechileType: %s\n", data[i].vechileType);
        printf("Begin month: %d\n", data[i].begin_month);
        printf("End month: %d\n", data[i].end_month);
        printf("Price : %lf\n", data[i].price);
    }
    ++i;
}

return 0;
}

It skips the next input to string statement during run time, "seems to"

Body:
Actually, there you can use while((getchar())!='\n'); to avoid such type of problem and one thing there is no need to use of fflush(stdin) function.
Here's code you can use

#include<stdio.h>
#include<string.h>
#define MAXLEN 50
int getString(char s[])
{
    char ch;
    int i=0;
    while( (ch = getchar()) != '\n'   &&   ch != EOF )
    {
        s[i] = ch;
        ++i;
    }
    s[i] = '\0';
    return i;
}
struct vechileData
{
    char vechileType[MAXLEN];
    int begin_month;
    int end_month;
    double price;
}data[5];
int main(int argc, char const *argv[])
{
    printf("Input Vechile data: \n");
    int i=0;
    while(i < 2)
    {
        printf("Input vechile Type : \n");
        fgets(data[i].vechileType, MAXLEN, stdin);

        printf("Input begin month : \n");
        scanf("%d", &data[i].begin_month);

        printf("Input end monhth : \n");
        scanf("%d", &data[i].end_month);

        printf("Input price : \n");
        scanf("%lf", &data[i].price);
        while((getchar())!='\n');
        ++i;
    }
    printf("Input Vechile Type to display information about the vechile : \n");
    char vech[MAXLEN];
    fgets(vech, MAXLEN, stdin);
    i=0;
    while(i < 2)
    {
        if (strcmp(vech,data[i].vechileType) == 0)
        {
            printf("vechileType: %s\n", data[i].vechileType);
            printf("Begin month: %d\n", data[i].begin_month);
            printf("End month: %d\n", data[i].end_month);
            printf("Price : %lf\n", data[i].price);
        }
        ++i;
    }
    return 0;
}

I hope this will help you.....


问:
Filter with ui-select Reversely
How can I filter the select options reversely?
I used ui-select for filtering my multi-select options. I can filter city based on country.
I want to add filtering country by city and tag the country name in the option.

Please take a look at this FIDDLE

答:
You need to implement this method to do this

```<code>$scope.getCityListByCity=function(){
      var sampletemp = [];
      $scope.selected.city.forEach(function(city) {
    var temp =  objectFromArrayFilter($scope.samples,'city',city);
    sampletemp = sampletemp.concat(temp);
            });
      $scope.uniquecountry = $filter('unique')(sampletemp, 'country');
        $scope.selected.country= [];

       $scope.country = $scope.uniquecountry.map(function(item) {
      return item.country
        })
      $scope.selected.country=$scope.country;

      if($scope.country.length == 0){

        $scope.uniquecountry = $filter('unique')($scope.samples, 'country');
    $scope.country = $scope.uniquecountry.map(function(item) {
      return item.country
    })
      }

    }
</code>```

please refer this working fiddle as per your requirement

Title: Filter with ui-select Reversely

Body:
You need to implement this method to do this

$scope.getCityListByCity=function(){
      var sampletemp = [];
      $scope.selected.city.forEach(function(city) {
    var temp =  objectFromArrayFilter($scope.samples,'city',city);
    sampletemp = sampletemp.concat(temp);
            });
      $scope.uniquecountry = $filter('unique')(sampletemp, 'country');
        $scope.selected.country= [];

       $scope.country = $scope.uniquecountry.map(function(item) {
      return item.country
        })
      $scope.selected.country=$scope.country;

      if($scope.country.length == 0){

        $scope.uniquecountry = $filter('unique')($scope.samples, 'country');
    $scope.country = $scope.uniquecountry.map(function(item) {
      return item.country
    })
      }

    }

please refer this working fiddle as per your requirement


问:
Creating a method that uses WebBrowser and returns HTML?
How do you create a method that does this:

Login to a website, then read a (member-only) page and return the HTML.

I came up with this (which obviously doesn't work because I don't know how to make it return the page content)

```<code>public string LoginAndReadPage() {
    WebBrowser wb = new WebBrowser();
    wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
    wb.Navigate("hxxp://mysite.com/login");
}

private async void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (wb.Url.ToString().Contains("login"))
    {
        wb.Document.GetElementsByTagName("input").GetElementsByName("email")[0].SetAttribute("value", _login);
        wb.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", _password);
        wb.Document.GetElementsByTagName("button")[0].InvokeMember("click");
    }
    else if (wb.Url.ToString().Contains("dashboard"))
    {
        return wb.DocumentText; // I want to return the content of mysite.com/dashboard
    }
    else
    {
        await Task.Delay(1000); //wait for 1 second just to let the WB catch up
        wb.Navigate("hxxp://mysite.com/dashboard");
    }
}
</code>```

Thanks in advance

答:
What you're trying to do is called "scraping" or sometimes "webscraping". It's a big topic so I'd recommend googling it.

Potentially you could use something like Selenium via the C# Driver to do this as well. Selenium was designed for automated UI testing but it definitely has all the tools you need to do what you want.

Body:
How do you create a method that does this:

Login to a website, then read a (member-only) page and return the HTML.

I came up with this (which obviously doesn't work because I don't know how to make it return the page content)

public string LoginAndReadPage() {
    WebBrowser wb = new WebBrowser();
    wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
    wb.Navigate("hxxp://mysite.com/login");
}

private async void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (wb.Url.ToString().Contains("login"))
    {
        wb.Document.GetElementsByTagName("input").GetElementsByName("email")[0].SetAttribute("value", _login);
        wb.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", _password);
        wb.Document.GetElementsByTagName("button")[0].InvokeMember("click");
    }
    else if (wb.Url.ToString().Contains("dashboard"))
    {
        return wb.DocumentText; // I want to return the content of mysite.com/dashboard
    }
    else
    {
        await Task.Delay(1000); //wait for 1 second just to let the WB catch up
        wb.Navigate("hxxp://mysite.com/dashboard");
    }
}

Thanks in advance