问:
Could not resolve project: CordovaLib
I'm learning how to build app using cordova and I'm currently able to emulate a mobile screen via google chrome browser. I'm attempting to test it on android platform which requires using Android studio (downloaded the 3.0 stable version). After importing the project, Gradle project sync failed and there seems to be issues resolving some dependencies for CordovaLib. See image below

I have gone through several post here and still haven't been able to find a solution or maybe I'm missing the point considering that this is my first time learning with it. Below are the settings for

build.gradle(Module: CordovaLib)

and build.gradle(Module: android)

Please how do i fix the issue and run my app in an emulator?

答:
Is  a typical error of migration, please read the paragraph 'Migrate dependency configurations for local modules':

You should instead configure your dependencies as follows:

```<code>dependencies {
// This is the old method and no longer works for local
// library modules:
// debugImplementation project(path: ':library', configuration: 'debug')
// releaseImplementation project(path: ':library', configuration: 'release')

// Instead, simply use the following to take advantage of
// variant-aware dependency resolution. You can learn more about
// the 'implementation' configuration in the section about
// new dependency configurations.
implementation project(':library')

// You can, however, keep using variant-specific configurations when
// targeting external dependencies. The following line adds 'app-magic'
// as a dependency to only the "debug" version of your module.

debugImplementation 'com.example.android:app-magic:12.3'
}
</code>```

Title: Could not resolve project: CordovaLib

Body:
Is  a typical error of migration, please read the paragraph 'Migrate dependency configurations for local modules':

You should instead configure your dependencies as follows:

dependencies {
// This is the old method and no longer works for local
// library modules:
// debugImplementation project(path: ':library', configuration: 'debug')
// releaseImplementation project(path: ':library', configuration: 'release')

// Instead, simply use the following to take advantage of
// variant-aware dependency resolution. You can learn more about
// the 'implementation' configuration in the section about
// new dependency configurations.
implementation project(':library')

// You can, however, keep using variant-specific configurations when
// targeting external dependencies. The following line adds 'app-magic'
// as a dependency to only the "debug" version of your module.

debugImplementation 'com.example.android:app-magic:12.3'
}


来源: stackexchange

问:
Overload and error differentiation by a CAN controller
How does a CAN controller differentiate the overload frame and error frame when it was received on the CAN bus?

As far as I know, theses two frames are having the same frame format. In my project, I mostly encountered an error frame rather than an overload frame.

答:
Both an error frame and overload frame has the same format in case the node is in error active mode. But how can the CAN controller differentiate both is based on the position of occurrence in the CAN frame.

An error frame will be transmitted whenever a node detects an error whereas an overload frame is transmitted only in IFS (inter frame space).

ContentLicense: CC BY-SA 4.0


问:
Is it possible to download an audio file and play it using React Native Expo?
I have audio files hosted on a server that I'd like my app to access after authenticating. Users send a GET request which includes an authentication token, and the server returns the binary audio data.

As far as I can see there is no way to save this 'blob' as an audio file to the filesystem. The current implementation of fetch in react-native doesn't support blobs: link

... and the ideally-suited react-native-fetch-blob library isn't supported in expo either: link

Additionally I can see no way of streaming the audio file from the server. The included audio library with expo allows streaming of audio from a url (e.g. http://example.com/myaudio.mp3) however I can't see any way to attach an authorisation header to the request (e.g. "Authorization": "Bearer [my-token]").

Is there a way of achieving this, either by downloading and saving the audio blob, or streaming from a url with an authorisation header included in the request? I could detach my project from Expo but I'd like to leave that as a last-resort.

答:
Yes, it is. You need to use the Audio module exposed by expo to do it. Below are the steps that you have to follow to load and play an audio file from a given URL. I've also copied over the code for my component that is doing the same for me.

Load Audio module exposed by expo

import { Audio } from 'expo'

Create a new sound Object from it

soundObject = new Audio.Sound()

Asynchronously load your file

await this.soundObject.loadAsync({ uri: this.props.source })

Once loaded play the loaded file using

this.soundObject.playAsync()

Below is a simple component that I wrote for doing it -

import React, { Component } from 'react';
import { View, TouchableNativeFeedback } from 'react-native';
import { Audio } from 'expo';

class AudioPlayer extends Component {
  constructor(props) {
    super(props);
    this.state = { isPlaying: false };

    this.loadAudio = this.loadAudio.bind(this);
    this.toggleAudioPlayback = this.toggleAudioPlayback.bind(this);
  }

  componentDidMount() {
    this.loadAudio();
  }

  componentWillUnmount() {
    this.soundObject.stopAsync();
  }

  async loadAudio() {
    this.soundObject = new Audio.Sound();
    try {
      await this.soundObject.loadAsync({ uri: this.props.source /* url for your audio file */ });
    } catch (e) {
      console.log('ERROR Loading Audio', e);
    }
  }

  toggleAudioPlayback() {
    this.setState({
      isPlaying: !this.state.isPlaying,
    }, () => (this.state.isPlaying
      ? this.soundObject.playAsync()
      : this.soundObject.stopAsync()));
  }

  render() {
    return (
      <TouchableNativeFeedback onPress={this.toggleAudioPlayback}>
        <View style={this.props.style}>
          {this.props.children}
        </View>
      </TouchableNativeFeedback>
    );
  }
}

export default AudioPlayer;
```

ContentLicense: CC BY-SA 3.0


问:
Why does event.mouseWheelScroll.delta always return 0 using SFML?
I am testing out the feature in the SFML library mouseWheelScroll.delta but I always get a return value of 0. Why could this be?

My code that I used is below, note that on some of the first lines of code in the program I initialised the variable sf::Event event;.

```<code>    if (event.type == sf::Event::MouseWheelScrolled) {
    std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
}
</code>```

Does the SFML library need a window or could it use the console? (I only ask because I am creating a console application)

答:
I'm almost sure that you've forgotten something in your event loop. I've tried this snippet and it works fine

```<code>#include <iostream>
#include <SFML\Graphics.hpp>

int main(){
    sf::RenderWindow v(sf::VideoMode::getDesktopMode(), "SFML");

    while (v.isOpen()){
        sf::Event event;
        while (v.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                v.close();
            else if (event.type == sf::Event::MouseWheelScrolled){
                std::cout << "Wheel: " << event.mouseWheelScroll.delta << std::endl;
            }
        }
        v.clear();
        v.display();
    }
    return 0;
}
</code>```

Please, try it and compare what are you doing wrong (and then share with us)

Answering your second question, i have created a render window, but i think your question it's more about if the project can be a Console Application, and in fact, this is it and if you try it, it show both console and window.

Body:
I am testing out the feature in the SFML library mouseWheelScroll.delta but I always get a return value of 0. Why could this be?

My code that I used is below, note that on some of the first lines of code in the program I initialised the variable sf::Event event;.

    if (event.type == sf::Event::MouseWheelScrolled) {
    std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
}

Does the SFML library need a window or could it use the console? (I only ask because I am creating a console application)

Body:
I'm almost sure that you've forgotten something in your event loop. I've tried this snippet and it works fine

#include <iostream>
#include <SFML\Graphics.hpp>

int main(){
    sf::RenderWindow v(sf::VideoMode::getDesktopMode(), "SFML");

    while (v.isOpen()){
        sf::Event event;
        while (v.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                v.close();
            else if (event.type == sf::Event::MouseWheelScrolled){
                std::cout << "Wheel: " << event.mouseWheelScroll.delta << std::endl;
            }
        }
        v.clear();
        v.display();
    }
    return 0;
}

Please, try it and compare what are you doing wrong (and then share with us)

Answering your second question, i have created a render window, but i think your question it's more about if the project can be a Console Application, and in fact, this is it and if you try it, it show both console and window.


问:
How can I sign XML SAML Assertions in ASP.NET CORE
When I try to sign XML (SAML) I get this error in a Web Api ASP.NET Core (2.0.2):

System.InvalidOperationException: There is an error in the XML
  document. ---> System.InvalidOperationException: Instance validation
  error: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' is not a
  valid value for SignatureMethodAlgorithm.

The target is full framework - .Net 4.7.1.

If I retarget to .Net 4.6.2 and .Net 4.7 the code is working.

UPDATE:
Turns out that I used a 3rd party library that expected the default hash algorithm in SignedXml to be sha1. And this was changed to sha256 as part of .net 4.7.1. And this was in fact not a signing problem but a deserialization problem. I fixed this by setting context switch according to .net 4.7.1 documentation https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/retargeting/4.7-4.7.1

答:
I think I had this problem in the past (just not in a core project) here is how I solved it:

Add the following classes to your project:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

namespace xxx.Infrastructure.Crypto
{
    /// <summary>
    ///     <para>
    ///         The RSAPKCS1SHA256SignatureDescription class provides a signature description implementation
    ///         for RSA-SHA256 signatures. It allows XML digital signatures to be produced using the
    ///         http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 signature type.
    ///         RSAPKCS1SHA256SignatureDescription provides the same interface as other signature description
    ///         implementations shipped with the .NET Framework, such as
    ///         <see cref="RSAPKCS1SHA1SignatureDescription" />.
    ///     </para>
    ///     <para>
    ///         RSAPKCS1SHA256SignatureDescription is not generally intended for use on its own, instead it
    ///         should be consumed by higher level cryptography services such as the XML digital signature
    ///         stack. It can be registered in <see cref="CryptoConfig" /> so that these services can create
    ///         instances of this signature description and use RSA-SHA256 signatures.
    ///     </para>
    ///     <para>
    ///         Registration in CryptoConfig requires editing the machine.config file found in the .NET
    ///         Framework installation's configuration directory (such as
    ///         %WINDIR%\Microsoft.NET\Framework\v2.0.50727\Config or
    ///         %WINDIR%\Microsoft.NET\Framework64\v2.0.50727\Config) to include registration information on
    ///         the type. For example:
    ///     </para>
    ///     <example>
    ///         <![CDATA[
    ///             <configuration>
    ///               <mscorlib>
    ///                 <!-- ... -->
    ///                 <cryptographySettings>
    ///                   <cryptoNameMapping>
    ///                     <cryptoClasses>
    ///                       <cryptoClass RSASHA256SignatureDescription="Security.Cryptography.RSAPKCS1SHA256SignatureDescription, Security.Cryptography, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    ///                     </cryptoClasses>
    ///                     <nameEntry name="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" class="RSASHA256SignatureDescription" />
    ///                   </cryptoNameMapping>
    ///                 </cryptographySettings>
    ///               </mscorlib>
    ///             </configuration>
    ///         ]]>
    ///     </example>
    ///     <para>
    ///         After adding this registration entry, the assembly which contains the
    ///         RSAPKCS1SHA256SignatureDescription (in the example above Security.Cryptography.dll) needs to
    ///         be added to the GAC.
    ///    </para>
    ///    <para>
    ///         Note that on 64 bit machines, both the Framework and Framework64 machine.config files should
    ///         be updated, and if the signature description assembly is built bit-specific it needs to be
    ///         added to both the 32 and 64 bit GACs.
    ///     </para>
    ///     <para>
    ///         RSA-SHA256 signatures are first available on the .NET Framework 3.5 SP 1 and as such the
    ///         RSAPKCS1SHA256SignatureDescription requires .NET 3.5 SP 1 and Windows Server 2003 or greater
    ///         to work properly.
    ///     </para>
    ///     <para>
    ///         On Windows 2003, the default OID registrations are not setup for the SHA2 family of hash
    ///         algorithms, and this can cause the .NET Framework v3.5 SP 1 to be unable to create RSA-SHA2
    ///         signatures. To fix this problem, the <see cref="Oid2.RegisterSha2OidInformationForRsa" />
    ///         method can be called to create the necessary OID registrations.
    ///     </para>
    /// </summary>
    public class RSAPKCS1SHA256SignatureDescription : SignatureDescription
    {
        /// <summary>
        ///     Construct an RSAPKCS1SHA256SignatureDescription object. The default settings for this object
        ///     are:
        ///     <list type="bullet">
        ///         <item>Digest algorithm - <see cref="SHA256Managed" /></item>
        ///         <item>Key algorithm - <see cref="RSACryptoServiceProvider" /></item>
        ///         <item>Formatter algorithm - <see cref="RSAPKCS1SignatureFormatter" /></item>
        ///         <item>Deformatter algorithm - <see cref="RSAPKCS1SignatureDeformatter" /></item>
        ///     </list>
        /// </summary>
        public RSAPKCS1SHA256SignatureDescription()
        {
            KeyAlgorithm = typeof(RSACryptoServiceProvider).FullName;
            DigestAlgorithm = typeof(SHA256Managed).FullName;   // Note - SHA256CryptoServiceProvider is not registered with CryptoConfig
            FormatterAlgorithm = typeof(RSAPKCS1SignatureFormatter).FullName;
            DeformatterAlgorithm = typeof(RSAPKCS1SignatureDeformatter).FullName;
        }

        public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
            deformatter.SetHashAlgorithm("SHA256");
            return deformatter;
        }

        public override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("SHA256");
            return formatter;
        }
    }
}
</code>```

in your settings area (as early as possible) add the following:

```<code>CryptoConfig.AddAlgorithm(typeof(xxx.Infrastructure.Crypto.RSAPKCS1SHA256SignatureDescription),
            "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
        );
</code>```

Body:
I think I had this problem in the past (just not in a core project) here is how I solved it:

Add the following classes to your project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

namespace xxx.Infrastructure.Crypto
{
    /// <summary>
    ///     <para>
    ///         The RSAPKCS1SHA256SignatureDescription class provides a signature description implementation
    ///         for RSA-SHA256 signatures. It allows XML digital signatures to be produced using the
    ///         http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 signature type.
    ///         RSAPKCS1SHA256SignatureDescription provides the same interface as other signature description
    ///         implementations shipped with the .NET Framework, such as
    ///         <see cref="RSAPKCS1SHA1SignatureDescription" />.
    ///     </para>
    ///     <para>
    ///         RSAPKCS1SHA256SignatureDescription is not generally intended for use on its own, instead it
    ///         should be consumed by higher level cryptography services such as the XML digital signature
    ///         stack. It can be registered in <see cref="CryptoConfig" /> so that these services can create
    ///         instances of this signature description and use RSA-SHA256 signatures.
    ///     </para>
    ///     <para>
    ///         Registration in CryptoConfig requires editing the machine.config file found in the .NET
    ///         Framework installation's configuration directory (such as
    ///         %WINDIR%\Microsoft.NET\Framework\v2.0.50727\Config or
    ///         %WINDIR%\Microsoft.NET\Framework64\v2.0.50727\Config) to include registration information on
    ///         the type. For example:
    ///     </para>
    ///     <example>
    ///         <![CDATA[
    ///             <configuration>
    ///               <mscorlib>
    ///                 <!-- ... -->
    ///                 <cryptographySettings>
    ///                   <cryptoNameMapping>
    ///                     <cryptoClasses>
    ///                       <cryptoClass RSASHA256SignatureDescription="Security.Cryptography.RSAPKCS1SHA256SignatureDescription, Security.Cryptography, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    ///                     </cryptoClasses>
    ///                     <nameEntry name="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" class="RSASHA256SignatureDescription" />
    ///                   </cryptoNameMapping>
    ///                 </cryptographySettings>
    ///               </mscorlib>
    ///             </configuration>
    ///         ]]>
    ///     </example>
    ///     <para>
    ///         After adding this registration entry, the assembly which contains the
    ///         RSAPKCS1SHA256SignatureDescription (in the example above Security.Cryptography.dll) needs to
    ///         be added to the GAC.
    ///    </para>
    ///    <para>
    ///         Note that on 64 bit machines, both the Framework and Framework64 machine.config files should
    ///         be updated, and if the signature description assembly is built bit-specific it needs to be
    ///         added to both the 32 and 64 bit GACs.
    ///     </para>
    ///     <para>
    ///         RSA-SHA256 signatures are first available on the .NET Framework 3.5 SP 1 and as such the
    ///         RSAPKCS1SHA256SignatureDescription requires .NET 3.5 SP 1 and Windows Server 2003 or greater
    ///         to work properly.
    ///     </para>
    ///     <para>
    ///         On Windows 2003, the default OID registrations are not setup for the SHA2 family of hash
    ///         algorithms, and this can cause the .NET Framework v3.5 SP 1 to be unable to create RSA-SHA2
    ///         signatures. To fix this problem, the <see cref="Oid2.RegisterSha2OidInformationForRsa" />
    ///         method can be called to create the necessary OID registrations.
    ///     </para>
    /// </summary>
    public class RSAPKCS1SHA256SignatureDescription : SignatureDescription
    {
        /// <summary>
        ///     Construct an RSAPKCS1SHA256SignatureDescription object. The default settings for this object
        ///     are:
        ///     <list type="bullet">
        ///         <item>Digest algorithm - <see cref="SHA256Managed" /></item>
        ///         <item>Key algorithm - <see cref="RSACryptoServiceProvider" /></item>
        ///         <item>Formatter algorithm - <see cref="RSAPKCS1SignatureFormatter" /></item>
        ///         <item>Deformatter algorithm - <see cref="RSAPKCS1SignatureDeformatter" /></item>
        ///     </list>
        /// </summary>
        public RSAPKCS1SHA256SignatureDescription()
        {
            KeyAlgorithm = typeof(RSACryptoServiceProvider).FullName;
            DigestAlgorithm = typeof(SHA256Managed).FullName;   // Note - SHA256CryptoServiceProvider is not registered with CryptoConfig
            FormatterAlgorithm = typeof(RSAPKCS1SignatureFormatter).FullName;
            DeformatterAlgorithm = typeof(RSAPKCS1SignatureDeformatter).FullName;
        }

        public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
            deformatter.SetHashAlgorithm("SHA256");
            return deformatter;
        }

        public override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("SHA256");
            return formatter;
        }
    }
}

in your settings area (as early as possible) add the following:

CryptoConfig.AddAlgorithm(typeof(xxx.Infrastructure.Crypto.RSAPKCS1SHA256SignatureDescription),
            "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
        );


问:
Get the duplicate entries from table mysql
I have the table structure as shown below. The database is MariaDB.

```<code>+-----------+----------+--------------+-----------------+
| id_object |   name   | value_double | value_timestamp |
+-----------+----------+--------------+-----------------+
|     1     | price    | 1589         |  null           |
|     1     | payment  | 1590         |  null           |
|     1     | date     | null         |  2012-04-17     |
|     2     | price    | 1589         |  null           |
|     2     | payment  | 1590         |  null           |
|     2     | date     | null         |  2012-04-17     |
|     3     | price    | 1589         |  null           |
|     3     | payment  | 1590         |  null           |
|     3     | date     | null         |  2012-09-25     |
|    ...    | ...      | ...          |  ..             |
+-----------+----------+--------------+-----------------+
</code>```

1) I need to get the duplicates by three entries: price & payment & date;

For example: the record with id_object=2 is duplicate because price, payment and date are the same as values of the record with id_object=1. Record with id_object = 3 is not the duplicate because the date is different (2012-09-25 != 2012-04-17)

2) I should remove the duplicates except one copy of them.

I thought to do three select operations and join each select on id_object. I can get the duplicates by one entry (price | payment | date). I faced the problem doing the joins

```<code>SELECT `id_object`,`name`,{P.`value_double` | P.`value_timestamp`}
FROM record P
INNER JOIN(
SELECT {value_double | value_timestamp}
FROM record
WHERE name = {required_entry}
GROUP BY {value_double | value_timestamp}
HAVING COUNT(id_object) > 1
)temp ON {P.value_double = temp.value_double | P.value_timestamp = temp.value_timestamp}
WHERE name = {required_entry}
</code>```

Can someone help and show the pure (better) solution?

答:
Though less efficient than certain alternatives, I find an approach along these lines easier to read...</p>

```<code>SELECT MIN(id_object) id_object
     , price
     , payment
     , date
  FROM
     ( SELECT id_object
            , MAX(CASE WHEN name = 'price'   THEN value_double END) price
            , MAX(CASE WHEN name = 'payment' THEN value_double END) payment
            , MAX(CASE WHEN name = 'date'    THEN value_timestamp END) date
         FROM eav
        GROUP
           BY id_object
     ) x
 GROUP
    BY price
     , payment
     , date;
</code>```

Body:
I have the table structure as shown below. The database is MariaDB.

+-----------+----------+--------------+-----------------+
| id_object |   name   | value_double | value_timestamp |
+-----------+----------+--------------+-----------------+
|     1     | price    | 1589         |  null           |
|     1     | payment  | 1590         |  null           |
|     1     | date     | null         |  2012-04-17     |
|     2     | price    | 1589         |  null           |
|     2     | payment  | 1590         |  null           |
|     2     | date     | null         |  2012-04-17     |
|     3     | price    | 1589         |  null           |
|     3     | payment  | 1590         |  null           |
|     3     | date     | null         |  2012-09-25     |
|    ...    | ...      | ...          |  ..             |
+-----------+----------+--------------+-----------------+

1) I need to get the duplicates by three entries: price & payment & date;

For example: the record with id_object=2 is duplicate because price, payment and date are the same as values of the record with id_object=1. Record with id_object = 3 is not the duplicate because the date is different (2012-09-25 != 2012-04-17)

2) I should remove the duplicates except one copy of them.

I thought to do three select operations and join each select on id_object. I can get the duplicates by one entry (price | payment | date). I faced the problem doing the joins

SELECT `id_object`,`name`,{P.`value_double` | P.`value_timestamp`}
FROM record P
INNER JOIN(
SELECT {value_double | value_timestamp}
FROM record
WHERE name = {required_entry}
GROUP BY {value_double | value_timestamp}
HAVING COUNT(id_object) > 1
)temp ON {P.value_double = temp.value_double | P.value_timestamp = temp.value_timestamp}
WHERE name = {required_entry}

Can someone help and show the pure (better) solution?

Body:
Though less efficient than certain alternatives, I find an approach along these lines easier to read...

SELECT MIN(id_object) id_object
     , price
     , payment
     , date
  FROM
     ( SELECT id_object
            , MAX(CASE WHEN name = 'price'   THEN value_double END) price
            , MAX(CASE WHEN name = 'payment' THEN value_double END) payment
            , MAX(CASE WHEN name = 'date'    THEN value_timestamp END) date
         FROM eav
        GROUP
           BY id_object
     ) x
 GROUP
    BY price
     , payment
     , date;


问:
What is the best way to define a constant in an Angular controller?
I currently put my constants on the $scope. I don't feel like this is the best way to do it as anyone can access the scope with their JS console.

What is the best method to define constants in Angular?

```<code>var app = angular.module('app', []);

app.controller('calculatorController', function($scope) {
    $scope.values = [];

    $scope.CONSTANTS = {
        ERROR_MESSAGES: {
            NOT_INTEGER: "One of the values input was not a number!"
        }
    };

    $scope.add = function () {
        var calculatedValue = 0;
        for (var i = 0; i <= $scope.values; i++) {
            if (typeof $scope.values[i] === 'string' || $scope.values[i] instanceof String) {
                alert($scope.CONSTANTS.ERROR_MESSAGES.NOT_INTEGER);
            }

            calculatedValue += $scope.values[i];
        }
        return calculatedValue;
    }
});
</code>```

答:
If you want all the constants at one place, another way is to declare constants as below .</p>

```<code> var app = angular.module('app', []);
  angular.module('AppName').constant('versionConstant', {
       "versionNum":"1.22"
   });

  // And inject them in your  controller

  angular.module(AppName).controller(ControllerName, ['$scope','versionConstant',
    function ($scope, versionConstant) {
         var version=versionConstant.versionNum;
    });
</code>```

Body:
I currently put my constants on the $scope. I don't feel like this is the best way to do it as anyone can access the scope with their JS console.

What is the best method to define constants in Angular?

var app = angular.module('app', []);

app.controller('calculatorController', function($scope) {
    $scope.values = [];

    $scope.CONSTANTS = {
        ERROR_MESSAGES: {
            NOT_INTEGER: "One of the values input was not a number!"
        }
    };

    $scope.add = function () {
        var calculatedValue = 0;
        for (var i = 0; i <= $scope.values; i++) {
            if (typeof $scope.values[i] === 'string' || $scope.values[i] instanceof String) {
                alert($scope.CONSTANTS.ERROR_MESSAGES.NOT_INTEGER);
            }

            calculatedValue += $scope.values[i];
        }
        return calculatedValue;
    }
});

Body:
If you want all the constants at one place, another way is to declare constants as below .

 var app = angular.module('app', []);
  angular.module('AppName').constant('versionConstant', {
       "versionNum":"1.22"
   });

  // And inject them in your  controller

  angular.module(AppName).controller(ControllerName, ['$scope','versionConstant',
    function ($scope, versionConstant) {
         var version=versionConstant.versionNum;
    });


问:
In what all scenarios does Windows File.Delete API throw UnauthorizedAccessException, especially when a file is in use?
I am trying to delete a File on windows using C# File.Delete API. https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx
I am facing UnauthorizedAccessException with this API intermittently. Actually multiple processes/threads use this file as lock with File.Open on this file. If a file is in use I expect IOException to be thrown from underlying windows code, but at sometimes I see UnauthorizedAccessException. The process which is doing this is having an appropriate permission and it works in most of the cases but randomly I hit this issue.

More Information:
The extension of the file I am using as a lock is .lck and it is always empty. It is just used for locking purpose with File.Open API.
Documentation says that UnauthorizedAccessException is also thrown if the file is an executable file that is in use.

Questions:
Is there a possibility that .lck is considered executable and UnauthorizedAccessException is thrown?

What else is the cause for UnauthorizedAccessException because I expect IOException if the file is being used?

答:
Internally the File.Delete function invokes the DeleteFile function of the Win32 API.

The documentation says:

If an application attempts to delete a file that does not exist, the DeleteFile function fails with ERROR_FILE_NOT_FOUND. If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED.

and below:

The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED.

The ERROR_ACCESS_DENIED code than leads to an UnauthorizedAccessException.

So there are still at least one write handle on the file active.

In general it is a bad idea to use file handles for synchronizing processes. A better way for solving this problem would be to use a named EventWaitHandle or named Mutex (See Synchronizing 2 processes using interprocess synchronizations objects - Mutex or AutoResetEvent for mor information)

For example execute in Process1:

```<code>while (true)
{
    using (var mutex = new Mutex(false, "THIS_IS_THE_UNIQUE_NAME_OF_THE_MUTEX"))
    {
        if (!mutex.WaitOne(0))
        {
            Console.WriteLine($"Process {Process.GetCurrentProcess().Id} waits");
            mutex.WaitOne();
        }
        Console.Write($"Process {Process.GetCurrentProcess().Id} has entered protected area...");

        Thread.Sleep(1000); // simulate work

        Console.WriteLine("and is about to leave!");
        mutex.ReleaseMutex();
    }
}
</code>```

and in Process2:

```<code>using (var mutex = new Mutex(false, "THIS_IS_THE_UNIQUE_NAME_OF_THE_MUTEX"))
{
    mutex.WaitOne();
    Thread.Sleep(5000); // simulate work on different process
    mutex.ReleaseMutex();
}
</code>```

Process1 will then wait until Process2 has released the mutex and vice versa.

Body:
Internally the File.Delete function invokes the DeleteFile function of the Win32 API.

The documentation says:

If an application attempts to delete a file that does not exist, the DeleteFile function fails with ERROR_FILE_NOT_FOUND. If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED.

and below:

The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED.

The ERROR_ACCESS_DENIED code than leads to an UnauthorizedAccessException.

So there are still at least one write handle on the file active.

In general it is a bad idea to use file handles for synchronizing processes. A better way for solving this problem would be to use a named EventWaitHandle or named Mutex (See Synchronizing 2 processes using interprocess synchronizations objects - Mutex or AutoResetEvent for mor information)

For example execute in Process1:

while (true)
{
    using (var mutex = new Mutex(false, "THIS_IS_THE_UNIQUE_NAME_OF_THE_MUTEX"))
    {
        if (!mutex.WaitOne(0))
        {
            Console.WriteLine($"Process {Process.GetCurrentProcess().Id} waits");
            mutex.WaitOne();
        }
        Console.Write($"Process {Process.GetCurrentProcess().Id} has entered protected area...");

        Thread.Sleep(1000); // simulate work

        Console.WriteLine("and is about to leave!");
        mutex.ReleaseMutex();
    }
}

and in Process2:

using (var mutex = new Mutex(false, "THIS_IS_THE_UNIQUE_NAME_OF_THE_MUTEX"))
{
    mutex.WaitOne();
    Thread.Sleep(5000); // simulate work on different process
    mutex.ReleaseMutex();
}

Process1 will then wait until Process2 has released the mutex and vice versa.


问:
How to smoothly toggle border-width with jquery?
I'm trying to smoothly toggle the border-width of a span between 0 and 5.
This is the code I have tried, developing in firefox

```<code>    function anim()
    {
     this.sw=!this.sw;
     if(this.sw)
     {
      //lower
      $('.cell_action').animate(
       {
        'border-width':'0px',
        'margin':0
       },
       600
      );
     }
     else
     {
      //raise
      $('.cell_action').animate(
       {
        'border-width':'5px',
        'margin':-5
       },
       600
      );
     }
     }
</code>```

When I try to go to 5px, it seems to work, but when I run the function again to animate back to 0, the border is set immediately to 0 and only the margin animates.

答:
Seems to be a bug...
I'm having the same problem, but noticed the following:

FireFox (3): No animation back to 0

Chrome: No animation back to 0

Safari(winXP): No animation back to 0

Opera (10): No problems. Animates nicely

IE (8): No problems. Animates nicely

Going to investigate further...

-- EDIT --

Found the answer on bugs.jquey.com: ticket 7085

The borderWidth property is a shorthand property and returns a string that is a series of numbers separated by spaces. The .animate() method is only documented to animate properties that are numeric, such as borderLeftWidth.

I fixed my problem by animating to 0px like this:

```<code>$this.animate({
  borderLeftWidth: "0px",
  borderTopWidth: "0px",
  borderRightWidth: "0px",
  borderBottomWidth: "0px"
}, 200);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to smoothly toggle the border-width of a span between 0 and 5.
This is the code I have tried, developing in firefox

    function anim()
    {
     this.sw=!this.sw;
     if(this.sw)
     {
      //lower
      $('.cell_action').animate(
       {
        'border-width':'0px',
        'margin':0
       },
       600
      );
     }
     else
     {
      //raise
      $('.cell_action').animate(
       {
        'border-width':'5px',
        'margin':-5
       },
       600
      );
     }
     }

When I try to go to 5px, it seems to work, but when I run the function again to animate back to 0, the border is set immediately to 0 and only the margin animates.

Body:
Seems to be a bug...
I'm having the same problem, but noticed the following:

FireFox (3): No animation back to 0

Chrome: No animation back to 0

Safari(winXP): No animation back to 0

Opera (10): No problems. Animates nicely

IE (8): No problems. Animates nicely

Going to investigate further...

-- EDIT --

Found the answer on bugs.jquey.com: ticket 7085

The borderWidth property is a shorthand property and returns a string that is a series of numbers separated by spaces. The .animate() method is only documented to animate properties that are numeric, such as borderLeftWidth.

I fixed my problem by animating to 0px like this:

$this.animate({
  borderLeftWidth: "0px",
  borderTopWidth: "0px",
  borderRightWidth: "0px",
  borderBottomWidth: "0px"
}, 200);


问:
How to delete R.java identifier?

I can't delete that id. What should I do?

答:
Its not a good idea to edit R.java as its a generated class and will get overwritten once you try to build again anyway. The variable you're trying to delete was obviously generated from one of your resources so you should look for the ID field in one of your layouts, drawables, etc, and just change its name to something other than "1". Just do a solution search (Cmd + Shift + O on a mac - likely Ctrl + Shift + O on win) for "@+id/1" and see if something comes up.

If you've already done this I sadly have no idea how that would have gotten there as Java doesn't allow numbers for variable names - and thats why its complaining in the first place.

Title: How to delete R.java identifier?


问:
Visual Studio ReportViewer Sum not working on decimal fields
I have a simple report in Reportviewer with 2 checkboxes on the footer that should display a sum.
The sum should however be conditional :

Only if the field "Checked" is true than the value must be included in the sum.

For the first field this works without problem, but for the second field I get #error on the report.

The first field is an integer field, the second is a decimal field.
Here is the expression I use in the value property of both textboxes :

```<code>=Sum(IIf(Fields!Checked.Value, Fields!TotaalBedrag.Value, 0), "DataSet1")
=Sum(IIf(Fields!Checked.Value, Fields!TotaalAantalKM.Value, 0), "DataSet1")
</code>```

Field Checked is boolean and not null

field TotaalBedrag is integer and not null

field TotaalAantalKM is decimal and not null

the sum is correct for field TotaalBedrag but the sum for field TotaalAantalKM returns #error

If I write

```<code>=Sum(Fields!TotaalAantalKM.Value, "DataSet1")
</code>```

than I do get a correct sum so I guess there is nothing wrong with this field. The only difference between the 2 fields is that one is int and the other is decimal.
Is there someting special I need to do for decimal fields maybe ?

答:
For decimal values you must use "0D" instead of "0".
So your expression will become:</p>

```<code>=Sum(IIf(Fields!Checked.Value, Fields!TotaalAantalKM.Value, 0D), "DataSet1")
</code>```

Body:
I have a simple report in Reportviewer with 2 checkboxes on the footer that should display a sum.
The sum should however be conditional :

Only if the field "Checked" is true than the value must be included in the sum.

For the first field this works without problem, but for the second field I get #error on the report.

The first field is an integer field, the second is a decimal field.
Here is the expression I use in the value property of both textboxes :

=Sum(IIf(Fields!Checked.Value, Fields!TotaalBedrag.Value, 0), "DataSet1")
=Sum(IIf(Fields!Checked.Value, Fields!TotaalAantalKM.Value, 0), "DataSet1")

Field Checked is boolean and not null

field TotaalBedrag is integer and not null

field TotaalAantalKM is decimal and not null

the sum is correct for field TotaalBedrag but the sum for field TotaalAantalKM returns #error

If I write

=Sum(Fields!TotaalAantalKM.Value, "DataSet1")

than I do get a correct sum so I guess there is nothing wrong with this field. The only difference between the 2 fields is that one is int and the other is decimal.
Is there someting special I need to do for decimal fields maybe ?

Body:
For decimal values you must use "0D" instead of "0".
So your expression will become:

=Sum(IIf(Fields!Checked.Value, Fields!TotaalAantalKM.Value, 0D), "DataSet1")


问:
Is "return i++, i, i++;" undefined behaviour in C?
If I write like this :

```<code>i = i++, i, i++;
</code>```

It is undefined behaviour in C language.

But, If I write like this:

```<code>return i++, i, i++; // Is it UB?
</code>```

Is it undefined behaviour?

Example:

```<code>#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}
</code>```

答:
```<code>return i++, i, i++;
</code>```

No, it's not undefined behaviour because the comma operator defines a sequence point which separates the modifying accesses to i.

Thus this code is equivalent to:

```<code>i++;        // The left-most subexpression
i;
return i++; // The right-most subexpression
</code>```

For comparison:

```<code>i = i++, i, i++;
</code>```

This is undefined behaviour because , has lower precedence than =, so it's equivalent to:

```<code>(i = i++), i, i++;
</code>```

And i = i++ is undefined behaviour (see this question for more on this particular case).

Body:
If I write like this :

i = i++, i, i++;

It is undefined behaviour in C language.

But, If I write like this:

return i++, i, i++; // Is it UB?

Is it undefined behaviour?

Example:

#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}

Body:
return i++, i, i++;

No, it's not undefined behaviour because the comma operator defines a sequence point which separates the modifying accesses to i.

Thus this code is equivalent to:

i++;        // The left-most subexpression
i;
return i++; // The right-most subexpression

For comparison:

i = i++, i, i++;

This is undefined behaviour because , has lower precedence than =, so it's equivalent to:

(i = i++), i, i++;

And i = i++ is undefined behaviour (see this question for more on this particular case).


问:
AspxErrorPath in Custom Error Page
We currently has a page that is used to display a generic error message when errors occur on our website. It has no functionality at all other than displaying a label that mentions there was an error.

Here is my issue, our client has ran a security review and tells us our error page contains phishing due to the URL in the query string, now I don't consider this a problem, but to put an end to the question, I'd like to remove the query string.

My web.config entry is this:

```<code><customErrors mode="On" defaultRedirect="~/DefaultErrorPage.aspx">
</customErrors>
</code>```

When an error occurs, it goes to DefaultErrorPage.aspx?aspxerrorpath=/Website1/LastPage.aspx

How can I prevent this? However, I could just redirect to the page if it contains the query, but I'm more looking for a way to prevent the query string instead of an extra redirection.

答:
you could catch/handle all errors in your global.asax file instead and do the redirect there</p>

```<code>    protected void Application_Error(object sender, EventArgs e)
    {
        //Exception ex = Server.GetLastError();

        Server.Transfer("~/DefaultErrorPage.aspx");
    }
</code>```

Title: AspxErrorPath in Custom Error Page

Body:
We currently has a page that is used to display a generic error message when errors occur on our website. It has no functionality at all other than displaying a label that mentions there was an error.

Here is my issue, our client has ran a security review and tells us our error page contains phishing due to the URL in the query string, now I don't consider this a problem, but to put an end to the question, I'd like to remove the query string.

My web.config entry is this:

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.aspx">
</customErrors>

When an error occurs, it goes to DefaultErrorPage.aspx?aspxerrorpath=/Website1/LastPage.aspx

How can I prevent this? However, I could just redirect to the page if it contains the query, but I'm more looking for a way to prevent the query string instead of an extra redirection.

Body:
you could catch/handle all errors in your global.asax file instead and do the redirect there

    protected void Application_Error(object sender, EventArgs e)
    {
        //Exception ex = Server.GetLastError();

        Server.Transfer("~/DefaultErrorPage.aspx");
    }


问:
Virtual Box Actual Size not increasing
I've Ubuntu 14.0.4 & Windows 7 installed in Virtual Box.
I ran the below command to increase the virtual box allocation size

```<code>VBoxManage modifyhd "/home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi" --resize 52200
</code>```

It gave me

```<code>0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
</code>```

And the size becomes:-

```<code>VBoxManage showhdinfo "/home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi"

UUID:           47c148a5-b97f-4cf3-97c1-69b39f9b2208
Parent UUID:    base
State:          created
Type:           normal (base)
Location:       /home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi
Storage format: VDI
Format variant: dynamic default
Capacity:       52200 MBytes
Size on disk:   25523 MBytes
</code>```

The problem here is Capacity has been increased to 52 GB but the Actual Size is not increasing.

Format variant: dynamic default  not fixed

I'd deeply appreciate any help.

答:
Problem solved!!

I went to Disk Management >> Disk Extend Volume >> Updated the disk size to Unallocated space.

Now it looks like below.

Title: Virtual Box Actual Size not increasing

Body:
I've Ubuntu 14.0.4 & Windows 7 installed in Virtual Box.
I ran the below command to increase the virtual box allocation size

VBoxManage modifyhd "/home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi" --resize 52200

It gave me

0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

And the size becomes:-

VBoxManage showhdinfo "/home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi"

UUID:           47c148a5-b97f-4cf3-97c1-69b39f9b2208
Parent UUID:    base
State:          created
Type:           normal (base)
Location:       /home/myname/VirtualBox VMs/Windows 7 RC/Windows 7 RC.vdi
Storage format: VDI
Format variant: dynamic default
Capacity:       52200 MBytes
Size on disk:   25523 MBytes

The problem here is Capacity has been increased to 52 GB but the Actual Size is not increasing.

Format variant: dynamic default  not fixed

I'd deeply appreciate any help.


问:
How to display error message when extra fields are not filled on registration in WordPress?
I would like to custamize the default user registration in Wordpress by adding first and last name and checkox with terms and coditions. The user is not able to register till all fields are filled and the checkbox is checked. I solved the checkbox with JavaScript. But now I want to add extra error messages when first and last name are not field. On the picture you see a massage for empty username and email. How could I add those kind of messages for first name and last name?

Error message for empty and email

答:
call a function before submitting the form ie onlick of submit button:

```<code>$('#btn').on('click', function() {
   if(validateForm()){
$( "#target" ).submit();
}else{
 event.preventDefault()

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

code your custom function to check the fields  validateForm();

Body:
call a function before submitting the form ie onlick of submit button:

$('#btn').on('click', function() {
   if(validateForm()){
$( "#target" ).submit();
}else{
 event.preventDefault()

}
;
});

code your custom function to check the fields  validateForm();


问:
Change SQL User to Trusted User Using Manifest File and C#
I inherited a project that uses SQL authentication and a manifest file to connect to the database.  We are using SQL Server.

This is the manifest file:

```<code><database>
   <server>server1\dbname</server>
   <catalog>CatName</catalog>
   <username>sysuser</username>
   <password>ksdjf290384</password>

</database>
</code>```

This is the code to it as a connection:

```<code>        this.Manifest = new XmlDocument();
        this.Manifest.Load(manifestPath);
        XmlNode rootNode = this.Manifest.DocumentElement.SelectSingleNode("/manifest");
        XmlNode dbNode = rootNode.SelectSingleNode("database");
        this.Connector = new SqlConnector(string.Format(CONNECTION_STRING_TEMPLATE, dbNode.SelectSingleNode("server").InnerText, dbNode.SelectSingleNode("catalog").InnerText, dbNode.SelectSingleNode("username").InnerText, dbNode.SelectSingleNode("password").InnerText));
</code>```

I need to change this to Windows Authentication.  I can't figure out how to change the manifest file and the code to work.

I have tried eliminating the username and password from the manifest file and connector.  I've tried to shoehorn Trusted_Connection in but nothing seems to work.

I would appreciate any thoughts or ideas on this.

答:
The following code should work:

Menifast file:

```<code><database>
   <server>server1\dbname</server>
   <catalog>CatName</catalog>
</database>
</code>```

The code:

```<code>        this.Manifest = new XmlDocument();
        this.Manifest.Load(manifestPath);
        XmlNode rootNode = this.Manifest.DocumentElement.SelectSingleNode("database");
        XmlNode userNameNode = rootNode.SelectSingleNode("username");
        XmlNode passwordNode = rootNode.SelectSingleNode("password");

        if (userNameNode != null && passwordNode != null)
        {

            this.Connector = new SqlConnector(string.Format(CONNECTION_STRING_TEMPLATE, rootNode.SelectSingleNode("server").InnerText, rootNode.SelectSingleNode("catalog").InnerText, userNameNode.InnerText, passwordNode.InnerText));

        }
        else
        {
            //Windows authentication
            this.Connector = new SqlConnector(string.Format("Server={0};Initial Catalog={1};Integrated Security=SSPI;", rootNode.SelectSingleNode("server").InnerText, rootNode.SelectSingleNode("catalog").InnerText);
        }
</code>```

Body:
I inherited a project that uses SQL authentication and a manifest file to connect to the database.  We are using SQL Server.

This is the manifest file:

<database>
   <server>server1\dbname</server>
   <catalog>CatName</catalog>
   <username>sysuser</username>
   <password>ksdjf290384</password>

</database>

This is the code to it as a connection:

        this.Manifest = new XmlDocument();
        this.Manifest.Load(manifestPath);
        XmlNode rootNode = this.Manifest.DocumentElement.SelectSingleNode("/manifest");
        XmlNode dbNode = rootNode.SelectSingleNode("database");
        this.Connector = new SqlConnector(string.Format(CONNECTION_STRING_TEMPLATE, dbNode.SelectSingleNode("server").InnerText, dbNode.SelectSingleNode("catalog").InnerText, dbNode.SelectSingleNode("username").InnerText, dbNode.SelectSingleNode("password").InnerText));

I need to change this to Windows Authentication.  I can't figure out how to change the manifest file and the code to work.

I have tried eliminating the username and password from the manifest file and connector.  I've tried to shoehorn Trusted_Connection in but nothing seems to work.

I would appreciate any thoughts or ideas on this.

Body:
The following code should work:

Menifast file:

<database>
   <server>server1\dbname</server>
   <catalog>CatName</catalog>
</database>

The code:

        this.Manifest = new XmlDocument();
        this.Manifest.Load(manifestPath);
        XmlNode rootNode = this.Manifest.DocumentElement.SelectSingleNode("database");
        XmlNode userNameNode = rootNode.SelectSingleNode("username");
        XmlNode passwordNode = rootNode.SelectSingleNode("password");

        if (userNameNode != null && passwordNode != null)
        {

            this.Connector = new SqlConnector(string.Format(CONNECTION_STRING_TEMPLATE, rootNode.SelectSingleNode("server").InnerText, rootNode.SelectSingleNode("catalog").InnerText, userNameNode.InnerText, passwordNode.InnerText));

        }
        else
        {
            //Windows authentication
            this.Connector = new SqlConnector(string.Format("Server={0};Initial Catalog={1};Integrated Security=SSPI;", rootNode.SelectSingleNode("server").InnerText, rootNode.SelectSingleNode("catalog").InnerText);
        }


问:
C++ static polymorphism (CRTP) and using typedefs from derived classes
I read the Wikipedia article about the curiously recurring template pattern in C++ for doing static (read: compile-time) polymorphism. I wanted to generalize it so that I could change the return types of the functions based on the derived type. (This seems like it should be possible since the base type knows the derived type from the template parameter). Unfortunately, the following code won't compile using MSVC 2010 (I don't have easy access to gcc right now so I haven't tried it yet). Anyone know why?

```<code>template <typename derived_t>
class base {
public:
    typedef typename derived_t::value_type value_type;
    value_type foo() {
        return static_cast<derived_t*>(this)->foo();
    }
};

template <typename T>
class derived : public base<derived<T> > {
public:
    typedef T value_type;
    value_type foo() {
        return T(); //return some T object (assumes T is default constructable)
    }
};

int main() {
    derived<int> a;
}
</code>```

BTW, I have a work-around using extra template parameters, but I don't like it---it will get very verbose when passing many types up the inheritance chain.

```<code>template <typename derived_t, typename value_type>
class base { ... };

template <typename T>
class derived : public base<derived<T>,T> { ... };
</code>```

EDIT:

The error message that MSVC 2010 gives in this situation is error C2039: 'value_type' : is not a member of 'derived<T>'

g++ 4.1.2 (via codepad.org) says error: no type named 'value_type' in 'class derived<int>'

答:
An alternative to type traits that requires less boilerplate is to nest your derived class inside a wrapper class that holds your typedefs (or using's) and pass the wrapper as a template argument to your base class.</p>

```<code>template <typename Outer>
struct base {
    using derived = typename Outer::derived;
    using value_type = typename Outer::value_type;
    value_type base_func(int x) {
        return static_cast<derived *>(this)->derived_func(x);
    }
};

// outer holds our typedefs, derived does the rest
template <typename T>
struct outer {
    using value_type = T;
    struct derived : public base<outer> { // outer is now complete
        value_type derived_func(int x) { return 5 * x; }
    };
};

// If you want you can give it a better name
template <typename T>
using NicerName = typename outer<T>::derived;

int main() {
    NicerName<long long> obj;
    return obj.base_func(5);
}
</code>```

Body:
I read the Wikipedia article about the curiously recurring template pattern in C++ for doing static (read: compile-time) polymorphism. I wanted to generalize it so that I could change the return types of the functions based on the derived type. (This seems like it should be possible since the base type knows the derived type from the template parameter). Unfortunately, the following code won't compile using MSVC 2010 (I don't have easy access to gcc right now so I haven't tried it yet). Anyone know why?

template <typename derived_t>
class base {
public:
    typedef typename derived_t::value_type value_type;
    value_type foo() {
        return static_cast<derived_t*>(this)->foo();
    }
};

template <typename T>
class derived : public base<derived<T> > {
public:
    typedef T value_type;
    value_type foo() {
        return T(); //return some T object (assumes T is default constructable)
    }
};

int main() {
    derived<int> a;
}

BTW, I have a work-around using extra template parameters, but I don't like it---it will get very verbose when passing many types up the inheritance chain.

template <typename derived_t, typename value_type>
class base { ... };

template <typename T>
class derived : public base<derived<T>,T> { ... };

EDIT:

The error message that MSVC 2010 gives in this situation is error C2039: 'value_type' : is not a member of 'derived<T>'

g++ 4.1.2 (via codepad.org) says error: no type named 'value_type' in 'class derived<int>'

Body:
An alternative to type traits that requires less boilerplate is to nest your derived class inside a wrapper class that holds your typedefs (or using's) and pass the wrapper as a template argument to your base class.

template <typename Outer>
struct base {
    using derived = typename Outer::derived;
    using value_type = typename Outer::value_type;
    value_type base_func(int x) {
        return static_cast<derived *>(this)->derived_func(x);
    }
};

// outer holds our typedefs, derived does the rest
template <typename T>
struct outer {
    using value_type = T;
    struct derived : public base<outer> { // outer is now complete
        value_type derived_func(int x) { return 5 * x; }
    };
};

// If you want you can give it a better name
template <typename T>
using NicerName = typename outer<T>::derived;

int main() {
    NicerName<long long> obj;
    return obj.base_func(5);
}


问:
docker-java/docker remote api block until container is finished
I am trying to use the docker remote API from java using docker-java and I'm struggling to find a way to see when the execution of my container has finished:

```<code> CreateContainerResponse container = dockerClient.createContainerCmd("me/vw:v0.1")
                .withVolumes(workingDIR)
                .withBinds(new Bind("/localDrive", workingDIR))
                .withCmd("vw", "/rcv1/rcv1.train.vw.gz", "--cache_file", "/rcv1/cache_train", "-f", "/rcv1/r_temp")
                .withLogConfig(logconf)
                .exec();
        dockerClient.startContainerCmd((container.getId())).exec();

        Thread.sleep(10000); //OBVIOUSLY BROKEN HACK IS BROKEN
        System.out.println("PRINTING LOGS");
        System.out.println(containerLog(container.getId(), dockerClient));
</code>```

What is the normal way to check if container is finished? Do I have to write something that polls the docker server, or do is there some convenient blocking function/invocation? docker-java has really bad documentation and most of what I've gotten to work is from looking at the test cases.

Cheers,

Nick

Body:
I am trying to use the docker remote API from java using docker-java and I'm struggling to find a way to see when the execution of my container has finished:

 CreateContainerResponse container = dockerClient.createContainerCmd("me/vw:v0.1")
                .withVolumes(workingDIR)
                .withBinds(new Bind("/localDrive", workingDIR))
                .withCmd("vw", "/rcv1/rcv1.train.vw.gz", "--cache_file", "/rcv1/cache_train", "-f", "/rcv1/r_temp")
                .withLogConfig(logconf)
                .exec();
        dockerClient.startContainerCmd((container.getId())).exec();

        Thread.sleep(10000); //OBVIOUSLY BROKEN HACK IS BROKEN
        System.out.println("PRINTING LOGS");
        System.out.println(containerLog(container.getId(), dockerClient));

What is the normal way to check if container is finished? Do I have to write something that polls the docker server, or do is there some convenient blocking function/invocation? docker-java has really bad documentation and most of what I've gotten to work is from looking at the test cases.

Cheers,

Nick

Body:
dockerClient.startContainerCmd(createContainerResponse.getId()).exec();
WaitContainerResultCallback resultCallback = new WaitContainerResultCallback();
dockerClient.waitContainerCmd(createContainerResponse.getId()).exec(resultCallback);
resultCallback.awaitCompletion();
dockerClient.removeContainerCmd(createContainerResponse.getId()).exec();


答:
Do you already have PHP set up for it? I'd say it is more important to have validation in PHP in case the user has javascript disabled.

http://docs.restrictcontentpro.com/article/1720-creating-custom-registration-fields https://archive.fo/369DX seems to do this... In step three, the author writes:

```<code><?php
/**
 * Determines if there are problems with the registration data submitted
 *
 */
function pw_rcp_validate_user_fields_on_register( $posted ) {

    if ( rcp_get_subscription_id() ) {
       return;
            }

    if( empty( $posted['rcp_profession'] ) ) {
            rcp_errors()->add( 'invalid_profession', __( 'Please enter your profession', 'rcp' ), 'register' );
    }

    if( empty( $posted['rcp_location'] ) ) {
            rcp_errors()->add( 'invalid_location', __( 'Please enter your location', 'rcp' ), 'register' );
    }

}
add_action( 'rcp_form_errors', 'pw_rcp_validate_user_fields_on_register', 10 );
</code>```

The thing to note is rcp_errors()->add()

The asker added:

I did it the way you suggested. I created a plugin that validates the
  extra fields(first and last name). Now the user is not able to
  register if all fields are not filled. User validation

Now the question is how could I change the error messages for user
  name and email address, so they can match mine? In other words where
  is the code that displays a message whena user does not fill in any
  required field?

Thank you for the help!

Can you try modifying the string in the line with rcp_errors()->add(?

Title: How to display error message when extra fields are not filled on registration in WordPress?

Body:
I would like to custamize the default user registration in Wordpress by adding first and last name and checkox with terms and coditions. The user is not able to register till all fields are filled and the checkbox is checked. I solved the checkbox with JavaScript. But now I want to add extra error messages when first and last name are not field. On the picture you see a massage for empty username and email. How could I add those kind of messages for first name and last name?

Error message for empty and email

Body:
Do you already have PHP set up for it? I'd say it is more important to have validation in PHP in case the user has javascript disabled.

http://docs.restrictcontentpro.com/article/1720-creating-custom-registration-fields https://archive.fo/369DX seems to do this... In step three, the author writes:

<?php
/**
 * Determines if there are problems with the registration data submitted
 *
 */
function pw_rcp_validate_user_fields_on_register( $posted ) {

    if ( rcp_get_subscription_id() ) {
       return;
            }

    if( empty( $posted['rcp_profession'] ) ) {
            rcp_errors()->add( 'invalid_profession', __( 'Please enter your profession', 'rcp' ), 'register' );
    }

    if( empty( $posted['rcp_location'] ) ) {
            rcp_errors()->add( 'invalid_location', __( 'Please enter your location', 'rcp' ), 'register' );
    }

}
add_action( 'rcp_form_errors', 'pw_rcp_validate_user_fields_on_register', 10 );

The thing to note is rcp_errors()->add()

The asker added:

I did it the way you suggested. I created a plugin that validates the
  extra fields(first and last name). Now the user is not able to
  register if all fields are not filled. User validation

Now the question is how could I change the error messages for user
  name and email address, so they can match mine? In other words where
  is the code that displays a message whena user does not fill in any
  required field?

Thank you for the help!

Can you try modifying the string in the line with rcp_errors()->add(?


问:
Could not resolve placeholder in string value in elastic beanstalk
I'm trying to get acess costume environment variable that I just added to Elastic beanstalk. The way i added the variable is only in Software Configuration.

The variable is FLAG and the value is 'true'.
In my code I'm doing this:

```<code>@Value("${FLAG}")
private Boolean flag1= true;
</code>```

but I'm getting this error:

```<code>java.lang.IllegalArgumentException: Could not resolve placeholder 'FLAG' in string value "${FLAG}"
</code>```

I'm working with java spring and AWS elastic beanstalk

Thank you

答: Solution: Maybe it will sound weird and not make sense, but it works only after i turn off the Intellij and open again</p>

Body:
I'm trying to get acess costume environment variable that I just added to Elastic beanstalk. The way i added the variable is only in Software Configuration.

The variable is FLAG and the value is 'true'.
In my code I'm doing this:

@Value("${FLAG}")
private Boolean flag1= true;

but I'm getting this error:

java.lang.IllegalArgumentException: Could not resolve placeholder 'FLAG' in string value "${FLAG}"

I'm working with java spring and AWS elastic beanstalk

Thank you


问:
How to identify an element in Selenium WebDriver that does not have any unique identifier/property?
There are two buttons on application named as "download" & "upload" with same properties/identifiers. Can someone help me how to click on button & how to handle such objects. I have tried CSS Selector, XPath other combinations as well, nothing worked for me. looking for Java code.
below is the HTML for those buttons:</p>

```<code><div class="control-label col-md-6 control-label-left"> <button class="btn blue form-control-btn" ngf-select="vm.uploadDemographic($file)"> <i class="fa fa-upload"/> Upload Template </button> </div> 2nd Button <div class="control-label col-md-6 control-label-left"> <button class="btn blue form-control-btn" ng-click="vm.downloadTemplate('demographic')"> <i class="fa fa-download"/> Download Template </button> </div>
</code>```

答:
Try this for finding your buttons:

For download button: driver.findElement(By.xpath("//*[text()='Download Template']"));

For upload button: driver.findElement(By.xpath("//*[text()='Upload Template']"));

Body:
There are two buttons on application named as "download" & "upload" with same properties/identifiers. Can someone help me how to click on button & how to handle such objects. I have tried CSS Selector, XPath other combinations as well, nothing worked for me. looking for Java code.
below is the HTML for those buttons:

 <button class="btn blue form-control-btn" ngf-select="vm.uploadDemographic($file)">  Upload Template </button>
 2nd Button
 <button class="btn blue form-control-btn" ng-click="vm.downloadTemplate('demographic')">  Download Template </button>


问:
Django HTML template to pdf consisting JS (Vue.js) charts and graphs
I am trying to generate a PDF from Html page. The Html includes various data returned from django view and also from Vue.js

I tried using 'Weasyprint' but it only generated data that returned from Django but not the charts and graphs that were generated from Vue. What will be an easy way to generate all the data as well as the graphs in PDF from the Html page.

答:
To generate a PDF with those charts, you will need to render the web-page first (in a browser) in order to run the client-side code and use that "result" to generate the final PDF.

It will depend on where you want to generate that PDF (on the server or on the client). In case it is on the server, one possible solution is to use phantomJS (or other similar projects) to render and save the result in a file with render().


问:
Most recent tag before tip in mercurial
I mark releases with hg tag <version-number>.  When I release a bugfix, I don't want to increment the version number, but I want to use the most recent version number during the build process.  If I run hg tags, it will show tip first, then the version numbers in descending order.  I can get it running hg tags | head -n2 | tail -n1.  I wonder if there is a more elegant, pure mercurial way to get it.

答: Well, I'm answering my own question.  I found the solution, hg help templates shows more options than the documentation on the mercurial site.  So hg tip --template '{latesttag}\n' is what I was looking for.

Title: Most recent tag before tip in mercurial


问:
.then is not a function
Why is this line a valid promise:

```<code>const promise = Promise.resolve('Hello');
</code>```

But not this:

```<code>const otherPromise = () => {
  return Promise.resolve('Hello');
}
</code>```

When trying to call the second example with:

```<code>function runOtherPromise() {
  otherPromise
    .then(v => console.log(v));
}
</code>```

...I get TypeError: otherPromise.then is not a function. It works fine with the first example, though. I don't understand why the second example doesn't return a promise.

答:
otherPromise is a function, you should call it like below:</p>

```<code>runOtherPromise() {
    otherPromise()
        .then(v => console.log(v));
}
</code>```

Title: .then is not a function

Body:
Why is this line a valid promise:

const promise = Promise.resolve('Hello');

But not this:

const otherPromise = () => {
  return Promise.resolve('Hello');
}

When trying to call the second example with:

function runOtherPromise() {
  otherPromise
    .then(v => console.log(v));
}

...I get TypeError: otherPromise.then is not a function. It works fine with the first example, though. I don't understand why the second example doesn't return a promise.

Body:
otherPromise is a function, you should call it like below:

runOtherPromise() {
    otherPromise()
        .then(v => console.log(v));
}


问:
How To Get BirthDate or Gender In Google Plus Login Ionic3?
How To Get BirthDate  or Gender In Google Plus Login Ionic3 ? </p>

```<code> GPLogin(){
      this.googlePlus.login({'scopes': 'https://www.googleapis.com/auth/plus.login'})
      .then(res => {
      console.log(res);
      alert("success "+JSON.stringify(res));
      })
      .catch(err => {
      console.error(err);
      alert("error "+JSON.stringify(err));
      });
    }
</code>```

答:
You should take a look at the google plus cordova plugin documentation.

If You search for scope, You will find what You are looking for. You need to add Your required scopes to be able to get the users profile data.

A complete list of all google scopes can be found here

In Your case it should be the Google People API, v1.

https://www.googleapis.com/auth/user.birthday.read = View your complete date of birth.

But beware of the known bugs related to the scope feature.

Body:
How To Get BirthDate  or Gender In Google Plus Login Ionic3 ?

 GPLogin(){
      this.googlePlus.login({'scopes': 'https://www.googleapis.com/auth/plus.login'})
      .then(res => {
      console.log(res);
      alert("success "+JSON.stringify(res));
      })
      .catch(err => {
      console.error(err);
      alert("error "+JSON.stringify(err));
      });
    }


问:
Gulp No errors but sass is not compiling into css
please help I'm not getting any errors but this code will not create the compiled css from the scss file. I am writing the code within the underscore WP theme if that matters I don't think it should though. I have all the dependences loaded on my machine. I will attach my JSON in the case someone would need to see that.

```<code>    var themename = 'taylerco';

var gulp = require('gulp'),
    //prepare and optimize code
    autoprefixer = require('autoprefixer'),
    browserSync = require('browser-sync').create(),
    image = require('gulp-image'),
    jshint = require('gulp-jshint'),
    postcss = require('gulp-postcss'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),

   //only work with new or updated files
   newer = require('gulp-newer'),

   //name of working theme folder
   root = '../' + themename + '/',
   scss = root + 'sass/',
   js = root + 'js/',
   img = root + 'images/',
   languages = root + 'languages/';

// css via sass and autoprefixer
gulp.task('css', function(){
    return gulp.src(scss + '{style.scss,rtl.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
        outputStyle:'expanded',
        indentType:'tab',
        indentWidth:'1'
    }).on('error', sass.logError))
    .pipe(postcss([
        autoprefixer('last 2 versions', '> 1%')
    ]))
    .pipe(sourcemaps.write(scss + 'maps'))
    .pipe(gulp.dest(root));
});

//optimize images through gulp-image
gulp.task('images', function(){
    return gulp.src(img + 'RAW/**/*.(jpg,JPG,png)')
    .pipe(newer(img))
    .pipe(image())
    .pipe(gulp.dest(img));
});

//javascript
gulp.task('javascript', function(){
    return gulp.src([js + '*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(js));

});

//watch everything
gulp.task('watch', function(){
    browserSync.init({
        open: 'external',
        proxy: 'localhost:8888',
        port: 8080
    });
    gulp.watch([root + '**/*.css',root + '**/*.scss'], ['css']);
    gulp.watch(js + '**/*.js', ['javascript']);
    gulp.watch(img + 'RAW/**/*.(jpg,JPG,png)', ['images']);
    gulp.watch(root + '**/*').on('change', browserSync.reload);
});

//default talk (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
</code>```

package.json

```<code>{
  "name": "tayler.co",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "browser-sync": "^2.18.13",
    "gulp": "^3.9.1",
    "gulp-image": "^4.1.0",
    "gulp-jshint": "^2.0.4",
    "gulp-newer": "^1.3.0",
    "gulp-postcss": "^7.0.0",
    "gulp-sass": "^3.1.0",
    "gulp-sourcemaps": "^2.6.1",
    "jshint": "^2.9.5"
  }
}
</code>```

答:
There seems to be a typo in your syntax.

Change

```<code> return gulp.src(scss + '{style.scss,rtl.scss')
</code>```

To

```<code> return gulp.src(scss + '{style.scss,rtl.scss}')
</code>```

Body:
please help I'm not getting any errors but this code will not create the compiled css from the scss file. I am writing the code within the underscore WP theme if that matters I don't think it should though. I have all the dependences loaded on my machine. I will attach my JSON in the case someone would need to see that.

    var themename = 'taylerco';

var gulp = require('gulp'),
    //prepare and optimize code
    autoprefixer = require('autoprefixer'),
    browserSync = require('browser-sync').create(),
    image = require('gulp-image'),
    jshint = require('gulp-jshint'),
    postcss = require('gulp-postcss'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),

   //only work with new or updated files
   newer = require('gulp-newer'),

   //name of working theme folder
   root = '../' + themename + '/',
   scss = root + 'sass/',
   js = root + 'js/',
   img = root + 'images/',
   languages = root + 'languages/';

// css via sass and autoprefixer
gulp.task('css', function(){
    return gulp.src(scss + '{style.scss,rtl.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
        outputStyle:'expanded',
        indentType:'tab',
        indentWidth:'1'
    }).on('error', sass.logError))
    .pipe(postcss([
        autoprefixer('last 2 versions', '> 1%')
    ]))
    .pipe(sourcemaps.write(scss + 'maps'))
    .pipe(gulp.dest(root));
});

//optimize images through gulp-image
gulp.task('images', function(){
    return gulp.src(img + 'RAW/**/*.(jpg,JPG,png)')
    .pipe(newer(img))
    .pipe(image())
    .pipe(gulp.dest(img));
});

//javascript
gulp.task('javascript', function(){
    return gulp.src([js + '*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(js));

});

//watch everything
gulp.task('watch', function(){
    browserSync.init({
        open: 'external',
        proxy: 'localhost:8888',
        port: 8080
    });
    gulp.watch([root + '**/*.css',root + '**/*.scss'], ['css']);
    gulp.watch(js + '**/*.js', ['javascript']);
    gulp.watch(img + 'RAW/**/*.(jpg,JPG,png)', ['images']);
    gulp.watch(root + '**/*').on('change', browserSync.reload);
});

//default talk (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);

package.json

{
  "name": "tayler.co",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "browser-sync": "^2.18.13",
    "gulp": "^3.9.1",
    "gulp-image": "^4.1.0",
    "gulp-jshint": "^2.0.4",
    "gulp-newer": "^1.3.0",
    "gulp-postcss": "^7.0.0",
    "gulp-sass": "^3.1.0",
    "gulp-sourcemaps": "^2.6.1",
    "jshint": "^2.9.5"
  }
}

Body:
There seems to be a typo in your syntax.

Change

 return gulp.src(scss + '{style.scss,rtl.scss')

To

 return gulp.src(scss + '{style.scss,rtl.scss}')


问:
How to convert a single Image to MP4 Video?
How to convert a single image to mp4 video.

For example, I need to play the same image for 20 seconds (duration will be dynamic)

I know it's possible with ffmpeg. I searched in google & SO but unfortunately, I am not able to find the correct tutorial.

I just want a correct direction.

Any comment or suggestion is welcome.

答:
Basic syntax is

```<code>ffmpeg -loop 1 -i image -pix_fmt yuv420p -t 20 out.mp4
</code>```

The -t option sets the time, in seconds.

Body:
Basic syntax is

ffmpeg -loop 1 -i image -pix_fmt yuv420p -t 20 out.mp4

The -t option sets the time, in seconds.


问:
Adding an overlay to a google map
I made my own google map with historical information (of houses and people in the 50-s in Princenhage, The Netherlands):
https://www.google.com/maps/d/viewer?mid=174YNyi2hs_iVpoU0qLqOPq-YUxI&ll=51.57704585455824%2C4.737584814456795&z=18

Now I would like to add an aerial photograph of 1950 as an extra layer on this map so that my map looks as 'google earth in 1950'.

Is this possible and how to do this?

答:
It is possible but you need to make a baseMap of your aerial photo. If you managed that you can use this example to add the basemap to your viewer:

https://github.com/rcknr/basemap-google-maps

Title: Adding an overlay to a google map


问:
Bokeh with Big Data in Millions
My problem is I am getting large amounts of data from HIVE (around 10 million points). Bokeh alone is not capable of handling it. I tried below using Datashader. But I'm having trouble saving my image:

```<code>import pyodbc
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf

conn = pyodbc.connect("xxxxxxxx", autocommit=True)
df = pd.read_sql("select devalue,fevalue,type from tblbigdata limit 10;",con=conn)
conn.close()

cvs = ds.Canvas(plot_width=400, plot_height=400)

agg = cvs.points(df, 'devalue', 'fevalue', ds.mean('fevalue'))
img = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='log')
img.save("out.png")
print("Done")
</code>```

Getting Error:
AttributeError: 'Image' object has no attribute 'save'

答:
Here is the complete code.</p>

```<code>import pyodbc
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
from PIL import Image

conn = pyodbc.connect("xxxxxxxx", autocommit=True)
df = pd.read_sql("select devalue,fevalue,type from tblbigdata limit 10;",con=conn)
conn.close()

cvs = ds.Canvas(plot_width=400, plot_height=400)

agg = cvs.points(df, 'devalue', 'fevalue', ds.mean('fevalue'))
img = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='log')
Image = img.to_pil()
Image.save("C:\MyPython\myimage123.bmp","BMP")
print("Done")
</code>```

Title: Bokeh with Big Data in Millions

Body:
My problem is I am getting large amounts of data from HIVE (around 10 million points). Bokeh alone is not capable of handling it. I tried below using Datashader. But I'm having trouble saving my image:

import pyodbc
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf

conn = pyodbc.connect("xxxxxxxx", autocommit=True)
df = pd.read_sql("select devalue,fevalue,type from tblbigdata limit 10;",con=conn)
conn.close()

cvs = ds.Canvas(plot_width=400, plot_height=400)

agg = cvs.points(df, 'devalue', 'fevalue', ds.mean('fevalue'))
img = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='log')
img.save("out.png")
print("Done")

Getting Error:
AttributeError: 'Image' object has no attribute 'save'

Body:
Here is the complete code.

import pyodbc
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
from PIL import Image

conn = pyodbc.connect("xxxxxxxx", autocommit=True)
df = pd.read_sql("select devalue,fevalue,type from tblbigdata limit 10;",con=conn)
conn.close()

cvs = ds.Canvas(plot_width=400, plot_height=400)

agg = cvs.points(df, 'devalue', 'fevalue', ds.mean('fevalue'))
img = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='log')
Image = img.to_pil()
Image.save("C:\MyPython\myimage123.bmp","BMP")
print("Done")


问:
Display Options when variant selected in Shopify
I want to display options when a particular variant is selected.

Products have have 2 variants : Normal and Custom

Want to display extra line items only when Custom variant is selected.

Adding in the extra line items is no issue, just having trouble making them only display when the variant "Custom" is selected.

Have searched through these forus, google and the Shopify forums and cannot find a definitive answer. Would appreciate any help.

I gather it will be using JavaScripts & most of the code will be in selectcallback function

答:
Just make that line items by default hidden (I mean display:none or visibility hidden). Then in selectCallback you need to check using if else condition that whether selected variant is "custom" or not, if it's custom then You need to make line items visible. Also in else condition you have to check if line items are visible then make them hidden again using display:none or visibility:hidden.

I hope this will work, If you have any query comment it :)


问:
Why is this code correct?
```<code>#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }
</code>```

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.

答: scanf "consumes" the char it reads, that means that in the next call of the function the line would be 1 character shorter since the previous one has already been used by the previous recursive call.

Title: Why is this code correct?

Body:
#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.


问:
Add Event Listener : How to Add even listener in typescript angular?
I am working with google-maps and i am showing a marker on clicking the coordinates which I am fetching through database. They work fine. But now i want to show the title of place on click of the marker, but I dont know where to put the code of event listener.

Given below is my app.component.ts

app.comp.ts

```<code>import { AfterViewInit, Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ProductService } from './product.service';

declare var google: any;

// Islamabad Cordinates ===================================================
var myLatLng = { lat: 33.7294, lng: 73.0931 };

// Declaare Map  ==========================================================
var map;

// Markers array to push all marker ======================================
var markers = [];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ProductService]
})
export class AppComponent {

  //define an array of products
  products = [];

  //constructor func
  constructor(private _productService: ProductService) { }

  //after constructor func this func runs , in which we are
  // accessing the class function getproducts and objects products
  // through this.
  // => means callback in which we are dumping data in products
  //array
  ngOnInit() {
    this._productService.getProducts()
      .subscribe(products => { this.products = products; console.log(this.products); })

  }

  ngAfterViewInit() {

    setTimeout(() => {
      map = new google.maps.Map(document.getElementById('map'), {
        center: myLatLng,
        zoom: 12
      });

      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'Hello World!'
      });

      markers.push(marker);
      console.log(map)

    }, 3000);
  }

  showMarker(latitude, longitude) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
    // TS convert string to Int using +
    var clickedLocation = { lat: +latitude, lng: +longitude }
    console.log(clickedLocation);

    map.panTo(clickedLocation);

    var marker = new google.maps.Marker({
      position: clickedLocation,
      map: map,
      title: 'Hello World!'
    });
  }
}
</code>```

Now where should I put this code ?

```<code>     google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
  });
</code>```

答:
you can write this code </p>

```<code>google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
});
</code>```

<p>Directly after the </p>

```<code>var marker = new google.maps.Marker({...
</code>```

Body:
I am working with google-maps and i am showing a marker on clicking the coordinates which I am fetching through database. They work fine. But now i want to show the title of place on click of the marker, but I dont know where to put the code of event listener.

Given below is my app.component.ts

app.comp.ts

import { AfterViewInit, Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ProductService } from './product.service';

declare var google: any;

// Islamabad Cordinates ===================================================
var myLatLng = { lat: 33.7294, lng: 73.0931 };

// Declaare Map  ==========================================================
var map;

// Markers array to push all marker ======================================
var markers = [];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ProductService]
})
export class AppComponent {

  //define an array of products
  products = [];

  //constructor func
  constructor(private _productService: ProductService) { }

  //after constructor func this func runs , in which we are
  // accessing the class function getproducts and objects products
  // through this.
  // => means callback in which we are dumping data in products
  //array
  ngOnInit() {
    this._productService.getProducts()
      .subscribe(products => { this.products = products; console.log(this.products); })

  }

  ngAfterViewInit() {

    setTimeout(() => {
      map = new google.maps.Map(document.getElementById('map'), {
        center: myLatLng,
        zoom: 12
      });

      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'Hello World!'
      });

      markers.push(marker);
      console.log(map)

    }, 3000);
  }

  showMarker(latitude, longitude) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
    // TS convert string to Int using +
    var clickedLocation = { lat: +latitude, lng: +longitude }
    console.log(clickedLocation);

    map.panTo(clickedLocation);

    var marker = new google.maps.Marker({
      position: clickedLocation,
      map: map,
      title: 'Hello World!'
    });
  }
}

Now where should I put this code ?

     google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
  });

Body:
you can write this code

google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
});

Directly after the

var marker = new google.maps.Marker({...


问:
Changing complex computed object in vue.js

I have complicated object for a table. Looks like this:

```<code>{
    1510002000: {
        date: "07.11.17"
        hours: {
            1510002000:{
                activity:{
                    activity: "Тест",
                    color: "#00ff00",
                    end_at: 1510005600,
                    start_at: 1510002000,
                    type_id: 1
                }
            },
            1510005600: {
                ...
            },
            ...
        }
    },
    ....
}
</code>```

This is a code from template that uses this object:

```<code>    <tr v-for="date in this.tds">
        <td>{{ date.date }}</td>
        <td is="hour-td"
            v-for="hour in date.hours"
            :color="hour.activity.color"
            :start_at="hour.activity.start_at"
            :end_at="hour.activity.end_at"
            :activity="hour.activity.activity"
            :type_id="hour.activity.type_id"
        >
        </td>
    </tr>
</code>```

I evaluated it as a computed property, but I need to rerender table when parent component provides data assync, so I have a watcher for prop (prop called "activities"):

```<code>watch: {
    activities: function(){
        var vm  = this;
        let dth = new DateTimeHelper;

        if (this.activities.length > 0){
            this.activities.forEach(function(activity){
                let dateTimestamp = dth.getDateTimestampFromTimestamp(activity.start_at); // just getting the key

                if (vm.tds[dateTimestamp]){
                    if (vm.tds[dateTimestamp].hours[activity.start_at]){
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
                    }
                }
            });
        }

        console.log(vm.tds) // here I can see that the object is filled with new data
    }
},
</code>```

The problem is that the table doesn't rerender. More precisely, the component "hour-td" does not contain the new data.

Also I've tried to use Vue.set, but no success with that

Can you help me with the updating table? I've spent like 5 hours for refactoring and attempts.

Thanks in advance

SOLUTION

In my case there can be two states: there are activities, there are no activities. So I made two computed props for each case and render them separately and switch by v-if="activities.length"

答:
I think that your problem is with Vue known issue for Change Detection Caveats (you can read here) with array direct assignation, that don't detect changes.

You should change this part of code (with direct array assignation):

```<code>if (vm.tds[dateTimestamp]){
   if (vm.tds[dateTimestamp].hours[activity.start_at]){
      vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
      vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
      vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
   }
}
</code>```

With the Vue.set() option for arrays in order to detect the change and re-renders the component. It worked for me in differents occassions:

```<code>// Vue.set(object, key, value)
// something like this:
Vue.set(vm.tds[dateTimestamp].hours[activity.start_at].activity.activity,1,activity.activity);
</code>```

More info here: https://codingexplained.com/coding/front-end/vue-js/array-change-detection

Edit:

I see now that you said:

Also I've tried to use Vue.set, but no success with that

What you mean with: "no success" ? Can you share the code? I have the same issue and I resolved with Vue.set..

You can also take a look to vm.$forceUpdate(), try to execute after the last console.log or grab all the code inside a vm.$nextTick( [callback] ) in order to execute all the actions (load data in the table) and then, re-render the component on next tick.

More info here: https://v2.vuejs.org/v2/api/#vm-forceUpdate && https://v2.vuejs.org/v2/api/#Vue-nextTick

Edit 2:

I think that your problem is with the index of the array, you should take a look here: https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection .
Try changing the:

```<code>if (vm.tds[dateTimestamp]){
                    if (vm.tds[dateTimestamp].hours[activity.start_at]){
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
                    }
                }

</code>```

and simplify with:

```<code>if (vm.tds[dateTimestamp] && vm.tds[dateTimestamp].hours[activity.start_at]){
   Vue.set( vm.tds, vm.tds.indexOf(vm.tds[dateTimestamp].hours[activity.start_at]), activity);
}
</code>```

Hope it helps!

Body:
I have complicated object for a table. Looks like this:

{
    1510002000: {
        date: "07.11.17"
        hours: {
            1510002000:{
                activity:{
                    activity: "Тест",
                    color: "#00ff00",
                    end_at: 1510005600,
                    start_at: 1510002000,
                    type_id: 1
                }
            },
            1510005600: {
                ...
            },
            ...
        }
    },
    ....
}

This is a code from template that uses this object:

        {{ date.date }}

I evaluated it as a computed property, but I need to rerender table when parent component provides data assync, so I have a watcher for prop (prop called "activities"):

watch: {
    activities: function(){
        var vm  = this;
        let dth = new DateTimeHelper;

        if (this.activities.length > 0){
            this.activities.forEach(function(activity){
                let dateTimestamp = dth.getDateTimestampFromTimestamp(activity.start_at); // just getting the key

                if (vm.tds[dateTimestamp]){
                    if (vm.tds[dateTimestamp].hours[activity.start_at]){
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
                    }
                }
            });
        }

        console.log(vm.tds) // here I can see that the object is filled with new data
    }
},

The problem is that the table doesn't rerender. More precisely, the component "hour-td" does not contain the new data.

Also I've tried to use Vue.set, but no success with that

Can you help me with the updating table? I've spent like 5 hours for refactoring and attempts.

Thanks in advance

SOLUTION

In my case there can be two states: there are activities, there are no activities. So I made two computed props for each case and render them separately and switch by v-if="activities.length"

Body:
I think that your problem is with Vue known issue for Change Detection Caveats (you can read here) with array direct assignation, that don't detect changes.

You should change this part of code (with direct array assignation):

if (vm.tds[dateTimestamp]){
   if (vm.tds[dateTimestamp].hours[activity.start_at]){
      vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
      vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
      vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
   }
}

With the Vue.set() option for arrays in order to detect the change and re-renders the component. It worked for me in differents occassions:

// Vue.set(object, key, value)
// something like this:
Vue.set(vm.tds[dateTimestamp].hours[activity.start_at].activity.activity,1,activity.activity);

More info here: https://codingexplained.com/coding/front-end/vue-js/array-change-detection

Edit:

I see now that you said:

Also I've tried to use Vue.set, but no success with that

What you mean with: "no success" ? Can you share the code? I have the same issue and I resolved with Vue.set..

You can also take a look to vm.$forceUpdate(), try to execute after the last console.log or grab all the code inside a vm.$nextTick( [callback] ) in order to execute all the actions (load data in the table) and then, re-render the component on next tick.

More info here: https://v2.vuejs.org/v2/api/#vm-forceUpdate && https://v2.vuejs.org/v2/api/#Vue-nextTick

Edit 2:

I think that your problem is with the index of the array, you should take a look here: https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection .
Try changing the:

if (vm.tds[dateTimestamp]){
                    if (vm.tds[dateTimestamp].hours[activity.start_at]){
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.activity = activity.activity;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.color    = activity.color;
                        vm.tds[dateTimestamp].hours[activity.start_at].activity.type_id  = activity.type_id;
                    }
                }

and simplify with:

if (vm.tds[dateTimestamp] && vm.tds[dateTimestamp].hours[activity.start_at]){
   Vue.set( vm.tds, vm.tds.indexOf(vm.tds[dateTimestamp].hours[activity.start_at]), activity);
}

Hope it helps!