问:
Python Error 13
We have a computer here at the office that is getting a permission error when we run "pip install opencv-python" from a powershell cmd window.

I tested this on a separate computer and it installed without a hitch. I tried this same command on the problem machine from a domain admin login and get the same permission issue.

Any ideas how to resolve this problem?

Error:

```<code>PS C:\users> pip install opencv-python
Collecting opencv-python
Using cached opencv_python-3.2.0.6-cp36-cp36m-win32.whl
Collecting numpy>=1.11.3 (from opencv-python)
Using cached numpy-1.12.1-cp36-none-win32.whl
Exception:
Traceback (most recent call last):
File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
status = self.run(options, args)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 324, in run
requirement_set.prepare_files(finder)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
session=self.session, hashes=hashes)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\download.py", line 821, in unpack_url
hashes=hashes
File "c:\program files (x86)\python36-32\lib\site-packages\pip\download.py", line 663, in unpack_http_url
unpack_file(from_path, location, content_type, link)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 599, in unpack_file
flatten=not filename.endswith('.whl')
File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 499, in unzip_file
fp = open(fn, 'wb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\%username&\\AppData\\Local\\Temp\\pip-build-g1uoy1vs\\numpy\\numpy/distutils/mingw/gfortran_vs2003_hack.c'
</code>```

答:
You have to set the root permission:

```<code>sudo pip install opencv-python
</code>```

now it should work

Title: Python Error 13

Body:
We have a computer here at the office that is getting a permission error when we run "pip install opencv-python" from a powershell cmd window.

I tested this on a separate computer and it installed without a hitch. I tried this same command on the problem machine from a domain admin login and get the same permission issue.

Any ideas how to resolve this problem?

Error:

PS C:\users> pip install opencv-python
Collecting opencv-python
Using cached opencv_python-3.2.0.6-cp36-cp36m-win32.whl
Collecting numpy>=1.11.3 (from opencv-python)
Using cached numpy-1.12.1-cp36-none-win32.whl
Exception:
Traceback (most recent call last):
File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
status = self.run(options, args)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 324, in run
requirement_set.prepare_files(finder)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
session=self.session, hashes=hashes)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\download.py", line 821, in unpack_url
hashes=hashes
File "c:\program files (x86)\python36-32\lib\site-packages\pip\download.py", line 663, in unpack_http_url
unpack_file(from_path, location, content_type, link)
File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 599, in unpack_file
flatten=not filename.endswith('.whl')
File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 499, in unzip_file
fp = open(fn, 'wb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\%username&\\AppData\\Local\\Temp\\pip-build-g1uoy1vs\\numpy\\numpy/distutils/mingw/gfortran_vs2003_hack.c'

Body:
You have to set the root permission:

sudo pip install opencv-python

now it should work


来源: stackexchange

问:
Handlebars confusion I don't get it
I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys

https://codepen.io/blaze4dem/pen/zZmqKa

```<code>    var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options){
      var radioList = options.fn();
      radioList = radioList.trim().split("\n");

      var output = "";
      for(var val in radioList){
        var item = radioList(val).trim();
      output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
      };
      return output;
    });

    var tempdata = template({});
    document.getElementById('dynamic').innaHTML += tempdata;
</code>```

答:
I see 3 issues in the code.

for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.

You have a typo, when you are replacing the element. Supposed to be innerHTML

radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].

You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n

```<code>var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options) {
  debugger;
  var radioList = options.fn();
  var hasSpaces = radioList.indexOf(' ') > -1;
  var hasNewLines = radioList.indexOf('\n') > -1;

  if (hasNewLines) {
    radioList = radioList.trim().split("\n");
  } else if (hasSpaces) {
    radioList = radioList.trim().split(" ");
  }

  var output = "";
  // for in is best to iterate over objects.
  // use for loop instead
  for (var i = 0; i < radioList.length; i++) {
    var item = radioList[i].trim();
    output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
  };
  return output;
});

var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;
</code>```

Check Fiddle

ContentLicense: CC BY-SA 3.0

Title: Handlebars confusion I don't get it

Body:
I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys

https://codepen.io/blaze4dem/pen/zZmqKa

    var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options){
      var radioList = options.fn();
      radioList = radioList.trim().split("\n");

      var output = "";
      for(var val in radioList){
        var item = radioList(val).trim();
      output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '
';
      };
      return output;
    });

    var tempdata = template({});
    document.getElementById('dynamic').innaHTML += tempdata;

Body:
I see 3 issues in the code.

for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.

You have a typo, when you are replacing the element. Supposed to be innerHTML

radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].

You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n

var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options) {
  debugger;
  var radioList = options.fn();
  var hasSpaces = radioList.indexOf(' ') > -1;
  var hasNewLines = radioList.indexOf('\n') > -1;

  if (hasNewLines) {
    radioList = radioList.trim().split("\n");
  } else if (hasSpaces) {
    radioList = radioList.trim().split(" ");
  }

  var output = "";
  // for in is best to iterate over objects.
  // use for loop instead
  for (var i = 0; i < radioList.length; i++) {
    var item = radioList[i].trim();
    output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
  };
  return output;
});

var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;

Check Fiddle


问:
How to construct two particle Brownian trajectory with respect to time in MATLAB?
I am studying a MATLAB code for constructing two dimensional Brownian motion trajectory generation,  from this link, it is given as:

```<code>particle = struct();
particle.x = cumsum( randn(N, 1) );
particle.y = cumsum( randn(N, 1) );
plot(particle.x, particle.y);
ylabel('Y Position');
xlabel('X Position');
title('position versus time in 2D');
</code>```

I want to generate two such Brownian particles but with a time gap i.e. suppose one particle is generated at '0' time than another one is at time 't'. I have no clue as how to incorporate this, in the this or some other code. Can somebody help?

答:
Just to highlight @RPM 's answer; here is some code which shows the animation of 10 successive launches of independent particles from (0,0):

```<code>close all; clear; clc;

N = 1e3; % Number of steps overall
Np = 10; % Number of diffusing particles
delay = 100; % Delay (in steps) between the launches

% Initialise particles at (0,0)
for k = 1:Np
   particle(k).x = nan(N,1); particle(k).x(1) = 0; %#ok<SAGROW>
   particle(k).y = nan(N,1); particle(k).y(1) = 0; %#ok<SAGROW>
end

% Take N-1 random steps
figure(1); axes;
for j = 2:N
    for k = 1:ceil((j-1)./delay)
        particle(k).x(j) = particle(k).x(j-1) + randn;
        particle(k).y(j) = particle(k).y(j-1) + randn;
    end
    for k = (ceil((j-1)./delay)+1):Np
        particle(k).x(j) = particle(k).x(j-1);
        particle(k).y(j) = particle(k).y(j-1);
    end
    % Plot the step
    plot(particle(1).x, particle(1).y); hold on;
    for k = 2:Np
        plot(particle(k).x, particle(k).y);
    end
    hold off;
    axis equal;
    title(sprintf('#%d',j));
    drawnow; pause(0.01);
end
</code>```

This is just for demonstration. Please use @RPM 's code - rand(N,1) as opposed to a for loop!

ContentLicense: CC BY-SA 4.0

Body:
I am studying a MATLAB code for constructing two dimensional Brownian motion trajectory generation,  from this link, it is given as:

particle = struct();
particle.x = cumsum( randn(N, 1) );
particle.y = cumsum( randn(N, 1) );
plot(particle.x, particle.y);
ylabel('Y Position');
xlabel('X Position');
title('position versus time in 2D');

I want to generate two such Brownian particles but with a time gap i.e. suppose one particle is generated at '0' time than another one is at time 't'. I have no clue as how to incorporate this, in the this or some other code. Can somebody help?

Body:
Just to highlight @RPM 's answer; here is some code which shows the animation of 10 successive launches of independent particles from (0,0):

close all; clear; clc;

N = 1e3; % Number of steps overall
Np = 10; % Number of diffusing particles
delay = 100; % Delay (in steps) between the launches

% Initialise particles at (0,0)
for k = 1:Np
   particle(k).x = nan(N,1); particle(k).x(1) = 0; %#ok<SAGROW>
   particle(k).y = nan(N,1); particle(k).y(1) = 0; %#ok<SAGROW>
end

% Take N-1 random steps
figure(1); axes;
for j = 2:N
    for k = 1:ceil((j-1)./delay)
        particle(k).x(j) = particle(k).x(j-1) + randn;
        particle(k).y(j) = particle(k).y(j-1) + randn;
    end
    for k = (ceil((j-1)./delay)+1):Np
        particle(k).x(j) = particle(k).x(j-1);
        particle(k).y(j) = particle(k).y(j-1);
    end
    % Plot the step
    plot(particle(1).x, particle(1).y); hold on;
    for k = 2:Np
        plot(particle(k).x, particle(k).y);
    end
    hold off;
    axis equal;
    title(sprintf('#%d',j));
    drawnow; pause(0.01);
end

This is just for demonstration. Please use @RPM 's code - rand(N,1) as opposed to a for loop!


问:
Git based automatic versioning in Gradle
I'd like to implement automatic versioning for java-projects in Gradle via Git tags. Currently I'm using the git describe command to generate a version string. The version string has to be used in a manifest-file and also be programmatically retrievable. This is why I implemented a method to save it in a properties file that get's included in the build and can be read by Java code.

What I currently have is this small Gradle plugin (I'm really new to gradle):

```<code>apply plugin: 'java'
apply plugin: VersioningPlugin

class VersioningPlugin implements Plugin<Project> {

    private Project project;

    private String getVersion() {
        def stdout = new ByteArrayOutputStream()
        project.exec {
            commandLine 'git', 'describe', '--tags'
            standardOutput = stdout
        }
        stdout.toString().trim()
    }

    @Override
    void apply(Project project) {
        this.project = project

        project.extensions.create('versioning', VersioningPluginExtension)

        project.versioning.version = getVersion()

        project.task('writeVersionFile') {
            doLast {
                def versionPropsFile = project.versioning.versionFile
                def versionProps = new Properties()
                versionProps.put('version', getVersion())
                versionProps.store(versionPropsFile.newWriter(), null)
            }
        }
    }
}

class VersioningPluginExtension {
    File versionFile
    String version
}

compileJava.dependsOn writeVersionFile
</code>```

I use it in my build scrips like this:

```<code>apply from: 'versioning.gradle'
versioning {
  versionFile = file('my/ressource/folder/version.properties')
}
println(versioning.version)
</code>```

Everything works OK. The only problem I have is the following: I use gradle to build and test my code, then commit the code and create a git tag. If I now ask gradle to package a jar file without cleaning first, it doesn't copy the new version.properties into the jar file because it didn't notice that the file changed. So my application shows the old version.

Is there anything I can do about this? How can I get gradle to notice the version change and create a jar with the current version.properties file?

答:
What you need to do is to configure a TaskOutputs (or from) for Jar task so that it can recognize if something has changed and be run without calling clean explicitly. This can be done in the following way:

```<code>jar {
  from versioning.versionFile
}
</code>```

Secondly. You can configure writeVersionFile in a similar way. If you configure both inputs and outputs the task will be cacheable. How it has changed can been seen here, a demo can be found here.

Also, mind that your task is created now in afterEvaluate closure. Why is that? Because this is after versioning {} extension is executed and versionFile property is set and can be configured as an output.

You can also configure jar input in versioning.gradle file.

Body:
I'd like to implement automatic versioning for java-projects in Gradle via Git tags. Currently I'm using the git describe command to generate a version string. The version string has to be used in a manifest-file and also be programmatically retrievable. This is why I implemented a method to save it in a properties file that get's included in the build and can be read by Java code.

What I currently have is this small Gradle plugin (I'm really new to gradle):

apply plugin: 'java'
apply plugin: VersioningPlugin

class VersioningPlugin implements Plugin<Project> {

    private Project project;

    private String getVersion() {
        def stdout = new ByteArrayOutputStream()
        project.exec {
            commandLine 'git', 'describe', '--tags'
            standardOutput = stdout
        }
        stdout.toString().trim()
    }

    @Override
    void apply(Project project) {
        this.project = project

        project.extensions.create('versioning', VersioningPluginExtension)

        project.versioning.version = getVersion()

        project.task('writeVersionFile') {
            doLast {
                def versionPropsFile = project.versioning.versionFile
                def versionProps = new Properties()
                versionProps.put('version', getVersion())
                versionProps.store(versionPropsFile.newWriter(), null)
            }
        }
    }
}

class VersioningPluginExtension {
    File versionFile
    String version
}

compileJava.dependsOn writeVersionFile

I use it in my build scrips like this:

apply from: 'versioning.gradle'
versioning {
  versionFile = file('my/ressource/folder/version.properties')
}
println(versioning.version)

Everything works OK. The only problem I have is the following: I use gradle to build and test my code, then commit the code and create a git tag. If I now ask gradle to package a jar file without cleaning first, it doesn't copy the new version.properties into the jar file because it didn't notice that the file changed. So my application shows the old version.

Is there anything I can do about this? How can I get gradle to notice the version change and create a jar with the current version.properties file?

Body:
What you need to do is to configure a TaskOutputs (or from) for Jar task so that it can recognize if something has changed and be run without calling clean explicitly. This can be done in the following way:

jar {
  from versioning.versionFile
}

Secondly. You can configure writeVersionFile in a similar way. If you configure both inputs and outputs the task will be cacheable. How it has changed can been seen here, a demo can be found here.

Also, mind that your task is created now in afterEvaluate closure. Why is that? Because this is after versioning {} extension is executed and versionFile property is set and can be configured as an output.

You can also configure jar input in versioning.gradle file.


问:
How to align the button right next to the search box
I am trying to align the search button right next to the search box however button seems to be below. This is what I got:</p>

```<code>        <form action="{linkto page="search.php"}" method="get" id="searchFormTest">
           <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" value="{$lang.enterKeywords}" placeholder="Suchbegriff oder Bildnummer">
              <div style="display: inline;">
                <button type="submit" value="Submit">
                  <i style="font-size: 40px;" class="fa fa-search" aria-hidden="true"></i>
               </button>
              </div>
        </form>
</code>```

答:
You code works just fine in jsfiddle. I think you should look into css styles which are being inherited by the button.</p>

```<code><form method="get" id="searchFormTest">
    <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" placeholder="Suchbegriff oder Bildnummer">
    <div style="display: inline;">
        <button type="submit" value="Submit">
            <i style="font-size: 15px;" class="fa fa-search" aria-hidden="true">Search</i>
        </button>
    </div>
</form>
</code>```

Body:
I am trying to align the search button right next to the search box however button seems to be below. This is what I got:

        <form action="{linkto page="search.php"}" method="get" id="searchFormTest">
           <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" value="{$lang.enterKeywords}" placeholder="Suchbegriff oder Bildnummer">

                <button type="submit" value="Submit">

               </button>

        </form>

Body:
You code works just fine in jsfiddle. I think you should look into css styles which are being inherited by the button.

<form method="get" id="searchFormTest">
    <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" placeholder="Suchbegriff oder Bildnummer">
    <div style="display: inline;">
        <button type="submit" value="Submit">
            <i style="font-size: 15px;" class="fa fa-search" aria-hidden="true">Search</i>
        </button>
    </div>
</form>


问:
How to implement the fork and pull model without Github or a git server?
Github is great! But, if you don't have access to Github or any other git server, and can't set up your own git server, then you're limited to using a central git repository on a Local Area Network (LAN) folder to collaborate with other developers on the same LAN.

There are two popular git workflows as far I know:

Pushing / Shared repository

Forking and Pulling

Forking and Pulling vs Pushing has some useful info.

I found lots of help online on how to get a 'Shared repository' model working (see this branching model). The model is pretty easy to implement on a LAN and doesn't require a git server. However, I am led to believe there is no control over the central repository with this workflow model.

It seems to me that the 'Forking and Pulling' model will give me control over the central repository, and allow me to freely share the repository with anyone. I wouldn't have to worry about them pushing bad code to the central repository.

However, there isn't much out there on how to implement a fork and pull workflow without a git server. I imagine the issue can be split into the following sub-questions:

How does a fellow developer submit a pull request to the central
repository owner?

How does the central repository owner see the pull
request, fetch the code from that developer's repository, test, and edit it to meet the required standard before pushing the feature to the public
repository?

How can one implement the fork and pull model without Github or a git server?

答:
How does a fellow developer submit a pull request to the central repository owner?

If everyone has publicly accessible repositories there is the git request-pull command, which generates on stdout a pull request suitable for emailing to someone.

If people don't have publicly accessible repositories, then email and git format-patch are probably how you would solve things.

How does the central repository owner see the pull request,

By reading email.

fetch the code from that developer's repository

Either pulling it from the remote repository, or using git am to apply patches that were generated with git format-patch.

test

That seems unrelated to git.  Presumably your project has a test suite that you can run.

and edit it to meet the required standard before pushing the feature to the public repository?

Just edit things locally after applying the patch(es), or ask the submitter to reformat things to meet your standards and resubmit.

The Linux Kernel uses email for managing patches; you can read about it here.


问:
AES encryption on iOS and android, output and buffer size is different
Implementing AES256 on iOS using CCCrypt function. But output and output buffer length is different than Android.

Cipher class in Android produces 48 bytes data where in iOS we get 80 bytes data.

In IOS using kCCAlgorithmAES, kCCOptionPKCS7Padding and in android using AES/CBC/PKCS5Padding.

in IOS IV is NULL and in android creating iv as new 16 bytes array.

Please help.

please find input and code for reference.

```<code> - (void)viewDidLoad {
    [super viewDidLoad];

    NSString *message = [NSString stringWithFormat:@"com.myapp.com|355004059196637|911111111111|11341e5e-9643-4559-bbb7-34d40555e96c"];
    NSString *key = [NSString stringWithFormat:@"4f28d5901b4b7b80d33fda76ca372c2a20bd1a6c2aad7fa215dc79d507330678"];
    NSString *shaEncryptMessage = [self sha256:message length:0];
    NSData *aesEncryptData = [self aesEncrypt:[shaEncryptMessage dataUsingEncoding:NSUTF8StringEncoding] key:key iv:nil];
    NSString *hMac = [aesEncryptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSLog(@"hMac = %@",hMac);

    // IOS output : Can+oQR79D3/lsQGctzY/d2VBNZbWWtJxGI8iRIu80R2yTskn9gf2oKHaRESX73u
    //                  LpJHLx1Xr6iH11jFPlmqwW7mQz0xAW4uACNAMEoZ0kY=
    // Android output : MiMDkdo5cGsPMj2qCnNobgp7dr5KMvBhGuKTonrqr1lCYte/kKegGMtI/4TPhUNI
}

- (NSString*) sha256:(NSString *)key length:(NSInteger) length{
    const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding];
    NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];

    uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
    CC_SHA256(keyData.bytes, (unsigned int)keyData.length, digest);
    NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
    NSString *hash=[out description];
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    return  hash;
}
-  (NSData *)aesEncrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv {
    char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
    ivPointer[kCCBlockSizeAES128];
    BOOL patchNeeded;
    bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding
    //key = [[StringEncryption alloc] md5:key];
    key = [self stringFromHex:key];
    patchNeeded= ([key length] > kCCKeySizeAES256+1);
    if(patchNeeded)
    {
        key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)
    }

    [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
    [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];

    //    if (patchNeeded) {
    //        keyPointer[0] = '\0';  // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256
    //    }

    NSUInteger dataLength = [plainText length];

    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
    size_t buffSize = dataLength + kCCBlockSizeAES128;
    void *buff = malloc(buffSize);

    size_t numBytesEncrypted = 0;

    CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */
                                     kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */
                                     kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */
                                     keyPointer, kCCKeySizeAES256, /* key and its length */
                                     NULL, /* initialization vector - use random IV everytime */
                                     [plainText bytes], [plainText length], /* input  */
                                     buff, buffSize,/* data RETURNED here */
                                     &numBytesEncrypted);

    if (status == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
    }

    free(buff);
    return nil;
}

- (NSString *) stringFromHex:(NSString *)str
{
    NSMutableData *stringData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [str length] / 2; i++) {
        byte_chars[0] = [str characterAtIndex:i*2];
        byte_chars[1] = [str characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return [[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding];
}
</code>```

Please find android code also,

```<code>   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    generateHMAC();
}

String K0 = "4f28d5901b4b7b80d33fda76ca372c2a20bd1a6c2aad7fa215dc79d507330678";
String generatedString = "com.myapp.com|355004059196637|911111111111|11341e5e-9643-4559-bbb7-34d40555e96c";

private void generateHMAC() {
    Log.d("Message of Hash", generatedString);
    byte[] var14 = new byte[0];
    try {
        var14 = SHA256(generatedString);
        byte[] var15 = new byte[0];
        var15 = encrypt(var14, hexStringToByteArray(K0));
        String var4 = Base64.encodeToString(var15, 2);
        Log.d("Existing K0", K0);
        Log.d("HMAC", var4);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public byte[] SHA256(String paramString) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(paramString.getBytes("UTF-8"));
    byte[] digest = md.digest();
    return digest;
}

public byte[] encrypt(byte[] var1, byte[] var2) throws Exception {
    SecretKeySpec var3 = new SecretKeySpec(var2, "AES");
    byte[] var4 = new byte[16];
    IvParameterSpec var5 = new IvParameterSpec(var4);
    Cipher var6 = Cipher.getInstance("AES/CBC/PKCS5Padding");
    var6.init(1, var3, var5);
    byte[] var7 = var6.doFinal(var1);
    return var7;
}

public byte[] hexStringToByteArray(String var1) {
    byte[] var2 = new byte[var1.length() / 2];

    for (int var3 = 0; var3 < var2.length; ++var3) {
        int var4 = var3 * 2;
        int var5 = Integer.parseInt(var1.substring(var4, var4 + 2), 16);
        var2[var3] = (byte) var5;
    }

    return var2;
}
</code>```

答:
Updates after you provided iOS code:

The aesEncryptData should be your output.  Get rid of the hmac, that has nothing to do with AES encryption (instead, it is for message integrity).

The only way you are going to match your Android code is if you are using the same IV that the Android code is using.

Earlier reply:

How long is the input?  Providing source code and sample data may help us solve the problem quicker.

Without the requested information, I don't have your answer, but I have a few pointers that might help you get to the bottom of it:

Your padding is okay.  PKCS5Padding in Java is wrongly named implementation of PKCS#7, so it should be compatible with Apple's kCCOptionPKCS7Padding.

Apple by default uses CBC mode under the hood if no mode is specified, so that agrees with the Android code.  So that cannot be the problem either.

When you encrypt, the ciphertext will be a multiple of 16 bytes (because AES has N=16 bytes block size and according to defn of PKCS #7).  Specifically:

If the input is a multiple of 16 bytes, then the output should be exactly 16 bytes more than the input.

If the input is not a multiple of 16 bytes, then the output should be 16*Ceiling(Input length/16).  Example: 47 byte input should be 16*Ceiling(17/16) = 16*3 = 48 byte output.

It is possible that one of the implementations is outputting the IV as part of the ciphertext.  If this is happening, it should be at the beginning of the ciphertext.  You should be able to test to see if this is happening.  (Let me know if that is happening please)

Having said that, something is weird and likely implemented wrong, and we need the code to get to the bottom of it.  It makes no sense that the Android code results in 3 blocks of 16 whereas the Apple code results in 5 blocks of 16.

Also, as I commented above, even though Apple tells you that the IV is optional, they mean that it is optional in terms of getting the code to work.  It is not optional for security.  IVs are required and must be unpredictable for CBC mode of operation, and they should never be repeated.  If you ignore that, you leak information about your data, and in some situations, an attacker may be able to decrypt the data (padding oracle attacks).

Body:
Implementing AES256 on iOS using CCCrypt function. But output and output buffer length is different than Android.

Cipher class in Android produces 48 bytes data where in iOS we get 80 bytes data.

In IOS using kCCAlgorithmAES, kCCOptionPKCS7Padding and in android using AES/CBC/PKCS5Padding.

in IOS IV is NULL and in android creating iv as new 16 bytes array.

Please help.

please find input and code for reference.

 - (void)viewDidLoad {
    [super viewDidLoad];

    NSString *message = [NSString stringWithFormat:@"com.myapp.com|355004059196637|911111111111|11341e5e-9643-4559-bbb7-34d40555e96c"];
    NSString *key = [NSString stringWithFormat:@"4f28d5901b4b7b80d33fda76ca372c2a20bd1a6c2aad7fa215dc79d507330678"];
    NSString *shaEncryptMessage = [self sha256:message length:0];
    NSData *aesEncryptData = [self aesEncrypt:[shaEncryptMessage dataUsingEncoding:NSUTF8StringEncoding] key:key iv:nil];
    NSString *hMac = [aesEncryptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSLog(@"hMac = %@",hMac);

    // IOS output : Can+oQR79D3/lsQGctzY/d2VBNZbWWtJxGI8iRIu80R2yTskn9gf2oKHaRESX73u
    //                  LpJHLx1Xr6iH11jFPlmqwW7mQz0xAW4uACNAMEoZ0kY=
    // Android output : MiMDkdo5cGsPMj2qCnNobgp7dr5KMvBhGuKTonrqr1lCYte/kKegGMtI/4TPhUNI
}

- (NSString*) sha256:(NSString *)key length:(NSInteger) length{
    const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding];
    NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];

    uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
    CC_SHA256(keyData.bytes, (unsigned int)keyData.length, digest);
    NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
    NSString *hash=[out description];
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    return  hash;
}
-  (NSData *)aesEncrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv {
    char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
    ivPointer[kCCBlockSizeAES128];
    BOOL patchNeeded;
    bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding
    //key = [[StringEncryption alloc] md5:key];
    key = [self stringFromHex:key];
    patchNeeded= ([key length] > kCCKeySizeAES256+1);
    if(patchNeeded)
    {
        key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)
    }

    [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
    [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];

    //    if (patchNeeded) {
    //        keyPointer[0] = '\0';  // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256
    //    }

    NSUInteger dataLength = [plainText length];

    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
    size_t buffSize = dataLength + kCCBlockSizeAES128;
    void *buff = malloc(buffSize);

    size_t numBytesEncrypted = 0;

    CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */
                                     kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */
                                     kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */
                                     keyPointer, kCCKeySizeAES256, /* key and its length */
                                     NULL, /* initialization vector - use random IV everytime */
                                     [plainText bytes], [plainText length], /* input  */
                                     buff, buffSize,/* data RETURNED here */
                                     &numBytesEncrypted);

    if (status == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
    }

    free(buff);
    return nil;
}

- (NSString *) stringFromHex:(NSString *)str
{
    NSMutableData *stringData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [str length] / 2; i++) {
        byte_chars[0] = [str characterAtIndex:i*2];
        byte_chars[1] = [str characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return [[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding];
}

Please find android code also,

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    generateHMAC();
}

String K0 = "4f28d5901b4b7b80d33fda76ca372c2a20bd1a6c2aad7fa215dc79d507330678";
String generatedString = "com.myapp.com|355004059196637|911111111111|11341e5e-9643-4559-bbb7-34d40555e96c";

private void generateHMAC() {
    Log.d("Message of Hash", generatedString);
    byte[] var14 = new byte[0];
    try {
        var14 = SHA256(generatedString);
        byte[] var15 = new byte[0];
        var15 = encrypt(var14, hexStringToByteArray(K0));
        String var4 = Base64.encodeToString(var15, 2);
        Log.d("Existing K0", K0);
        Log.d("HMAC", var4);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public byte[] SHA256(String paramString) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(paramString.getBytes("UTF-8"));
    byte[] digest = md.digest();
    return digest;
}

public byte[] encrypt(byte[] var1, byte[] var2) throws Exception {
    SecretKeySpec var3 = new SecretKeySpec(var2, "AES");
    byte[] var4 = new byte[16];
    IvParameterSpec var5 = new IvParameterSpec(var4);
    Cipher var6 = Cipher.getInstance("AES/CBC/PKCS5Padding");
    var6.init(1, var3, var5);
    byte[] var7 = var6.doFinal(var1);
    return var7;
}

public byte[] hexStringToByteArray(String var1) {
    byte[] var2 = new byte[var1.length() / 2];

    for (int var3 = 0; var3 < var2.length; ++var3) {
        int var4 = var3 * 2;
        int var5 = Integer.parseInt(var1.substring(var4, var4 + 2), 16);
        var2[var3] = (byte) var5;
    }

    return var2;
}


问:
SQL Order By within Order By
So I have two tables, Questions and Answers, joined by a many to many relation table, QuestionsAnswers.  Questions have a Sort column that allows me to control how they are displayed to the user, and QuestionsAnswers also has a sort column that allows me to control the order of the answers for each Question.  My problem is that I am trying to write a SQL query that will select all the Questions and their Answers ordered first by Question.Sort and then by QuestionsAnswers.Sort.  Both sort columns are nullable and integers in these columns should take precedence over nulls.

I can get the Order By Questions.Sort to work fine but once I add in the second sort column, it goes awry.  For instance, if a Question has a Sort = 0 meaning it should be the first Question displayed but does not have any preference for its Answers, it will get ordered below a QuestionsAnswers row that has Questions.Sort = null and QuestionsAnswers.Sort = 0.

Any tips or thoughts if this is even workable would be great.

edit:

```<code>SELECT
    Q.Id AS QuestionId,
    Q.Name AS Question,
    A.Id AS AnswerId,
    A.Text AS Answer
FROM
    dbo.Questions AS Q
INNER JOIN
    dbo.QuestionsAnswers AS QA
        ON Q.Id = QA.QuestionId
INNER JOIN
    dbo.Answers AS A
        ON QA.AnswerId = A.Id
ORDER BY
    ISNUMERIC(Q.Sort) DESC,
    Q.Sort,
    Q.Id,
    A.Text;
</code>```

答:
```<code>ORDER BY COALESCE(Questions.Sort, 999999999), COALESCE(Answers.Sort, 999999999)
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL Order By within Order By

Body:
So I have two tables, Questions and Answers, joined by a many to many relation table, QuestionsAnswers.  Questions have a Sort column that allows me to control how they are displayed to the user, and QuestionsAnswers also has a sort column that allows me to control the order of the answers for each Question.  My problem is that I am trying to write a SQL query that will select all the Questions and their Answers ordered first by Question.Sort and then by QuestionsAnswers.Sort.  Both sort columns are nullable and integers in these columns should take precedence over nulls.

I can get the Order By Questions.Sort to work fine but once I add in the second sort column, it goes awry.  For instance, if a Question has a Sort = 0 meaning it should be the first Question displayed but does not have any preference for its Answers, it will get ordered below a QuestionsAnswers row that has Questions.Sort = null and QuestionsAnswers.Sort = 0.

Any tips or thoughts if this is even workable would be great.

edit:

SELECT
    Q.Id AS QuestionId,
    Q.Name AS Question,
    A.Id AS AnswerId,
    A.Text AS Answer
FROM
    dbo.Questions AS Q
INNER JOIN
    dbo.QuestionsAnswers AS QA
        ON Q.Id = QA.QuestionId
INNER JOIN
    dbo.Answers AS A
        ON QA.AnswerId = A.Id
ORDER BY
    ISNUMERIC(Q.Sort) DESC,
    Q.Sort,
    Q.Id,
    A.Text;


问:
Apache - Proxy external files to download
Consider this:

we have an external server for files that can be downloaded

our website (plone based) is the interface for downloading them and we try to hide the direct links as much as possible

jquery.fileDownload plugin needs a cookie set on file on download

I'm trying to set our Apache configuration to replace links like this:

original: data-files-example.com/folder/subfolder/file.zip

replaced: our-website-example.com/_downloads/folder/subfolder/file.zip

So, the missing part in my case is: how to set Apache to work like this?

I'm trying:

```<code>NameVirtualHost *:80
<VirtualHost :80>
    ServerAdmin email@our-website-example.com
    ServerName our-website-example.com

    RewriteEngine On
    RewriteRule "^/_downloads(.)$" "https://data-files-example.com/$1" [P]

    RewriteCond %{REQUEST_METHOD} ^(PUT|DELETE|PROPFIND|OPTIONS|TRACE|PROPFIND|PROPPATCH|MKCOL|COPY|MOVE|LOCK|UNLOCK)$

    RewriteRule .* - [F,L]
    RewriteRule ^/(.*) http://127.0.0.1:/VirtualHostBase/http/data-files-example.com:80/my_plone_website/VirtualHostRoot/$1 [L,P]

</VirtualHost>
</code>```

I receive 503 Service Unavailable.

How to fix this?

答:
Following code at least rewrites your given original- to your desired target-URL:

```<code><VirtualHost>
    SSLProxyEngine On
    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^our-website-example.com$
    RewriteRule   "^/_downloads(.*)$"  "https://data-files-example.com/$1"  [P,L]
</VirtualHost>
</code>```

This requires the modules mod_ssl, mod_proxy and mod_rewrite to be activated.

Let us know if it was your sought solution and if not, where it went wrong :)

Body:
Consider this:

we have an external server for files that can be downloaded

our website (plone based) is the interface for downloading them and we try to hide the direct links as much as possible

jquery.fileDownload plugin needs a cookie set on file on download

I'm trying to set our Apache configuration to replace links like this:

original: data-files-example.com/folder/subfolder/file.zip

replaced: our-website-example.com/_downloads/folder/subfolder/file.zip

So, the missing part in my case is: how to set Apache to work like this?

I'm trying:

NameVirtualHost *:80
<VirtualHost :80>
    ServerAdmin email@our-website-example.com
    ServerName our-website-example.com

    RewriteEngine On
    RewriteRule "^/_downloads(.)$" "https://data-files-example.com/$1" [P]

    RewriteCond %{REQUEST_METHOD} ^(PUT|DELETE|PROPFIND|OPTIONS|TRACE|PROPFIND|PROPPATCH|MKCOL|COPY|MOVE|LOCK|UNLOCK)$

    RewriteRule .* - [F,L]
    RewriteRule ^/(.*) http://127.0.0.1:/VirtualHostBase/http/data-files-example.com:80/my_plone_website/VirtualHostRoot/$1 [L,P]

</VirtualHost>

I receive 503 Service Unavailable.

How to fix this?

Body:
Following code at least rewrites your given original- to your desired target-URL:

<VirtualHost>
    SSLProxyEngine On
    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^our-website-example.com$
    RewriteRule   "^/_downloads(.*)$"  "https://data-files-example.com/$1"  [P,L]
</VirtualHost>

This requires the modules mod_ssl, mod_proxy and mod_rewrite to be activated.

Let us know if it was your sought solution and if not, where it went wrong :)


问:
How to limit the CSS only affected in a particular npm package?
Here is a npm package I am using:
http://blueprintjs.com/docs/#components.usage

I would like to use their component with CSS, but I don't their CSS affect to my own CSS. Is this possible to allow the CSS package ONLY affected in that npm components? Thanks.

答:
Precisely what @barry-johnson said in his comment above: we use pt- as a namespace for all of our CSS classes to avoid collisions with your own application styles. For instance, you could use your own .custom-button alongside our .pt-button with no conflicts.

However, if you use a Blueprint React component, then it's going to use the Blueprint classes, and you're going to want to use our CSS (because it's not just pretty colors, there's some useful layout stuff in there too). Hope that helps!


问:
Remove precedent scatterplot while updating python animation
Although hours of browsing stackoverflow definitely improved my python animate code, I could not quite figure out one thing and therefore I'm turning towards the kind souls of the community in the hope that someone might be able to shred some light.

In a nutshell, I have a background image that is about 2000 x 1000 pixels let's say, I need to scatter some points over this image and animate the process and save whole thing as a video. I'm able to update the scatterplot as needed only with the exception that I can't remove the precedent scatterplot. So the output is not what I would really want. I would be glad if someone could have a glance at the code and see where the glitch is. I've used scat.remove() which seems to be doing nothing.

Thank you in advance folks.

```<code>import matplotlib.pyplot as plt
import pylab as pl
import numpy as np
from pylab import savefig
from matplotlib import animation
import matplotlib

######################################################
fig = plt.figure()
ax = plt.axes()
a = plt.imread('background.jpg')
im = plt.imshow(a)

#######################################################

def randpair(n):
    x,y=[],[]
    for i in xrange(n):
        x.append(np.random.randint(100,1900))
        y.append(np.random.randint(100,900))
    return x,y

def animate(i):

    scat = ax.scatter(0,0,color='white')
    points = np.random.randint(5,size=10)

    for j in points:
        xy = randpair(j)
        x = xy[0]
        y = xy[1]
        print x,y

        if len(x) > 0 :
            scat.remove()
            scat = ax.scatter(x,y,color='r',s=18)

        plt.xticks([])
        plt.yticks([])

    return scat,ax,  # ax returns the text to be updated and scat returns the scatterplot.

anim = animation.FuncAnimation(fig, animate, 49,interval=300, blit=True)
writer = animation.writers['ffmpeg']
anim.save('film_3.mp4')
#plt.show()
</code>```

答:
In the code you already remove the last scatter before the loop is finished; so some scatter plots will be added and then removed immediately.

One can prevent this by collecting the scatters in a list, then removing the scatters in the list from the canvas using remove and cleaning the list.

Apart from that, returning the complete ax object is a little useless. So I would suggest to simply turn blitting off, since it will not matter for saving the animation.

Here is a complete code that worked for me:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation

fig = plt.figure()
ax = plt.axes()
scats = []
a = np.random.rand(8,18)
im = ax.imshow(a, cmap="YlGn", vmin=0, vmax=3, extent=[0,2000,0,1000])
plt.xticks([])
plt.yticks([])

def randpair(n):
    x,y=[],[]
    for i in xrange(n):
        x.append(np.random.randint(100,1900))
        y.append(np.random.randint(100,900))
    return x,y

def animate(i):
    global scats
    # first remove all old scatters
    for scat in scats:
        scat.remove()
    scats=[]
    # now draw new scatters
    points = np.random.randint(5,size=10)
    for j in points:
        x, y = randpair(j)
        if len(x) > 0 :
            scats.append(ax.scatter(x,y,color='r',s=18))

anim = matplotlib.animation.FuncAnimation(fig, animate, 50,
                                interval=1000, blit=False)

writer = matplotlib.animation.FFMpegWriter(fps=15,
            codec="h264",
            extra_args=["-preset", "veryslow","-crf","0"])
anim.save(__file__+".mp4", writer=writer)

plt.show()
</code>```

Body:
Although hours of browsing stackoverflow definitely improved my python animate code, I could not quite figure out one thing and therefore I'm turning towards the kind souls of the community in the hope that someone might be able to shred some light.

In a nutshell, I have a background image that is about 2000 x 1000 pixels let's say, I need to scatter some points over this image and animate the process and save whole thing as a video. I'm able to update the scatterplot as needed only with the exception that I can't remove the precedent scatterplot. So the output is not what I would really want. I would be glad if someone could have a glance at the code and see where the glitch is. I've used scat.remove() which seems to be doing nothing.

Thank you in advance folks.

import matplotlib.pyplot as plt
import pylab as pl
import numpy as np
from pylab import savefig
from matplotlib import animation
import matplotlib

######################################################
fig = plt.figure()
ax = plt.axes()
a = plt.imread('background.jpg')
im = plt.imshow(a)

#######################################################

def randpair(n):
    x,y=[],[]
    for i in xrange(n):
        x.append(np.random.randint(100,1900))
        y.append(np.random.randint(100,900))
    return x,y

def animate(i):

    scat = ax.scatter(0,0,color='white')
    points = np.random.randint(5,size=10)

    for j in points:
        xy = randpair(j)
        x = xy[0]
        y = xy[1]
        print x,y

        if len(x) > 0 :
            scat.remove()
            scat = ax.scatter(x,y,color='r',s=18)

        plt.xticks([])
        plt.yticks([])

    return scat,ax,  # ax returns the text to be updated and scat returns the scatterplot.

anim = animation.FuncAnimation(fig, animate, 49,interval=300, blit=True)
writer = animation.writers['ffmpeg']
anim.save('film_3.mp4')
#plt.show()

Body:
In the code you already remove the last scatter before the loop is finished; so some scatter plots will be added and then removed immediately.

One can prevent this by collecting the scatters in a list, then removing the scatters in the list from the canvas using remove and cleaning the list.

Apart from that, returning the complete ax object is a little useless. So I would suggest to simply turn blitting off, since it will not matter for saving the animation.

Here is a complete code that worked for me:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation

fig = plt.figure()
ax = plt.axes()
scats = []
a = np.random.rand(8,18)
im = ax.imshow(a, cmap="YlGn", vmin=0, vmax=3, extent=[0,2000,0,1000])
plt.xticks([])
plt.yticks([])

def randpair(n):
    x,y=[],[]
    for i in xrange(n):
        x.append(np.random.randint(100,1900))
        y.append(np.random.randint(100,900))
    return x,y

def animate(i):
    global scats
    # first remove all old scatters
    for scat in scats:
        scat.remove()
    scats=[]
    # now draw new scatters
    points = np.random.randint(5,size=10)
    for j in points:
        x, y = randpair(j)
        if len(x) > 0 :
            scats.append(ax.scatter(x,y,color='r',s=18))

anim = matplotlib.animation.FuncAnimation(fig, animate, 50,
                                interval=1000, blit=False)

writer = matplotlib.animation.FFMpegWriter(fps=15,
            codec="h264",
            extra_args=["-preset", "veryslow","-crf","0"])
anim.save(__file__+".mp4", writer=writer)

plt.show()


问:
Name casing convention across all languages in an Application
I'm build a web app using Javascript (on the browser), C# and Sql Server. Is it a good idea to have a consistent naming convention across all three languages?

For Javscript, it seems to be best practice is to use camelCase, but in C# and Sql Server it's TitleCase.

Problem though is when the Javascript consumes and sends data to C# / Sql server the naming conventions are inconsistent.  So I have to write code to map them.

For example

In Sql I have a table called 'Foo' with columns 'Name', 'EmailAddress'

In C# I have an POCO object called 'Foo' that maps to this table with
  properties 'Name', 'EmailAddress'  and exposes an api endpoint to GET this is
  json
  e.g {"Name": "Joe Bloggs", "EmailAddres":"joe@test.org"}

My Javascripts makes an ajax call to GET this JSON and maps it to its own
  JSON object e.g {"name": data.Name, "emailAddress": data.EmailAddress}

This mapping between column/property naming conventions seems silly to me, and wouldn't be needed if all languages just agreed on casing convention.  Is there a better approach to this?

答:
In my opinion, you should continue to use the standard conventions for each language.

Benefits:

Consistency in each piece of software.

Easier for your fellow developer, since they won't need to learn a homebrew naming convention(s).

It will be easier to communicate code to the rest of the world in places like SO, or if you decide to to implement a solution found on SO.

Don't add extra conventions just to make the languages consistent. Your languages will end up with meaningless rules that are not relevant, and it'll be confusing to anyone who works on your code in the future.

To play Devil's Advocate, here's an opinion that disagrees with mine stolen from here:

This is where you find the big issue with coding standards based on
  style - if your team doesn't write the entire codebase, then you're
  going to find you have mismatches with the other code's standard.

So, my advice is not to sweat it. As long as your code is clear, it
  really doesn't matter whether you use camel case, pascal case, or
  underscore style. Its more important that the code is readable.

You should never alter the style of the 3rd parties as that will make
  comparison with new versions impossible, so you have to stick with
  them. If you have 2 different-style libraries, you have no choice but
  to follow a standard that ignores code style. Its not that bad, if
  you're a good coder you can read any code style. If you're not, having
  a solitary style won't help you at all.

I include it because I think they make a good point, and because you're working on your own code outside of a team context. However, it's always good to practice good habits (or rather, avoid bad habits) on side projects, since they might carry through to code you write with/for others, so it would be beneficial to learn how to deal with naming conventions on a large codebase if you think you'll run into that issue in the future while on a team.


问:
Change colour of SVG loaded from file
I have an SVG loaded from file in an  tag like so...

```<code><img class="svgbutton" src="filepath/icon.svg">
</code>```

the svg is just a simple icon in a single colour. Is it possible to control the colour of the svg in someway (possibly a filter?), either using css or javascript?

Or is the only proper way to do this to draw it fully in the script..?

答:
I suggest to use inline SVG like this in HTML:

```<code><div style="color: red;">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        [ ... ]
    </svg>
</div>
</code>```

By doing so you may use standard CSS (and JavaScript if required for dynamic changes, but keep in mind that there are pseudo-classes to style mouse-over and much more). The trick here is to apply the inherited CSS color to the SVG fill color with fill: currentColor;

```<code><style type="text/css">
    svg {
        fill: currentColor;
    }
</style>
</code>```

You could also keep multiple symbols together, hide thie whole "collection" with CSS display: none; on the <svg ...> element and reuse the symbols separately in multiple places.

A symbol definition in the "collection":

```<code><g id="icon1">
    <path class="path1" d="M22 20c-2 2-2 4-4 4s-4-2-6-4-4-4-4-6 2-2 4-4-4-8-6-8-6 6-6 6c0 4 4.109 12.109 8 16s12 8 16 8c0 0 6-4 6-6s-6-8-8-6z"></path>
</g>
</code>```

Use it anywhere like this:

```<code><svg viewBox="0 0 64 64">
    <use xlink:href="#icon1"></use>
</svg>
</code>```

NOTE: xlink:href is deprecated as of SVG 2.0 and is being replaced by href which might not yet be supported by your browser though...

You could also color multiple paths in one symbol differently:

```<code><style type="text/css">
    .path1 {
        color: blue;
        fill: currentColor;
    }
</style>
</code>```

Keep experimenting with classes and pseudo-classes before choosing JavaScript for dynamically changing your element's classes as it might not be necessary.

Title: Change colour of SVG loaded from file

Body:
I have an SVG loaded from file in an  tag like so...

the svg is just a simple icon in a single colour. Is it possible to control the colour of the svg in someway (possibly a filter?), either using css or javascript?

Or is the only proper way to do this to draw it fully in the script..?

Body:
I suggest to use inline SVG like this in HTML:

<div style="color: red;">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        [ ... ]
    </svg>
</div>

By doing so you may use standard CSS (and JavaScript if required for dynamic changes, but keep in mind that there are pseudo-classes to style mouse-over and much more). The trick here is to apply the inherited CSS color to the SVG fill color with fill: currentColor;

<style type="text/css">
    svg {
        fill: currentColor;
    }
</style>

You could also keep multiple symbols together, hide thie whole "collection" with CSS display: none; on the <svg ...> element and reuse the symbols separately in multiple places.

A symbol definition in the "collection":

<g id="icon1">
    <path class="path1" d="M22 20c-2 2-2 4-4 4s-4-2-6-4-4-4-4-6 2-2 4-4-4-8-6-8-6 6-6 6c0 4 4.109 12.109 8 16s12 8 16 8c0 0 6-4 6-6s-6-8-8-6z"></path>
</g>

Use it anywhere like this:

<svg viewBox="0 0 64 64">
    <use xlink:href="#icon1"></use>
</svg>

NOTE: xlink:href is deprecated as of SVG 2.0 and is being replaced by href which might not yet be supported by your browser though...

You could also color multiple paths in one symbol differently:

<style type="text/css">
    .path1 {
        color: blue;
        fill: currentColor;
    }
</style>

Keep experimenting with classes and pseudo-classes before choosing JavaScript for dynamically changing your element's classes as it might not be necessary.


问:
WindowsDeviceGroup claims
ADFS 2016 supports a new claim type "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup" which contains the Windows devices group SIDs. How may I cast the claims on a simple claims aware ASP.Net Application ? I am on VS 2015, .Net 4.6. What are the minimum requirements to grab this claim type and its value from ADFS so I may use it. Any code snippet would be highly appreciated.

I need help in getting the code that can do something like this but for a Windows Device -

ClaimType - http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup , ClaimValue - S-1-21-5-xxxx-xyyyy-zzzzzz.

Where S-1-21-5-xxxx-xyyyy-zzzzzz is the SID of a Group the computer is member of.
Also, Any chance that this claim type may be used with ADFS 2012R2 ?

答:
This uses the compound authentication pattern that was released as part of WS2012 Active Directory. See https://www.microsoft.com/en-us/download/confirmation.aspx?id=36830 for details on it. Look for the compound authentication section. Then you need to pass the necessary claims by modifying the ADFS's claims provider trust for "Active Directory". Now you have those claims that can be consumed by a downstream application.

Note that this works through Kerberos. So, only if the client is inside the corporate network with line of sight to the a correctly enabled domain controller, will this use case light up.

Thanks
//Sam (@MrADFS)

Title: WindowsDeviceGroup claims


问:
How can I use external libraries with the scripts atom package and java?
How do I go about configuring the classpath when using the scripts package with atom/java?

I know my classpath is:

usr/local/algs4/algs4.jar

Here is the code I am testing with:

import edu.princeton.cs.algs4.*;

public class Wget {

```<code>public static void main(String[] args) {

    // read in data from URL
    String url = args[0];
    In in = new In(url);
    String data = in.readAll();

    // write data to a file
    String filename = url.substring(url.lastIndexOf('/') + 1);
    Out out = new Out(filename);
    out.println(data);
    out.close();
}
</code>```

}

答:
Since you're using algs4, Use Princeton's site and search for classpath.
http://algs4.cs.princeton.edu/code/</p>

Body:
How do I go about configuring the classpath when using the scripts package with atom/java?

I know my classpath is:

usr/local/algs4/algs4.jar

Here is the code I am testing with:

import edu.princeton.cs.algs4.*;

public class Wget {

public static void main(String[] args) {

    // read in data from URL
    String url = args[0];
    In in = new In(url);
    String data = in.readAll();

    // write data to a file
    String filename = url.substring(url.lastIndexOf('/') + 1);
    Out out = new Out(filename);
    out.println(data);
    out.close();
}

}


问:
Hover image - display div over it
On hover I want a link apear at the top-right of the image. Just like on your profile picture on Facebook, where it says "Change Picture".

I have tried to to get it working with a bit of jquery but had no luck, as it doesn't go t the right of the image. The images are going to be different sizes as they are profile pictures. So whatever the size, it needs to stay at the top-right of the image.

JQuery:

```<code>$(".imgHover").hover(function() {
    $(this).children("img").fadeTo(200, 0.25)
           .end().children(".hover").show();
}, function() {
    $(this).children("img").fadeTo(200, 1)
           .end().children(".hover").hide();
});
</code>```

HTML:

```<code><div class="imgHover">
    <div class="hover"><a href="htpp://google.com">Edit</a></div>
    <img src="http://img14.imageshack.us/img14/9698/29588166.jpg" alt="" />
</div>
</code>```

CSS:

```<code>.imgHover .hover {
    display: none;
    position:absolute;
    z-index: 2;

}
</code>```

Thanks!

答:
This is the way I done it:
CSS:

```<code>.imgHover {
    display: inline;
    position: relative;
}
.imgHover .hover {
    display: none;
    position: absolute;
    right:0;
    z-index: 2;
}
</code>```

HTML:

```<code><div class="imgHover">
<div class="hover"><a href="htpp://google.com">Edit</a></div>
<img src="http://img14.imageshack.us/img14/9698/29588166.jpg" alt="">
</div>
</code>```

JQuery:

```<code>$(function() {
    $(".imgHover").hover(
        function() {
            $(this).children("img").fadeTo(200, 0.85).end().children(".hover").show();
        },
        function() {
            $(this).children("img").fadeTo(200, 1).end().children(".hover").hide();
        });
});
</code>```

Test this on jsfiddle.

Title: Hover image - display div over it

Body:
On hover I want a link apear at the top-right of the image. Just like on your profile picture on Facebook, where it says "Change Picture".

I have tried to to get it working with a bit of jquery but had no luck, as it doesn't go t the right of the image. The images are going to be different sizes as they are profile pictures. So whatever the size, it needs to stay at the top-right of the image.

JQuery:

$(".imgHover").hover(function() {
    $(this).children("img").fadeTo(200, 0.25)
           .end().children(".hover").show();
}, function() {
    $(this).children("img").fadeTo(200, 1)
           .end().children(".hover").hide();
});

HTML:

Edit

CSS:

.imgHover .hover {
    display: none;
    position:absolute;
    z-index: 2;

}

Thanks!

Body:
This is the way I done it:
CSS:

.imgHover {
    display: inline;
    position: relative;
}
.imgHover .hover {
    display: none;
    position: absolute;
    right:0;
    z-index: 2;
}

HTML:

<div class="imgHover">
<div class="hover"><a href="htpp://google.com">Edit</a></div>
<img src="http://img14.imageshack.us/img14/9698/29588166.jpg" alt="">
</div>

JQuery:

$(function() {
    $(".imgHover").hover(
        function() {
            $(this).children("img").fadeTo(200, 0.85).end().children(".hover").show();
        },
        function() {
            $(this).children("img").fadeTo(200, 1).end().children(".hover").hide();
        });
});

Test this on jsfiddle.


问:
IMB MQ: Getting message from queue before it leaves it. Java
For example, I have a queue manager with two queues. I put message to Q1 than is goes to another queue Q2. And in Q1 my message get some new things in it's body, like unique ID.

So the question is Can I somehow using Java get my message from Q1 before it goes to Q2 ? Or at least get some info about it.

Actually this example is very simplified and I just want to know is it possible to get message before it leaves the queue.

Update:

I also have a message broker with some logic. My queue manager and it's queues are local. Q2 is a transmission queue, from which message is send to adapter. So I'm interesting in browsing my message which I put in Q1 before it goes to adapter or Q2. Can I make it with Java classes or JMS without changing message flow triggers and handlers or changing adapter source code?

答:
Your question is not very clear.  Messages in a local queue do not magically move from one queue to another queue.  You should update your question and be more precise on what type of queues you are using.

Is Q1 a cluster or remote queue?


问:
Angular 2 Error with ViewContainerRef
I'm using this package (https://github.com/shlomiassaf/angular2-modal) for Modals in my Angular 2 project.

It's working fine, but in my Edit Page that there is a resolve, it's showing this error:

```<code>Unhandled Promise rejection: No provider for ViewContainerRef! ; Zone: <root> ; Task: Promise.then ;
</code>```

My edit page:

import { ActivatedRoute, Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import {Location} from '@angular/common';
import {NgForm, FormBuilder, FormControl, FormGroup, Validators, FormArray} from '@angular/forms';
import { Overlay } from 'angular2-modal';
import { Modal } from 'angular2-modal/plugins/bootstrap';

import {CnpjValidator} from '../../shared/validators/cnpjValidator';
import {PartValidator} from './validators/valParts';

import { EmpresasCrudService } from './services/empresas-crud.service';

import {Config} from '../../shared/config/config.service';

import { ArraySocios, Empresa, Socios} from './models/arraySocios';

@Component({
  selector: 'empresas-edit',
  templateUrl: './empresas-edit.component.html'
})

export class EmpresasEditComponent implements Resolve<any>{

    fieldsSocios: any[] = [];
    showSocios: any[] = [];

    errors: any[] = [];
    form1 : FormGroup;
    form2 : FormGroup;
    form3 : FormGroup;
    form4 : FormGroup;

    contCampos = 1;
    maxCampos = 2;
    formBuilder;
    estados;

    // loading da table
    _loading = false;

    id: number;

    // Item
    data: any[];

    data2;

    // Item
    socios: any[];

    // Item
    socios2: any[];

    // Item
    socioss;

    // onde buscar os registros API
    _endpoint_url_estados: string = this.configService.getBaseUrl()+'contato/estados';
    endpoint_url_patch: string = this.configService.getBaseUrl()+'empresas/';
    endpoint_url_Get: string = this.configService.getBaseUrl()+'empresas/';

    public mask = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/];
    public maskCep = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/];
    public maskTel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
    public maskCel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

    constructor(
        private _location: Location,
        formBuilder: FormBuilder,
        private dataService: EmpresasCrudService,
        private configService: Config,
        private router: Router,
        private route: ActivatedRoute,
        overlay: Overlay,
        vcRef: ViewContainerRef,
        public modal: Modal
    ){
        overlay.defaultViewContainer = vcRef;
        this.formBuilder = formBuilder;

    } // constructor
    resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean {

        return new Promise((resolve, reject) => {

            if (route.params['id'] !== undefined) {
                this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
                    .subscribe(result => {

                        if (result) {
                            console.log("ok");
                            return resolve(result);
                        } else {
                            console.log("erro");
                        }

                    });
            }
        });
    }

         alerts(titulo,alerta,botao) {
        this.modal.alert()
        .size('sm')
        .showClose(false)
        .isBlocking(true)
        .title(titulo)
        .body(`
           ${alerta}`)
        .okBtnClass(botao)
        .open()
        .catch((err: any) => console.log('ERROR: ' + err))
        .then((dialog: any) => { return dialog.result })
        .then((result: any) => { this.backClicked() })
        .catch(err => {}) // if were here it was cancelled (click or non block click);
  }

    disableBanco(e, b) {
        let valor = false;

        if(e !== null)
        {
            if(e.target.checked){
            valor = true;
            }
        }
        if(b){
            valor = true;
        }

        if(valor){
            this.form3.get('pessoa').enable();
            this.form3.get('banco').enable();
            this.form3.get('ag').enable();
            this.form3.get('conta').enable();
            this.form3.get('op').enable();
            this.form3.get('tipo_conta').enable();
            this.form3.get('favorecido').enable();
            this.form3.get('doc').enable();
            this.form3.get('obs').enable();

        }else{
            this.form3.get('pessoa').disable();
            this.form3.get('banco').disable();
            this.form3.get('ag').disable();
            this.form3.get('conta').disable();
            this.form3.get('op').disable();
            this.form3.get('tipo_conta').disable();
            this.form3.get('favorecido').disable();
            this.form3.get('doc').disable();
            this.form3.get('obs').disable();
        }

    }

    disableSocio(e, b) {
            let valor = false;

            if(e !== null)
            {
                if(e.target.checked){
                valor = true;
                }
            }
            if(b){
                valor = true;
            }

        if(valor){
            this.form4.controls['socios'].enable();

        }else{
            this.form4.controls['socios'].disable();
        }

    }

    submitForm(): void{

         /* this.form4.controls['socios']['controls'].forEach( key => {
                        teste.push(key.value);
                    });  */

    //Zera os erros
    this.errors = [];
    let form3Updated;
    let form4Updated;

    //Get Valores e Tira os pontos do CNPJ e CEP
    let form1Updated = this.form1.value;
        form1Updated.cnpj ? form1Updated.cnpj = form1Updated.cnpj.replace(/\D/g, '') : "";
    let form2Updated = this.form2.value;
        form2Updated.cep ? form2Updated.cep = form2Updated.cep.replace(/\D/g, '') : "";

    //Se estiver checked o CadBanco ele atribui os dados
    if(this.form3.get('cadBanco').value == true){
        //Get valores form3
        form3Updated = this.form3.value;
    }

    var socios;

    //Se estiver checked o CadSocios ele atribui os dados
    if(this.form4.get('cadSocios').value == true){

        //Get valores form4
        form4Updated = this.form4.controls['cadSocios'].value;

        let result2 = [];

        let result = {
        "cadSocios" : true
        };

        for (let i = 0; i < this.form4.controls['socios']['controls'].length; i++) {
        this.form4.controls['socios']['controls'][i]['controls']['socio_id'].patchValue(this.socios[i] ? this.socios[i]['socio_id'] : 0);
        }

       this.form4.controls['socios']['controls'].forEach( key => {
                    result2.push(key.value);
                    });

        socios = Object.assign({}, result, {socios : result2});

    }

    //Monta os dados a serem cadastrados
    let data = Object.assign({}, form1Updated, form2Updated, form3Updated, socios);

       //Faz o PUT
     let consulta = this.dataService.patchHttpEmpresas(this.endpoint_url_patch + this.id, data);
        consulta.subscribe(data => {
            this.alerts("Sucesso!", "Empresa editada com sucesso!", "btn btn-primary")
            },
            error => {
                console.log(error);
                window.scrollTo(0,0);
                if(error[0] == 422){
                let fer = error[1];
                Object.keys(fer).forEach( key => {
                     this.errors.push(fer[key]); //value
                });
                }else{
                 this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            });

    }
    //Botão voltar
    backClicked() {
        this._location.back();
    }
    //Botão redirect to index
    redirectToIndex() {
        this.router.navigate(['/empresas']);
    }

    redirectToEmpresa() {
        this.router.navigate(['/empresas/' + this.id]);
    }

    //Adiciona campos socios
    adcSocios() {
    if(this.form4.get('cadSocios').value == true){

             // add address to the list
    const control = <FormArray>this.form4.controls['socios'];
    control.push(this.initAddress());
    }
    }

    //Adiciona campos socios
    removeSocios(i: number) {
    if(this.form4.get('cadSocios').value == true){
        // remove address from the list
    const control = <FormArray>this.form4.controls['socios'];
    control.removeAt(i);
    }
    }

    initAddress() {

        // initialize our address
        return this.formBuilder.group({
            nome: [{value: '', disabled: false}, [Validators.required]],
        participacao: [{value: '', disabled: false}, [Validators.required,
                Validators.pattern("[0-9]*")]],
                socio_id: ['']
        });

    }

    ngOnInit(){
        this.id = this.route.params['value']['id'];

        if(this.route.snapshot.data['data'])
        {
            this.data = this.route.snapshot.data['data']['data'];
            this.socios = this.route.snapshot.data['data']['socios']['socios'];
            this.socios2 = this.route.snapshot.data['data']['socios']['cadSocios'];
        }

        this.data.forEach((data) => {
            this.data = data;
        });

         this.form1 = this.formBuilder.group({
            razao_social: ['', [
                Validators.required
            ]],
            nome_fantasia: [],
            cnpj: ['', [
                Validators.required,
                CnpjValidator.cnpjValidator
            ]],
            insc_estadual: ['', [
                Validators.pattern("[0-9]*")
            ]],
            insc_municipal: ['', [
                Validators.pattern("[0-9]*")
            ]]

        });
        this.form2 = this.formBuilder.group({
            endereco: ['', [
                Validators.required
            ]],
            numero: ['', [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            complemento: [],
            bairro: ['', [
                Validators.required
            ]],
            cidade: ['', [
                Validators.required
            ]],
            estado_id: ['', [
                Validators.required
            ]],
            cep: ['', [
                Validators.required,
                Validators.pattern("[0-9]{2}[\.]?[0-9]{3}[-]?[0-9]{3}")
            ]],
            tel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            tel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            cel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            cel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            email: ['', [
                Validators.pattern("[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")
            ]],
            nome_contato: []

        });

        this.form3 = this.formBuilder.group({
            cadBanco: [{value: true, disabled: false}],
            pessoa: [{value: '', disabled: true}, [
                Validators.required
            ]],
            banco: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            ag: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            op: [{value: '', disabled: true}, []],
            tipo_conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            favorecido: [{value: '', disabled: true}, [
                Validators.required
            ]],
            doc: [{value: '', disabled: true}, []],
            obs: [{value: '', disabled: true}, []]

        });

        this.form4 = this.formBuilder.group({
            cadSocios: [{value: true, disabled: false}],

            socios: this.formBuilder.array([
                this.initAddress(),
            ])

        }, {validator: PartValidator.valPart()});

        this.getEstados();

        for (var _i = 1; _i < this.socios.length; _i++) {
            this.adcSocios();
        }
         var socios22 = [];
         this.socios.forEach((data) => {
        socios22.push({nome: data.nome, participacao: data.participacao});
        });

        this.form4.patchValue({
        socios: socios22
        });

        this.disableBanco(null, this.data['cadBanco']);
        this.disableSocio(null, this.socios2);

    }

    getEstados(){
        let consulta = this.dataService.getHttpEstados(this._endpoint_url_estados);
        consulta.subscribe(
            estados => {
                estados.estados ? this.estados = estados.estados : ""
            },
            error =>  { this.alerts("Ops, houve um erro!", "Erro ao criar empresa!", "btn btn-danger") },
            () => ''

        );

    }

    getEmpresa(_endpoint_url){
        this._loading = true;

        let consulta = this.dataService.getHttpEmpresaShow(_endpoint_url);
        consulta.subscribe(
            people => {

                people.data ? this.data = people.data : "",
                    people.socios ? this.socios = people.socios.socios : "",
                    this._loading = false
            },
            error => {
                this._loading = false
                window.scrollTo(0,0);
                if(error[0] == 400){
                    this.alerts("Ops, houve um erro!", "A empresa selecionada não existe!", "btn btn-danger");
                }else{
                    this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            }

        );

    }

}
```

答:
It seems you're using a component as resolver

```<code>implements Resolve<any>
</code>```

that won't work, because DI can't instantiate it if you have ViewContainerRef as dependency.

Title: Angular 2 Error with ViewContainerRef

Body:
I'm using this package (https://github.com/shlomiassaf/angular2-modal) for Modals in my Angular 2 project.

It's working fine, but in my Edit Page that there is a resolve, it's showing this error:

Unhandled Promise rejection: No provider for ViewContainerRef! ; Zone: <root> ; Task: Promise.then ;

My edit page:

import { ActivatedRoute, Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import {Location} from '@angular/common';
import {NgForm, FormBuilder, FormControl, FormGroup, Validators, FormArray} from '@angular/forms';
import { Overlay } from 'angular2-modal';
import { Modal } from 'angular2-modal/plugins/bootstrap';

import {CnpjValidator} from '../../shared/validators/cnpjValidator';
import {PartValidator} from './validators/valParts';

import { EmpresasCrudService } from './services/empresas-crud.service';

import {Config} from '../../shared/config/config.service';

import { ArraySocios, Empresa, Socios} from './models/arraySocios';

@Component({
  selector: 'empresas-edit',
  templateUrl: './empresas-edit.component.html'
})

export class EmpresasEditComponent implements Resolve<any>{

    fieldsSocios: any[] = [];
    showSocios: any[] = [];

    errors: any[] = [];
    form1 : FormGroup;
    form2 : FormGroup;
    form3 : FormGroup;
    form4 : FormGroup;

    contCampos = 1;
    maxCampos = 2;
    formBuilder;
    estados;

    // loading da table
    _loading = false;

    id: number;

    // Item
    data: any[];

    data2;

    // Item
    socios: any[];

    // Item
    socios2: any[];

    // Item
    socioss;

    // onde buscar os registros API
    _endpoint_url_estados: string = this.configService.getBaseUrl()+'contato/estados';
    endpoint_url_patch: string = this.configService.getBaseUrl()+'empresas/';
    endpoint_url_Get: string = this.configService.getBaseUrl()+'empresas/';

    public mask = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/];
    public maskCep = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/];
    public maskTel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
    public maskCel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

    constructor(
        private _location: Location,
        formBuilder: FormBuilder,
        private dataService: EmpresasCrudService,
        private configService: Config,
        private router: Router,
        private route: ActivatedRoute,
        overlay: Overlay,
        vcRef: ViewContainerRef,
        public modal: Modal
    ){
        overlay.defaultViewContainer = vcRef;
        this.formBuilder = formBuilder;

    } // constructor
    resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean {

        return new Promise((resolve, reject) => {

            if (route.params['id'] !== undefined) {
                this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
                    .subscribe(result => {

                        if (result) {
                            console.log("ok");
                            return resolve(result);
                        } else {
                            console.log("erro");
                        }

                    });
            }
        });
    }

         alerts(titulo,alerta,botao) {
        this.modal.alert()
        .size('sm')
        .showClose(false)
        .isBlocking(true)
        .title(titulo)
        .body(`
           ${alerta}`)
        .okBtnClass(botao)
        .open()
        .catch((err: any) => console.log('ERROR: ' + err))
        .then((dialog: any) => { return dialog.result })
        .then((result: any) => { this.backClicked() })
        .catch(err => {}) // if were here it was cancelled (click or non block click);
  }

    disableBanco(e, b) {
        let valor = false;

        if(e !== null)
        {
            if(e.target.checked){
            valor = true;
            }
        }
        if(b){
            valor = true;
        }

        if(valor){
            this.form3.get('pessoa').enable();
            this.form3.get('banco').enable();
            this.form3.get('ag').enable();
            this.form3.get('conta').enable();
            this.form3.get('op').enable();
            this.form3.get('tipo_conta').enable();
            this.form3.get('favorecido').enable();
            this.form3.get('doc').enable();
            this.form3.get('obs').enable();

        }else{
            this.form3.get('pessoa').disable();
            this.form3.get('banco').disable();
            this.form3.get('ag').disable();
            this.form3.get('conta').disable();
            this.form3.get('op').disable();
            this.form3.get('tipo_conta').disable();
            this.form3.get('favorecido').disable();
            this.form3.get('doc').disable();
            this.form3.get('obs').disable();
        }

    }

    disableSocio(e, b) {
            let valor = false;

            if(e !== null)
            {
                if(e.target.checked){
                valor = true;
                }
            }
            if(b){
                valor = true;
            }

        if(valor){
            this.form4.controls['socios'].enable();

        }else{
            this.form4.controls['socios'].disable();
        }

    }

    submitForm(): void{

         /* this.form4.controls['socios']['controls'].forEach( key => {
                        teste.push(key.value);
                    });  */

    //Zera os erros
    this.errors = [];
    let form3Updated;
    let form4Updated;

    //Get Valores e Tira os pontos do CNPJ e CEP
    let form1Updated = this.form1.value;
        form1Updated.cnpj ? form1Updated.cnpj = form1Updated.cnpj.replace(/\D/g, '') : "";
    let form2Updated = this.form2.value;
        form2Updated.cep ? form2Updated.cep = form2Updated.cep.replace(/\D/g, '') : "";

    //Se estiver checked o CadBanco ele atribui os dados
    if(this.form3.get('cadBanco').value == true){
        //Get valores form3
        form3Updated = this.form3.value;
    }

    var socios;

    //Se estiver checked o CadSocios ele atribui os dados
    if(this.form4.get('cadSocios').value == true){

        //Get valores form4
        form4Updated = this.form4.controls['cadSocios'].value;

        let result2 = [];

        let result = {
        "cadSocios" : true
        };

        for (let i = 0; i < this.form4.controls['socios']['controls'].length; i++) {
        this.form4.controls['socios']['controls'][i]['controls']['socio_id'].patchValue(this.socios[i] ? this.socios[i]['socio_id'] : 0);
        }

       this.form4.controls['socios']['controls'].forEach( key => {
                    result2.push(key.value);
                    });

        socios = Object.assign({}, result, {socios : result2});

    }

    //Monta os dados a serem cadastrados
    let data = Object.assign({}, form1Updated, form2Updated, form3Updated, socios);

       //Faz o PUT
     let consulta = this.dataService.patchHttpEmpresas(this.endpoint_url_patch + this.id, data);
        consulta.subscribe(data => {
            this.alerts("Sucesso!", "Empresa editada com sucesso!", "btn btn-primary")
            },
            error => {
                console.log(error);
                window.scrollTo(0,0);
                if(error[0] == 422){
                let fer = error[1];
                Object.keys(fer).forEach( key => {
                     this.errors.push(fer[key]); //value
                });
                }else{
                 this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            });

    }
    //Botão voltar
    backClicked() {
        this._location.back();
    }
    //Botão redirect to index
    redirectToIndex() {
        this.router.navigate(['/empresas']);
    }

    redirectToEmpresa() {
        this.router.navigate(['/empresas/' + this.id]);
    }

    //Adiciona campos socios
    adcSocios() {
    if(this.form4.get('cadSocios').value == true){

             // add address to the list
    const control = <FormArray>this.form4.controls['socios'];
    control.push(this.initAddress());
    }
    }

    //Adiciona campos socios
    removeSocios(i: number) {
    if(this.form4.get('cadSocios').value == true){
        // remove address from the list
    const control = <FormArray>this.form4.controls['socios'];
    control.removeAt(i);
    }
    }

    initAddress() {

        // initialize our address
        return this.formBuilder.group({
            nome: [{value: '', disabled: false}, [Validators.required]],
        participacao: [{value: '', disabled: false}, [Validators.required,
                Validators.pattern("[0-9]*")]],
                socio_id: ['']
        });

    }

    ngOnInit(){
        this.id = this.route.params['value']['id'];

        if(this.route.snapshot.data['data'])
        {
            this.data = this.route.snapshot.data['data']['data'];
            this.socios = this.route.snapshot.data['data']['socios']['socios'];
            this.socios2 = this.route.snapshot.data['data']['socios']['cadSocios'];
        }

        this.data.forEach((data) => {
            this.data = data;
        });

         this.form1 = this.formBuilder.group({
            razao_social: ['', [
                Validators.required
            ]],
            nome_fantasia: [],
            cnpj: ['', [
                Validators.required,
                CnpjValidator.cnpjValidator
            ]],
            insc_estadual: ['', [
                Validators.pattern("[0-9]*")
            ]],
            insc_municipal: ['', [
                Validators.pattern("[0-9]*")
            ]]

        });
        this.form2 = this.formBuilder.group({
            endereco: ['', [
                Validators.required
            ]],
            numero: ['', [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            complemento: [],
            bairro: ['', [
                Validators.required
            ]],
            cidade: ['', [
                Validators.required
            ]],
            estado_id: ['', [
                Validators.required
            ]],
            cep: ['', [
                Validators.required,
                Validators.pattern("[0-9]{2}[\.]?[0-9]{3}[-]?[0-9]{3}")
            ]],
            tel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            tel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            cel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            cel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            email: ['', [
                Validators.pattern("[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")
            ]],
            nome_contato: []

        });

        this.form3 = this.formBuilder.group({
            cadBanco: [{value: true, disabled: false}],
            pessoa: [{value: '', disabled: true}, [
                Validators.required
            ]],
            banco: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            ag: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            op: [{value: '', disabled: true}, []],
            tipo_conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            favorecido: [{value: '', disabled: true}, [
                Validators.required
            ]],
            doc: [{value: '', disabled: true}, []],
            obs: [{value: '', disabled: true}, []]

        });

        this.form4 = this.formBuilder.group({
            cadSocios: [{value: true, disabled: false}],

            socios: this.formBuilder.array([
                this.initAddress(),
            ])

        }, {validator: PartValidator.valPart()});

        this.getEstados();

        for (var _i = 1; _i < this.socios.length; _i++) {
            this.adcSocios();
        }
         var socios22 = [];
         this.socios.forEach((data) => {
        socios22.push({nome: data.nome, participacao: data.participacao});
        });

        this.form4.patchValue({
        socios: socios22
        });

        this.disableBanco(null, this.data['cadBanco']);
        this.disableSocio(null, this.socios2);

    }

    getEstados(){
        let consulta = this.dataService.getHttpEstados(this._endpoint_url_estados);
        consulta.subscribe(
            estados => {
                estados.estados ? this.estados = estados.estados : ""
            },
            error =>  { this.alerts("Ops, houve um erro!", "Erro ao criar empresa!", "btn btn-danger") },
            () => ''

        );

    }

    getEmpresa(_endpoint_url){
        this._loading = true;

        let consulta = this.dataService.getHttpEmpresaShow(_endpoint_url);
        consulta.subscribe(
            people => {

                people.data ? this.data = people.data : "",
                    people.socios ? this.socios = people.socios.socios : "",
                    this._loading = false
            },
            error => {
                this._loading = false
                window.scrollTo(0,0);
                if(error[0] == 400){
                    this.alerts("Ops, houve um erro!", "A empresa selecionada não existe!", "btn btn-danger");
                }else{
                    this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            }

        );

    }

}

Body:
It seems you're using a component as resolver

implements Resolve<any>

that won't work, because DI can't instantiate it if you have ViewContainerRef as dependency.