问:
doctrine2 ifnull
hi is there in doctrine2 ifnull?
i need to use... how to?

```<code>SELECT *
FROM `apns_task_message`
ORDER BY IFNULL( `sent_at` , NOW( ) ) , `priority` DESC , `position` ASC
</code>```

how convert this sql into doctrine?

```<code>    $qb = $this->getRepository()->createQueryBuilder('tm');
    $qb->leftJoin('tm.apnsTask', 't');
    $qb->add('where', 't.id = :task_id')->setParameter('task_id', $task_id);
    //$qb->add('orderBy', 'IFNULL(tm.sent_at, NOW()), tm.priority DESC, tm.position ASC');
    $qb->add('orderBy', 'd_date, tm.priority DESC, tm.position ASC');
    $q = $qb->getQuery();
    return $q->getResult();
</code>```

found!!!
Thanks to @AdrienBrault for "coalesce" operator

```<code>$now = new \DateTime("now");
$qb = $this->getRepository()->createQueryBuilder('tm');
$qb->addSelect('coalesce (tm.sentAt, :sent_date) as sent_date')->setParameter('sent_date', $now->format("Y-m-d H:i:s"));
$qb->leftJoin('tm.apnsTask', 't');
$qb->add('where', 't.id = :task_id')->setParameter('task_id', $task_id);
$qb->add('orderBy', 'sent_date ASC, tm.priority DESC, tm.position ASC');
$q = $qb->getQuery();
</code>```

答:
If you want to use IFNULL function of sql in doctrine query builder, You need to use doctrine extension for IFNULL.

First of all you need to register extension class to use in Doctrine bootstrap

```<code>        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode, $proxies_dir);
        $driver = new AnnotationDriver(new AnnotationReader());
        $config->setMetadataDriverImpl($driver);

        require_once './Doctrine/DoctrineExtensions/Query/MySql/IfNull.php';

        $config->addCustomStringFunction('IfNull', '\DoctrineExtensions\Query\Mysql\IfNull');

        $this->em = EntityManager::create($connection_options, $config);

        $classLoader = new ClassLoader('DoctrineExtensions', $extension_dir);
        $classLoader->register();
</code>```

Here are IFNULL doctrine extension code.

```<code><?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode,
    Doctrine\ORM\Query\Lexer;

/**
 * @author Andrew Mackrodt <andrew@ajmm.org>
 */
class IfNull extends FunctionNode
{
    private $expr1;
    private $expr2;

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->expr1 = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_COMMA);
        $this->expr2 = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'IFNULL('
            .$sqlWalker->walkArithmeticPrimary($this->expr1). ', '
            .$sqlWalker->walkArithmeticPrimary($this->expr2).')';
    }
}
</code>```

You can download extensions from here

For your case, use this.

```<code>$qb = $this->getRepository()->createQueryBuilder('tm');
return $qb
        ->select("*")
        ->from("tm.apnsTask", "t")
        ->orderBy("IFNULL(t.sent_at, NOW()), t.priority DESC, t.position ASC")
        ->getQuery()
        ->getResult();
</code>```

Title: doctrine2 ifnull

Body:
hi is there in doctrine2 ifnull?
i need to use... how to?

SELECT *
FROM `apns_task_message`
ORDER BY IFNULL( `sent_at` , NOW( ) ) , `priority` DESC , `position` ASC

how convert this sql into doctrine?

    $qb = $this->getRepository()->createQueryBuilder('tm');
    $qb->leftJoin('tm.apnsTask', 't');
    $qb->add('where', 't.id = :task_id')->setParameter('task_id', $task_id);
    //$qb->add('orderBy', 'IFNULL(tm.sent_at, NOW()), tm.priority DESC, tm.position ASC');
    $qb->add('orderBy', 'd_date, tm.priority DESC, tm.position ASC');
    $q = $qb->getQuery();
    return $q->getResult();

found!!!
Thanks to @AdrienBrault for "coalesce" operator

$now = new \DateTime("now");
$qb = $this->getRepository()->createQueryBuilder('tm');
$qb->addSelect('coalesce (tm.sentAt, :sent_date) as sent_date')->setParameter('sent_date', $now->format("Y-m-d H:i:s"));
$qb->leftJoin('tm.apnsTask', 't');
$qb->add('where', 't.id = :task_id')->setParameter('task_id', $task_id);
$qb->add('orderBy', 'sent_date ASC, tm.priority DESC, tm.position ASC');
$q = $qb->getQuery();

Body:
If you want to use IFNULL function of sql in doctrine query builder, You need to use doctrine extension for IFNULL.

First of all you need to register extension class to use in Doctrine bootstrap

        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode, $proxies_dir);
        $driver = new AnnotationDriver(new AnnotationReader());
        $config->setMetadataDriverImpl($driver);

        require_once './Doctrine/DoctrineExtensions/Query/MySql/IfNull.php';

        $config->addCustomStringFunction('IfNull', '\DoctrineExtensions\Query\Mysql\IfNull');

        $this->em = EntityManager::create($connection_options, $config);

        $classLoader = new ClassLoader('DoctrineExtensions', $extension_dir);
        $classLoader->register();

Here are IFNULL doctrine extension code.

<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode,
    Doctrine\ORM\Query\Lexer;

/**
 * @author Andrew Mackrodt <andrew@ajmm.org>
 */
class IfNull extends FunctionNode
{
    private $expr1;
    private $expr2;

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->expr1 = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_COMMA);
        $this->expr2 = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'IFNULL('
            .$sqlWalker->walkArithmeticPrimary($this->expr1). ', '
            .$sqlWalker->walkArithmeticPrimary($this->expr2).')';
    }
}

You can download extensions from here

For your case, use this.

$qb = $this->getRepository()->createQueryBuilder('tm');
return $qb
        ->select("*")
        ->from("tm.apnsTask", "t")
        ->orderBy("IFNULL(t.sent_at, NOW()), t.priority DESC, t.position ASC")
        ->getQuery()
        ->getResult();


来源: stackexchange

问:
Deploying Service fabric project on azure cluster
I have created  a project with 2 microservices and had made then listen on two different ports but when i deploy them on Azure Cluster(remote) Only one microservice work which is at port 19080 </p>

答: Have you opened the appropriate ports for the service in Azure?</p>

ContentLicense: CC BY-SA 3.0


问:
Access Remote Git Repo
I want to access the remote repo files of all branches to analyze the committed code without cloning to the local through java. How can I achieve this one and what is the procedure if there any way to do?

Thanks in advance.

答:
Try scm4j-vcs-git:</p>

```<code>public static final String WORKSPACE_DIR = System.getProperty("java.io.tmpdir") + "git-workspaces";
...
IVCSWorkspace workspace = new VCSWorkspace(WORKSPACE_DIR);
String repoUrl = "https://github.com/MyUser/MyRepo";
IVCSRepositoryWorkspace repoWorkspace = workspace.getVCSRepositoryWorkspace(repoUrl);
IVCS vcs = new GitVCS(repoWorkspace);
vcs.setCredentials("user", "password"); // if necessary
vcs.getBranchesList();
</code>```

Title: Access Remote Git Repo

Body:
Try scm4j-vcs-git:

public static final String WORKSPACE_DIR = System.getProperty("java.io.tmpdir") + "git-workspaces";
...
IVCSWorkspace workspace = new VCSWorkspace(WORKSPACE_DIR);
String repoUrl = "https://github.com/MyUser/MyRepo";
IVCSRepositoryWorkspace repoWorkspace = workspace.getVCSRepositoryWorkspace(repoUrl);
IVCS vcs = new GitVCS(repoWorkspace);
vcs.setCredentials("user", "password"); // if necessary
vcs.getBranchesList();


问:
implementing include/sched.h functions
I wanted to study how threads can be assigned manually to specific cores on a multi core machine. I found that include/sched.h defines some macros and functions (sched_setaffinity, etc.)that can help for this. However, the functions are extern'ed and I can't find their definitions. Are those functions implemented anywhere? If yes, where and is it possible to override the default implementation? If no, how can I implement them?

And would adding new implementation imply that I have to recompile my Linux kernel?

答: The code for sched_setaffinity is in the kernel.  The header file just provides the prototype to call it, and the library which satisfies it just forwards the call to the system.</p>

ContentLicense: CC BY-SA 2.5

Title: implementing include/sched.h functions


问:
xades4j verification issue with embeded x509 certificate
I am using smart card for signing and SunMSCAPI provider and windows key store.
Using xades4j 1.3.2 version I am singing an xml file as follows and it is working perfectly and the certificate is also embeded in xml file in KeyInfo,

```<code>private Document signXMLData(Document doc) {
        try {
            XadesSigningProfile p;
            p = new XadesBesSigningProfile(keyingDataProvider).withSignaturePropertiesProvider(new SignaturePropertiesProvider() {
                @Override
                public void provideProperties(SignaturePropertiesCollector signedPropsCol) {
                    signedPropsCol.setSignerRole(new SignerRoleProperty(SignerRole));
                    signedPropsCol.setSignatureProductionPlace(new SignatureProductionPlaceProperty(City, State, PostalCode, Country));
                    signedPropsCol.setSigningTime(new SigningTimeProperty());
                }
            });
            XadesSigner signer = p.newSigner();
            Element elemToSign = doc.getDocumentElement();
            new Enveloped(signer).sign(elemToSign);
            Log.LogOperation("XML signing completed successfully.");
        } catch (Exception ex) {
            Log.LogException(ex);
            doc = null;
        }
        return doc;
    }
</code>```

But my problem is, while verifying using following code, I am getting following error,

Code

```<code>public boolean VerifyXMLSign(String data) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, Exception {
        InputSource isIn = new InputSource();
        isIn.setCharacterStream(new StringReader(data));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().parse(isIn);
        //Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("c:/xml.xml"));
        DOMHelper.useIdAsXmlId(doc.getDocumentElement());

        KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
        ks.load(null, null);

        X509Certificate x509Certificate = null;
        PublicKey key = null;
        DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(ks), getSigElement(doc));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        fac.newDigestMethod(DigestMethod.SHA256, null);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        KeyInfo keyInfo = signature.getKeyInfo();
        Iterator hKeyInfo = keyInfo.getContent().iterator();
        while (hKeyInfo.hasNext()) {
            XMLStructure hX509Data = (XMLStructure) hKeyInfo.next();
            if (!(hX509Data instanceof X509Data)) {
                continue;
            }
            X509Data x509Data = (X509Data) hX509Data;
            Iterator hX509Certificate = x509Data.getContent().iterator();
            while (hX509Certificate.hasNext()) {
                Object oX509Certificate = hX509Certificate.next();
                if (!(oX509Certificate instanceof X509Certificate)) {
                    continue;
                }
                x509Certificate = ((X509Certificate) oX509Certificate);
                key = x509Certificate.getPublicKey();
            }
        }

        //FileSystemDirectoryCertStore certStore = createDirectoryCertStore("my");
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        ks.setCertificateEntry("df", x509Certificate);

        CertificateValidationProvider validationProviderMySigs = new PKIXCertificateValidationProvider(ks, false, null);//certStore.getStore());
        XadesVerificationProfile instance = new XadesVerificationProfile(validationProviderMySigs);
        XadesVerifier verifier = instance.newVerifier();
        XAdESVerificationResult r = verifier.verify(getSigElement(doc), null);

        System.out.println(r.getSignatureForm());
        System.out.println(r.getSignatureAlgorithmUri());
        System.out.println(r.getSignedDataObjects().size());
        System.out.println(r.getQualifyingProperties().all().size());
        return false;
    }
</code>```

Error

```<code>Log Date Time:- 2017/06/08 14:38:01
xades4j.utils.XadesProfileResolutionException: com.google.inject.internal.ComputationException: java.lang.SecurityException: class "org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter"'s signer information does not match signer information of other classes in the same package
    at xades4j.utils.XadesProfileCore.getInstance(XadesProfileCore.java:223)
    at xades4j.verification.XadesVerificationProfile.newVerifier(XadesVerificationProfile.java:147)
    at slr.DigitalVerification.VerifyXMLSign(DigitalVerification.java:163)
    at slr.Handlers$OpenEVerifierHandler.handle(Handlers.java:186)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
    at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80)
    at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:677)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
    at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
    at sun.net.httpserver.ServerImpl$DefaultExecutor.execute(ServerImpl.java:158)
    at sun.net.httpserver.ServerImpl$Dispatcher.handle(ServerImpl.java:433)
    at sun.net.httpserver.ServerImpl$Dispatcher.run(ServerImpl.java:398)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.inject.internal.ComputationException: ..........
</code>```

I tried the method suggested in https://github.com/luisgoncalves/xades4j/issues/37 but that also giving the same error.

Please suggest what am I doing wrong.

答:
From the error it seems something related to mixing up security providers, probably because you create the KeyStore from "SunMSCAPI" and then the X509Certificate is created by the provider used on the XML signature, which seems to be bouncy castle.

Anyway, since the signing certificate is included on the signature you don't need to be parsing the XML and looking for it. The purpose of xades4j is to abstract you away from that stuff. xades4j will collect all the certificates in KeyInfo and use them to build a chain when validating the signing certificate (in this case there's likely only one).

If all the intermediate certificates and root certificates needed to validate your singing certificate are either on Windows-ROOT or within KeyInfo, you just need to create the trusted roots KeyStore and pass it to PKIXCertificateValidationProvider as-is. If you need to include additional certificates, you can use the CertStore parameter of PKIXCertificateValidationProvider constructor.

So, to sum up, all the code you should need is the first and last parts. Something like:

```<code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(isIn);
DOMHelper.useIdAsXmlId(doc.getDocumentElement());

KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
ks.load(null, null);
CertificateValidationProvider validationProviderMySigs = new PKIXCertificateValidationProvider(ks, false, null);
XadesVerificationProfile instance = new XadesVerificationProfile(validationProviderMySigs);
XadesVerifier verifier = instance.newVerifier();
XAdESVerificationResult r = verifier.verify(getSigElement(doc), null);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using smart card for signing and SunMSCAPI provider and windows key store.
Using xades4j 1.3.2 version I am singing an xml file as follows and it is working perfectly and the certificate is also embeded in xml file in KeyInfo,

private Document signXMLData(Document doc) {
        try {
            XadesSigningProfile p;
            p = new XadesBesSigningProfile(keyingDataProvider).withSignaturePropertiesProvider(new SignaturePropertiesProvider() {
                @Override
                public void provideProperties(SignaturePropertiesCollector signedPropsCol) {
                    signedPropsCol.setSignerRole(new SignerRoleProperty(SignerRole));
                    signedPropsCol.setSignatureProductionPlace(new SignatureProductionPlaceProperty(City, State, PostalCode, Country));
                    signedPropsCol.setSigningTime(new SigningTimeProperty());
                }
            });
            XadesSigner signer = p.newSigner();
            Element elemToSign = doc.getDocumentElement();
            new Enveloped(signer).sign(elemToSign);
            Log.LogOperation("XML signing completed successfully.");
        } catch (Exception ex) {
            Log.LogException(ex);
            doc = null;
        }
        return doc;
    }

But my problem is, while verifying using following code, I am getting following error,

Code

public boolean VerifyXMLSign(String data) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, Exception {
        InputSource isIn = new InputSource();
        isIn.setCharacterStream(new StringReader(data));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().parse(isIn);
        //Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("c:/xml.xml"));
        DOMHelper.useIdAsXmlId(doc.getDocumentElement());

        KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
        ks.load(null, null);

        X509Certificate x509Certificate = null;
        PublicKey key = null;
        DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(ks), getSigElement(doc));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        fac.newDigestMethod(DigestMethod.SHA256, null);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        KeyInfo keyInfo = signature.getKeyInfo();
        Iterator hKeyInfo = keyInfo.getContent().iterator();
        while (hKeyInfo.hasNext()) {
            XMLStructure hX509Data = (XMLStructure) hKeyInfo.next();
            if (!(hX509Data instanceof X509Data)) {
                continue;
            }
            X509Data x509Data = (X509Data) hX509Data;
            Iterator hX509Certificate = x509Data.getContent().iterator();
            while (hX509Certificate.hasNext()) {
                Object oX509Certificate = hX509Certificate.next();
                if (!(oX509Certificate instanceof X509Certificate)) {
                    continue;
                }
                x509Certificate = ((X509Certificate) oX509Certificate);
                key = x509Certificate.getPublicKey();
            }
        }

        //FileSystemDirectoryCertStore certStore = createDirectoryCertStore("my");
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        ks.setCertificateEntry("df", x509Certificate);

        CertificateValidationProvider validationProviderMySigs = new PKIXCertificateValidationProvider(ks, false, null);//certStore.getStore());
        XadesVerificationProfile instance = new XadesVerificationProfile(validationProviderMySigs);
        XadesVerifier verifier = instance.newVerifier();
        XAdESVerificationResult r = verifier.verify(getSigElement(doc), null);

        System.out.println(r.getSignatureForm());
        System.out.println(r.getSignatureAlgorithmUri());
        System.out.println(r.getSignedDataObjects().size());
        System.out.println(r.getQualifyingProperties().all().size());
        return false;
    }

Error

Log Date Time:- 2017/06/08 14:38:01
xades4j.utils.XadesProfileResolutionException: com.google.inject.internal.ComputationException: java.lang.SecurityException: class "org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter"'s signer information does not match signer information of other classes in the same package
    at xades4j.utils.XadesProfileCore.getInstance(XadesProfileCore.java:223)
    at xades4j.verification.XadesVerificationProfile.newVerifier(XadesVerificationProfile.java:147)
    at slr.DigitalVerification.VerifyXMLSign(DigitalVerification.java:163)
    at slr.Handlers$OpenEVerifierHandler.handle(Handlers.java:186)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
    at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80)
    at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:677)
    at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
    at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
    at sun.net.httpserver.ServerImpl$DefaultExecutor.execute(ServerImpl.java:158)
    at sun.net.httpserver.ServerImpl$Dispatcher.handle(ServerImpl.java:433)
    at sun.net.httpserver.ServerImpl$Dispatcher.run(ServerImpl.java:398)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.inject.internal.ComputationException: ..........

I tried the method suggested in https://github.com/luisgoncalves/xades4j/issues/37 but that also giving the same error.

Please suggest what am I doing wrong.

Body:
From the error it seems something related to mixing up security providers, probably because you create the KeyStore from "SunMSCAPI" and then the X509Certificate is created by the provider used on the XML signature, which seems to be bouncy castle.

Anyway, since the signing certificate is included on the signature you don't need to be parsing the XML and looking for it. The purpose of xades4j is to abstract you away from that stuff. xades4j will collect all the certificates in KeyInfo and use them to build a chain when validating the signing certificate (in this case there's likely only one).

If all the intermediate certificates and root certificates needed to validate your singing certificate are either on Windows-ROOT or within KeyInfo, you just need to create the trusted roots KeyStore and pass it to PKIXCertificateValidationProvider as-is. If you need to include additional certificates, you can use the CertStore parameter of PKIXCertificateValidationProvider constructor.

So, to sum up, all the code you should need is the first and last parts. Something like:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(isIn);
DOMHelper.useIdAsXmlId(doc.getDocumentElement());

KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
ks.load(null, null);
CertificateValidationProvider validationProviderMySigs = new PKIXCertificateValidationProvider(ks, false, null);
XadesVerificationProfile instance = new XadesVerificationProfile(validationProviderMySigs);
XadesVerifier verifier = instance.newVerifier();
XAdESVerificationResult r = verifier.verify(getSigElement(doc), null);


问:
how to use both Groovy-defined and OS system variable in a multi-line shell script within Jenkins Groovy
I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)

But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)

How can I use both of them? any help will be much appreciated.

e.g.

```<code>node ("Jenkins-Test-Slave") {
stage ("hello world") {
    echo 'Hello World'
}

def var1="bin"
stage ("test") {
    withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
        echo var1
        sh '''
            echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
            echo default value of aws_api_key is \$aws_api_key
            aws_api_key='changed in shell'
            echo new value of aws_api_key is \$aws_api_key

            export newvar='newxxx'
            echo the new var value is \$newvar
        '''
    }
}
}
</code>```

The result is:

```<code>+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx
</code>```

答:
def var1 = 'bin'

//the following are `groovy` strings (evaluated)

sh "echo var1 = $var1"
//outputs> echo var1 = bin

sh "echo var1 = ${var1}"
//outputs> echo var1 = bin

sh """echo var1 = ${var1}"""
//outputs> echo var1 = bin

sh "echo var1 = \$var1"
//outputs> echo var1 = $var1

//the following are usual strings (not evaluated)

sh 'echo var1 = $var1'
//outputs> echo var1 = $var1

sh '''echo var1 = $var1'''
//outputs> echo var1 = $var1
```

<p>so, in your case just use </p>

<pre class="lang-java prettyprint-override"><code>def var1 = 'bin'
sh """
   echo var1 = $var1
   shell_var = 'yyy'
   echo shell_var = \$shell_var
""""
</code>```

Body:
I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)

But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)

How can I use both of them? any help will be much appreciated.

e.g.

node ("Jenkins-Test-Slave") {
stage ("hello world") {
    echo 'Hello World'
}

def var1="bin"
stage ("test") {
    withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
        echo var1
        sh '''
            echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
            echo default value of aws_api_key is \$aws_api_key
            aws_api_key='changed in shell'
            echo new value of aws_api_key is \$aws_api_key

            export newvar='newxxx'
            echo the new var value is \$newvar
        '''
    }
}
}

The result is:

+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx

Body:
def var1 = 'bin'

//the following are `groovy` strings (evaluated)

sh "echo var1 = $var1"
//outputs> echo var1 = bin

sh "echo var1 = ${var1}"
//outputs> echo var1 = bin

sh """echo var1 = ${var1}"""
//outputs> echo var1 = bin

sh "echo var1 = \$var1"
//outputs> echo var1 = $var1

//the following are usual strings (not evaluated)

sh 'echo var1 = $var1'
//outputs> echo var1 = $var1

sh '''echo var1 = $var1'''
//outputs> echo var1 = $var1

so, in your case just use

def var1 = 'bin'
sh """
   echo var1 = $var1
   shell_var = 'yyy'
   echo shell_var = \$shell_var
""""


问:
Is this TypeError linked to a wrong this.$emit?
I am building a component which is supposed to get an Array of Objects from the parent, display them and allow for some of the Objects to be deleted (= the child sends to the parent a new Array).

A previous answer was very useful to understand the child -> parent communication but I am now stuck on an error I do no understand:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      var user = _.filter(this.who, function(w) {
        return w.id === p.id
      })
      this.$emit('delete-id', user)
    }
  }
})
var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="who"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template></code>```

Running this code correcly lists the users, but when trying to delete one I get in the console

```<code>vue.js:1739 Uncaught TypeError: fns[i].apply is not a function
    at VueComponent.invoker (vue.js:1739)
    at VueComponent.Vue.$emit (vue.js:2210)
    at VueComponent.deleteID (search.html:31)
    at Proxy.boundFn (vue.js:170)
    at click (eval at makeFunction (vue.js:9323), <anonymous>:2:164)
    at HTMLButtonElement.invoker (vue.js:1743)
invoker @   vue.js:1739
Vue.$emit   @   vue.js:2210
deleteID    @   search.html:31
boundFn @   vue.js:170
click   @   VM9358:2
invoker @   vue.js:1743
</code>```

What does this error mean? Is the $emit correct?

答:
Following up on Linus' excellent answer, for  the record below is my corrected code which emits and Array as when a user is deleted.

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
                var user = _.filter(this.who, function (w) {
                return w.id != p.id
            })
      this.$emit('delete-id', user)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(users) {
      this.who = users
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template></code>```

Body:
I am building a component which is supposed to get an Array of Objects from the parent, display them and allow for some of the Objects to be deleted (= the child sends to the parent a new Array).

A previous answer was very useful to understand the child -> parent communication but I am now stuck on an error I do no understand:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      var user = _.filter(this.who, function(w) {
        return w.id === p.id
      })
      this.$emit('delete-id', user)
    }
  }
})
var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  }
})

  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="who"></search-box>
  who is: {{who}}

<template id="search-box-template">

person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button>

</template>

Running this code correcly lists the users, but when trying to delete one I get in the console

vue.js:1739 Uncaught TypeError: fns[i].apply is not a function
    at VueComponent.invoker (vue.js:1739)
    at VueComponent.Vue.$emit (vue.js:2210)
    at VueComponent.deleteID (search.html:31)
    at Proxy.boundFn (vue.js:170)
    at click (eval at makeFunction (vue.js:9323), <anonymous>:2:164)
    at HTMLButtonElement.invoker (vue.js:1743)
invoker @   vue.js:1739
Vue.$emit   @   vue.js:2210
deleteID    @   search.html:31
boundFn @   vue.js:170
click   @   VM9358:2
invoker @   vue.js:1743

What does this error mean? Is the $emit correct?

Body:
Following up on Linus' excellent answer, for  the record below is my corrected code which emits and Array as when a user is deleted.

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
                var user = _.filter(this.who, function (w) {
                return w.id != p.id
            })
      this.$emit('delete-id', user)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(users) {
      this.who = users
    }
  }
})

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template>


问:
Using skew on parent causes sidenav to lose position
Sorry for the wording, i'm not sure exactly how to phrase it.

I have a header and a container which contains a sidenav and button to toggle it. I am trying to skew the header while keeping the container normal by skewing in the opposite direction. However doing this causes the sidenav to lose it's height:100% and it doesn't stick to the left.

How can i skew the background without affecting the sidenave?

Here is the fiddle and code
https://jsfiddle.net/q0ddzw4v/

HTML

```<code><body id="body">
    <header class="header">
        <div class="header__container">
            <div id="mySidenav" class="sidenav">
                <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
                <a href="#">About</a>
                <a href="#">Services</a>
                <a href="#">Clients</a>
                <a href="#">Contact</a>
            </div>

            <div id="main">
                <h2>Sidenav Push Example</h2>
                <p>Click on the element below to open the side navigation menu, and push this content to the right.</p>
                <span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>
            </div>
        </div>
    </header>

    <script>
        function openNav() {
            document.getElementById("mySidenav").style.width = "250px";
        }

        function closeNav() {
            document.getElementById("mySidenav").style.width = "0";
        }
    </script>
</body>
</code>```

CSS

```<code>body {
    font-family: sans-serif;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
}

.sidenav a:hover,
.offcanvas a:focus {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    padding: 16px;
}

.header {
    width: 100%;
    height: 100vh;
    background-color: #C18D8D;
    transform: skewY(-10deg);
}

.header__container {
    width: 80%;
    max-width: 71.25rem;
    margin: auto;
    display: flex;
    flex-direction: column;
    height: 100%;
    transform: skewY(10deg);
}
</code>```

答:
Instead of skewing the .header container, add a pseduo-element and skew it:

body {
  font-family: "Lato", sans-serif;
  transition: margin-left 0.5s;
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

.header {
  position: relative;
  width: 100%;
  height: 100vh;
}

.header::before {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #C18D8D;
  transform: skewY(-10deg);
  content: '';
}

.header__container {
  position: relative;
  z-index: 0;
  width: 80%;
  max-width: 71.25rem;
  margin: auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="header__container">
    <div id="mySidenav" class="sidenav">
      ×
      About
      Services
      Clients
      Contact
    </div>

    <div id="main">
      <h2>Sidenav Push Example</h2>
      <p>Click on the element below to open the side navigation menu, and push this content to the right.</p>
      <span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>
    </div>
  </div>
</header>

<script>
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    // document.getElementById("body").style.marginLeft = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    // document.getElementById("body").style.marginLeft = "0";
  }
</script></code>```

Body:
Sorry for the wording, i'm not sure exactly how to phrase it.

I have a header and a container which contains a sidenav and button to toggle it. I am trying to skew the header while keeping the container normal by skewing in the opposite direction. However doing this causes the sidenav to lose it's height:100% and it doesn't stick to the left.

How can i skew the background without affecting the sidenave?

Here is the fiddle and code
https://jsfiddle.net/q0ddzw4v/

HTML

                ×
                About
                Services
                Clients
                Contact

Sidenav Push Example

Click on the element below to open the side navigation menu, and push this content to the right.

                ☰ open

CSS

body {
    font-family: sans-serif;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
}

.sidenav a:hover,
.offcanvas a:focus {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    padding: 16px;
}

.header {
    width: 100%;
    height: 100vh;
    background-color: #C18D8D;
    transform: skewY(-10deg);
}

.header__container {
    width: 80%;
    max-width: 71.25rem;
    margin: auto;
    display: flex;
    flex-direction: column;
    height: 100%;
    transform: skewY(10deg);
}

Body:
Instead of skewing the .header container, add a pseduo-element and skew it:

body {
  font-family: "Lato", sans-serif;
  transition: margin-left 0.5s;
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

.header {
  position: relative;
  width: 100%;
  height: 100vh;
}

.header::before {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #C18D8D;
  transform: skewY(-10deg);
  content: '';
}

.header__container {
  position: relative;
  z-index: 0;
  width: 80%;
  max-width: 71.25rem;
  margin: auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}

<header class="header">
  <div class="header__container">
    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
      <a href="#">About</a>
      <a href="#">Services</a>
      <a href="#">Clients</a>
      <a href="#">Contact</a>
    </div>

    <div id="main">
      <h2>Sidenav Push Example</h2>
      <p>Click on the element below to open the side navigation menu, and push this content to the right.</p>
      <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>
    </div>
  </div>
</header>

<script>
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    // document.getElementById("body").style.marginLeft = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    // document.getElementById("body").style.marginLeft = "0";
  }
</script>


问:
Do Spark RDD's have something similar to set allowing rapid lookup?
I have some data consisting of pairs such as

```<code>data = [(3,7), (2,4), (7,3), ...]
</code>```

These correspond to connections in a graph I want to build. I want to keep only the pairs whose reverse pair is contained in the data, and only one copy of each. For instance, in the above data, I want [(3,7)] because the reverse ((7,3)) is also in the data.

In Python, I would do something like this:

```<code>pairs = set(data)
edges = [p for p in pairs if p[0] < p[1] and (p[1], p[0]) in pairs]
</code>```

Can I do something similar on Spark? The closest I can get is creating a new RDD with the pairs reversed, taking the intersection with the original data, and filtering based on pair elements being sorted, but that seems inefficient.

答:
<-- language: python -->

```<code>rdd = sc.parallelize([(3, 7), (2, 4), (7, 3)]) \
    .map(lambda x: ((min(x), max(x)), [x])) \
    .reduceByKey(lambda x, y: x + y) \
    .filter(lambda x: len(x[1]) > 1) \
    .map(lambda x: x[0])
</code>```

this can work as well

Body:
I have some data consisting of pairs such as

data = [(3,7), (2,4), (7,3), ...]

These correspond to connections in a graph I want to build. I want to keep only the pairs whose reverse pair is contained in the data, and only one copy of each. For instance, in the above data, I want [(3,7)] because the reverse ((7,3)) is also in the data.

In Python, I would do something like this:

pairs = set(data)
edges = [p for p in pairs if p[0] < p[1] and (p[1], p[0]) in pairs]

Can I do something similar on Spark? The closest I can get is creating a new RDD with the pairs reversed, taking the intersection with the original data, and filtering based on pair elements being sorted, but that seems inefficient.

Body:
<-- language: python -->

rdd = sc.parallelize([(3, 7), (2, 4), (7, 3)]) \
    .map(lambda x: ((min(x), max(x)), [x])) \
    .reduceByKey(lambda x, y: x + y) \
    .filter(lambda x: len(x[1]) > 1) \
    .map(lambda x: x[0])

this can work as well


问:
How do I best create a button with a left aligned icon and the text centered in the remaining area
I need to have a button that looks like this:

Right now I went for a view with two buttons inside it. But the problem with that is that I can either hook up the two individual buttons to the same outlet, or add a UITapGestureRecognizer to the container view.

I went with the second option because I thought it would be cleaner, but that only works when I disable the buttons (and therefore disable the press-down animation).

Am I on the right track, and should I just find a way to trigger the button's animation when the UITapGestureRecognizer calls my method? Or is there a better way to do this?

答:
The size inspector tab for UIButton has an Insets section at the top. Play around with the insets values of title insets and image insets to achieve the desired result.

And you don't need to use multiple buttons in a view or tap gesture to achieve this. Just 1 single button would suffice.


问:
help with inport csv file to my C# program
i try to inport csv file to my database in my C# winform program.

for example the csv file:

```<code>code  ,name    ,price
101010,computer,200$
</code>```

and i done this:

```<code>char[] BI = { ',' };
string[] WI = TEMP.Split(BI);
A = WI[0].Trim().ToString();
B = WI[1].Trim().ToString();
C = WI[2].Trim().ToString();
</code>```

but what i can do if the name contain (,) ?

for example

```<code>code  ,name              ,price
101010,computer 12,200.00,200$
</code>```

if i get this type of csv:

```<code>code    ,name                ,price
"101010","computer 12,200.00","200$"
</code>```

how to deal with this ?

答: Have a look at http://www.codeproject.com/KB/database/CsvReader.aspx, I believe this solves your problem.</p>

Body:
i try to inport csv file to my database in my C# winform program.

for example the csv file:

code  ,name    ,price
101010,computer,200$

and i done this:

char[] BI = { ',' };
string[] WI = TEMP.Split(BI);
A = WI[0].Trim().ToString();
B = WI[1].Trim().ToString();
C = WI[2].Trim().ToString();

but what i can do if the name contain (,) ?

for example

code  ,name              ,price
101010,computer 12,200.00,200$

if i get this type of csv:

code    ,name                ,price
"101010","computer 12,200.00","200$"

how to deal with this ?


问:
MySQL on OSX Sierra can't start: The server quit without updating PID file
Several problems with mysql since last Sierra Update.
Reinstalled several times with brew or mysql dmg and followd many many "solutions" on SO.

Finally it worked but after a Mac Crash, I face the same problem.

MySql won't start from preference panel

Mysql won't start from terminal: Can't connect through /tmp/mysql.sock...of course, mysqld is not running

trying to start mysqld:

sudo /usr/local/mysql/support-files/mysql.server start

ERROR! The server quit without updating PID file (/usr/local/mysql/data/My-iMac.local.pid)

sudo /usr/local/mysql/bin/mysqld several errors and shutdown

a bit stuck

答: Oh, I feel your pain. I've had this happen many times. Stopping the processes didn't always work. To solve this I simply went into System Preferences and MySQL... stop the process from there and try to restart.</p>


问:
Remove unnecessary memory allocation during serialization
I have a wrapper class holding a protobuf as a private member, myInstance. The protobuf contains an optional bytes payload which i want to set using a function template in the wrapper class (making the wrapper class payload agnostic until template instantiation).

I wrote this set_payload function in the wrapper class:

```<code>  template <typename T>
  inline void set_payload(const T& somePayload)
  {
    uint32_t payloadSize = somePayload.ByteSize();
    uint8_t* serializedPayload = new uint8_t[payloadSize];
    somePayload.SerializeToArray(serializedPayload, payloadSize);
    myInstance->set_payload(serializedPayload, payloadSize);
    delete [] serializedPayload;
  }
</code>```

This function can take any protobuf and serialize it into the payload member of myInstance inside the wrapper class.

My problem is the extra memory allocation step. I would like to remove the use of new and delete inside the function template, as this memory will be allocated for myInstance::payload anyways. Possible?

The identity of the function could have been inline void set_payload(const ::google::protobuf::Message& somePayload) instead, without being a template. Same implementation.

答:
Protobuf now has move-aware setters that accept rvalue references.

In order to use a move-aware setter for payload, you need to do something like this:

make serializedPayload a std::string

```<code>std::string payload;
</code>```

grow it to needed size:

```<code> payload.resize(payloadSize);
</code>```

serialize to its data:

```<code>somePayload.SerializeToArray(payload.data(), payloadSize); // c++17, or
somePayload.SerializeToArray(&payload[0], payloadSize); // c++<17
</code>```

call the move-aware setter:

```<code>myInstance->set_payload(std::move(serializedPayload), payloadSize);
</code>```

Body:
I have a wrapper class holding a protobuf as a private member, myInstance. The protobuf contains an optional bytes payload which i want to set using a function template in the wrapper class (making the wrapper class payload agnostic until template instantiation).

I wrote this set_payload function in the wrapper class:

  template <typename T>
  inline void set_payload(const T& somePayload)
  {
    uint32_t payloadSize = somePayload.ByteSize();
    uint8_t* serializedPayload = new uint8_t[payloadSize];
    somePayload.SerializeToArray(serializedPayload, payloadSize);
    myInstance->set_payload(serializedPayload, payloadSize);
    delete [] serializedPayload;
  }

This function can take any protobuf and serialize it into the payload member of myInstance inside the wrapper class.

My problem is the extra memory allocation step. I would like to remove the use of new and delete inside the function template, as this memory will be allocated for myInstance::payload anyways. Possible?

The identity of the function could have been inline void set_payload(const ::google::protobuf::Message& somePayload) instead, without being a template. Same implementation.

Body:
Protobuf now has move-aware setters that accept rvalue references.

In order to use a move-aware setter for payload, you need to do something like this:

make serializedPayload a std::string

std::string payload;

grow it to needed size:

 payload.resize(payloadSize);

serialize to its data:

somePayload.SerializeToArray(payload.data(), payloadSize); // c++17, or
somePayload.SerializeToArray(&payload[0], payloadSize); // c++<17

call the move-aware setter:

myInstance->set_payload(std::move(serializedPayload), payloadSize);


问:
Swift: I'm not able to make autolayout constraints work for my UIScrollView
I'm trying to make a simple layout that should scroll vertically when views are too many to fit on the screen.

So this is what I have so far:

I created a scrollview and a container view like that

```<code>let mainScrollView: UIScrollView = {

    let scrollView = UIScrollView()

    scrollView.isUserInteractionEnabled = true
    scrollView.translatesAutoresizingMaskIntoConstraints = false

    return scrollView
}()

let containerView: UIView = {

    let view = UIView()

    view.backgroundColor = .lightGray
    view.translatesAutoresizingMaskIntoConstraints = false

    return view
}()
</code>```

Then I added the scrollview to the main view, added the container view to the scrollview and a couple of labels to the container view

```<code>view.addSubview(mainScrollView)
mainScrollView.addSubview(containerView)

containerView.addSubview(firstLabel)
containerView.addSubview(secondLabel)
</code>```

I pinned the scrollview to the main view, and the container view to the scrollview. After that I started adding the labels inside the container view like this

```<code>mainScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mainScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mainScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
mainScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

containerView.topAnchor.constraint(equalTo: mainScrollView.layoutMarginsGuide.topAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: mainScrollView.layoutMarginsGuide.bottomAnchor).isActive = true
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

firstLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
firstLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 30).isActive = true
firstLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
firstLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

secondLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 750).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
</code>```

The problem is that for some reason the scrollview is not able to calculate it's height and it doesn't scroll vertically. The second label remains invisible because it's too "low" on the screen.

I tried setting the bottom constraint of the container view to the bottom of the second label but I'm going nowhere honestly.

What am I missing? How can I set constraints to make the scrollview scroll with autolayout (without setting a specific height of the container view)?

答:
Thank you very much @GoodSp33d, you pointed me to the right direction.

I added the width constraint as you said like that:

containerView.widthAnchor.constraint(equalTo: mainScrollView.widthAnchor).isActive = true

And the key point was to update the bottom constraint after all:

containerView.bottomAnchor.constraint(equalTo: secondLabel.bottomAnchor).isActive = true

Here is the full working code:

```<code>mainScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mainScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mainScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
mainScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

containerView.topAnchor.constraint(equalTo: mainScrollView.topAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: mainScrollView.trailingAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: mainScrollView.bottomAnchor).isActive = true
containerView.leadingAnchor.constraint(equalTo: mainScrollView.leadingAnchor).isActive = true
containerView.widthAnchor.constraint(equalTo: mainScrollView.widthAnchor).isActive = true

firstLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
firstLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 30).isActive = true
firstLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
firstLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

secondLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 550).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

containerView.bottomAnchor.constraint(equalTo: secondLabel.bottomAnchor).isActive = true
</code>```

Thanks for the help.

Body:
I'm trying to make a simple layout that should scroll vertically when views are too many to fit on the screen.

So this is what I have so far:

I created a scrollview and a container view like that

let mainScrollView: UIScrollView = {

    let scrollView = UIScrollView()

    scrollView.isUserInteractionEnabled = true
    scrollView.translatesAutoresizingMaskIntoConstraints = false

    return scrollView
}()

let containerView: UIView = {

    let view = UIView()

    view.backgroundColor = .lightGray
    view.translatesAutoresizingMaskIntoConstraints = false

    return view
}()

Then I added the scrollview to the main view, added the container view to the scrollview and a couple of labels to the container view

view.addSubview(mainScrollView)
mainScrollView.addSubview(containerView)

containerView.addSubview(firstLabel)
containerView.addSubview(secondLabel)

I pinned the scrollview to the main view, and the container view to the scrollview. After that I started adding the labels inside the container view like this

mainScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mainScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mainScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
mainScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

containerView.topAnchor.constraint(equalTo: mainScrollView.layoutMarginsGuide.topAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: mainScrollView.layoutMarginsGuide.bottomAnchor).isActive = true
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

firstLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
firstLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 30).isActive = true
firstLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
firstLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

secondLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 750).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

The problem is that for some reason the scrollview is not able to calculate it's height and it doesn't scroll vertically. The second label remains invisible because it's too "low" on the screen.

I tried setting the bottom constraint of the container view to the bottom of the second label but I'm going nowhere honestly.

What am I missing? How can I set constraints to make the scrollview scroll with autolayout (without setting a specific height of the container view)?

Body:
Thank you very much @GoodSp33d, you pointed me to the right direction.

I added the width constraint as you said like that:

containerView.widthAnchor.constraint(equalTo: mainScrollView.widthAnchor).isActive = true

And the key point was to update the bottom constraint after all:

containerView.bottomAnchor.constraint(equalTo: secondLabel.bottomAnchor).isActive = true

Here is the full working code:

mainScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mainScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mainScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
mainScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

containerView.topAnchor.constraint(equalTo: mainScrollView.topAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: mainScrollView.trailingAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: mainScrollView.bottomAnchor).isActive = true
containerView.leadingAnchor.constraint(equalTo: mainScrollView.leadingAnchor).isActive = true
containerView.widthAnchor.constraint(equalTo: mainScrollView.widthAnchor).isActive = true

firstLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
firstLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 30).isActive = true
firstLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
firstLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

secondLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 550).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true

containerView.bottomAnchor.constraint(equalTo: secondLabel.bottomAnchor).isActive = true

Thanks for the help.


问:
System V - LIFO way
I'm using System V to manage a message queue.
I successfully made a working prototype, everything works as expected, however I would like to have a LIFO queue instead of FIFO (expected last msgsnd message sent is first read msgget).

Is this possible ?

答:
Yes if you manage correctly message types. msgrcv manual specifies:

The argument msgtyp specifies the type of message requested as
  follows:

If msgtyp is 0, the first message on the queue is received.

If msgtyp
  is greater than 0, the first message of type msgtyp is received.

If
  msgtyp is less than 0, the first message of the lowest type that is
  less than or equal to the absolute value of msgtyp is received.

Then if you send messages with strictly decreasing msgtyp, an extraction with msgtyp equals to LONG_MIN will always give you the last sent message. msgtyp plays the role of a priority in this case, 1 being the greatest.

Title: System V - LIFO way


问:
Problem writing string to a file ...(iPhone SDK )
I want to grab all URL's accessed in webview and write them to a text file.I don't want to use writeToFile coz in -(BOOL)webView method it would overwrite instead of appending to file. I can create file but all it writes to that file is string I used to create the file using FileManager createFileAtPath with Content ...
Also  in the -(BOOL) webView  method... when I tried to see if the file is read-only or writable ( isWritableFileAtPath ) it gives read-only.
POSIX Permissions in viewDidLoad -> 511 ...
checked file attributes in terminal going to that location its -rwxrwxrwx
I am new to Stack Overflow don't know how to post code here so using pastebin...http://pastebin.com/Tx7CsXVB</p>

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    [myBrowser loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com"]]]; // UIWebView *myBrowser; is an instance variable
    NSFileManager *fileMgr=[NSFileManager defaultManager];
    NSDictionary* fileAttrs = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:777] forKey:NSFilePosixPermissions]; /*for setting attribute to rwx for all users */
    NSDictionary *attribs; // To read attributes after writing something to file
    NSString *aPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"];
    myBrowser.delegate = self; // UIWebView delegate Self
    // if the File Doesn't exist create one
    if([fileMgr fileExistsAtPath:aPath])
    {
        NSLog(@"File Exists at this Location");
    }
    else
    {
        NSString *someString = @"This is start of file";
        NSData *startString =[someString dataUsingEncoding: NSASCIIStringEncoding];
        [fileMgr createFileAtPath:aPath contents:startString attributes: fileAttrs]; // earlier attributes was nil changed to fileAttrs
    }
    NSLog(@"aPath is %@",aPath);
    attribs = [fileMgr attributesOfItemAtPath:aPath error: NULL];
    NSLog (@"Created on %@", [attribs objectForKey: NSFileCreationDate]);
    NSLog (@"File type %@", [attribs objectForKey: NSFileType]);
    NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);
}

//UIWebView delegate calls this method every time user touches any embedded URL's in the current WebPage. I want to grab all the URL's accessed and write them to file.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        NSFileManager *fileManager =[NSFileManager defaultmanager];
    NSString *path =  [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"];
    fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    [fileHandle seekToEndOfFile]; // Moved up next to fileHandleForWritingAtPath since the above would place pointer to start of file again so setting handle to seek to End of File
    /* section of code to check if the file at that path is writable or not */
    if ([fileManager isWritableFileAtPath:path]  == YES)
        NSLog (@"File is writable");
    else
        NSLog (@"File is read only");
    /* section of code to check if the file at that path is writable or not ENDS*/
    NSURL *url = request.URL;
    NSString *currenturl = url.absoluteString;
    NSString *currentURL = [NSString stringWithFormat:@"%@\n",currenturl];
    NSString *str =[NSString stringWithFormat:@"%@",currentURL];/* has already been set up */
    [fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    // testing if string has been written to file by reading it...
    NSData *dataBuffer = [fileMgr contentsAtPath:path];
    NSString *some;
    some = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
    NSLog(@"SOme String is: %@",some);
    [fileHandle closeFile];
}
</code>```

答:
I think your issue may be that you're testing Documents/file1.txt and not /Documents/file1.txt

The leading '/' is important

[edit]

May I make a suggestion?  Distill this down to what works first and then figure out what makes it fail?
I would recommend using the following form and continuing from there:

```<code>if ([fileManager isWritableFileAtPath: @"/Documents/file1.txt"] == YES)
   NSLog (@"File is writable");
else
   NSLog (@"File is read only");
</code>```

[/edit]

Body:
I want to grab all URL's accessed in webview and write them to a text file.I don't want to use writeToFile coz in -(BOOL)webView method it would overwrite instead of appending to file. I can create file but all it writes to that file is string I used to create the file using FileManager createFileAtPath with Content ...
Also  in the -(BOOL) webView  method... when I tried to see if the file is read-only or writable ( isWritableFileAtPath ) it gives read-only.
POSIX Permissions in viewDidLoad -> 511 ...
checked file attributes in terminal going to that location its -rwxrwxrwx
I am new to Stack Overflow don't know how to post code here so using pastebin...http://pastebin.com/Tx7CsXVB

- (void)viewDidLoad {
    [super viewDidLoad];
    [myBrowser loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com"]]]; // UIWebView *myBrowser; is an instance variable
    NSFileManager *fileMgr=[NSFileManager defaultManager];
    NSDictionary* fileAttrs = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:777] forKey:NSFilePosixPermissions]; /*for setting attribute to rwx for all users */
    NSDictionary *attribs; // To read attributes after writing something to file
    NSString *aPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"];
    myBrowser.delegate = self; // UIWebView delegate Self
    // if the File Doesn't exist create one
    if([fileMgr fileExistsAtPath:aPath])
    {
        NSLog(@"File Exists at this Location");
    }
    else
    {
        NSString *someString = @"This is start of file";
        NSData *startString =[someString dataUsingEncoding: NSASCIIStringEncoding];
        [fileMgr createFileAtPath:aPath contents:startString attributes: fileAttrs]; // earlier attributes was nil changed to fileAttrs
    }
    NSLog(@"aPath is %@",aPath);
    attribs = [fileMgr attributesOfItemAtPath:aPath error: NULL];
    NSLog (@"Created on %@", [attribs objectForKey: NSFileCreationDate]);
    NSLog (@"File type %@", [attribs objectForKey: NSFileType]);
    NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);
}

//UIWebView delegate calls this method every time user touches any embedded URL's in the current WebPage. I want to grab all the URL's accessed and write them to file.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        NSFileManager *fileManager =[NSFileManager defaultmanager];
    NSString *path =  [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"];
    fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    [fileHandle seekToEndOfFile]; // Moved up next to fileHandleForWritingAtPath since the above would place pointer to start of file again so setting handle to seek to End of File
    /* section of code to check if the file at that path is writable or not */
    if ([fileManager isWritableFileAtPath:path]  == YES)
        NSLog (@"File is writable");
    else
        NSLog (@"File is read only");
    /* section of code to check if the file at that path is writable or not ENDS*/
    NSURL *url = request.URL;
    NSString *currenturl = url.absoluteString;
    NSString *currentURL = [NSString stringWithFormat:@"%@\n",currenturl];
    NSString *str =[NSString stringWithFormat:@"%@",currentURL];/* has already been set up */
    [fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    // testing if string has been written to file by reading it...
    NSData *dataBuffer = [fileMgr contentsAtPath:path];
    NSString *some;
    some = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
    NSLog(@"SOme String is: %@",some);
    [fileHandle closeFile];
}

Body:
I think your issue may be that you're testing Documents/file1.txt and not /Documents/file1.txt

The leading '/' is important

[edit]

May I make a suggestion?  Distill this down to what works first and then figure out what makes it fail?
I would recommend using the following form and continuing from there:

if ([fileManager isWritableFileAtPath: @"/Documents/file1.txt"] == YES)
   NSLog (@"File is writable");
else
   NSLog (@"File is read only");

[/edit]


问:
When insert elements of php array in table mysql what kind of data should be ? Only string?
I have to insert elements of multi-dimensional php array into table mysql but i don't know what kind of method should be used there.

First create the table

```<code>CREATE TABLE earthquakes (
  milliseconds BIGINT,
  latitude FLOAT,
  longitude FLOAT,
  magnitude FLOAT,
  depth FLOAT,
  source VARCHAR(2),
  region SMALLINT,
  serial VARCHAT(16)
);
</code>```

Should I add the length of the characters even for the other columns?

Now the code to insert elements:

```<code>$array = array(
 array(12345678901112145,-35.4905,167.7843,7.5,450.4,"E",134,"2017-01-10-134"),
 array(12345678901112145,35.4905,-167.7843,3.2,45.4,"U",13,"2016-01-10-14"),
 array(12345678901112145,-35.4905,-167.7843,10.0,4,"I",1,"2016-01-10-1")
);

$data = array();
foreach($array as $row) {
 $milliseconds = mysql_real_escape_string($row[0]);
 $latitude = mysql_real_escape_string($row[1]);
 $longitude = mysql_real_escape_string($row[2]);
 $magnitude = mysql_real_escape_string($row[3]);
 $depth= mysql_real_escape_string($row[4]);
 $source= mysql_real_escape_string($row[5]);
 $code= mysql_real_escape_string($row[6]);
 $serial= mysql_real_escape_string($row[7]);

 $data[] = "($milliseconds,$latitude,$longitude,$magnitude,$depth,'$source',$code,'$serial')";
}

$values = implode(',', $data);

$sql = "INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES $values";
</code>```

My doubt is if the code is correct but especially if i have to add " " double quotes or single quotes for each element (each value that add to the table).

I hope you help me and understand my english :(

UPDATE

this is result if i echo $sql

```<code>INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES (12345678901112145,-35.4905,167.7843,7.5,450.4,'E',134,'2017-01-10-134'),(12345678901112145,35.4905,-167.7843,3.2,45.4,'U',13,'2016-01-10-14'),(12345678901112145,-35.4905,-167.7843,10,4,'I',1,'2016-01-10-1')
</code>```

答:
You should try this :-

```<code> $array = array(
 array(12345678901112145,-35.4905,"222",7.5,450.4,"E",134,"2017-01-10-134"),
 array(12345678901112145,35.4905,-167.7843,3.2,45.4,"U",13,"2016-01-10-14"),
 array(12345678901112145,-35.4905,-167.7843,10.0,4,"I",1,"2016-01-10-1")
);

//----------------------------
 connection to db is necessary to use mysql_real_escape_string function
//----------------------------

$sql = "INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES ";

foreach($array as $row) {
     $milliseconds = mysql_real_escape_string($row[0]);
     $latitude = mysql_real_escape_string($row[1]);
     $longitude = mysql_real_escape_string($row[2]);
     $magnitude = mysql_real_escape_string($row[3]);
     $depth= mysql_real_escape_string($row[4]);
     $source= mysql_real_escape_string($row[5]);
     $code= mysql_real_escape_string($row[6]);
     $serial= mysql_real_escape_string($row[7]);
     $sql .="($milliseconds,$latitude,$longitude,$magnitude,$depth,'$source',$code,'$serial'),";
}
$sql = rtrim($sql, ',');
excute the sql here.
</code>```

If the column type is varchar then you have to add '' single colon to the values.

Body:
I have to insert elements of multi-dimensional php array into table mysql but i don't know what kind of method should be used there.

First create the table

CREATE TABLE earthquakes (
  milliseconds BIGINT,
  latitude FLOAT,
  longitude FLOAT,
  magnitude FLOAT,
  depth FLOAT,
  source VARCHAR(2),
  region SMALLINT,
  serial VARCHAT(16)
);

Should I add the length of the characters even for the other columns?

Now the code to insert elements:

$array = array(
 array(12345678901112145,-35.4905,167.7843,7.5,450.4,"E",134,"2017-01-10-134"),
 array(12345678901112145,35.4905,-167.7843,3.2,45.4,"U",13,"2016-01-10-14"),
 array(12345678901112145,-35.4905,-167.7843,10.0,4,"I",1,"2016-01-10-1")
);

$data = array();
foreach($array as $row) {
 $milliseconds = mysql_real_escape_string($row[0]);
 $latitude = mysql_real_escape_string($row[1]);
 $longitude = mysql_real_escape_string($row[2]);
 $magnitude = mysql_real_escape_string($row[3]);
 $depth= mysql_real_escape_string($row[4]);
 $source= mysql_real_escape_string($row[5]);
 $code= mysql_real_escape_string($row[6]);
 $serial= mysql_real_escape_string($row[7]);

 $data[] = "($milliseconds,$latitude,$longitude,$magnitude,$depth,'$source',$code,'$serial')";
}

$values = implode(',', $data);

$sql = "INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES $values";

My doubt is if the code is correct but especially if i have to add " " double quotes or single quotes for each element (each value that add to the table).

I hope you help me and understand my english :(

UPDATE

this is result if i echo $sql

INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES (12345678901112145,-35.4905,167.7843,7.5,450.4,'E',134,'2017-01-10-134'),(12345678901112145,35.4905,-167.7843,3.2,45.4,'U',13,'2016-01-10-14'),(12345678901112145,-35.4905,-167.7843,10,4,'I',1,'2016-01-10-1')

Body:
You should try this :-

 $array = array(
 array(12345678901112145,-35.4905,"222",7.5,450.4,"E",134,"2017-01-10-134"),
 array(12345678901112145,35.4905,-167.7843,3.2,45.4,"U",13,"2016-01-10-14"),
 array(12345678901112145,-35.4905,-167.7843,10.0,4,"I",1,"2016-01-10-1")
);

//----------------------------
 connection to db is necessary to use mysql_real_escape_string function
//----------------------------

$sql = "INSERT INTO earthquakes (milliseconds,latitude,longitude,magnitude,depth,source,region,serial) VALUES ";

foreach($array as $row) {
     $milliseconds = mysql_real_escape_string($row[0]);
     $latitude = mysql_real_escape_string($row[1]);
     $longitude = mysql_real_escape_string($row[2]);
     $magnitude = mysql_real_escape_string($row[3]);
     $depth= mysql_real_escape_string($row[4]);
     $source= mysql_real_escape_string($row[5]);
     $code= mysql_real_escape_string($row[6]);
     $serial= mysql_real_escape_string($row[7]);
     $sql .="($milliseconds,$latitude,$longitude,$magnitude,$depth,'$source',$code,'$serial'),";
}
$sql = rtrim($sql, ',');
excute the sql here.

If the column type is varchar then you have to add '' single colon to the values.


问:
Add particles on button click in unity
I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:

```<code>ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();
</code>```

I have also added particles component from unity editor..

Thanks in advance

Edit :

as @kardux suggested:

declaration :

```<code>[SerializeField] private ParticleSystem ps;
</code>```

on method :

```<code>ps.Play()
</code>```

Screenshot from inspector:

Error:

```<code>I/Unity   (23313): NullReferenceException
I/Unity   (23313):   at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661
</code>```

答:
Are you using the New Unity UI System or GUI, Is the UI worldspace?

Create a empty gameobject - attach the particle to that.

Whenever you want emit particles call Gameobject.SetActive(true);

Make sure Play on Awake option is checked in the particle system.

Set the position of the particle according to your UI.

Title: Add particles on button click in unity

Body:
I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:

ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();

I have also added particles component from unity editor..

Thanks in advance

Edit :

as @kardux suggested:

declaration :

[SerializeField] private ParticleSystem ps;

on method :

ps.Play()

Screenshot from inspector:

Error:

I/Unity   (23313): NullReferenceException
I/Unity   (23313):   at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661


问:
Spring @Autowire is behaving in a weird way returning null for initialized bean
I have a legacy spring application, with a mix of xml and java config. (not my choice sorry). The spring context is initialized from the xml config, which has a component scan instruction to scan the java configs.

There are many java config classes, below are code snippets from 2 of them where I see a problem.
My @Bean DateProvider dateProvider() in ReplayConfig is initialized first, and I can see this by putting a breakpoint in the constructor. And then in AnotherConfig I autowire  @Autowired private DateProvider dateProvider; After having used @Import(ReplayConfig.class).

All good so far, except it turns out the instance of my portfolioService has been passed a null dateProvider. It is frustrating to see experience this, given I can clearly see that dateProvider has been instantiated earlier.

I can actually get it to work if I add to PortfolioServiceImpl

```<code>@Autowired setDateProvider(DateProvider dateProvider)
</code>```

Which I thought would remove all doubt about possibility of confusing packages or different classes with the same name or silly things like that.

The only thing I can think of is something else is wrong. If someone can suggest any ideas it would be great.

Unfortunately I can't get away from the xml initialisation for now.

More code below:

```<code>@Import (EnvironmentConfig.class)
@Config
ReplayConfig{
   @Bean
    DateProvider dateProvider() {
        SystemDateProvider systemDateProvider = new SystemDateProvider (bean());
        return systemDateProvider;
    }
}
</code>```

Then we import that and try to auto wire dateProvider

```<code> @Import(ReplayConfig.class)
    @Configuration
    public class AnotherConfig {
        @Autowired
        private DateProvider dateProvider;

        @Bean
        PortfolioService portfolioService() {
            PortfolioService  portfolioService = new PortfolioServiceImpl(dateProvider, bean(),otherBean());
            return portfolioService
        }
    }
</code>```

this is how we trigger component scan:

```<code><!--******************************************  Scan for JavaConfig  ******************************************-->
<context:component-scan base-package="com.app.config, com.app.common.config">
         <context:exclude-filter type="regex" expression="com\.app\.a4\.systest.*"/>
         <context:exclude-filter type="regex" expression="com\.app\.common\.systest.*"/>
</context:component-scan>
</code>```

And here's how we start the application, and create the context:

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

        try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(getResourcePath())){
            context.setClassLoader(Thread.currentThread().getContextClassLoader());
        }
}
</code>```

答:
I guess instead of Autowiring dateProvider to your AnotherConfig you can try to adjust bean declaration of portfolioService to the following one:

```<code>@Bean
PortfolioService portfolioService(DateProvider dateProvider) {
    PortfolioService  portfolioService = new PortfolioServiceImpl(dateProvider, bean(),otherBean());
    return portfolioService
}
</code>```

Body:
I have a legacy spring application, with a mix of xml and java config. (not my choice sorry). The spring context is initialized from the xml config, which has a component scan instruction to scan the java configs.

There are many java config classes, below are code snippets from 2 of them where I see a problem.
My @Bean DateProvider dateProvider() in ReplayConfig is initialized first, and I can see this by putting a breakpoint in the constructor. And then in AnotherConfig I autowire  @Autowired private DateProvider dateProvider; After having used @Import(ReplayConfig.class).

All good so far, except it turns out the instance of my portfolioService has been passed a null dateProvider. It is frustrating to see experience this, given I can clearly see that dateProvider has been instantiated earlier.

I can actually get it to work if I add to PortfolioServiceImpl

@Autowired setDateProvider(DateProvider dateProvider)

Which I thought would remove all doubt about possibility of confusing packages or different classes with the same name or silly things like that.

The only thing I can think of is something else is wrong. If someone can suggest any ideas it would be great.

Unfortunately I can't get away from the xml initialisation for now.

More code below:

@Import (EnvironmentConfig.class)
@Config
ReplayConfig{
   @Bean
    DateProvider dateProvider() {
        SystemDateProvider systemDateProvider = new SystemDateProvider (bean());
        return systemDateProvider;
    }
}

Then we import that and try to auto wire dateProvider

 @Import(ReplayConfig.class)
    @Configuration
    public class AnotherConfig {
        @Autowired
        private DateProvider dateProvider;

        @Bean
        PortfolioService portfolioService() {
            PortfolioService  portfolioService = new PortfolioServiceImpl(dateProvider, bean(),otherBean());
            return portfolioService
        }
    }

this is how we trigger component scan:

<context:component-scan base-package="com.app.config, com.app.common.config">
         <context:exclude-filter type="regex" expression="com\.app\.a4\.systest.*"/>
         <context:exclude-filter type="regex" expression="com\.app\.common\.systest.*"/>
</context:component-scan>

And here's how we start the application, and create the context:

public static void main(String[] args) {

        try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(getResourcePath())){
            context.setClassLoader(Thread.currentThread().getContextClassLoader());
        }
}

Body:
I guess instead of Autowiring dateProvider to your AnotherConfig you can try to adjust bean declaration of portfolioService to the following one:

@Bean
PortfolioService portfolioService(DateProvider dateProvider) {
    PortfolioService  portfolioService = new PortfolioServiceImpl(dateProvider, bean(),otherBean());
    return portfolioService
}


问:
Debug protractor test in visual studio code(VS code)
I want to debug my protractor project built in Javascript and nodeJS with open source IDE. As I have already tried with this(VS Code), but it is unable to proceed further as there is no "sync" between browser and code.
Can any one please suggest any solution for this or rather any better alternative to this.

Note that I have already tried my luck with :

1.) Webstorm - Can't use because it is a licensed and not allowed in our Organization

2.)elementExplorer - used only for locating elements in interactive mode.

3.) Netbeans - Not supported debugging.

4.) Eclipse with nodeclipse and Webclipse- Not much effective to debug.

5.) Apatana Studio 3.0 - cannot use existing javascript & nodeJS projects .

Kindly help me out . Better solutions are welcome.

Thanks,

答:
in command line run following command:  webdriver-manager start

launch.json file is below

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "node",
      "request": "launch",
      "program": "c:/Users/yourUserName/AppData/Roaming/npm/node_modules/protractor/bin/protractor",
      "args": [
        "${workspaceRoot}/conf.js"
      ],
      "stopOnEntry": false,
      "cwd": "${workspaceRoot}",
      "preLaunchTask": null,
      "runtimeExecutable": null,
      "runtimeArgs": [
        "--nolazy"
      ],
      "env": {
        "NODE_ENV": "development"
      },
      "externalConsole": false,
      "sourceMaps": false
    },
    {
      "name": "Attach",
      "type": "node",
      "request": "attach",
      "port": 5858,
      "address": "localhost",
      "restart": false,
      "sourceMaps": false,
      "localRoot": "${workspaceRoot}",
      "remoteRoot": null
    },
    {
      "name": "launch",
      "type": "node",
      "request": "launch",
      "processId": "${command.PickProcess}",
      "port": 5858,
      "sourceMaps": false,
      "outDir": null
    }
  ]
}
</code>```

Body:
in command line run following command:  webdriver-manager start

launch.json file is below

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "node",
      "request": "launch",
      "program": "c:/Users/yourUserName/AppData/Roaming/npm/node_modules/protractor/bin/protractor",
      "args": [
        "${workspaceRoot}/conf.js"
      ],
      "stopOnEntry": false,
      "cwd": "${workspaceRoot}",
      "preLaunchTask": null,
      "runtimeExecutable": null,
      "runtimeArgs": [
        "--nolazy"
      ],
      "env": {
        "NODE_ENV": "development"
      },
      "externalConsole": false,
      "sourceMaps": false
    },
    {
      "name": "Attach",
      "type": "node",
      "request": "attach",
      "port": 5858,
      "address": "localhost",
      "restart": false,
      "sourceMaps": false,
      "localRoot": "${workspaceRoot}",
      "remoteRoot": null
    },
    {
      "name": "launch",
      "type": "node",
      "request": "launch",
      "processId": "${command.PickProcess}",
      "port": 5858,
      "sourceMaps": false,
      "outDir": null
    }
  ]
}


问:
Calling a polymer function on onchange event in input tag
This is my demo code

```<code><link rel="import" href="../bower_components/polymer/polymer.html">

<script type="text/javascript">
  function myFunction() {
    console.log('this workes');
  }
</script>

<dom-module id="element-a">
  <template>
   <div style="text-align: center;">
    <label for="fileinput" class="custom-file-upload">Change Picture</label>
    <input id="fileinput" type="file" onchange="myFunction()"/>
   </div>
  </template>

<script>
 Polymer({
  is: 'element-a',

   myPolymerFunction: function(){
      console.log('success')
   }
 });
</script>
</dom-module>
</code>```

In the above code when ever I select a new picture the onchange event will be trigered and it will call myFunction(). How do I call a polymer function in the same way?

When I replace onchange with myPolymerFunction it gives the following error

Uncaught ReferenceError: myPolymerFunction is not defined at HTMLInputElement.onchange

答:
Do not use "()" when binding a polymer function.

"onchange" should be "on-change"

```<code><dom-module id="my-element">

  <template>
    <input id="fileinput" type="file" on-change="hello"/>
  </template>

  <script>
    class MyElement extends Polymer.Element {
      static get is() { return 'my-element'; }

      hello(evt) {
        console.log(evt);
      }
    }
    window.customElements.define(MyElement.is, MyElement);
  </script>

</dom-module>
</code>```

JSBin: http://jsbin.com/rixibucepa/edit?html,console,output

Body:
This is my demo code

<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="element-a">
  <template>

    Change Picture
    <input id="fileinput" type="file" onchange="myFunction()"/>

  </template>

</dom-module>

In the above code when ever I select a new picture the onchange event will be trigered and it will call myFunction(). How do I call a polymer function in the same way?

When I replace onchange with myPolymerFunction it gives the following error

Uncaught ReferenceError: myPolymerFunction is not defined at HTMLInputElement.onchange

Body:
Do not use "()" when binding a polymer function.

"onchange" should be "on-change"

<dom-module id="my-element">

  <template>
    <input id="fileinput" type="file" on-change="hello"/>
  </template>

  <script>
    class MyElement extends Polymer.Element {
      static get is() { return 'my-element'; }

      hello(evt) {
        console.log(evt);
      }
    }
    window.customElements.define(MyElement.is, MyElement);
  </script>

</dom-module>

JSBin: http://jsbin.com/rixibucepa/edit?html,console,output


问:
Node.js and ExpressJS body-parser package retrieve data
OK first time user of Node, and I am trying to send data to backend/index.js

Requirements

Post data to back-end node

Retrieve posted data and store values as variables

Whats the problem

The post is 200 success, that works.

however when I navigate to  :

http://localhost:8080/backend/index

I get :

Cannot GET /backend/index

Where am I going wrong ?

Here is my front end post post

```<code>var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8080/backend/index.js",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "id": "1223",
    "token": "223",
    "geo": "ee"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

I am trying to retrieve this data from and store as variable in the back end node.

backend/index.js

```<code>// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/backend/index', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});
</code>```

UPDATE using screen shots

答:
Because you Post Api  and you can not get result without parameter.
Your  Post Api will not give output until you hit only url on web browser, so need postman for Post Api.

Now you get Output without any problem.

Thanks in Advance

Body:
OK first time user of Node, and I am trying to send data to backend/index.js

Requirements

Post data to back-end node

Retrieve posted data and store values as variables

Whats the problem

The post is 200 success, that works.

however when I navigate to  :

http://localhost:8080/backend/index

I get :

Cannot GET /backend/index

Where am I going wrong ?

Here is my front end post post

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8080/backend/index.js",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "id": "1223",
    "token": "223",
    "geo": "ee"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

I am trying to retrieve this data from and store as variable in the back end node.

backend/index.js

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/backend/index', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

UPDATE using screen shots


问:
JMeterTest and JMeterTestManager dependencies
I am trying to exeucte a .jmx file through the java class, but JMeterTest and JMeterTestManager are not getting imported.
JMeter, as per my knowledge is itself a bundle of jar.
can anyone tell me if i need dependency(ies) for these two or not, iif yes the please do provide.
Thanks in advance.</p>

答:
As far as I can see you need to include org.wso2.carbon.automation.extensions to your project as these classes don't come with JMeter API

Check out Five Ways To Launch a JMeter Test without Using the JMeter GUI guide to get started with creating a JMeter test purely in Java. You can also use jmeter-from-code project as a reference