问:
in this extension , where is my fault?
The following code is from an extension I am writing. It is an extension that when you click on button it will show a notification.  However, when I run it, nothing happens when you press the button.

Manifest File

```<code>{
    "manifest_version":2,

    "name":"NOTE",
    "description":"It is an example for using Notification",
    "version":"1.0",

    "browser_action":{
        "default_popup":"popup.html",
        "default_icon":{
            "16":"icon_16.png",
            "48":"icon_48.png",
            "128":"icon_128.png"
        }
    },

    "permissions": [
        "notifications"
    ]
}
</code>```

popupHtml

```<code><html>
    <head>
        <title>NOTIFICATION</title>
        <script src="popup.js"></script>
        <script src="jquery-1.10.2.js"></script>
    </head>
    <body>
        <input id="change" type="submit" value="Notification" />
    </body>
</html>
</code>```

popupJS // function is in this file:

```<code>$(function(){
    $('#change').click(function(){
        var opt ={
           type: "basic",
           title: "notification",
          message: "Total has been reset back to 0.",
           iconUrl: "icon_48.png"
        }
        chrome.notifications.create('change', opt, function () { });
    });
});
</code>```

答:
You're using jQuery before you load it. The order is significant:

```

<p>should be instead</p>

<pre class="lang-html prettyprint-override"><code><script src="jquery-1.10.2.js"></script>
<script src="popup.js"></script>
</code>```

As mentioned, you should also use button instead of submit.

You would be able to see this error if you properly debugged your popup; to do so, right-click the button and select "Inspect popup" to bring up Dev Tools for it.

Title: in this extension , where is my fault?

Body:
The following code is from an extension I am writing. It is an extension that when you click on button it will show a notification.  However, when I run it, nothing happens when you press the button.

Manifest File

{
    "manifest_version":2,

    "name":"NOTE",
    "description":"It is an example for using Notification",
    "version":"1.0",

    "browser_action":{
        "default_popup":"popup.html",
        "default_icon":{
            "16":"icon_16.png",
            "48":"icon_48.png",
            "128":"icon_128.png"
        }
    },

    "permissions": [
        "notifications"
    ]
}

popupHtml

        <title>NOTIFICATION</title>

        <input id="change" type="submit" value="Notification" />

popupJS // function is in this file:

$(function(){
    $('#change').click(function(){
        var opt ={
           type: "basic",
           title: "notification",
          message: "Total has been reset back to 0.",
           iconUrl: "icon_48.png"
        }
        chrome.notifications.create('change', opt, function () { });
    });
});

Body:
You're using jQuery before you load it. The order is significant:

<script src="popup.js"></script>
<script src="jquery-1.10.2.js"></script>

should be instead

<script src="jquery-1.10.2.js"></script>
<script src="popup.js"></script>

As mentioned, you should also use button instead of submit.

You would be able to see this error if you properly debugged your popup; to do so, right-click the button and select "Inspect popup" to bring up Dev Tools for it.


来源: stackexchange

问:
Importing Certificate with private key
I am trying to import a certificate with a private key and although my script is "working" it is missing something which I can't seem to figure out.

I have an app which talks to KeyVault and uses this certificate for authorization. I have the password for said certificate and when I install the PFX manually along with assigning the NETWORK SERVICE account permission this works fine. However, using the following PowerShell I get the error Keyset does not exist. Everything seems normal when I check this under cert manager. Clearly, the UI is doing something different.. any ideas?

EDIT
When I add the NETWORK SERVICE account manually this works fine. PowerShell is running in admin mode when I execute the script so perhaps its some weirdness in that?

The script

```<code>cls
$certName = "certname.pfx"
$path = "C:\Certificates\$certName"
$serviceAccount = 'NETWORK SERVICE'
$permissionType = 'Read'
$password = 'somepassword'

try {
    # Import the certificate maintaining the private key format
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cert.Import($path, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")

    # Add the cert to personal store location
    $store = Get-Item Cert:\LocalMachine\My
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
    $store.Add($cert)
    $store.Close()

    # Get SecurityIdentifier value from current username
    $currentUser = New-Object System.Security.Principal.NTAccount($env:USERNAME)
    $strSID = $currentUser.Translate([System.Security.Principal.SecurityIdentifier])
    $path = "$env:USERPROFILE\AppData\Roaming\Microsoft\Crypto\RSA\$($strSID.Value)\$($cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName)"
    $acl = Get-Acl $path
    $rule = New-Object Security.AccessControl.FileSystemAccessRule $serviceAccount, 'FullControl', Allow
    $acl.AddAccessRule($rule)
    Set-Acl $path $acl

    Write-Host "Cert installed, press any key to continue" -ForegroundColor Green
    Read-Host
}
catch {
    Write-Error -Message $_
}
</code>```

ANSWER
For others experiencing the same issues as I was, simply provide multiple storage flags:

```<code>$flags = @([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"MachineKeySet", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($path, $password, $flags)
</code>```

答:
You probably want to import the certificate using both PersistKeySet and MachineKeySet.  Looking at how you're doing things here you have

Open the PFX without specifying User vs Machine KeySet

Add it to the LocalMachine store.

Find the key file under the current user's SID.

The Windows Cert store, AFAIK, doesn't write down which user owns a key, just that this cert is paired with "user key {id}".  So it needs to be the machine (shared) key store.

The "keyset does not exist" is because the Network Service user doesn't have a key named with that ID in their keystore.

So the difference, probably, is that the UI is asserting the MachineKeySet (equivalent) because it knows you're importing into a LocalMachine store.

ContentLicense: CC BY-SA 3.0

Title: Importing Certificate with private key

Body:
I am trying to import a certificate with a private key and although my script is "working" it is missing something which I can't seem to figure out.

I have an app which talks to KeyVault and uses this certificate for authorization. I have the password for said certificate and when I install the PFX manually along with assigning the NETWORK SERVICE account permission this works fine. However, using the following PowerShell I get the error Keyset does not exist. Everything seems normal when I check this under cert manager. Clearly, the UI is doing something different.. any ideas?

EDIT
When I add the NETWORK SERVICE account manually this works fine. PowerShell is running in admin mode when I execute the script so perhaps its some weirdness in that?

The script

cls
$certName = "certname.pfx"
$path = "C:\Certificates\$certName"
$serviceAccount = 'NETWORK SERVICE'
$permissionType = 'Read'
$password = 'somepassword'

try {
    # Import the certificate maintaining the private key format
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cert.Import($path, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")

    # Add the cert to personal store location
    $store = Get-Item Cert:\LocalMachine\My
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
    $store.Add($cert)
    $store.Close()

    # Get SecurityIdentifier value from current username
    $currentUser = New-Object System.Security.Principal.NTAccount($env:USERNAME)
    $strSID = $currentUser.Translate([System.Security.Principal.SecurityIdentifier])
    $path = "$env:USERPROFILE\AppData\Roaming\Microsoft\Crypto\RSA\$($strSID.Value)\$($cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName)"
    $acl = Get-Acl $path
    $rule = New-Object Security.AccessControl.FileSystemAccessRule $serviceAccount, 'FullControl', Allow
    $acl.AddAccessRule($rule)
    Set-Acl $path $acl

    Write-Host "Cert installed, press any key to continue" -ForegroundColor Green
    Read-Host
}
catch {
    Write-Error -Message $_
}

ANSWER
For others experiencing the same issues as I was, simply provide multiple storage flags:

$flags = @([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"MachineKeySet", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($path, $password, $flags)


问:
SCons - Headers/Libraries in a non-standard location
I'm trying to use SCons to compile a program that requires a set of dependencies which I've installed in a non-standard location.

I've installed the dependencies in /home/dja/ocr. Now I'm trying to compile the main program and can't figure out how to tell SCons where to look for the libraries and headers.

I've tried (amongst others):

```<code>scons prefix=/home/dja/ocr

scons includepath=/home/dja/ocr/include libpath=/home/dja/ocr/lib

env LIBPATH=/home/dja/ocr/lib INCLUDEPATH=/home/dja/ocr/include scons

...etc...
</code>```

The results are always the same:

```<code>scons: Reading SConscript files ...
Currently supported OS version: Ubuntu 10.04
Checking for C++ library iulib... no
AssertionError: :
  File "/home/dja/ocr/src/ocropus/SConstruct", line 107:
    assert conf.CheckLibWithHeader("iulib","iulib/iulib.h","C++");
</code>```

I haven't been able to find an answer on Google.

What is the correct SCons foo to get this to work?

答:
You need to create an environment and set appropriate variables:

```<code>env = Environment(
          CPPPATH=['/home/dja/ocr/include'],
          LIBPATH=['/home/dja/ocr/lib'],
          LIBS=['iulib'])
env.Program('my_executable', Glob('*.c'))
</code>```

The CPPPATH points to a list of C Pre-Processor Paths (Note: 3 P's). LIBPATH points to where your libraries reside. Finally, LIBS is a list of libraries to link with your program.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use SCons to compile a program that requires a set of dependencies which I've installed in a non-standard location.

I've installed the dependencies in /home/dja/ocr. Now I'm trying to compile the main program and can't figure out how to tell SCons where to look for the libraries and headers.

I've tried (amongst others):

scons prefix=/home/dja/ocr

scons includepath=/home/dja/ocr/include libpath=/home/dja/ocr/lib

env LIBPATH=/home/dja/ocr/lib INCLUDEPATH=/home/dja/ocr/include scons

...etc...

The results are always the same:

scons: Reading SConscript files ...
Currently supported OS version: Ubuntu 10.04
Checking for C++ library iulib... no
AssertionError: :
  File "/home/dja/ocr/src/ocropus/SConstruct", line 107:
    assert conf.CheckLibWithHeader("iulib","iulib/iulib.h","C++");

I haven't been able to find an answer on Google.

What is the correct SCons foo to get this to work?

Body:
You need to create an environment and set appropriate variables:

env = Environment(
          CPPPATH=['/home/dja/ocr/include'],
          LIBPATH=['/home/dja/ocr/lib'],
          LIBS=['iulib'])
env.Program('my_executable', Glob('*.c'))

The CPPPATH points to a list of C Pre-Processor Paths (Note: 3 P's). LIBPATH points to where your libraries reside. Finally, LIBS is a list of libraries to link with your program.


问:
Cocossharp CCFadeOut not working
I use cocossharp. I want to add fade in/out transition when replacing scene. The fade in for the second scene works fine, but the current scene's fade out is not working.

My code for transition at GameStartScene.cs is:

```<code>gameStartLayer.RunAction (new CCFadeOut (1.5f));
GameAppDelegate.GoToGameScene (); //director.ReplaceScene (new CCTransitionFade(1.5f, gamePlayScene));
</code>```

How can I implement a fade out effect for the scene?

答:
jaybers is right about: "The GoToGameScene runs immediately after the RunAction above"
BUT!
you should do this:

```<code> await gameStartLayer.RunActionAsync(new CCFadeOut (1.5f));
 GameAppDelegate.GoToGameScene();
</code>```

If you want to wait until going to next scene

Title: Cocossharp CCFadeOut not working

Body:
I use cocossharp. I want to add fade in/out transition when replacing scene. The fade in for the second scene works fine, but the current scene's fade out is not working.

My code for transition at GameStartScene.cs is:

gameStartLayer.RunAction (new CCFadeOut (1.5f));
GameAppDelegate.GoToGameScene (); //director.ReplaceScene (new CCTransitionFade(1.5f, gamePlayScene));

How can I implement a fade out effect for the scene?

Body:
jaybers is right about: "The GoToGameScene runs immediately after the RunAction above"
BUT!
you should do this:

 await gameStartLayer.RunActionAsync(new CCFadeOut (1.5f));
 GameAppDelegate.GoToGameScene();

If you want to wait until going to next scene


问:
Refactor javascript if statement
I have a unusual nested if statement where a third condition is needed to execute some code, but this condition is independent of my else clause. Thus, I've nested this condition inside the outer 2 conditions. The below works as it should, but I'm not positive this is the best way to handle a case like this. Should I use another method or refactor this in a way I'm not thinking of?

```<code>if ($('#preferred-contact').prop('selectedIndex') == index && !$(selector).val())
{
    if (!$(label).parent().hasClass('has-error')) {
        $(selector).after("<span class='help-block form-error'>Required Field</span>");
        $(label).parent().addClass('has-error');
    }
}
else {
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}
</code>```

答:
The way you are using conditionals if fine enaugh. However if you insist on getting rid of inner condition, you can rewrite it from backwards and use else if:

```<code>if ($('#preferred-contact').prop('selectedIndex') != index || $(selector).val())
{
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}
else if (!$(label).parent().hasClass('has-error')) {
    $(selector).after("<span class='help-block form-error'>Required Field</span>");
    $(label).parent().addClass('has-error');
}
</code>```

Title: Refactor javascript if statement

Body:
I have a unusual nested if statement where a third condition is needed to execute some code, but this condition is independent of my else clause. Thus, I've nested this condition inside the outer 2 conditions. The below works as it should, but I'm not positive this is the best way to handle a case like this. Should I use another method or refactor this in a way I'm not thinking of?

if ($('#preferred-contact').prop('selectedIndex') == index && !$(selector).val())
{
    if (!$(label).parent().hasClass('has-error')) {
        $(selector).after("Required Field");
        $(label).parent().addClass('has-error');
    }
}
else {
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}

Body:
The way you are using conditionals if fine enaugh. However if you insist on getting rid of inner condition, you can rewrite it from backwards and use else if:

if ($('#preferred-contact').prop('selectedIndex') != index || $(selector).val())
{
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}
else if (!$(label).parent().hasClass('has-error')) {
    $(selector).after("<span class='help-block form-error'>Required Field</span>");
    $(label).parent().addClass('has-error');
}


问:
Stub the include_recipe call to take no action but still count the recipe as included
The default recipe for my cookbook simply includes several other recipes. I know that I can test that the appropriate recipes are included using:

expect(chef_run).to include_recipe 'cookbook::recipe_name

but this doesn't work when I've stubbed the include_recipe call like so

Chef::Recipe.any_instance.stub(:include_recipe).with(anything).and_return(true)

I'm stubbing the include_recipe call as I don't want to have to define all the missing attributes for all of my recipes in this spec.

I would have thought that by stubbing the method to return true ChefSpec would report it as having run and consider the recipes included but it doesn't. Any ideas?

答:
I think I have an updated and cleaner solution to this if you want to ensure include_recipe is called with the right recipe(s), but don't want to load the resources in the included recipe(s):

```<code>before(:all) { @included_recipes = [] }
before do
  @stubbed_recipes = %w[test_cookbook::included_recipe apt]
  @stubbed_recipes.each do |r|
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(r) do
      @included_recipes << r
    end
  end
end

it 'includes the correct recipes' do
  chef_run
  expect(@included_recipes).to match_array(@stubbed_recipes)
end
</code>```

A complete example of this: https://github.com/atheiman/test-cookbook/pull/4

Body:
I think I have an updated and cleaner solution to this if you want to ensure include_recipe is called with the right recipe(s), but don't want to load the resources in the included recipe(s):

before(:all) { @included_recipes = [] }
before do
  @stubbed_recipes = %w[test_cookbook::included_recipe apt]
  @stubbed_recipes.each do |r|
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(r) do
      @included_recipes << r
    end
  end
end

it 'includes the correct recipes' do
  chef_run
  expect(@included_recipes).to match_array(@stubbed_recipes)
end

A complete example of this: https://github.com/atheiman/test-cookbook/pull/4


问:
The mysql use of addslashes()

Possible Duplicate:

  What does mysql_real_escape_string() do that addslashes() doesn't?

If you are trying to prevent sql injection, the first thing you would do is use mysql_real_escape_string.  Is it possible to inject a database using addslashes()?

答:
This is what happens when you only add slashes in a language which understands unicode encodings (or mix up encodings while sending the query): http://bugs.mysql.com/bug.php?id=22243

Basically it's safer to know what the database expects in term of encoding - this way you won't end up escaping half of the character by accident, or leaving later part of a character unescaped.

Title: The mysql use of addslashes()


问:
Sencha Architect 4 - ExtJS 6.5 -> Dreamfactory 2.9 Authentication Session Token
I got a little bit stuck and I would like to ask your advice, I am trying to setup a login window // authentication using DreamFactory in Sencha Architect however I am pretty much a beginner.

My current Code is:

```<code>var username = Ext.getCmp('usr').getValue(),
password = Ext.getCmp('pwd').getValue();

Ext.Ajax.defaultHeaders = {
'X-DreamFactory-Api-Key' : 'xyz',
'Content-Type' : 'application/json'
};

Ext.Ajax.request({
url: 'http://dreamfactoryaddy:8080/api/v2/user/session',
withCredentials: true,
email: username,
password: password,
cors: true,

success: function(response) {
    var obj = Ext.decode(response.responseText);
    Ext.Ajax.defaultHeaders = {
        'X-DreamFactory-Api-Key' :
'xyz', 'Content-Type' : 'application/json', 'X-DreamFactory-Session-
Token': obj.session_token
    };
    console.log(obj);
},

failure: function(response) {
        console.log(response.responseText);
}

});
</code>```

I receive this error:

```<code>{"error":{"code":401,"context":null,"message":"There is no valid session for the current request.","status_code":401}}
</code>```

http://prntscr.com/hate2e

Can you give me some advice how to handle Sessions properly?

UPDATE 2:

```<code>            var username = Ext.getCmp('usr').getValue(),
                password = Ext.getCmp('pwd').getValue(),
                headers = {
                    'X-DreamFactory-Api-Key' : 'xyz',
                    'Content-Type' : 'application/json'
                };

            Ext.Ajax.setDefaultHeaders(headers);
            Ext.Ajax.request({
                url: 'http://chalton.swiftmedia.ca:8080/api/v2/user/session',
                withCredentials: true,
                jsonData: {
                    "email" : username,
                    "password" : password
                },
                cors: true,

                success: function(response) {
                    var obj = Ext.util.JSON.decode(response.responseText),
                        newheaders = {
                            'X-DreamFactory-Api-Key' : 'xyz',
                            'Content-Type' : 'application/json',
                            'X-DreamFactory-Session-Token': obj.session_token
                        };
                    console.log(response.responseText);
                    Ext.Ajax.setDefaultHeaders(newheaders);
                },

                failure: function(response) {
                    console.log(response.responseText);
                }

            });
        },
</code>```

答:
If you check the browser console, you may find that the defaultHeaders are not correctly applied to your ajax requests.

I had the very same issue with arbitrary other headers I wanted as the default headers. Ext.Ajax.defaultHeaders = x just doesn't work, Ext.Ajax.setDefaultHeaders(x) does.

Body:
I got a little bit stuck and I would like to ask your advice, I am trying to setup a login window // authentication using DreamFactory in Sencha Architect however I am pretty much a beginner.

My current Code is:

var username = Ext.getCmp('usr').getValue(),
password = Ext.getCmp('pwd').getValue();

Ext.Ajax.defaultHeaders = {
'X-DreamFactory-Api-Key' : 'xyz',
'Content-Type' : 'application/json'
};

Ext.Ajax.request({
url: 'http://dreamfactoryaddy:8080/api/v2/user/session',
withCredentials: true,
email: username,
password: password,
cors: true,

success: function(response) {
    var obj = Ext.decode(response.responseText);
    Ext.Ajax.defaultHeaders = {
        'X-DreamFactory-Api-Key' :
'xyz', 'Content-Type' : 'application/json', 'X-DreamFactory-Session-
Token': obj.session_token
    };
    console.log(obj);
},

failure: function(response) {
        console.log(response.responseText);
}

});

I receive this error:

{"error":{"code":401,"context":null,"message":"There is no valid session for the current request.","status_code":401}}

http://prntscr.com/hate2e

Can you give me some advice how to handle Sessions properly?

UPDATE 2:

            var username = Ext.getCmp('usr').getValue(),
                password = Ext.getCmp('pwd').getValue(),
                headers = {
                    'X-DreamFactory-Api-Key' : 'xyz',
                    'Content-Type' : 'application/json'
                };

            Ext.Ajax.setDefaultHeaders(headers);
            Ext.Ajax.request({
                url: 'http://chalton.swiftmedia.ca:8080/api/v2/user/session',
                withCredentials: true,
                jsonData: {
                    "email" : username,
                    "password" : password
                },
                cors: true,

                success: function(response) {
                    var obj = Ext.util.JSON.decode(response.responseText),
                        newheaders = {
                            'X-DreamFactory-Api-Key' : 'xyz',
                            'Content-Type' : 'application/json',
                            'X-DreamFactory-Session-Token': obj.session_token
                        };
                    console.log(response.responseText);
                    Ext.Ajax.setDefaultHeaders(newheaders);
                },

                failure: function(response) {
                    console.log(response.responseText);
                }

            });
        },


问:
How to set up blogdown / Travis-CI to ignore certain files?
I have a blog written in blogdown and deployed via Travis CI.

This means that every time I make a change to a single post the whole site is regenerated. This takes about 10 minutes, so time is not an issue.

One of my posts however calls an exotic API, which sometimes gives unexpected results causing the whole build to crash. This happens even when there has been no change in the offending post.

Is there an option to deploy only changed content and / or specify that the one post should be ignored from the whole site rebuild?

答: You have been warned agaist building your website on Travis in Section 3.4 of the blogdown book. I don't think it is a good idea to use this approach unless your website does not contain Rmd posts. If you want to ignore a certain post, you may use a different filename extension (i.e. not .Rmd); please see Section 1.5 for details (scroll to the bottom if you do not have the patience to read the full section).


问:
Stack Pointer does not load at the startup in ARM Cortex M4 (Tiva C Series TM4C123GH6PM)
I'm trying to write the most simple program for Tiva C launchpad. Stack pointer value and program counter value are automaticaly taken from the two first 32-bits words of flash. But, for somehow reason, when I debug with gdb, the stack pointer gets 0x0. This causes that program fails. I'm using this instructions to debug:

```<code>(gdb) target extended-remote :3333
(gdb) monitor reset halt
(gdb) load
(gdb) monitor reset init
</code>```

Program in assembly is startup.s:

```<code>        .syntax unified

        .section .vector_interrupt, "x"

    g_pfnVectors:
        .word 0x20007FFF
        .word _Reset

        .text
    .global _Reset
    _Reset:
        mov   r0, #0
        b stop

    stop:
        add   r0, r0, #1
        b stop
</code>```

the linker file Tiva.lds:

```<code>ENTRY(_Reset)

MEMORY
{
    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00040000
    SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

SECTIONS {
        .vector_interrupt : {
        KEEP(*(.vector_interrupt));
    } > FLASH

    .text : {
        . = 0x0000026c;
        * (.text);
    } > FLASH

}
</code>```

and the makefile:

```<code>gcc=arm-none-eabi-gcc
objcopy=arm-none-eabi-objcopy

FLAGS= -ggdb3 -nostdlib -std=c99 -mcpu=cortex-m4 \
       -mfloat-abi=softfp -mfpu=fpv4-sp-d16 -Wall \
       -Werror -nostartfiles

csum.bin: csum.elf
    $(objcopy) -O binary csum.elf csum.bin

csum.elf: startup.s
    $(gcc) $(FLAGS) -T Tiva.lds -o csum.elf \
    startup.s

openocd:
    openocd -f ../openOCD/ek-tm4c123gxl.cfg
</code>```

What is wrong?

Actualization

I was trying to avoid put the exception handlers. However, Now I put them. The problem is that i'm getting an UsageFault at startup.

I did this modifications:
startup.s:

```<code>.syntax unified

        .section .vector_interrupt, "x"
g_pfnVectors:
        .word   _stack_start
        .word   _Reset
        .word   NMI           /* NMI Handler */
        .word   HardFault     /* Hard Fault Handler */
        .word   MemManage     /* MPU Fault Handler */
        .word   BusFault      /* Bus Fault Handler */
        .word   UsageFault    /* Usage Fault Handler */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   SVC           /* SVCall Handler */
        .word   DebugMon      /* Debug Monitor Handler */
        .word   0             /* Reserved */
        .word   PendSV        /* PendSV Handler */
        .word   SysTick       /* SysTick Handler */

        .text
.global _Reset
_Reset:
        mov   r0, #0
        b stop

stop:
        add   r0, r0, #1
        b stop               @ Infinite loop to stop execution

        .align  1
        .thumb_func
        .weak   Default_Handler
        .type   Default_Handler, %function
Default_Handler:
        b   .

/* Macro to define default handlers */
        .macro  def_handler handler_name
            .weak   \handler_name
            .set    \handler_name, Default_Handler
        .endm

        def_handler NMI
        def_handler HardFault
        def_handler MemManage
        def_handler BusFault
        def_handler UsageFault
        def_handler SVC
        def_handler DebugMon
        def_handler PendSV
        def_handler SysTick
        def_handler DEF_IRQHandler
</code>```

Tiva.lds:

```<code>ENTRY(_Reset)

MEMORY
{
    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00040000
    SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

_stack_start = ORIGIN(SRAM)+LENGTH(SRAM);

SECTIONS {
        .text : {
            KEEP(*(.vector_interrupt));
            * (.text);
        } > FLASH

}
</code>```

This is the output from arm-none-eabi-objdump -d csum.elf

```<code>csum.elf:     file format elf32-littlearm

Disassembly of section .text:

00000000 <g_pfnVectors>:
   0:   20008000    .word   0x20008000
   4:   00000040    .word   0x00000040
   8:   0000004d    .word   0x0000004d
   c:   0000004d    .word   0x0000004d
  10:   0000004d    .word   0x0000004d
  14:   0000004d    .word   0x0000004d
  18:   0000004d    .word   0x0000004d
    ...
  2c:   0000004d    .word   0x0000004d
  30:   0000004d    .word   0x0000004d
  34:   00000000    .word   0x00000000
  38:   0000004d    .word   0x0000004d
  3c:   0000004d    .word   0x0000004d

00000040 <_Reset>:
  40:   f04f 0000   mov.w   r0, #0
  44:   e7ff        b.n 46 <stop>

00000046 <stop>:
  46:   f100 0001   add.w   r0, r0, #1
  4a:   e7fc        b.n 46 <stop>

0000004c <BusFault>:
  4c:   f7ff bff8   b.w 4c <BusFault>
</code>```

The reasons for the UsageFault can be:

An undefined instruction

– An illegal unaligned access

– Invalid state on instruction execution

– An error on exception return

but i don't figure out what is the reason.

答:
Writing in ARM assembly is tricky. There were three problems with this code.

The .vector_interrupt section did not make it to the binary file because it did not have the ALLOC attribute. objcopy ignores sections without the ALLOC attribute. As a result, the initial stack pointer and reset vector were zeroes. To fix this, the section attributes should read "xa":

```<code>.section .vector_interrupt, "xa"
</code>```

Another problem: initial stack pointer is unaligned. Change it to:

```<code>.word 0x20008000
</code>```

This is assuming the MCU has at least 32KB RAM.

Branch target addresses should have the LSB bit set to one to indicate Thumb mode. Cortex-M4 supports the Thumb instruction set only, therefore, it generates a fault when trying to jump to an even address. In order to let the assembler generate correct address values, the .thumb_func should precede each label that identified a branch target.

See https://sourceware.org/binutils/docs/as/ARM-Directives.html

Body:
I'm trying to write the most simple program for Tiva C launchpad. Stack pointer value and program counter value are automaticaly taken from the two first 32-bits words of flash. But, for somehow reason, when I debug with gdb, the stack pointer gets 0x0. This causes that program fails. I'm using this instructions to debug:

(gdb) target extended-remote :3333
(gdb) monitor reset halt
(gdb) load
(gdb) monitor reset init

Program in assembly is startup.s:

        .syntax unified

        .section .vector_interrupt, "x"

    g_pfnVectors:
        .word 0x20007FFF
        .word _Reset

        .text
    .global _Reset
    _Reset:
        mov   r0, #0
        b stop

    stop:
        add   r0, r0, #1
        b stop

the linker file Tiva.lds:

ENTRY(_Reset)

MEMORY
{
    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00040000
    SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

SECTIONS {
        .vector_interrupt : {
        KEEP(*(.vector_interrupt));
    } > FLASH

    .text : {
        . = 0x0000026c;
        * (.text);
    } > FLASH

}

and the makefile:

gcc=arm-none-eabi-gcc
objcopy=arm-none-eabi-objcopy

FLAGS= -ggdb3 -nostdlib -std=c99 -mcpu=cortex-m4 \
       -mfloat-abi=softfp -mfpu=fpv4-sp-d16 -Wall \
       -Werror -nostartfiles

csum.bin: csum.elf
    $(objcopy) -O binary csum.elf csum.bin

csum.elf: startup.s
    $(gcc) $(FLAGS) -T Tiva.lds -o csum.elf \
    startup.s

openocd:
    openocd -f ../openOCD/ek-tm4c123gxl.cfg

What is wrong?

Actualization

I was trying to avoid put the exception handlers. However, Now I put them. The problem is that i'm getting an UsageFault at startup.

I did this modifications:
startup.s:

.syntax unified

        .section .vector_interrupt, "x"
g_pfnVectors:
        .word   _stack_start
        .word   _Reset
        .word   NMI           /* NMI Handler */
        .word   HardFault     /* Hard Fault Handler */
        .word   MemManage     /* MPU Fault Handler */
        .word   BusFault      /* Bus Fault Handler */
        .word   UsageFault    /* Usage Fault Handler */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   0             /* Reserved */
        .word   SVC           /* SVCall Handler */
        .word   DebugMon      /* Debug Monitor Handler */
        .word   0             /* Reserved */
        .word   PendSV        /* PendSV Handler */
        .word   SysTick       /* SysTick Handler */

        .text
.global _Reset
_Reset:
        mov   r0, #0
        b stop

stop:
        add   r0, r0, #1
        b stop               @ Infinite loop to stop execution

        .align  1
        .thumb_func
        .weak   Default_Handler
        .type   Default_Handler, %function
Default_Handler:
        b   .

/* Macro to define default handlers */
        .macro  def_handler handler_name
            .weak   \handler_name
            .set    \handler_name, Default_Handler
        .endm

        def_handler NMI
        def_handler HardFault
        def_handler MemManage
        def_handler BusFault
        def_handler UsageFault
        def_handler SVC
        def_handler DebugMon
        def_handler PendSV
        def_handler SysTick
        def_handler DEF_IRQHandler

Tiva.lds:

ENTRY(_Reset)

MEMORY
{
    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00040000
    SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

_stack_start = ORIGIN(SRAM)+LENGTH(SRAM);

SECTIONS {
        .text : {
            KEEP(*(.vector_interrupt));
            * (.text);
        } > FLASH

}

This is the output from arm-none-eabi-objdump -d csum.elf

csum.elf:     file format elf32-littlearm

Disassembly of section .text:

00000000 <g_pfnVectors>:
   0:   20008000    .word   0x20008000
   4:   00000040    .word   0x00000040
   8:   0000004d    .word   0x0000004d
   c:   0000004d    .word   0x0000004d
  10:   0000004d    .word   0x0000004d
  14:   0000004d    .word   0x0000004d
  18:   0000004d    .word   0x0000004d
    ...
  2c:   0000004d    .word   0x0000004d
  30:   0000004d    .word   0x0000004d
  34:   00000000    .word   0x00000000
  38:   0000004d    .word   0x0000004d
  3c:   0000004d    .word   0x0000004d

00000040 <_Reset>:
  40:   f04f 0000   mov.w   r0, #0
  44:   e7ff        b.n 46 <stop>

00000046 <stop>:
  46:   f100 0001   add.w   r0, r0, #1
  4a:   e7fc        b.n 46 <stop>

0000004c <BusFault>:
  4c:   f7ff bff8   b.w 4c <BusFault>

The reasons for the UsageFault can be:

An undefined instruction

– An illegal unaligned access

– Invalid state on instruction execution

– An error on exception return

but i don't figure out what is the reason.

Body:
Writing in ARM assembly is tricky. There were three problems with this code.

The .vector_interrupt section did not make it to the binary file because it did not have the ALLOC attribute. objcopy ignores sections without the ALLOC attribute. As a result, the initial stack pointer and reset vector were zeroes. To fix this, the section attributes should read "xa":

.section .vector_interrupt, "xa"

Another problem: initial stack pointer is unaligned. Change it to:

.word 0x20008000

This is assuming the MCU has at least 32KB RAM.

Branch target addresses should have the LSB bit set to one to indicate Thumb mode. Cortex-M4 supports the Thumb instruction set only, therefore, it generates a fault when trying to jump to an even address. In order to let the assembler generate correct address values, the .thumb_func should precede each label that identified a branch target.

See https://sourceware.org/binutils/docs/as/ARM-Directives.html


问:
Java 8 filter a stream to replace SQL IN (...) clause
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL</p>

```<code>SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);
</code>```

答:
Just use Apache Commons Collection

```<code>ListUtils.intersection(numbers, range);
</code>```

https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/ListUtils.html#intersection

Body:
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL

SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);

Body:
Just use Apache Commons Collection

ListUtils.intersection(numbers, range);

https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/ListUtils.html#intersection


问:
how to pass ServletRequest to pojo that does i/o in graphql-java
I need to pass a servlet attribute value to the Query object on a per request basis.  I have this much working, but how can I get the real Query object from the qt variable?</p>

```<code>    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    GraphQLSchema schema = getSchemaProvider().getSchema();
    //schema.transform(c -> {});
    GraphQLObjectType t = schema.getQueryType();
    String rootLib = (String) req.getAttribute("ROOTLIB");
    super.service(req, res);
}
</code>```

答:
extend DefaultQLSchemaProvider and override the getSchema(request:HttpServletRequest):GraphQLSchema method.
Then override the GraphQLEndpoint ctor and create the schemaProvider when calling super(GrapQLProvider, ...) ctor.</p>

Body:
I need to pass a servlet attribute value to the Query object on a per request basis.  I have this much working, but how can I get the real Query object from the qt variable?

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    GraphQLSchema schema = getSchemaProvider().getSchema();
    //schema.transform(c -> {});
    GraphQLObjectType t = schema.getQueryType();
    String rootLib = (String) req.getAttribute("ROOTLIB");
    super.service(req, res);
}


问:
Dijkstra - find destinations within budget
I was given a graph, including a start vertex, other vertices, and edges represent the costs going from one vertex to another. I need to find the set of destination vertices that I can travel to from the start vertex. The budget is a certain amount of dollars and the travel total cost should be within the budget. How can i implement the Dijkstra's algorithm to this problem? I think we usually use Dijkstra to find the shortest path between two fixed vertices before. But I am not sure how to implement Dijkstra on this budget problem. If someone can give some ideas, that really helps!</p>

答: To my undersatanding, Dijkstra's algorithm solves the single-source shortest path problem. This means that the resulting data structure is a tree rooted at the starting node. Typically, an implementation would store the minimum cost to reach each node from the starting node. In total, the set of vertices that can be reached within the budget are the ones to which the cost of the shortest path does not exceed the budget. The algorithm itself does not need to be modified; in an additional step, the nodes which can be reached within budged has to be returned as the output.</p>


问:
which automated web testing framework is kept most up-to-date?
Related: Automated Web UI Testing

I'm evaluating ui testing frameworks. It seems like some of them aren't updated very often (esp. Selenium, the core hasn't been updated since 6/2009).

My concern here is that I'll adopt/learn a testing framework that isn't going to be compatible with HTML5. I'm working in C# land, so I'd prefer a framework that will output tests in C# (Nunit).

Which UI testing framework is most likely to be kept up-to-date as HTML5 features become more commonplace?

Candidates:

Selenium

Molybdenum

Watin

Sahi

??

答:
I'd recommend using WebDriver/Selenium. This has wide adoption at many major companies (including Google for example) so isn't likely to go away any time soon. It also has wide support from browser vendors.

Otherwise Watir is also popular.


问:
Page Object Pattern for Xcode 7 UI Tests
Has anyone successfully implemented the Page Object pattern in their UI tests?  I gave it a try and ran into an issue.  When I use the predicate to wait for the element to exist, I get a warning in the log.  Here's a code snippet from the Page Object class:

```<code>XCUIElement *myCoolButton = self.app.buttons[@"Super Cool Button"];
[self expectationForPredicate:self.existsPredicate evaluatedWithObject:myCoolButton handler:nil];
[self waitForExpectationsWithTimeout:5.0f handler:nil];
</code>```

When this code executes, I see the following in the log:

```<code>Questionable API usage: creating XCTestExpectation for test case -[MyPageObject (null)] which is not the currently running test case -[MyTestCase test]
</code>```

and when the timeout is exceeded, I see the error in the log but the test itself doesn't actually fail.  I'm assuming that this is because the predicate is set up in the Page Object class, not the test itself.  Has anyone been able to work around this?

答:
I used the same idea of passing the testCase by parameter, but it became pretty ugly later. One of the approaches (the one I prefere) for PageObjects says you should not have asserts on Pages.

So I came up with this implementation:

```<code>class Page {
    required init(_ c: ((Bool) -> Void)? = nil) {
        c?(waitForExistence())
    }
    func waitForExistence() -> Bool {
        fatalError("Subclass of Page should override \(#function)")
    }
}
</code>```

Then, instead of using the waitForExpectation, which would require XCTestCase, you can use the new XCode9 API for XCUIElement: waitForExistence(timeout:) (or XCTWaiter if you need a more complex expectation)

```<code>class LoginPage: Page {
    override func waitForExistence() -> Bool {
        return XCUIApplication().otherElements["view_login"].waitForExistence(timeout: 10)
    }
</code>```

And the use would be:

```<code>LoginPage {
   XCTAssertTrue($0, "Login page not shown")
}
.type(email: "solid@snake.com")
</code>```

Body:
Has anyone successfully implemented the Page Object pattern in their UI tests?  I gave it a try and ran into an issue.  When I use the predicate to wait for the element to exist, I get a warning in the log.  Here's a code snippet from the Page Object class:

XCUIElement *myCoolButton = self.app.buttons[@"Super Cool Button"];
[self expectationForPredicate:self.existsPredicate evaluatedWithObject:myCoolButton handler:nil];
[self waitForExpectationsWithTimeout:5.0f handler:nil];

When this code executes, I see the following in the log:

Questionable API usage: creating XCTestExpectation for test case -[MyPageObject (null)] which is not the currently running test case -[MyTestCase test]

and when the timeout is exceeded, I see the error in the log but the test itself doesn't actually fail.  I'm assuming that this is because the predicate is set up in the Page Object class, not the test itself.  Has anyone been able to work around this?

Body:
I used the same idea of passing the testCase by parameter, but it became pretty ugly later. One of the approaches (the one I prefere) for PageObjects says you should not have asserts on Pages.

So I came up with this implementation:

class Page {
    required init(_ c: ((Bool) -> Void)? = nil) {
        c?(waitForExistence())
    }
    func waitForExistence() -> Bool {
        fatalError("Subclass of Page should override \(#function)")
    }
}

Then, instead of using the waitForExpectation, which would require XCTestCase, you can use the new XCode9 API for XCUIElement: waitForExistence(timeout:) (or XCTWaiter if you need a more complex expectation)

class LoginPage: Page {
    override func waitForExistence() -> Bool {
        return XCUIApplication().otherElements["view_login"].waitForExistence(timeout: 10)
    }

And the use would be:

LoginPage {
   XCTAssertTrue($0, "Login page not shown")
}
.type(email: "solid@snake.com")


问:
Check if a value from a list of values in a python dictionary exists in another dictionary
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

```<code> import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')
</code>```

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

```<code>errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1
</code>```

However the output I get is wrong. I get :

```<code>name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report
</code>```

My expected output would :

```<code>AccountReport is an invalid report
dob is an invalid field in PersonReport report
</code>```

Any help is appreciated
Thanks
p.s I'm using python 3.6

答:
Your code had couple of mistakes which lead to you checking every field. Use of continue and only iterating over the correct key solved this.
Here's a fixed code snippet:

```<code>for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
        continue # Continue to next key
    cols = master[key] # Get the correct column names from the current key
    errorFlag = False
    for field in template[key]:
        if field not in cols:
            print("{} is an invalid field in {} report".format(field, key))
            errorCount += 1
            errorFlag = True # You can break here if you wish not to keep incrementing the errorCount.

    if not errorFlag: # We did not find any bad column
        print("Success finding valid {} report in master".format(key))
</code>```

This outputs:

```<code> dob is an invalid field in  PersonReport report
 AccountReport is an invalid report
Success finding valid  TransactionReport report in master
</code>```

Body:
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

 import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1

However the output I get is wrong. I get :

name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report

My expected output would :

AccountReport is an invalid report
dob is an invalid field in PersonReport report

Any help is appreciated
Thanks
p.s I'm using python 3.6

Body:
Your code had couple of mistakes which lead to you checking every field. Use of continue and only iterating over the correct key solved this.
Here's a fixed code snippet:

for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
        continue # Continue to next key
    cols = master[key] # Get the correct column names from the current key
    errorFlag = False
    for field in template[key]:
        if field not in cols:
            print("{} is an invalid field in {} report".format(field, key))
            errorCount += 1
            errorFlag = True # You can break here if you wish not to keep incrementing the errorCount.

    if not errorFlag: # We did not find any bad column
        print("Success finding valid {} report in master".format(key))

This outputs:

 dob is an invalid field in  PersonReport report
 AccountReport is an invalid report
Success finding valid  TransactionReport report in master


问:
Namespace not found
I have defined the following code for my interface:

```<code>using Android.Widget;
using Android.Graphics;
using Xamarin.Forms;
using Android.Content.Res;
using MyApp.Droid;

[assembly: Dependency(typeof(MeasureString))]
namespace MyApp.UWP
{
        public class MeasureString : IMeasureString
        {
            public double calculateWidth(string text)
            {
                    Rect bounds = new Rect();
                    TextView textView = new TextView(Forms.Context);
                    textView.Paint.GetTextBounds(text, 0, text.Length, bounds);
                    var length = bounds.Width();
                    return length / Resources.System.DisplayMetrics.ScaledDensity;
            }
        }
}
</code>```

This is my interface class:

```<code>using System.Threading.Tasks;

namespace MyApp
{
    public interface IMeasureString
    {
        public double calculateWidth(string text);
    }
}
</code>```

I'm getting the error "Type or Namespace MeasureString not found". Possible missing using directive or assembly reference".

I thought I'd copied everything over from my template interface which works fine and contains just the same namings.

How would I go on investigation what I'm missing?

答:
Your attribute is applied outside the namespace block, so that class isn't actually in scope.

You can either add a using statement for your own namespace or fully qualify the classname.

Title: Namespace not found

Body:
I have defined the following code for my interface:

using Android.Widget;
using Android.Graphics;
using Xamarin.Forms;
using Android.Content.Res;
using MyApp.Droid;

[assembly: Dependency(typeof(MeasureString))]
namespace MyApp.UWP
{
        public class MeasureString : IMeasureString
        {
            public double calculateWidth(string text)
            {
                    Rect bounds = new Rect();
                    TextView textView = new TextView(Forms.Context);
                    textView.Paint.GetTextBounds(text, 0, text.Length, bounds);
                    var length = bounds.Width();
                    return length / Resources.System.DisplayMetrics.ScaledDensity;
            }
        }
}

This is my interface class:

using System.Threading.Tasks;

namespace MyApp
{
    public interface IMeasureString
    {
        public double calculateWidth(string text);
    }
}

I'm getting the error "Type or Namespace MeasureString not found". Possible missing using directive or assembly reference".

I thought I'd copied everything over from my template interface which works fine and contains just the same namings.

How would I go on investigation what I'm missing?


问:
C# Class as one Value in Class // Mimic int behaviour
Is there a way to make my new Class mimic the behavior of an int or any Valuetype?

I want something, so these assignments are valid

```<code>MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!
</code>```

The MyClass looks roughly like this

```<code>public class MyClass {
    public int Value{get;set;}
    public int AnotherValue{get;set;}
    public T GetSomething<T>() {..}
}
</code>```

Every assignment of MyClass should return the Variable Value as Type int.

So far i found implicit operator int and implicit operator MyClass (int value). But this is not 'good enough'.

I want that MyClass realy behaves like an int. So var i = myClass lets i be an int.

Is this even possible?

答:
If you´d created a cast from your class to int as this:

```<code>public static implicit operator int(MyClass instance) { return instance.Value; }
</code>```

you could implicetly cast an instance of MyClass to an int:

```<code>int i = myClass;
</code>```

However you can not expect the var-keyword to guess that you actually mean typeof int instead of MyClass, so this does not work:

```<code>var x = myClass;  // x will never be of type int
</code>```

Apart from this I would highly discourage from an implicit cast as both types don´t have anything in common. Make it explicit instead:

```<code>int i = (int) myClass;
</code>```

See this excellent answer from Marc Gravell for why using an explicit cast over an implicit one. Basically it´s about determing if data will be lost when converting the one in the other. In your case you´re losing any information about AnotherValue, as the result is just a primitive int. When using an explicit cast on the other hand you claim: the types can be converted, however we may lose information of the original object and won´t care for that.

Body:
Is there a way to make my new Class mimic the behavior of an int or any Valuetype?

I want something, so these assignments are valid

MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!

The MyClass looks roughly like this

public class MyClass {
    public int Value{get;set;}
    public int AnotherValue{get;set;}
    public T GetSomething<T>() {..}
}

Every assignment of MyClass should return the Variable Value as Type int.

So far i found implicit operator int and implicit operator MyClass (int value). But this is not 'good enough'.

I want that MyClass realy behaves like an int. So var i = myClass lets i be an int.

Is this even possible?

Body:
If you´d created a cast from your class to int as this:

public static implicit operator int(MyClass instance) { return instance.Value; }

you could implicetly cast an instance of MyClass to an int:

int i = myClass;

However you can not expect the var-keyword to guess that you actually mean typeof int instead of MyClass, so this does not work:

var x = myClass;  // x will never be of type int

Apart from this I would highly discourage from an implicit cast as both types don´t have anything in common. Make it explicit instead:

int i = (int) myClass;

See this excellent answer from Marc Gravell for why using an explicit cast over an implicit one. Basically it´s about determing if data will be lost when converting the one in the other. In your case you´re losing any information about AnotherValue, as the result is just a primitive int. When using an explicit cast on the other hand you claim: the types can be converted, however we may lose information of the original object and won´t care for that.


问:
Multithreading not working - Create thread per loop index Java
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?</p>

```<code>   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
</code>```

答:
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads.

There are many reasons why that can happen although it's hard to know what is going on without seeing the myfn(...) code.  Here are some possible reasons:

It could be that myfn runs so quickly that running it in different threads isn't going to be any faster.

It could be that myfn is waiting on some other resource in which case the threads can't really run concurrently.

It could be that myfn is blocking on IO (network or disk) and even though you are doing 2 (or more) of them at a time, the disk or the remote server can't handle the increased requests any faster.

Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions...

The right thing to do here is to create your own class which takes the lower and upper bounds.  The right way to do this is to implement Runnable, not extend Thread.  Something like:

```<code>public class MyRunnable implements Runnable {
    private final int start;
    private final int end;
    public MyRunnable(int start, int end) {
        this.start = start;
        this.end = end;
    }
    public void run() {
        for (int i = start; i < end; i++) {
            myfn(i);
        }
    }
}
</code>```

You can then either start the threads by hand or use an ExecutorService which makes the thread maintenance a lot easier:

```<code>// this will start a new thread for every job
ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(new MyRunnable(0, 2));
threadPool.submit(new MyRunnable(2, 4));
// once you've submitted your last task, you shutdown the pool
threadPool.shutdown();
// then we wait until all of the tasks have run
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
</code>```

Body:
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?

   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Body:
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads.

There are many reasons why that can happen although it's hard to know what is going on without seeing the myfn(...) code.  Here are some possible reasons:

It could be that myfn runs so quickly that running it in different threads isn't going to be any faster.

It could be that myfn is waiting on some other resource in which case the threads can't really run concurrently.

It could be that myfn is blocking on IO (network or disk) and even though you are doing 2 (or more) of them at a time, the disk or the remote server can't handle the increased requests any faster.

Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions...

The right thing to do here is to create your own class which takes the lower and upper bounds.  The right way to do this is to implement Runnable, not extend Thread.  Something like:

public class MyRunnable implements Runnable {
    private final int start;
    private final int end;
    public MyRunnable(int start, int end) {
        this.start = start;
        this.end = end;
    }
    public void run() {
        for (int i = start; i < end; i++) {
            myfn(i);
        }
    }
}

You can then either start the threads by hand or use an ExecutorService which makes the thread maintenance a lot easier:

// this will start a new thread for every job
ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(new MyRunnable(0, 2));
threadPool.submit(new MyRunnable(2, 4));
// once you've submitted your last task, you shutdown the pool
threadPool.shutdown();
// then we wait until all of the tasks have run
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);


问:
Why no need to synchronize buffer when only have one producer and one consumer?
The following pseudo code comes from Wiki - producer-consumer problem.

```<code>semaphore fillCount = 0; // items produced
semaphore emptyCount = BUFFER_SIZE; // remaining space

procedure producer()
{
    while (true)
    {
        item = produceItem();
        down(emptyCount);
        putItemIntoBuffer(item);
        up(fillCount);
    }
}

procedure consumer()
{
    while (true)
    {
        down(fillCount);
        item = removeItemFromBuffer();
        up(emptyCount);
        consumeItem(item);
    }
}
</code>```

My question is that why we can invoke putItemIntoBuffer and removeItemFromBuffer simultaneously without synchronization? Why is there no race condition here?

答:
Why we can invoke putItemIntoBuffer and removeItemFromBuffer simultaneously without synchronization?

The short answer: it is a pseudo code, so do not take it literally. The purpose of the code is to show how to synchronize the consumer and producer, not the data access, just like the Wiki article states at the beginning:

The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.

The pseudo code you are referring solve this problem using semaphores:

Semaphores solve the problem of lost wakeup calls.

In case the buffer size is 1, the code might work just fine without any extra hassle. But the actual implementation of putItemIntoBuffer()/removeItemFromBuffer() for any buffer size might use locks internally to access shared buffer or could be implemented as a lock-less cyclic queues just like one of producer()/consumer() functions showed below in the article, i.e.:

```<code>volatile unsigned int produceCount = 0, consumeCount = 0;
ItemType buffer[BUFFER_SIZE];

void putItemIntoBuffer(ItemType *item) {
    buffer[produceCount % BUFFER_SIZE] = *item;
    ++produceCount;
}
void removeItemFromBuffer(ItemType *item) {
    *item = buffer[consumeCount % BUFFER_SIZE];
    ++consumeCount;
}
</code>```

Why is there no race condition here?

There might be race conditions accessing shared buffer, but it is not a main point of the Producer–consumer problem and hence not the main point of the mentioned Wiki article.

Body:
The following pseudo code comes from Wiki - producer-consumer problem.

semaphore fillCount = 0; // items produced
semaphore emptyCount = BUFFER_SIZE; // remaining space

procedure producer()
{
    while (true)
    {
        item = produceItem();
        down(emptyCount);
        putItemIntoBuffer(item);
        up(fillCount);
    }
}

procedure consumer()
{
    while (true)
    {
        down(fillCount);
        item = removeItemFromBuffer();
        up(emptyCount);
        consumeItem(item);
    }
}

My question is that why we can invoke putItemIntoBuffer and removeItemFromBuffer simultaneously without synchronization? Why is there no race condition here?

Body:
Why we can invoke putItemIntoBuffer and removeItemFromBuffer simultaneously without synchronization?

The short answer: it is a pseudo code, so do not take it literally. The purpose of the code is to show how to synchronize the consumer and producer, not the data access, just like the Wiki article states at the beginning:

The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.

The pseudo code you are referring solve this problem using semaphores:

Semaphores solve the problem of lost wakeup calls.

In case the buffer size is 1, the code might work just fine without any extra hassle. But the actual implementation of putItemIntoBuffer()/removeItemFromBuffer() for any buffer size might use locks internally to access shared buffer or could be implemented as a lock-less cyclic queues just like one of producer()/consumer() functions showed below in the article, i.e.:

volatile unsigned int produceCount = 0, consumeCount = 0;
ItemType buffer[BUFFER_SIZE];

void putItemIntoBuffer(ItemType *item) {
    buffer[produceCount % BUFFER_SIZE] = *item;
    ++produceCount;
}
void removeItemFromBuffer(ItemType *item) {
    *item = buffer[consumeCount % BUFFER_SIZE];
    ++consumeCount;
}

Why is there no race condition here?

There might be race conditions accessing shared buffer, but it is not a main point of the Producer–consumer problem and hence not the main point of the mentioned Wiki article.


问:
Python - write long string of bits inside a binary file
I've a string composed of ~75 000 bits (very long string).

I would like to create a binary file which is represented by this sequence of bits.
I did the following code :

```<code>byte_array = bytearray(global_bits_str.encode())
with open('file1.bin', 'wb') as f:
    f.write(byte_array)
</code>```

But when I check file1.bin I can see that it's composed of 75 000 bytes instead of 75 000 bits. I guess it has been encoded in ascii (1 byte per bit) in the file.

Any suggestions ?

答:
You can use the int builtin to convert your binary string into a sequence of integers, then pass that to bytearray.

Example for one byte:

```<code>>>> int('10101010', 2)
170
>>> bytearray([170])
bytearray(b'\xaa')
</code>```

Splitting the string:

```<code>chunks = [bit_string[n:n+8] for n in range(0, len(bit_string), 8)]
</code>```

You'll have to do some special casing for the last chunk since it may not be a full byte, which can be done by ljust to left-pad it with zeros.

Putting it together:

```<code>def to_bytes(bits, size=8, pad='0'):
    chunks = [bits[n:n+size] for n in range(0, len(bits), size)]
    if pad:
        chunks[-1] = chunks[-1].ljust(size, pad)
    return bytearray([int(c, 2) for c in chunks]

# Usage:
byte_array = to_bytes(global_bits_str)
</code>```

Body:
I've a string composed of ~75 000 bits (very long string).

I would like to create a binary file which is represented by this sequence of bits.
I did the following code :

byte_array = bytearray(global_bits_str.encode())
with open('file1.bin', 'wb') as f:
    f.write(byte_array)

But when I check file1.bin I can see that it's composed of 75 000 bytes instead of 75 000 bits. I guess it has been encoded in ascii (1 byte per bit) in the file.

Any suggestions ?

Body:
You can use the int builtin to convert your binary string into a sequence of integers, then pass that to bytearray.

Example for one byte:

>>> int('10101010', 2)
170
>>> bytearray([170])
bytearray(b'\xaa')

Splitting the string:

chunks = [bit_string[n:n+8] for n in range(0, len(bit_string), 8)]

You'll have to do some special casing for the last chunk since it may not be a full byte, which can be done by ljust to left-pad it with zeros.

Putting it together:

def to_bytes(bits, size=8, pad='0'):
    chunks = [bits[n:n+size] for n in range(0, len(bits), size)]
    if pad:
        chunks[-1] = chunks[-1].ljust(size, pad)
    return bytearray([int(c, 2) for c in chunks]

# Usage:
byte_array = to_bytes(global_bits_str)


问:
How do I export modal data from the program OpenModal

I am asking this question for Moritz:

I managed to run the programme (ubuntu-linux-tested branch) and upload a .uff-file. When I perform the analysis it also works decently but how do I extract the modal parameters (eigen frequencies, damping and mode shape). When I click on export and select the analysis results it saves an almost empty .uff-file (see .txt file)

Thank you in advance!!

答:
Currently modal vectors are not yet exported in uff you would have to
open saved *.mdd file with python (mdd file is actually pickled data).
Within data you will find geometry data, modal vectors, etc.

Here is the python code to do this (see also: https://github.com/openmodal/OpenModal/issues/31):

```<code>import OpenModal as OM # In order to reload modules to new location when unpickling files
import pickle
import sys
import pandas as pd

sys.modules['openModal'] = OM  # In order to reload modules to new location when unpickling files
## see: https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path

file_name=r'beam_accel.mdd'
f = open(file_name, 'rb')
data = pickle.load(f)

writer = pd.ExcelWriter('output.xlsx')
data[0].tables['analysis_index'].astype(str).to_excel(writer, 'index')
data[0].tables['analysis_values'].astype(str).to_excel(writer, 'values')
writer.save()
</code>```

Body:
Currently modal vectors are not yet exported in uff you would have to
open saved *.mdd file with python (mdd file is actually pickled data).
Within data you will find geometry data, modal vectors, etc.

Here is the python code to do this (see also: https://github.com/openmodal/OpenModal/issues/31):

import OpenModal as OM # In order to reload modules to new location when unpickling files
import pickle
import sys
import pandas as pd

sys.modules['openModal'] = OM  # In order to reload modules to new location when unpickling files
## see: https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path

file_name=r'beam_accel.mdd'
f = open(file_name, 'rb')
data = pickle.load(f)

writer = pd.ExcelWriter('output.xlsx')
data[0].tables['analysis_index'].astype(str).to_excel(writer, 'index')
data[0].tables['analysis_values'].astype(str).to_excel(writer, 'values')
writer.save()


问:
Script runtime execution time limit
My Google Apps Script is iterating through the user's Google Drive files and copying and sometimes moving files to other folders. The script is always stopped after certain minutes with no error message in the log.

EDITOR's NOTE: The time limit have varied over the time and might vary between "consumer" (free) and "Workspace" (paid) accounts but as of December 2022 most of the answers are still valid.

I am sorting tens or sometimes thousands files in one run.

Are there any settings or workarounds?

答:
If you are using G Suite Business or Enterprise edition.
You can register early access for App Maker after App maker enabled your script run runtime will increase run time from 6 minutes to 30 minutes :)

More details about app maker Click here

ContentLicense: CC BY-SA 4.0

Title: Script runtime execution time limit


问:
OneM2M coap client in node.js
I have to develop a node.js app which can interact with another oneM2M server.
In particular the node.js app need to exchange data using CoaP protocol, but I don't know how to do that in a oneM2M compliant manner.

I started my node.js project using this module: https://github.com/mcollina/node-coap
but I need some support to create a CoaP client using oneM2M protocol.

Code samples are really appreciated.

答:
If you want to communicate with a oneM2M CSE from your application, then you should implement the Mca interface. This is the interface between a CSE and your application, technically called an Application Entity, or AE.

The simplest way is to use the REST binding. You may have a look at the oneM2M's developer guide at http://www.onem2m.org/application-developer-guide.

You also might want to read the following specifications:

TS-0001: Functional Specification, which is the core specification document of oneM2M. Here, the basic concepts as well as all resource types are defined.

TS-0004: Service Layer Core Protocol for further details on the actual encodings and representation of resources.

TS-0008: CoAP Protocol Binding

TS-0009: HTTP Protocol Binding

You can find the latest version of these and other specifications here: http://www.onem2m.org/technical/published-documents

Title: OneM2M coap client in node.js


问:
Javascript: invoking objects like functions
Can I have a constructor that creates an instance, but when invoked executes a specific function?</p>

```<code>var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return .... // what to do here
};

var foo = new Foo();

return foo;       // return the instance of Foo:  { bar: "some variable" }
return foo.bar; // returns "some variable"
return foo() ;    // returns "some variable"
</code>```

答:
In your class function, return a function that returns what you want. So something like this:</p>

```<code>var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return this.invokeFunction.bind(this);
};
</code>```

Body:
Can I have a constructor that creates an instance, but when invoked executes a specific function?

var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return .... // what to do here
};

var foo = new Foo();

return foo;       // return the instance of Foo:  { bar: "some variable" }
return foo.bar; // returns "some variable"
return foo() ;    // returns "some variable"

Body:
In your class function, return a function that returns what you want. So something like this:

var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return this.invokeFunction.bind(this);
};


问:
How to activate two network interfaces at a time?
I have two network interfaces. Both interfaces have two private ip each for a total of 4. All are set to elastic ip.

I can ping only two public IP.

How can I activate 4 IP at a time?

答:
You need to configure the secondory IPs from ec2 OS too.

From AWS Documentation:

Configuring the Operating System on Your Instance to Recognize the Secondary Private IPv4 Address

After you assign a secondary private IPv4 address to your instance,
  you need to configure the operating system on your instance to
  recognize the secondary private IP address.

If you are using Amazon Linux, the ec2-net-utils package can take care
  of this step for you. It configures additional network interfaces that
  you attach while the instance is running, refreshes secondary IPv4
  addresses during DHCP lease renewal, and updates the related routing
  rules. You can immediately refresh the list of interfaces by using the
  command sudo service network restart and then view the up-to-date list
  using ip addr li. If you require manual control over your network
  configuration, you can remove the ec2-net-utils package. For more
  information, see Configuring Your Network Interface Using
  ec2-net-utils. If you are using another Linux distribution, see the
  documentation for your Linux distribution. Search for information
  about configuring additional network interfaces and secondary IPv4
  addresses. If the instance has two or more interfaces on the same
  subnet, search for information about using routing rules to work
  around asymmetric routing. For information about configuring a Windows
  instance, see Configuring a Secondary Private IP Address for Your
  Windows Instance in a VPC in the Amazon EC2 User Guide for Windows
  Instances

For Linux here is the post where the steps are explained:
https://bobcares.com/blog/an-easy-guide-to-setup-amazon-ec2-multiple-ips/


问:
error in .local (obj, ) cannat derive coordinates from non-numeric matrix in kriging interpolation
I tried to use the kriging interpolation on map using R. However, I got stuck in the first step. I used this to import the data into R.

```<code>td<read.table(pipe("pbpaste"),header=TRUE,sep="\t",dec=".",na.strings="NA",stringsAsFactors=F)
</code>```

And I need to transform my data to a SpatialPixelsDataFrame (provided by the sp package):

```<code>gridded(td) = c("x","y")
</code>```

And this returns an error:

error in .local(obj, ...) : cannot derive coordinates from non-numeric matrix

Are that anything wrong with my dataset, how can I deal with it?

答: I had the same problem. My X,Y coordinates were floats. I changed them into integers and then it worked. Try that !! </p>

Body:
I tried to use the kriging interpolation on map using R. However, I got stuck in the first step. I used this to import the data into R.

td<read.table(pipe("pbpaste"),header=TRUE,sep="\t",dec=".",na.strings="NA",stringsAsFactors=F)

And I need to transform my data to a SpatialPixelsDataFrame (provided by the sp package):

gridded(td) = c("x","y")

And this returns an error:

error in .local(obj, ...) : cannot derive coordinates from non-numeric matrix

Are that anything wrong with my dataset, how can I deal with it?


问:
How do I detect with JavaScript or JQuery whether a URL points to a web page or a binary file?
I'm crawling a web page list of links that are either web pages or large binary files (PPT etc), using javascript and jquery. </p>

<p>How do I detect whether the content is a web page ('text/html') or not? I'm pretty sure it is looking at the HTTP header using $.ajax, and I know there are some similar posted questions, but I can't find an example that fits this particular question. </p>

答:
If you have the file names, you can use
filename.split('.').pop()
This returns the extension of the file.

Body:
I'm crawling a web page list of links that are either web pages or large binary files (PPT etc), using javascript and jquery.

How do I detect whether the content is a web page ('text/html') or not? I'm pretty sure it is looking at the HTTP header using $.ajax, and I know there are some similar posted questions, but I can't find an example that fits this particular question.


问:
Can you avoid unboxing in a memoizing generic method?
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

```<code>public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

答:
The code you give is somewhat bizarre. How does "DoSomethingExpensive" know to return a T for arbitrary T?  That makes no sense to me.

The way you typically write a generic memoizer is like this:

```<code>public static Func<T> Memoize(this Func<T> func)
{
    bool executed = false;
    T result = default(T);
    Func<T> memoized = ()=>
    {
        if (!executed)
        {
            result = func();
            executed = true;
        }
        return result;
    };
    return memoized;
}
</code>```

And now you can say:

```<code>Func<int> expensive = DoSomethingExpensiveThatGetsAnInt;
Func<int> memoized = expensive.Memoize();
</code>```

And you're done. No boxing required.

Body:
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

Body:
The code you give is somewhat bizarre. How does "DoSomethingExpensive" know to return a T for arbitrary T?  That makes no sense to me.

The way you typically write a generic memoizer is like this:

public static Func<T> Memoize(this Func<T> func)
{
    bool executed = false;
    T result = default(T);
    Func<T> memoized = ()=>
    {
        if (!executed)
        {
            result = func();
            executed = true;
        }
        return result;
    };
    return memoized;
}

And now you can say:

Func<int> expensive = DoSomethingExpensiveThatGetsAnInt;
Func<int> memoized = expensive.Memoize();

And you're done. No boxing required.


问:
Is there a simpler way of unpacking a tuple?
The below is an example of some code I wrote in a RPG game that I've been working on. Upon winning a battle, the stats are updated in the level_up() function, and returned in the form of a list.
Which brings up my question. Is there a better way of writing the below code?</p>

```<code>stats = level_up()
level = stats[0]
exp = stats[1]
exp_nextlev = stats[2]
health = stats[3]
defense = stats[4]
attack = stats[5]
speed = stats[6]
</code>```

答:
```<code>level, exp, exp_nextlev, health, defense, attack, speed = stats
</code>```

Body:
The below is an example of some code I wrote in a RPG game that I've been working on. Upon winning a battle, the stats are updated in the level_up() function, and returned in the form of a list.
Which brings up my question. Is there a better way of writing the below code?

stats = level_up()
level = stats[0]
exp = stats[1]
exp_nextlev = stats[2]
health = stats[3]
defense = stats[4]
attack = stats[5]
speed = stats[6]


问:
Reg exp functionality breaking password strength function
Following this tutorial, I have adjusted the script so rather than displaying a gradient progress bar, a block progress bar is displayed using li items like so:

```<code><ul id="passwordStrength">
    <li class="point-reg"></li>
    <li class="point-reg"></li>
    <li class="point-reg"></li>
    <li class="point-reg"></li>
</ul>
</code>```

Depending on what criteria has been filled, the first li item will fill with the colour red, then second li will fill if they used an uppercase character or special character etc. until the user has met all the criteria and the 4th li item is filled a dark colour green.

I have two issues (I know I should keep each post to a single issue).

First is the colouring of the li items. When the user removes text from the input, I want the colouring to reset to the default value of #dcdcdc.

Second is an inconsistent behaviour in the reg exp. When I enter a special character before a number, it then only logs special characters, so the counter never reaches 4, so the statement for the strength bar to turn green and fill the final li item never happens.

Question/s

How can I get the colours for each li item to reset to grey if the user removes input, thus the criteria is filled?

Why when I enter a special character does it then persist on only registering special characters, even if I press a number?

Apologies for asking 2 questions.

```<code>$('#password').bind('keyup', function(){

    if($(this).val().length == 0) {
        password_li.css('background', '#DDD');
        return;
    }

        var regex = new Array();
    regex.push("[A-Z]"); //Uppercase Alphabet.
    regex.push("[a-z]"); //Lowercase Alphabet.
    regex.push("[0-9]"); //Digit.
    regex.push("[$@$!%*#?&]"); //Special Character.

    var passed = 0;

    //Validate for each Regular Expression.
    for (var i = 0; i < regex.length; i++) {
        if (new RegExp(regex[i]).test($(this).val())) {
            console.log(regex[i]) //here I can see what expression is being entered
            passed++;
        }
    }

    //Validate for length of Password.
    if (passed > 2 && $(this).val().length > 8) {
        passed++;
    }

    switch(passed) {
        case 0:
        break;
        case 1:
        console.log('red')
            $(password_li[0]).css('background', '#e30613'); //red
        break;
        case 2:
        console.log('amber')
            $(password_li[1]).css('background', '#f9b233'); //amber
        break;
        case 3:
        console.log('green')
            $(password_li[2]).css('background', '#53ab58'); //green
        break;
        case 4:
        console.log('dark green')
            $(password_li[3]).css('background', '#53ab58');
        break;

    }

})
</code>```

UPDATE

Resolved issue with resetting colours to grey. Just the reg exp issue now

答:
I think you need to count to 5, not 4 as you have 5 tests including length.
The additional debug here shows it's working fine:

```<code>$password="aA$"
var passed = 0;

for (var i = 0; i < regex.length; i++) {
    if (new RegExp(regex[i]).test($password)) {
        passed++;
        console.log(regex[i]+" passed "+passed)
    } else {
        console.log(regex[i]+" failed")
    }
}
console.log("Total "+passed);
</code>```

Result:

```<code>[A-Z] passed 1
[a-z] passed 2
[0-9] failed
[$@$!%*#?&] passed 3
Total 3
</code>```

Body:
Following this tutorial, I have adjusted the script so rather than displaying a gradient progress bar, a block progress bar is displayed using li items like so:

Depending on what criteria has been filled, the first li item will fill with the colour red, then second li will fill if they used an uppercase character or special character etc. until the user has met all the criteria and the 4th li item is filled a dark colour green.

I have two issues (I know I should keep each post to a single issue).

First is the colouring of the li items. When the user removes text from the input, I want the colouring to reset to the default value of #dcdcdc.

Second is an inconsistent behaviour in the reg exp. When I enter a special character before a number, it then only logs special characters, so the counter never reaches 4, so the statement for the strength bar to turn green and fill the final li item never happens.

Question/s

How can I get the colours for each li item to reset to grey if the user removes input, thus the criteria is filled?

Why when I enter a special character does it then persist on only registering special characters, even if I press a number?

Apologies for asking 2 questions.

$('#password').bind('keyup', function(){

    if($(this).val().length == 0) {
        password_li.css('background', '#DDD');
        return;
    }

        var regex = new Array();
    regex.push("[A-Z]"); //Uppercase Alphabet.
    regex.push("[a-z]"); //Lowercase Alphabet.
    regex.push("[0-9]"); //Digit.
    regex.push("[$@$!%*#?&]"); //Special Character.

    var passed = 0;

    //Validate for each Regular Expression.
    for (var i = 0; i < regex.length; i++) {
        if (new RegExp(regex[i]).test($(this).val())) {
            console.log(regex[i]) //here I can see what expression is being entered
            passed++;
        }
    }

    //Validate for length of Password.
    if (passed > 2 && $(this).val().length > 8) {
        passed++;
    }

    switch(passed) {
        case 0:
        break;
        case 1:
        console.log('red')
            $(password_li[0]).css('background', '#e30613'); //red
        break;
        case 2:
        console.log('amber')
            $(password_li[1]).css('background', '#f9b233'); //amber
        break;
        case 3:
        console.log('green')
            $(password_li[2]).css('background', '#53ab58'); //green
        break;
        case 4:
        console.log('dark green')
            $(password_li[3]).css('background', '#53ab58');
        break;

    }

})

UPDATE

Resolved issue with resetting colours to grey. Just the reg exp issue now

Body:
I think you need to count to 5, not 4 as you have 5 tests including length.
The additional debug here shows it's working fine:

$password="aA$"
var passed = 0;

for (var i = 0; i < regex.length; i++) {
    if (new RegExp(regex[i]).test($password)) {
        passed++;
        console.log(regex[i]+" passed "+passed)
    } else {
        console.log(regex[i]+" failed")
    }
}
console.log("Total "+passed);

Result:

[A-Z] passed 1
[a-z] passed 2
[0-9] failed
[$@$!%*#?&] passed 3
Total 3