Q: Joss eap 6.4 upgrade to 7.2 :javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype Jboss eap 6.4 upgrade to 7.2 deploy ear error
{"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WLS_DOM_SPS.ear\".FIRST_MODULE_USE" => "WFLYSRV0153: Failed to process phase FIRST_MODULE_USE of deployment \"WLS_DOM_SPS.ear\"
    Caused by: java.util.ServiceConfigurationError: javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype"}}

eclipse link module config :
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.eclipse.persistence">
    <resources>
        <resource-root path="javax.persistence_1.1.0.0_2-0.jar"/>
        <resource-root path="eclipselink-2.1.2_TMSModified1.jar">
            <filter>
                <exclude path="javax/**" />
            </filter>
        </resource-root>
    </resources>

    <dependencies>
        <module name="asm.asm"/>
        <module name="javax.api"/>
        <module name="javax.annotation.api"/>
        <module name="javax.enterprise.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <module name="javax.xml.bind.api"/>
        <module name="org.antlr"/>
        <module name="org.apache.commons.collections"/>
        <module name="org.dom4j"/>
        <module name="org.javassist"/>
        <module name="org.jboss.as.jpa.spi"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.vfs"/>
    </dependencies>
</module>

jboss eap 6.4 can deploy success. Don't know where the problem is.
javax.persistence.jar-javax.persistence.spi.PersistenceProvider
package javax.persistence.spi;

import java.util.Map;
import javax.persistence.EntityManagerFactory;

public interface PersistenceProvider {
    EntityManagerFactory createEntityManagerFactory(String var1, Map var2);

    EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo var1, Map var2);

    ProviderUtil getProviderUtil();
}

eclipselink-org.eclipse.persistence.jpa.PersistenceProvider
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.eclipse.persistence.jpa;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
import org.eclipse.persistence.exceptions.PersistenceUnitLoadingException;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider;
import org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl;
import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceInitializationHelper;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo;
import org.eclipse.persistence.internal.weaving.PersistenceWeaved;

public class PersistenceProvider implements javax.persistence.spi.PersistenceProvider, ProviderUtil {
    protected PersistenceInitializationHelper initializationHelper = null;

    public PersistenceProvider() {
        this.initializationHelper = new PersistenceInitializationHelper();
    }

    public EntityManagerFactory createEntityManagerFactory(String emName, Map properties) {
        ClassLoader classloader = this.initializationHelper.getClassLoader(emName, properties);
        return this.createEntityManagerFactory(emName, properties, classloader);
    }

    protected EntityManagerFactory createEntityManagerFactory(String emName, Map properties, ClassLoader classLoader) {
        Map nonNullProperties = properties == null ? new HashMap() : properties;
        String name = emName;
        if (emName == null) {
            name = "";
        }

        JPAInitializer initializer = this.initializationHelper.getInitializer(classLoader, (Map)nonNullProperties);
        EntityManagerSetupImpl emSetupImpl = null;
        boolean isNew = false;

        String uniqueName;
        String sessionName;
        SEPersistenceUnitInfo factory;
        try {
            factory = initializer.findPersistenceUnitInfo(name, (Map)nonNullProperties, this.initializationHelper);
            if (factory == null) {
                return null;
            }

            if (initializer.isPersistenceUnitUniquelyDefinedByName()) {
                uniqueName = name;
            } else {
                uniqueName = initializer.createUniquePersistenceUnitName(factory);
            }

            sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, factory, uniqueName);
            synchronized(EntityManagerFactoryProvider.emSetupImpls) {
                emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
                if (emSetupImpl == null) {
                    if (EntityManagerFactoryProvider.initialEmSetupImpls != null) {
                        emSetupImpl = (EntityManagerSetupImpl)EntityManagerFactoryProvider.initialEmSetupImpls.remove(uniqueName);
                        if (emSetupImpl != null) {
                            emSetupImpl.changeSessionName(sessionName);
                            factory.setClassLoader(classLoader);
                        }
                    }

                    if (emSetupImpl == null) {
                        emSetupImpl = initializer.callPredeploy(factory, (Map)nonNullProperties, this.initializationHelper, uniqueName, sessionName);
                    }

                    emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
                    EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
                    isNew = true;
                }
            }
        } catch (Exception var18) {
            throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(classLoader, var18);
        }

        if (!isNew) {
            if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
                throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
            }

            boolean undeployed = false;
            synchronized(emSetupImpl) {
                if (emSetupImpl.isUndeployed()) {
                    undeployed = true;
                }

                emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
            }

            if (undeployed) {
                return this.createEntityManagerFactory(emName, properties, classLoader);
            }
        }

        factory = null;

        try {
            EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
            if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
                factory.getServerSession();
            }

            return factory;
        } catch (RuntimeException var15) {
            if (factory != null) {
                factory.close();
            } else {
                emSetupImpl.undeploy();
            }

            throw var15;
        }
    }

    public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
        Map nonNullProperties = properties == null ? new HashMap() : properties;
        EntityManagerSetupImpl emSetupImpl = null;
        boolean isNew = false;
        ClassTransformer transformer = null;
        String uniqueName = PersistenceUnitProcessor.buildPersistenceUnitName(info.getPersistenceUnitRootUrl(), info.getPersistenceUnitName());
        String sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, info, uniqueName);
        synchronized(EntityManagerFactoryProvider.emSetupImpls) {
            emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
            if (emSetupImpl == null) {
                emSetupImpl = new EntityManagerSetupImpl(uniqueName, sessionName);
                isNew = true;
                emSetupImpl.setIsInContainerMode(true);
                transformer = emSetupImpl.predeploy(info, (Map)nonNullProperties);
                EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
            }
        }

        if (!isNew) {
            if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
                throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
            }

            boolean undeployed = false;
            synchronized(emSetupImpl) {
                if (emSetupImpl.isUndeployed()) {
                    undeployed = true;
                }

                transformer = emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
            }

            if (undeployed) {
                return this.createContainerEntityManagerFactory(info, properties);
            }
        }

        if (transformer != null) {
            info.addTransformer(transformer);
        }

        EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
        if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
            factory.getServerSession();
        }

        return factory;
    }

    public ProviderUtil getProviderUtil() {
        return this;
    }

    public LoadState isLoadedWithoutReference(Object entity, String attributeName) {
        return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, attributeName) : LoadState.UNKNOWN;
    }

    public LoadState isLoadedWithReference(Object entity, String attributeName) {
        Iterator setups = EntityManagerFactoryProvider.getEmSetupImpls().values().iterator();

        while(setups.hasNext()) {
            EntityManagerSetupImpl setup = (EntityManagerSetupImpl)setups.next();
            if (setup.isDeployed()) {
                Boolean isLoaded = EntityManagerFactoryImpl.isLoaded(entity, setup.getSession());
                if (isLoaded != null) {
                    if (isLoaded && attributeName != null) {
                        isLoaded = EntityManagerFactoryImpl.isLoaded(entity, attributeName, setup.getSession());
                    }

                    if (isLoaded != null) {
                        return isLoaded ? LoadState.LOADED : LoadState.NOT_LOADED;
                    }
                }
            }
        }

        return LoadState.UNKNOWN;
    }

    public LoadState isLoaded(Object entity) {
        return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, (String)null) : LoadState.UNKNOWN;
    }
}

The above is the interface and implementation of PersistenceProvider.
Can't see any mismatch


Q: Facebook SDK (Require "Like" for access) I only want people that like'd our Facebook page to access a specific section of the site. But i'm relatively new with the Facebook SDK. Is there a way to check whether someone liked our page? If not possible with SDK are there other reliable ways to do so?

A: Like-gating is not allowed by the Facebook platform policies (chapter 4.5).
See

*

*https://developers.facebook.com/policy/#properuse

Only incentivize a person to log into your app, enter a promotion on your app’s Page, or check-in at a place. Don’t incentivize other actions.


Q: How to produce and consume JSON messages between Django services using Redis as a message queue? I am trying to find a way to enable communication between two Django services using Redis as a message queue.
One service would produces JSON data, publish it to the queue and the other one would consume the message.
Something similar to what I want to achieve is described here using Spring Boot and RabbitMQ: https://www.javainuse.com/spring/spring-boot-rabbitmq-consume
Any articles or suggestions would mean a lot.

A: I think there are two things to you think about:

*

*if you want to use redis with django celery (Celery beat).

*if you want to use just redis as M.Q with django.

Below are the references to help you with each case:
For Case 1: check out the link below

*

*https://enlear.academy/hands-on-with-redis-and-django-ed7df9104343
For Case 2: check out the link below

*How can I publish a message in Redis channel asynchronously with python?
(I recommand this one best : https://stackabuse.com/working-with-redis-in-python-with-django/) -- it covers all you need about using redis for caching


Q: xsl 1.0 Group by with comma separated items I have a XML similar to this
<profiles>
<profile>
  <customer>customer a </customer>
  <collateral>
    summary a
   <related>
     <solutions>sol1,sol2</solutions>
   </related>
  <collateral>
</profile>
<profile>
  <customer>customer b </customer>
  <collateral>
    summary b
   <related>
     <solutions>sol1</solutions>
   </related>
  <collateral>
</profile>

<profile>
  <customer>customer c </customer>
  <collateral>
    summary c
   <related>
     <solutions>sol2,sol3</solutions>
   </related>
  <collateral>
</profile>
</profiles>

Desired output

  customer a,summary a
 customer b, summary b

  customer a,summary a
  customer c,summary c

..............
Iam aware of Muenchian way of grouping, but not sure how I can accomplish, if I have comma separated groub-by element values. Any help will be appreciated.

A: While this is straight-forward in XSLT 2.0, in XSLT a two-pass transformation can produce the wanted results:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kSolByVal" match="solution" use="."/>

 <xsl:template match="node()|@*" name="identity">
         <xsl:copy>
           <xsl:apply-templates select="node()|@*"/>
         </xsl:copy>
 </xsl:template>

 <xsl:template match="/">
  <xsl:variable name="vrtfPass1">
   <xsl:apply-templates/>
  </xsl:variable>

  <xsl:apply-templates select=
  "ext:node-set($vrtfPass1)
                /*/*/*/*
                   /solutions/solution
                    [generate-id()
                    =
                    generate-id(key('kSolByVal', .)[1])
                    ]"
   mode="pass2"/>
 </xsl:template>

 <xsl:template mode="pass2" match="solution">

    <xsl:apply-templates mode="pass2"
       select="key('kSolByVal', .)/../../../.."/>

 </xsl:template>

 <xsl:template match="profile" mode="pass2">
  <xsl:if test="position() = 1">
   <xsl:text>
</xsl:text>
  </xsl:if>
  <xsl:value-of select=
      "concat(customer, ', ', */summary, '
')"/>
 </xsl:template>

 <xsl:template match="solutions">
   <solutions>
     <xsl:apply-templates select="." mode="split"/>
   </solutions>
 </xsl:template>

  <xsl:template match="solutions" name="split" mode="split">
   <xsl:param name="pText" select="."/>

   <xsl:if test="string-length($pText)">
    <xsl:variable name="vText1"
         select="concat($pText, ',')"/>
    <xsl:variable name="vPart" select=
       "substring-before($vText1, ',')"/>

     <solution>
      <xsl:value-of select="$vPart"/>
     </solution>

     <xsl:call-template name="split">
      <xsl:with-param name="pText"
           select="substring($pText, string-length($vPart)+2)"/>
     </xsl:call-template>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document (corrected for well-formedness):
<profiles>
    <profile>
        <customer>customer a </customer>
        <collateral>
            summary a
            <related>
                <solutions>sol1,sol2</solutions>
            </related>
        </collateral>
    </profile>
    <profile>
        <customer>customer b </customer>
        <collateral>
            summary b
            <related>
                <solutions>sol1</solutions>
            </related>
        </collateral>
    </profile>
    <profile>
        <customer>customer c </customer>
        <collateral>
            summary c
            <related>
                <solutions>sol2,sol3</solutions>
            </related>
        </collateral>
    </profile>
</profiles>

the wanted, correct result is produced:

customer a , summary a
customer b , summary b

customer a , summary a
customer c , summary c

customer c , summary c

Explanation:

*

*We carry out the transformation in two passes. Pass2 is applied on the result of applying Pass1 on the provided XML document.

*Pass 1 is essentially the identity rule overriden for any solutions element. The processing of a solutions element consists in recursive splitting of its string value. The final result of Pass1 is the following:
--
<profiles>
   <profile>
      <customer>customer a </customer>
      <collateral>
         summary a
         <related>
            <solutions>
               <solution>sol1</solution>
               <solution>sol2</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
   <profile>
      <customer>customer b </customer>
      <collateral>
         summary b
         <related>
            <solutions>
               <solution>sol1</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
   <profile>
      <customer>customer c </customer>
      <collateral>
         summary c
         <related>
            <solutions>
               <solution>sol2</solution>
               <solution>sol3</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
</profiles>

.3. We then apply templates (in mode="pass2") on the result of Pass1. This is a typical and traditional Muenchian grouping.


Q: Is there a way to unload dynamic text once its loaded in Actionscript 3? I'm enlisting your help on how to unload text that dynamically loaded through a text file in Actionscript 3.0.
I have managed to load the data to my stage, but I  want that when the user hits the back button to go home, the data vanishes. At the moment, the data is still appearing even when you hit the back button (whose instance is page3home in the code below.)
Below is my code:
import flash.display.Loader;

var myTextLoader:URLLoader = new URLLoader();
var myTextField_txt:TextField = new TextField();
var myTextUnloader:Loader=new Loader();
var textStyle:TextFormat = new TextFormat();
textStyle.font = "Verdana";
textStyle.size = 14;
myTextField_txt.wordWrap=true;
myTextField_txt.autoSize=TextFieldAutoSize.LEFT;
myTextField_txt.multiline = true;
myTextField_txt.width = 480;
myTextField_txt.height = 300;
myTextField_txt.x = 50;
myTextField_txt.y = 80;

myTextLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void {
myTextField_txt.text = e.target.data;
addChild(myTextField_txt);
     myTextField_txt.setTextFormat(textStyle);
}

myTextLoader.load(new URLRequest("myText.txt"));

up_btn.addEventListener(MouseEvent.CLICK, scrollUp);

function scrollUp(e:MouseEvent):void
{
     myTextField_txt.scrollV--;
}

down_btn.addEventListener(MouseEvent.CLICK, scrollDown);

function scrollDown(e:MouseEvent):void
{
     myTextField_txt.scrollV++;
}

page3home.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_11);

function fl_ClickToGoToAndStopAtFrame_11(event:MouseEvent):void
{
    gotoAndStop(1);

}

A: To remove a DisplayObject ( the text field in your case ) from its parent DisplayObjectContainer, you can use the removeChild() method :
myTextField_txt.parent.removeChild(myTextField_txt);

Then to free the associated memory, you can add :
myTextField_txt = null;

You can also remove all event listeners added to your URLLoader object like this :
myTextLoader.removeEventListener(Event.COMPLETE, onLoaded);

Hope that can help.


Q: Can Tensorflow/Deep Learning be used for Gradient Boosted Trees, Logistic regression? Tensorflow and deep learning has mostly been used for Image Processing (Classification, Identification), NLP, Voice and text processing. I have used Spark MLLIB and Mahout in the past? Tensorflow has examples of Deep Neural Network - https://www.tensorflow.org/tutorials/wide_and_deep. Can logistic regression, Gradient Boosted Trees etc, be modeled in Tensorflow or a DL Framework?

A: Yes, of course. In fact you can find a lot of examples:
There are some ready implementations like tf.contrib.learn.LinearClassifier in https://www.tensorflow.org/tutorials/wide
Or something like this: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py where you use tf.matmul and appropriate activations.
There is even something with gradient boosting: https://arogozhnikov.github.io/2016/07/05/gradient_boosting_playground.html


Q: Join one array with multiple index php How to join 2 arrays with multiple index into 1 array ?
I have array like this
Array
(
    [0] => Array
        (
            [wd[wd5][amount]] => 1.00
            [wd[wd5][address]] => 1BitcoinAddress
            [wd[wd5][currency]] => BTC

        )

    [1] => Array
        (
            [wd[wd7][amount]] => 1.00
            [wd[wd7][address]] => 1BitcoinAddress
            [wd[wd7][currency]] => BTC

        )

)

I want to convert/change/merge that array into something exactly like this
array(
        'wd[wd5][amount]' => 1.00,
        'wd[wd5][address]' => '1BitcoinAddress',
        'wd[wd5][currency]' => 'BTC',
        'wd[wd7][amount]' => 0.0001,
        'wd[wd7][address]' => '1BitcoinAddress',
        'wd[wd7][currency]' => 'BTC'

);

how do I do that ?

A: Using call_user_func_array and array_merge
<?php

$array = [

    [
        "[wd[wd5][amount]]" => 1.00,
        "[wd[wd5][address]]" => "1BitcoinAddress",
        "[wd[wd5][currency]]" => "BTC"
    ],
    [
        "[wd[wd7][amount]]" => 1.00,
        "[wd[wd7][address]]" => "1BitcoinAddress",
        "[wd[wd7][currency]]" => "BTC"
    ]
];

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

A: Loop the array using foreach and create an new array.
$new_array = array();
foreach($array as $value){
    foreach($value as $k=>$v){
        $new_array[$k] = $v;
    }
}
print_r($new_array);

Output:
Array
(
    [wd[wd5][amount]] => 1.00
    [wd[wd5][address]] => 1BitcoinAddress
    [wd[wd5][currency]] => BTC
    [wd[wd7][amount]] => 1.00
    [wd[wd7][address]] => 1BitcoinAddress
    [wd[wd7][currency]] => BTC
)

A: you can do this like:
$result = array();
foreach($array as $item) {
    $result = array_merge($result, $item);
}

here $result is a new blank array, and $array is the array to merge.

A: You can do it using RecursiveIteratorIterator and RecursiveArrayIterator.
Though I'm liking @BilalAkbar's answer abit more now for the simplicity.
<?php
$array = [
    [
        'wd[wd5][amount]' => 1.00,
        'wd[wd5][address]' => '1BitcoinAddress',
        'wd[wd5][currency]' => 'BTC',
    ],
        [
        'wd[wd7][amount]' => 1.00,
        'wd[wd7][address]' => '1BitcoinAddress',
        'wd[wd7][currency]' => 'BTC'
    ],

];

$result = [];
foreach (new RecursiveIteratorIterator(
         new RecursiveArrayIterator($array)
) as $key => $value) {
  $result[$key] = $value;
}

print_r($result);
/*
Array
(
    [wd[wd5][amount]] => 1
    [wd[wd5][address]] => 1BitcoinAddress
    [wd[wd5][currency]] => BTC
    [wd[wd7][amount]] => 1
    [wd[wd7][address]] => 1BitcoinAddress
    [wd[wd7][currency]] => BTC
)
*/

https://3v4l.org/0fCKj

A: Use array_merge to merge combine the arrays.
http://php.net/manual/en/function.array-merge.php
<?php

$arrayWithSubarrays = array(
    array(
        "[wd[wd5][amount]]" => 1.00,
        "[wd[wd5][address]]" => "1BitcoinAddress",
        "[wd[wd5][currency]]" => "BTC"
    ),
    array(
        "[wd[wd7][amount]]" => 1.00,
        "[wd[wd7][address]]" => "1BitcoinAddress",
        "[wd[wd7][currency]]" => "BTC"
    )
);

// merge each array explicitly:
$mergedArray1 = array_merge($arrayWithSubarrays[0],$arrayWithSubarrays[1]);

// or merge as many as you have in the array:
$mergedArray2 = array();
foreach($arrayWithSubarrays as $array) {
    $mergedArray2 = array_merge($mergedArray2, $array);
}

// (mergedArray1 contains the same data as mergedArray2)

A: Here answer, but you have 2 solution one different key then below answer.
otherwise only save array last values beacause every time  3 keys same.
hope you understand.
<?php

$a = array
(
     array
        (
            'wd[wd[amount]]' => '1.00',
            '[wd[wd5][address]]' => '1BitcoinAddress',
            '[wd[wd5][currency]]' => 'BTC'

        ),

    array
        (
            'wd[wd[amount1]]' => '1.00',
            '[wd[wd5][address1]]' => '1BitcoinAddress',
            '[wd[wd5][currency1]]' => 'BTC'
        )

);
$total = count($a);
$p = array();
$q = array();
$pq = array();
for($i=0;$i<$total;$i++){
    $tarray = $a[$i];
    foreach($tarray as $k=>$v){
        array_push($p,$k);
        array_push($q,$v);

    }
}
$pq = array_combine($p,$q);
print_r($pq);

?>


Q: How can I sync my maven artifacts to jcenter? I have deploy my fist version to the maven central repository. Now I want sync this to JCenter / Bintray. Is this possible and how can I do this?

A: Yes, all you need to do is just download your artifacts from JCenter.
On a related note, I'd suggest doing it the other way around - publish to JCenter and sync to Central. It should be easier for you.

I am with JFrog, the company behind Bintray and [artifactory], see my profile for details and links.


Q: ICE Faces fileInput file path and file name properties I'd like to utilize an ICE Faces fileInput control to fill in the file path & file name for the input to an input field on a web page based on file that the user selects. How can I capture these properties without actually performing any file transfer operations?

A: I believe that the real answer is that you can't.  The file path won't be sent by the browser for security reasons.  The file name will be sent, however I don't believe it gets sent without an actual upload.
The closest you could come, afaik, would be to forcibly kill the connection just when the upload starts.  That would net you the filename with little actual transferred data, but it doesn't sound like it would be useful to you.
Alternatively, a signed Java applet might get you closer to a solution that you'd want.


Q: How to download a file from a VDI (citrix workspace) Artifactory through Python I have a question regarding VDI, Artifactory, and Python.
I wanted to download an artifact that I have tested inside the VDI with the command:
curl https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml --output filename.xml

It outputs an XML file, just what I wanted.
I tried doing the same with the Python requests module on my computer (download.py):
import requests

r = requests.get('https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml')
with open("filename.xml", "wb") as file:
    file.write(r.content)

and it returns an error :
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

then
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='artifactory-scanner.asml.com', port=443): Max retries exceeded with url: /artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

To access these file I am required to connect to a VPN. I am connected to the VPN and are able to get the data inside the VDI. But during my Python run, it does not connect. Anybody know what seems to be the problem here?

A: Based on the error snippet shared during the artifact download from the Artifactory application, it looks like there is a connectivity issue from the client(your computer) to Artifactory. You can validate the connectivity using the telnet from your computer to connect to the Artifactory IP/port.
Also, you can validate the Artifactory request logs to check whether the request is reaching the application or not.


Q: Data selection/Row selection I have a scenario where I have to write a SQL query where I consider only the negative values for selected date.
how to achieve the output

what i want is to convert all non negative numbers to zero for a particular date. In this case 2021.

A: You seem to be looking for a conditional sum. The logic is to put a case expression within the aggregate function, like so:
select
    sum(case when "2020" < 0 then "2020" else 0 end)  result_2020,
    sum(case when "2021" < 0 then "2021" else 0 end)  result_2021
from mytable

It is quite unusal to have columns with all-digits names such as 2020, so I wonder whether what you are showing is your actual sample data or the results of an intermediate query (in which case, further optimizations may be possible).

Edit
The above answers the original version of the question. This answers the edited question:
You can use a case expression to turn positive numbers for date 2021 to 0:
select
    fab,
    date,
    case when output > 0 and date = 2021
         then 0
         else output
    end output
from mytbale

A: Say if you have a table like below

I think you are looking for something like this
SELECT id,
    year,
    (case when (a>0 and year = 2021) then 0 else a end) as a_filtered,
    (case when (b>0 and year = 2021) then 0 else b end) as b_filtered
FROM `table_name`
WHERE 1

The output will be the following.


Q: PHP batch extract DB row BLOBs to files We are in the midst of a data migration , and the project needs from one particular table BLOB data saved to files, and sent to the vendor, due to their structure
I am able to achieve this one at a time, but needed to create a batch process, as there are 50,000 rows/potential files.
my current code is
 $sql = "SELECT a.guid  AS file_name, a.attachment AS file_blob"
     ." FROM attachment a";

 $squery = oci_parse($link, $sql);
 oci_execute($squery);

 while ($row = oci_fetch_array($squery, OCI_ASSOC | OCI_RETURN_LOBS)) {
    header('Content-type: octet-stream;');
    header('Content-disposition: attachment;filename='.$row['FILE_NAME']);
    print $row['FILE_BLOB'];
    }

oci_free_statement($squery);

I do understand that I would rather be saving the data rather than streaming it to the browser, I just am not wrapping my head around how to achieve this, should i be looking at php file I/O fputs()?
End result is I would like the process to batch write binary files based on the query to a folder
EDIT
Thank you for your direction and help, based on that I ended up coming up with two separate ways to achieve this
first i did the following getcwd() to verify where the server was pointing to, and did an absolute path if needed
 $basedir = '/path/to/host/www/blobdoc/';

set permissions on the blobdoc folder then used either of the following scripts in the while loop
 $filename='';
 $filename=$basedir.$row['FILE_NAME'];
 file_put_contents( $filename, $row['FILE_BLOB']);

 $filename='';
 $filename=$basedir.$row['FILE_NAME'];
 $File = @fopen( $filename, 'w' );
 if( $File ) {
      if( FALSE === fwrite( $File, $row['FILE_BLOB'] ))
      return FALSE;
 fclose( $File );
 return TRUE;
 }

A: Instead of:
print $row['FILE_BLOB'];
Use something like:
file_put_contents( $filename, $row['FILE_BLOB']); //save locally
You need to write the blob to a file.
If you want to force a download of that file then you need to make use of the correct headers in combinarion with readfile, like so:
$file = '/var/www/html/file-to-download.zip';
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);


Q: Efficient way to get median in a unindexed table I am trying to find median salary in this table.
Is there an aggregate function like AVG() to find a median in an unindexed table efficiently? Thanks.
id | Salary
-----------
1    300
2    250
7    180
8    150
9    150
10   160
11   180
15   140

A: There is no MEDIAN() function in MySQL but there is a somewhat simple way to calculate it as demonstrated on this website:
https://www.eversql.com/how-to-calculate-median-value-in-mysql-using-a-simple-sql-query/
Assuming your table is named salaries:
SET @rowindex := -1;

SELECT
   AVG(salary)
FROM
   (SELECT @rowindex:=@rowindex + 1 AS rowindex,
           salaries.salary AS salary
    FROM salaries
    ORDER BY salaries.salary) AS s
WHERE
s.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2));

Explanation:

*

*Let's start with the internal subquery - the subselect assigns @rowindex as an incremental index for each salary that is selected, and sorts the salaries.

*Once we have the sorted list of salaries, the outer query will fetch the middle items in the array. If the array contains an odd number of items, both values will be the single middle value.

*Then, the SELECT clause of the outer query returns the average of those two values as the median value.

A: select avg(Salary)
from
(
select *,
         ROW_NUMBER() over (order by Salary desc) as desc_salary,
         ROW_NUMBER() over (order by Salary asc) as asc_salary
from Table_Name
) as a
where asc_salary in (desc_salary,desc_salary+1, desc_salary-1)


Q: Google Analytics API - Integration With Symfony2 I am trying to gain access to Google Analytics API through OAuth2.
What i did:

*

*Open developers console > APIs and Auth > Credentials

*Create a new Client ID

*Generate p12 key

*Copy the key on the server

*Open google analytics page > admin > Account > User Management

*Add the email from generated Client ID, something like:    xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com

*Give to this email Read and Analyze permissions

*Then when I go back to developers console > permission.    The new email is added on Service accounts with Edit permissions

*Recheck if Google Analytics is enabled and data is going in.
Now I had installed widop/google-analytics-bundle and configure the bundle:
widop_google_analytics:
    client_id:        "xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com"
    profile_id:       "ga:12345678"
    private_key_file: "mykey.p12"
    http_adapter:     "widop_http_adapter.curl"

And the query I try to create is:
        $profileId = 'ga:12345678';
        $query = new Query($profileId);

        $query->setStartDate(new \DateTime('-2months'));
        $query->setEndDate(new \DateTime());

        $query->setMetrics(array('ga:visits' ,'ga:bounces'));
        $query->setDimensions(array('ga:browser', 'ga:city'));

        $query->setSorts(array('ga:country', 'ga:browser'));

        $query->setFilters(array('ga:browser=~^Firefox'));

        $query->setSegment('gaid::10');

        $query->setStartIndex(1);
        $query->setMaxResults(10000);
        $query->setPrettyPrint(false);
        $query->setCallback(null);

        $clientId = 'xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com';
        $privateKeyFile = 'mykey.p12';
        $httpAdapter = new CurlHttpAdapter();

        $client = new Client($clientId, $privateKeyFile, $httpAdapter);
        $token = $client->getAccessToken();

        $service = new Service($client);
        $response = $service->query($query);

        return $response;

As a response I get this error:
User does not have sufficient permissions for this profile.

When I open developers console > overview > 1 hour (tab)
I had notice that requests are going in.
From all that - I assume that authentication and query is OK but the user has no permissions to get any kind of data which is weird because I had granted Read and Analyze permissions to
xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com
What could by the reason for that exception?

A: I do not know if you already solved this issue.
The solution for me was use the view ID instead of account ID on the analytics account.
The view ID is on the third column in settings, on Google Analytics administration panel.
Sorry for my english.


Q: Merge two directories keeping larger files Consider for example
mkdir dir1
mkdir dir2

cd dir1
echo "This file contains something" > a
touch b
echo "This file contains something" > c
echo "This file contains something" > d
touch e

cd ../dir2
touch a
echo "This file contains something" > b
echo "This file contains something" > c
echo "This file contains more data than the other file that has the same name but is in the other directory.  BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla. bla!" > d

I would like to merge dir1 and dir2. If two files have the same name, then only the one which size is the largest must be kept. Here is the expected content of the merged directory
a # Comes from `dir1`
b # Comes from `dir2`
c # Comes from either `dir1` or `dir2`
d # Comes from `dir2`
e # Comes from `dir1`(is empty)

A: Assuming that no file name a newline:
find . -type f -printf '%s %p\n' \
  | sort -nr \
  | while read -r size file; do
    if ! [ -e "dest/${file#./*/}" ]; then
      cp "$file" "dest/${file#./*/}";
    fi;
   done

The output of find is a list of "filesize path":
221 ./dir1/a
1002 ./dir1/b
11 ./dir2/a

Then we sort the list numeric:
1002 ./dir1/b
221 ./dir1/a
11 ./dir2/a

And fianlly we reach the while read -r size filename loop, where each file is copied over to the destination dest/${file#./*/} if they don't already exists.
${file#./*/} expands to the value of the parameter file with the leading directory removed:
./abc/def/foo/bar.txt -> def/foo/bar.txt, which means you might need to create the directory def/foo in the dest directory:
  | while read -r size file; do
    dest=dest/${file#./*/}
    destdir=${dest%/*}
    [ -e "$dest" ] && continue
    [ -e "$destdir" ] || mkdir -p -- "$destdir"
    cp -- "$file" "$dest"
   done

A: I cannot comment on the other answer due to not enough reputation, but I was getting a syntax error due to missing fi. I also got an error where the target directory needed to be created before copying. So:
find . -type f -printf '%s %p\n' | sort -nr | while read -r size file; do if ! [ -e "dest/${file#./*/}" ]; then mkdir -p "$(dirname "dest/${file#./*/}")" && cp "$file" "dest/${file#./*/}"; fi; done


Q: What is the best way to instruct user to capture a clear or better image of a document.? I am working on an app where user needs to click an image of a document and upload and server will do the further processing of doing OCR and extracting specific data from it. OCR and data extraction completely depends on the image quality. So what is the best way, i can instruct user to take a near to perfect image of document at run-time.
Factors i am considering.
1) Light available while capturing image
(Can't use the light sensor because it is present on front side of phone whereas document will be on bottom side)
2) Document angle.
(Tried edge detection using openCV but not properly works on white document with light color background surface. Any Edge detection tutorial for run-time document detection over custom camera surface will also be a  great help)
3) Distance from document.
Processing the image after capturing (Transforming the document to a rectangle using openCV) is not always giving a great result with OCR because of character distortion.
So please suggest some way to instruct the user to take a better image of straight document from a perfect distance and better lightening conditions. And also after capturing best way to judge the image quality.

A: If proportions of document is known, you can draw appropriate inner (for min document size) and outer (for max document size) bounding rectangles on preview (as shown on pict)  and control that user positioned document within outer and over inner bounding rect. That is also helps to control right document angle. Also You can control tilt and orientation of smartphone as described in answers for this questions.
Then process preview image (or even its small copy) on-the-fly with lightweight quality estimation algorithms and inform user about low quality and its reason (e.g. low brightness, you can estimate brightness of outer rectangle region, for example, as described in this question) and, may be, block "take snapshot" control.

A: You can use classifier (Machine Learning techniques) to reject low quality images using various features which can differentiate between low and good quality or images captured from long distance by detecting the document in the image.


Q: How do I change the data type in an HDF5 file from MATLAB? I have a HDF5 datafile that has an array of int32 data values. I wish to change the data stored in that array to different values which are of a different format (double).
for example I can query the data type with the following:
 finf=h5info('file.hdf5');
 finf.Datasets(1).Datatype

 ans =

      Name: ''
      Class: 'H5T_INTEGER'
      Type: 'H5T_STD_I32LE'
      Size: 4
      Attributes: []

If I try to recreate the data in the same node location it gives me the following error that the data set already exists:
t=double(h5read([filepath filename],'/t'));

% more t calculations here....

h5create('file.hdf5','/t',size(t),'DataType','double');

Error using h5create>create_dataset (line 159)
The dataset '/t' already exists.

Error in h5create (line 69)
create_dataset(options);

I've looked in the Matlab docs for a function for deleting a data set in an hdf5 file but can't find any references.  Any one have any ideas?

A: It is not possible to either delete a dataset or change its datatype. From section 5.3.2 of the HDF5 manual:
The datatype is set when the dataset is created and can never be changed.

This is due to how space is assigned in an HDF5 file. While it's not possible to delete a dataset (for the same reasons), it can be "unlinked" and be made inaccessible, but this does not reclaim the used space.
If you really need to change the datatype, you have two choices: the first is to unlink the old dataset and create a new one in its place. The new dataset can have the same name as the old one. However, if space is a concern, you may prefer to just create an entirely new HDF5 file, and copy the old data into the new one.

A: According to This post which is a similar problem there is no mechanism for deleting a dataset in an HDF5 file. It also indicates that it is possible to Modify in place.


Q: Plotting multiple probability distributions in a single graph in R I tried to plot probability distributions from different sources in a single plot. I used the following codes.
require(ggplot2)
require(ggfortify)
p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.777409 , shape2 = 2.7947, fill ='blue')
p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.934973 , shape2 = 2.553981, fill ='red', p=p)
ggdistribution(dbeta, seq(0,1,0.01), shape1 = 0.93427 , shape2 = 1.777248, fill ='green', p=p)

Is it possible to use point values (min, max, median and interquartile range) instead of shape1 and shape 2 to plot the distributions?


Q: Error: Can't set headers after they are sent Node.js and ExpressJS I am using Node.js and ExpressJS to save a mongoose model. I am getting the error of Error: Can't set headers after they are sent. I think it has to do with the line res.redirect("/dashboard/it/model"); conflicting with setRedirect({auth: '/login'}), from my route, the code in the setRedirect is below labeled. The setRedirect is from a middleware called middleware-responder that came as part of the template I am using to create Stripe user accounts. I can not remove it as far as I know. my GitHub repo I have committed all files that are not test files and are relevant (no unneeded views ect than what is already there)
Save Model
if(type=="aps"){
      var newAccessPoint = {
          name: name,
          manufacturer: manufacturer,
          model: model,
          range: range,
          bands: bands,
          channel: channel,
          poe: poe,
          notes: notes,
          signout: signout,
          author:author
        };
      // Create a new access point and save to DB
      AP.create(newAccessPoint, function(err, newlyCreated){
          if(err){
              console.log(err);
          } else {
              //redirect back to models page
              res.redirect("/dashboard/it/model");
          }
      });
    }

Route
app.post('/dashboard/it/model/new',
    setRender('dashboard/it/modelCreate'),
    setRedirect({auth: '/login'}),
    isAuthenticated,
    dashboard.getDefault,
   (req, res) => {

setRedirect code
exports.setRedirect = function(options){
  return function(req, res, next){
   if(req.redirect){
     req.redirect = _.merge(req.redirect, options);
   } else {
     req.redirect = options;
   }
   next();
 };
};

setRender code
exports.setRender = function(view){
  return function(req, res, next){
    req.render = view;

    next();
  };
};

A: That's happening because you are trying to send a response to the client when you already closed the connection.
Hard to tell by the way you are showing us your code but it seems like you are redirecting to options and then in the same request you are redirecting to dashboard/it/model

A: I pull your code from github.
I think the error message was clear. in your getDefault() middleware you are rendering a response so the server start sending data to your client and just after you try to redirect him to another url. Thats why when your comment out that middleware all work nicely.


Q: Sqlite3.Binary gives TypeError: buffer object expected I have a list which I extracted from a txt file as follows:
authors = re.match('#@(.*)', line)
if authors:
   authors_list = authors.group(1).split(",")

Now I need to insert these into my database, which should be done as follows:
for a in authors_list:
    c.execute("INSERT INTO authors(Name) VALUES (?)", (a))

But when I do that I get the following error:
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 17 supplied.

So I did some research and found that I should change my variable a into a tuple (a, ) as such:
c.execute("INSERT INTO authors(Name) VALUES (?)", (a,))

And I also tried this:
c.execute("INSERT INTO authors(Name) VALUES (?)", ((a,)))

But got the following error:
ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

So I did more research and found that I should use sqlite3's Binary function. So I tried the following:
c.execute("INSERT INTO authors(Name) VALUES (?)", (sqlite3.Binary((a,))))

And got the following error:
TypeError: buffer object expected

I keep going back and forth between all three errors no mater what combination I try. Any help would be appreciated. I don't know what I'm doing wrong.

A: You are passing in a tuple, not a bytestring:
sqlite3.Binary((a,))

Create a tuple with the result of sqlite3.Binary(), having passed in just a:
(sqlite3.Binary(a),)

The whole statement is then run as:
c.execute("INSERT INTO authors(Name) VALUES (?)",
          (sqlite3.Binary(a),))

However, if this is supposed to be text, you'd normally decode the bytes to a string instead of trying to insert binary data:
c.execute("INSERT INTO authors(Name) VALUES (?)",
          (a.decode('utf8'),))

This does assume that your text is encoded using the UTF-8 codec; adjust the decoding as needed to match your data.


Q: react conditional component rendering I'm currently trying to create a React component to upload and crop an image using Croppie library.
I've found this code sample
import "croppie/croppie.css"
import { Button, Grid } from "@material-ui/core"
import * as React from "react"
import Croppie from "croppie"

export function CroppieExample() {
  const [image, setImage] = React.useState("")
  const [croppie, setCroppie] = React.useState<Croppie | null>(null)

  function handleImage(image: string) {
    setImage(image)
    const el = document.getElementById("image-helper")
    if (el) {
      const croppieInstance = new Croppie(el, {
        enableExif: true,
        viewport: {
          height: 250,
          width: 250,
        },
        boundary: {
          height: 280,
          width: 400,
       }
    });
    croppieInstance.bind({
      url: image,
    });
    setCroppie(croppieInstance)
    }
  }

  function handleSubmit(event: any) {
    event.preventDefault()
    if (croppie !== null) {
      croppie.result({type: 'base64',
      size: {
          width: 480,
          height: 480
      }}).then((blob) => {
        console.log(blob)
      }
      )
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <Grid container spacing={2}>
        {image === "" && (
            <Grid item xs={12}>
                {/* Your image upload functionality here */}
                <ImageUpload image={image} setImage={handleImage} />
            </Grid>
            )}
        {image !== "" && (
            <Grid item container justify="center" xs={12}>

            </Grid>
            )}
        <Grid container item xs={12} justify="flex-end">
          <Button color="primary" variant="contained" type="submit">
            Submit
          </Button>
        </Grid>
      </Grid>
    </form>
  )
}

I've a question regarding the conditional part of this piece of code:
In order to work, a Croppie instance must be attached to the div element "image-helper". The handleImage event is in charge of the croppieInstance creation. But by the time it is called, it seems that  is not rendered so no croppie instance can be created.
Is my assumption right?
If it's the case, what would be the React way to correct the code?
Thank you for your help

A: Yes your analysis is right. The code snippet is egregious. The correct way in React to initialize any code when DOM elements are finally available is via a callback ref.
const initImageHelper = useCallback(
  (element) => {
    if (element) {
      const croppieInstance = new Croppie(element, settings);
      croppieInstance.bind({ url: image });
      setCroppie(croppieInstance);
    }
  }, [image]
);

          {image !== "" && (
            <Grid item container justify="center" xs={12}>

            </Grid>
          )}


Q: clean-webpack-plugin only accepts an options object I'm getting

Error: clean-webpack-plugin only accepts an options object. See:
    https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-

My Webpack.config.js file looks like this:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

var plugins = [
    new CleanWebpackPlugin(['dist'], {}),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new CopyWebpackPlugin([{
        from: './src/images/',
        to: './images/'
    }]),
    new HtmlWebpackPlugin({
        inject: false,
        template: 'src/index.html'
    })
];

var config = {
    entry: [
        './src/js/main.js'
    ],

    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
        filename: 'js/bundle.js',
    },

    plugins: plugins.concat([
        new ExtractTextPlugin('css/bundle.css'),
        //new webpack.optimize.UglifyJsPlugin(require('./uglifyjs.json'))
    ]),
    devServer: {
        inline: true,
        port: 8080
    },

    module: {
        loaders: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            include: path.join(__dirname, 'src'),
            loader: 'babel',
            query: {
                presets: ['react', 'es2015']
            }},
            {
                test: /.s?css$/,
                include: path.join(__dirname, 'src'),
                loader: ExtractTextPlugin.extract('style', [
                    'css?sourceMap',
                    'postcss',
                    'sass?sourceMap'
                ])
            },
            {
                test: /\.css$/,
                include: path.join(__dirname, 'node_modules'),
                loader: 'style!css'
            }
        ]
    },
    postcss: function() {
        return [
            require('autoprefixer')({
                browsers: ['last 2 versions']
            })
        ];
    }
}
module.exports = config;

A: Like @AKX mentioned, newest version of clean-webpack-plugin doesn't accept array argument anymore.
The path which should be clearing is reading from webpack's output.path. In your example code it's here:
output: {
  path: path.join(__dirname, 'dist'),
  // rest of code
},

You should be very carefull, because someones still use pattern like this:
output: {
  path: __dirname,
  filename: './dist/bundle.js'
},

Above configuration will cause removing all files in your project!
If you need to clear only some files from webpack's output.path you should set cleanOnceBeforeBuildPatterns field in object passed into CleanWebpackPlugin constructor.

A: As you can see from the page the error message links, CleanWebpackPlugin does not accept two arguments as you're passing in:
new CleanWebpackPlugin(['dist'], {}),

Instead, just try
new CleanWebpackPlugin(),

if you don't need to pass in any options.
You may be seeing this problem if you're, say, following an older tutorial or such which uses a different version of the plugin, and the interface has changed meanwhile.


Q: Some more advanced recursion I've been looking around for awhile now, and I haven't found anything that helped me. I have to write a program that uses one method (the main method) to read in the size of/and elements of an array. Then I must write a recursive method titled "forwardsEqualBackwards" which returns true if the elements of the array can be read the same way regardless of whether the array is read forwards or backwards (it's a a test to see whether or not it's a palindrome) and false otherwise.

A: pseudocode:
bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0)
{
  if (indexToLookAt >= length-indexToLookAt-1)
    return true; //reached end of recursion
  if (a[indexToLookAt] == a[length-indexToLookAt-1])
    return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here
  else
    return false;
}

forwardsEqualBackwards("",0);  //returns true
forwardsEqualBackwards("a",1);  //returns true
forwardsEqualBackwards("otto",4);  //returns true
forwardsEqualBackwards("otsto",5);  //returns true
forwardsEqualBackwards("otstou",5);  //returns false

A: bool method(int start, int end)
{
     if(start<=end)
     {
           if(Array[start]!=array[end])
                 return false;
           return method(start+1, end-1)
     }
     return true;

}


Q: Simplify and summarize data table in R One of my data set is as follows
name  alias (list of alias)
x     c("R","V","Q")
y     "Z"
q     c("A", "R", "M")
w     c("C","A","R")

I would like to first simplify the table as follows
name alias
x  "R"
x  "V"
x  "Q"
y  "Z"
q  "A"
q  "R"
q  "M"
w  "C"
w  "A"
w  "R"

and later modify the data to get
alias name
"R"   c(x,q,w)
"V"   x
"Q"   x
"Z"   y
"A"  c(q,w)
"M"  q
"C"  w

How can I achieve this in R?
Here is the actual data set
> \dput(head(cases))
structure(list(caseid = c(7703415, 7758128, 7858259, 8802954,
8829620, 8847200), tcount = c(2L, 2L, 3L, 10L, 4L, 2L), helplinks = c("character(0",
"c(\"60107\", \"56085\", \"57587\", \"3000020\"", "character(0",
"character(0", "c(\"60107\", \"3000023\", \"3000020\", \"60107\", \"56085\", \"57587\"",
"character(0")), .Names = c("caseid", "tcount", "helplinks"), row.names = c(NA,
6L), class = "data.frame")

> head(cases)
   caseid tcount                                                  helplinks
1 7703415      2                                                character(0
2 7758128      2                     c("60107", "56085", "57587", "3000020"
3 7858259      3                                                character(0
4 8802954     10                                                character(0
5 8829620      4 c("60107", "3000023", "3000020", "60107", "56085", "57587"
6 8847200      2                                                character(0

A: New answer
Use cSplit from my "splistackshape" package:
cSplit(cases, "helplinks", ",", "long")[, helplinks := gsub(
  'character\\(0|c\\(|\\"', "", helplinks)][, list(
    caseid = list(caseid)), by = helplinks]
#    helplinks                          caseid
# 1:           7703415,7858259,8802954,8847200
# 2:     60107         7758128,8829620,8829620
# 3:     56085                 7758128,8829620
# 4:     57587                 7758128,8829620
# 5:   3000020                 7758128,8829620
# 6:   3000023                         8829620

Old answer
I'm assuming you're starting with something like this:
df <- data.frame(
  name = c("x", "y", "q", "w"),
  alias = I(list(c("R","V","Q"), "Z", c("A", "R", "M"), c("C","A","R")))
)
df
#   name   alias
# 1    x R, V, Q
# 2    y       Z
# 3    q A, R, M
# 4    w C, A, R

If that's the case, here's one approach using listCol_l from my "splitstackshape" package in conjunction with "data.table".
library(splitstackshape)
listCol_l(df, "alias")[, list(name = list(name)), by = alias_ul]
#    alias_ul  name
# 1:        R x,q,w
# 2:        V     x
# 3:        Q     x
# 4:        Z     y
# 5:        A   q,w
# 6:        M     q
# 7:        C     w

You don't really need "splitstackshape" for that, so if you want to remove the self-promotion part of my answer and just use "data.table", you could do:
library(data.table)
as.data.table(df)[, list(
  alias = unlist(alias)), by = name][, list(
  name = list(name)), by = alias]

A: First we clean up the "character(0"'s. Then we read in those character values that were once lists but now need to be scan-ned. Then we apply a function that makes a dataframe from every line:
good.case <- cases[ grepl("c\\(", cases$helplinks),]
 lapply( split(good.case, row.names(good.case) ), function(d){
   vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="")
   do.call( data.frame, list(caseid=d$caseid, alias=vec) )
 }
 )
#-------
#Read 4 items
#Read 6 items
$`2`
   caseid   alias
1 7758128   60107
2 7758128   56085
3 7758128   57587
4 7758128 3000020

$`5`
   caseid   alias
1 8829620   60107
2 8829620 3000023
3 8829620 3000020
4 8829620   60107
5 8829620   56085
6 8829620   57587

 expanded <- lapply( split(good.case, row.names(good.case) ), function(d){
    vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="")
    do.call( data.frame, list(caseid=rep(d$caseid, length(vec)), alias=vec) )
  }
  )
#Read 4 items
#Read 6 items

Now we bind the dataframes together:
 do.call(rbind, expanded)
#---------------
     caseid   alias
2.1 7758128   60107
2.2 7758128   56085
2.3 7758128   57587
2.4 7758128 3000020
5.1 8829620   60107
5.2 8829620 3000023
5.3 8829620 3000020
5.4 8829620   60107
5.5 8829620   56085
5.6 8829620   57587

But only half the way there I suppose. No point in pursuing further with Ananda's 5 caret answer sitting there.


Q: How to convert NSDictionary to custom object I have a json object:
@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;

- (NSMutableDictionary *)toNSDictionary;
...

- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    return dictionary;
}

In string this is:
{
  "Title" : "test",
  "Weight" : "32",
  "OrderId" : "55"
}

I get string JSON with code:
NSMutableDictionary* str = [o toNSDictionary];

    NSError *writeError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Now I need to create and map object from JSON string:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];

This returns me filled NSDictionary.
What should I do to get object from this dictionary?

A: Assuming that your properties names and the dictionary keys are the same, you can use this function to convert any object
- (void) setObject:(id) object ValuesFromDictionary:(NSDictionary *) dictionary
{
    for (NSString *fieldName in dictionary) {
        [object setValue:[dictionary objectForKey:fieldName] forKey:fieldName];
    }
}

A: this will be more convenient for you :
 - (instancetype)initWithDictionary:(NSDictionary*)dictionary {
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dictionary];}
        return self;
    }

A: Add a new initWithDictionary: method to Order:
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
    if (self = [super init]) {
        self.OrderId = dictionary[@"OrderId"];
        self.Title = dictionary[@"Title"];
        self.Weight = dictionary[@"Weight"];
    }
    return self;
}

Don't forget to add initWithDictionary's signature to Order.h file
In the method where you get JSON:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Order *order = [[Order alloc] initWithDictionary:dict];

A: If the property names on your object match the keys in the JSON string you can do the following:
To map the JSON string to your Object you need to convert the string into a NSDictionary first and then you can use a method on NSObject that uses Key-Value Coding to set each property.
NSError *error = nil;
NSData *jsonData = ...; // e.g. [myJSONString dataUsingEncoding:NSUTF8Encoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingOptionsAllowFragments error:&error];

MyObject *object = [[MyObject alloc] init];
[object setValuesForKeysWithDictionary:jsonDictionary];

If the keys do not match you can override the instance method of NSObject -[NSObject valueForUndefinedKey:] in your object class.
To map you Object to JSON you can use the Objective-C runtime to do it automatically. The following works with any NSObject subclass:
#import <objc/runtime.h>

- (NSDictionary *)dictionaryValue
{
    NSMutableArray *propertyKeys = [NSMutableArray array];
    Class currentClass = self.class;

    while ([currentClass superclass]) { // avoid printing NSObject's attributes
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            const char *propName = property_getName(property);
            if (propName) {
                NSString *propertyName = [NSString stringWithUTF8String:propName];
                [propertyKeys addObject:propertyName];
            }
        }
        free(properties);
        currentClass = [currentClass superclass];
    }

    return [self dictionaryWithValuesForKeys:propertyKeys];
}

A: The perfect way to do this is by using a library for serialization/deserialization
many libraries are available but one i like is
JagPropertyConverter
https://github.com/jagill/JAGPropertyConverter
it can convert your Custom object into NSDictionary and vice versa
even it support to convert dictionary or array or any custom object within your object (i.e Composition)
JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init];
converter.classesToConvert = [NSSet setWithObjects:[Order class], nil];

@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;
@end

//For Dictionary to Object (AS IN YOUR CASE)

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];

Order *order = [[Order alloc]init];
[converter setPropertiesOf:order fromDictionary:dictionary];

 //For Object to Dictionary

Order *order = [[Order alloc]init];
order.OrderId = @"10";
order.Title   = @"Title;
order.Weight  = @"Weight";

NSDictionary *dictPerson = [converter convertToDictionary:person];

A: Define your custom class inherits from "AutoBindObject". Declare properties which has the same name with keys in NSDictionary. Then call method:
[customObject loadFromDictionary:dic];

Actually, we can customize class to map different property names to keys in dictionary. Beside that, we can bind nested objects.
Please have a look to this demo. The usage is easy:
https://github.com/caohuuloc/AutoBindObject


Q: How am I supposed to use the -audiodev option in QEMU? There is a thread Fwd: How am I supposed to use the -audiodev option?, but unfortunately it does not contain an answer. I use QEMU on Windows, and when I run my image in QEMU qemu-system-arm.exe , I get:
dsound: Could not initialize DirectSound
dsound: Reason: No sound driver is available for use, or the given GUID is not a valid DirectSound device ID
sdl: SDL_OpenAudioDevice for playback failed
sdl: Reason: WASAPI can't find requested audio endpoint: Element not found.
sdl: SDL_OpenAudioDevice for playback failed
sdl: Reason: WASAPI can't find requested audio endpoint: Element not found.
audio: Failed to create voice `lm4549.out'

So, I want to disable audio completely, and get rid of those messages.
So, I add this (found via https://unix.stackexchange.com/questions/564844/disable-sound-when-using-spice-with-kvm-libvirt) to my command line:
-audiodev id=none,driver=none

This then results with:
audio: Device lm4549: audiodev default parameter is deprecated, please specify audiodev=none

As recommended in that thread, I tried:
C:\bin\qemu\qemu-system-arm.exe -audio-help
Environment variable based configuration deprecated.
Please use the new -audiodev option.

Equivalent -audiodev to your current environment variables:
(Since you didn't specify QEMU_AUDIO_DRV, I'll list all possibilities)
-audiodev id=dsound,driver=dsound
-audiodev id=sdl,driver=sdl
-audiodev id=none,driver=none

Ok, I then try this instead of the above:
audiodev=none

... and I get:
qemu-system-arm.exe: audiodev=none: drive with bus=0, unit=0 (index=0) exists

Ok, I try this:
-audiodev=none

... and I get:
qemu-system-arm.exe: -audiodev=none: invalid option

So ... how do I set audio device to none in QEMU?


Q: How to replace a sentence with space on the basis of a pattern if it occurs in the middle of a sentence Suppose I have a line like this:
aaaa ---- bbbb

I want to erase the ----bbbb part, but I want to keep the aaaa part as it is in the file. How can I do it?

A: Using sed:
s='aaaa ---- bbbb'
echo "$s"|sed 's/--* bb*/foo/'
aaaa foo


Q: How to use API Key in Google Speech grpc Java library How do I use an API Key in Google Speech grpc Java or any other library. For HTTP request I am able to see that we can append key=API_KEY as mentioned in
https://cloud.google.com/docs/authentication/api-keys.
But for the given libraries (https://cloud.google.com/speech/docs/reference/libraries#client-libraries-install-java) all examples show how to use the Credential file.
Please help.

A: Use metadata with a key of X-Goog-Api-Key. See this other answer. If you have API restrictions, you may need additional headers. For example, an iOS example mentioned a bundle id restriction.


Q: Check size(variable) of all string in List using Java Stream I have a list of strings (given below), each string required to be in a specific size(Variable).
for e.g.
{"abc","xyz","def"}

this list elements has a fixed size of 3 and i would like to check if this size is not exceed to X=3 or 4.
Requirement is to return a boolean if that size exceed or lower the size. I refereed Java Stream docs couldn't find any relevant information.
Does Java Stream API is useful to solve this or should i solve it in classical way.

A: You can use the allMatch method like this:
int correctSize = 3;
List<String> myStrings = List.of("abc", "xyz", "def");
boolean allAreCorrectSize = myStrings.stream()
    .allMatch(s -> s.length() == correctSize);

A: Here both implementation, both can be used

*

*Using Stream API

public static boolean isValidUsingStreamAPI(List<String> list){
        int correctSize=3;
        return list.stream().allMatch(f->f.length()==correctSize);
}

*Classic Way

public static boolean isValidClassic(List<String> list){
        int correctSize=3;
        for(String s:list){
            if(s.length()!=correctSize)return false;
        }
        return true;
    }


Q: html2canvas is not working in Safari browser: Taking Screenshot I just want to take a screenshot of any HTML element ( "container" div in my case ).
it works fine in Chrome and Firefox browsers but not in Safari.
Following is how I am doing it:
<!doctype HTML>

Take screenshot of webpage with html2canvas

DIV 1

DIV 2

DIV 3

<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'>

it shows the following error in the Safari browser:
and here is the specific part of code of html2canvas.js (it is by-default file I have just used).

A: we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows:
function screenshot(){
    html2canvas(document.getElementById('id-screenshot'),{
        allowTaint: true,
        useCORS : true,
    }).then(function(canvas) {
        console.log("canvas: " + canvas);
        document.getElementById('test-s').appendChild(canvas);
    });
}


Q: how to make multiple tkinter buttons to press together while as user presses any one of them? how to make multiple tkinter buttons to press together while as user presses any one of them?
To be clear i want multiple tkinter buttons look like pressed at the same time user presses any one of them .
i tried this:
from tkinter import *
from tkinter import ttk

class one_for_all:
    def __init__(self):
        self.root = Tk()
        self.root.title("One For All, All For One")

        self.frame = ttk.Frame(self.root, padding="3 3 12 12")
        self.frame.grid(row=0, column=0)
        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)

        self.btn1 = ttk.Button(self.frame, text="btn1", command=lambda : self.push_all(1))
        self.btn2 = ttk.Button(self.frame, text="btn2", command=lambda : self.push_all(2))
        self.btn3 = ttk.Button(self.frame, text="btn3", command=lambda : self.push_all(3))
        self.btn4 = ttk.Button(self.frame, text="btn4", command=lambda : self.push_all(4))

        self.btn1.grid(row=0, column=0, sticky="nsew")
        self.btn2.grid(row=0, column=1, sticky="nsew")
        self.btn3.grid(row=1, column=0, sticky="nsew")
        self.btn4.grid(row=1, column=1, sticky="nsew")

        for child in self.frame.winfo_children():
            child.grid_configure(padx=5, pady=5)

    def push_all(self, caller):
        if caller != 1:
            self.btn1.configure(command=lambda : None)
            self.btn1.event_generate("<ButtonPress-1>")
            self.btn1.event_generate("<ButtonRelease-1>")
            self.btn1.configure(command=lambda: self.push_all(1))
        if caller != 2:
            self.btn2.configure(command=lambda : None)
            self.btn2.event_generate("<ButtonPress-1>")
            self.btn2.event_generate("<ButtonRelease-1>")
            self.btn2.configure(command=lambda: self.push_all(2))
        if caller != 3:
            self.btn3.configure(command=lambda : None)
            self.btn3.event_generate("<ButtonPress-1>")
            self.btn3.event_generate("<ButtonRelease-1>")
            self.btn3.configure(command=lambda: self.push_all(3))
        if caller != 4:
            self.btn4.configure(command=lambda : None)
            self.btn4.event_generate("<ButtonPress-1>")
            self.btn4.event_generate("<ButtonRelease-1>")
            self.btn4.configure(command=lambda: self.push_all(4))

    def mainloop(self):
        self.root.mainloop()

if __name__ == "__main__":
    one_for_all().mainloop()

but it looks like only button 4 is stimulated by other buttons not all 4 :(
Note: i just started the tkinter without any prior experience of GUI
Thanks in Advance.

A: You can do something like this:
from tkinter import Tk, Button

class MainWindow(Tk):
    def __init__(self):
        super().__init__()

        self.buttons = list()
        for i in range(4):
            button = Button(self, text=f'Button {i}')
            button.bind('<ButtonPress-1>', self.press)
            button.bind('<ButtonRelease-1>', self.release)
            button.pack(fill='both')
            self.buttons.append(button)

    def press(self, event=None):
        for btn in self.buttons:
            btn.config(relief='sunken')

    def release(self, event=None):
        for btn in self.buttons:
            btn.config(relief='raised')

if __name__ == '__main__':
    MainWindow().mainloop()

It will visually make them appear to be clicked at once.
You can simply inherit from Tk and it will reduce the code written a bit since instead of self.root it would simply be just self and the features would be inherited and other stuff, for example, don't need to define mainloop as it is already inherited.
Also:
I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Have two blank lines around function and class declarations.
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.


Q: Receiving "error: conflicting types for 'function'" I am creating a program to convert from binary, decimal, hex, and oct to any one of those options.  For hex, I need a way to format values greater than 9 into one of A, B, C, D, E, F.  Since this will be repeated in several functions, I decided to make the following function:
char hexRepresentation(double n){
    if(n > 9){
        if(n==10) return 'A';
        if(n==11) return 'B';
        if(n==12) return 'C';
        if(n==13) return 'D';
        if(n==14) return 'E';
        if(n==15) return 'F';
    }

    return (char)n;
}

However, when I try to compile, I receive the error

conflicting types for 'hexRepresentation'

I'm utterly new at C, coming from Java, and am banging my head against a wall over what should be the simplest things to implement.  Any help would be greatly appreciated!

A: You don't get a declaration kind-of error because in C, when you do not forward declare a function most compilers assume an extern function that returns an int type. Actually the compiler should warn you about this (most do). Then later on when the compiler actually reaches the function implementation it finds a different return type, in this case a char, and then throws the "conflicting type" error. Just forward declare all the functions to avoid this kind of errors.
About what would be the best way somthing like following code woudl yield a similar result:
if (n > 9)
{
   return('A' + (n - 10));
}

A: Whatever you are doing in the code posted, you are not using double datatype at all, within the function. And from the function return type, it appears you will never see the return value >127.
This code highlights some issues:(This is just illustrative)
char hexRepresentation(double n){
    if(n > 9){//comparing (double>int). Bad.
        if(n==10) return 'A';
        if(n==11) return 'B';
        if(n==12) return 'C';//You wrote if(double == int). Bad.
        if(n==13) return 'D';
        if(n==14) return 'E';
        if(n==15) return 'F';
    }

    return (char)n; //again unsafe downgrade from 8 bytes double to 1 byte char.
}

Even if you fix your compiler error, you may not get the desired results always, due to such dangerous usage of datatype in the function.
To know why its bad, look here:
http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm
I would use fabs(n) instead of n everywhere in that function body.
And the error "conflicting types for 'hexRepresentation'" will be shown when there exists a prior declaration or definition of the same named function hexRepresentation before this function definition. Also, if you do not declare a function and it only appears after being called, it is automatically assumed to be int by the compiler.
So, declare and define your function before main()
or declare before main() and define the function anywhere else in the file, but, with the same function prototype.
Do:
 char hexRepresentation(double); //Declaration before main
 main()
 {
   ...
 }
 char hexRepresentation(double n){//Definition after main
 ...
 }

Or
 char hexRepresentation(double n){ //Declaration and definition before main
  ...
 }

 main()
 {
    ...
 }

A: Just create one stack ( for char) which has push and pop functions. I am not returning the value just printing it there in the same function. (have implemented for integral values only)
#define max 100
char a[max];

void hex(int n)
{
 while(n>0)
 {
 int rem = n%16;
 if (rem<10)
   push(rem+'0');
 elsif(rem >=10 && rem <16)
   {
     switch(rem)
     {
       case 10:
         push('A');break;
         case 11:
         push('B');break;
         case 12:
         push('C');break;
         case 13:
         push('D');break;
         case 14:
         push('E');break;
         case 15:
         push('F');break;
     }
    else
       n=n/16;
   }
   }
   i=0;
   while(top>-1)
     a[i++]=pop();
   i=0;
   while(a[i]!='\0')
     printf("%c",a[i++]);
}

Is it helpful ?


Q: Using sed inside php script is causing unexpected T_STRING error I'm adding a line to my php script:
exec('sed -i 1i'MAILTO=""' /var/spool/cron/' '.$clientName.');

But it shows me an error:
PHP Parse error:  syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368

Parse error: syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368

A: I think the error says it quite well. You have a syntax error.
Perhaps this is what you wanted?
exec('sed -i \'1i MAILTO=""\'  /var/spool/cron/'.$clientName);


Q: Is it possible to center align a number in a diamond? I'm trying to center align this 1 in the diamond, but I can't figure out how to. Is this even possible? Please help...

.num {
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-bottom-color: pink;
  position: relative;
  top: -15px;
  text-align: center;
  color: white;
  font-weight: bold;
  vertical-align: center;
}

.num:after {
  text-align: center;
  content: '';
  position: absolute;
  left: -15px;
  top: 15px;
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-top-color: pink;
}

1

A: Use clip-path

.num {
  background:pink;
  display:inline-flex;
  font-size:20px;
  width:80px;
  height:80px;
  align-items:center;
  justify-content:center;
  clip-path:polygon(50% 0,100% 50%,50% 100%,0 50%);
}

1

A: Or if you don't want to play with clips than you can use the following:

1

CSS
.num {
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-bottom-color: pink;
  position: relative;
  top: -15px;
  text-align: center;
  color: white;
  font-weight: bold;
  vertical-align: center;
}

.num span {
  width: 20px !important;
  height: 40px !important;
  position: absolute;
  margin-left: -10px;
  vertical-align: center;
  margin-top: 5px;
  z-index: 1
}

.num:after {
  text-align: center;
  content: '';
  position: absolute;
  left: -15px;
  top: 15px;
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-top-color: pink;
}

But be aware: this only works if you have fix sizes. If you use percentage, than you have to always calculate the margins/paddings.


Q: Am I able to complement a virtual function of subclasses? i have a question. Lets say i have this virtual function in main class:
virtual void h_w() { cout << "Hello, wolrd!" << endl; }

And Im doing with the same function that:
void h_w() { cout << "Today is: " << math.rand(); << endl; }

Am I allowed to do that? I mean, can i change body of main function like I want in subclasses? Thanks.

A: Assuming you mean you want something like this:
class base {
public:
    virtual void h_w() { std::cout << "Hello world!\n"; }
};

class derived : public base {
public:
    void h_w() { std::cout << "Today is: " << rand() << "\n"; }
};

int main() {
    std::unique_ptr<base> b = std::make_unique<derived>();

    b->h_w();
}

...then yes, C++ supports that. In fact, this is pretty much a canonical demonstration of virtual functions, at least if you change names to (for example) "animal" as the base class and "duck" as the derived class, and have them print out something like "generic animal" and "duck" respectively. For the record, it's probably worth noting that most example based on animals are more or less broken in various ways, such as animals simply not following simple sets of rules like we expect code to.
A better example, would be something like a base class defining a generic interface to a database that allows things like reading a record, writing a record, and finding a set of records that satisfy some criteria. The derived class could then (for example) provide an implementation to carry out those "commands" in terms of some specific type of database--perhaps SQL, or perhaps some simple key/value storage engine, but the client doesn't know or care, beyond minor details like performance.
As to why this is better: first of all, because it corresponds much more closely to things you're likely to really do with a computer. Second, because we can define databases to really follow our rules and fulfill the obligations we set. With animals, we're stuck with all sorts of exceptions to any meaningful rule we might try to make, as well as the simple fact that (of course) being able to make a Duck say "quack" and a dog say "bow wow" isn't really very useful (and in the rare case that it is useful, we probably just want to save/retrieve its sound as some sort of blob, not define an entire new type to encode something better stored as data).


Q: Is there a way to work with arrays and use Protege I am trying to perform the functions on arrays such as inverse of and transpose on matrices and use it along with Protege so as to calculate the forces and deflections using reasoner. We can perform the calculations using SWRL rules in ontology but it does not support array as data type. But we have Postgres and MongoDB which supports arrays. Is there any way to work with arrays and use inverse operation in ontology? Suppose inverse operation is done by database such as Postgres then how to display the array elements in ontology? Can MongoDB be used here? If yes how do we connect to Protege 5.2. I understand WebProtege can be used along MongoDB but the current version of WebProtege does not support reasoning part. Also Ontop plugin does not support connectivity with MongoDB. Kindly clarify if I am missing some thing in meeting the objective of working with arrays in ontology.


Q: Associating ViewPager with navigation tabs Is there any way to associate each fragment in the ViewPager with a certain navigation tab? So when we flip right/left ,the right tab will be highlighted.
Thank you.

A: Use TabLayout from the Material Design support library.
See the "Tabs" paragraph in the blog post that introduces the library:

However, if you are using a ViewPager for horizontal paging between
  tabs, you can create tabs directly from your PagerAdapter’s
  getPageTitle() and then connect the two together using
  setupWithViewPager(). This ensures that tab selection events update
  the ViewPager and page changes update the selected tab.


Q: Keep XML namespaces after split or grep I have a huge xml-file (several GB) which I can split with xml_split or I can extract the relevant subbnode with xml_grep. I run out of RAM if I try to read the whole XML.
But when I try to parse one of the splitted files, or the grep:ed file, I get the error "Namespace prefix xx on yy is not defined" thousands of times.
Is there a way to copy the namespace-definition from the original file to the splitted or grep:ed files? Or have I misunderstood the errors?
I'm very new to XML and I find XML::TWIG useful. Here is the grep-command I use:
xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml > Outfile.xml

A: Which tool are you using to parse the result of the split (or the grep)? xmllint (from libxml2) complains, but xmlwf (from expat) doesn't. So I think any expat-based tool would be ok with the XML, but not libxml2-based ones.
It looks like xml_split and xml_grep could declare the namespaces though. At least it should be an option. I'll have a look at it.
In the meantime, here is a quick'n dirty way to post-process the result you get with xml_grep:
xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml | perl -MXML::Twig -e'XML::Twig->new( start_tag_handlers => { xml_grep => sub { $_->set_att( "xmlns:m" => "http://m.org") }, SubInformation => sub { $_->flush } })->parse( \*STDIN)' > Outfile.xml

replace xmlns:m and "http://m.org" with the appropriate values.
Let me think of a way to do this in a generic way for the result of xml_split. Can I assume that the namespace declarations are not too tricky (ie that the prefix(es) are declared just once)?
Edit: Here is a way to add the namespace declarations to the files resulting from xml_split, call it as add_ns Infile after you have run xml_split on Infile.xml:
#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $root= shift @ARGV;

my( $base, @files)= sort glob( "$root-*.xml");

my %ns= ns_for_file( $base);

foreach my $file (@files)
  { add_ns( $file, %ns); }

sub ns_for_file
  { my( $base)= @_;
    my %ns;
    XML::Twig->new( start_tag_handlers
      # get namespace declarations from the root and bail
      => { 'level(0)' => sub { %ns= ns_for_tag( $_);
                               $_[0]->finish_now();
                             }
         },
                  )
             ->parsefile( $base);
    return %ns;
  }

# get all namespace declarations from the root element
sub ns_for_tag
  { my( $e)= @_;
    return map { $_ => $e->att( $_) if m{^xmlns:} } $e->att_names;
  }

sub add_ns
  { my( $file, %ns)= @_;
     XML::Twig->new( start_tag_handlers => { 'level(0)' => sub { $_->set_att( %ns); } },
                     twig_handlers => { _all_ => sub { $_->flush; } },
                     keep_spaces => 1,
                   )
              ->parsefile_inplace( $file);

}

A: To process large XML files, you can also use a pull parser. See XML::LibXML::Reader.


Q: Can I remove the JSON-LD schema that Yoast adds to my WordPress site? I would like to remove the JSON-LD schema that Yoast applies to my WordPress site so that I can add my own.  I have already added my own, and Google Structured Data Testing says that it is OK, but basically I have 3 separate JSON-LD schemas instead of two because of Yoast.
You can see what I mean here: https://search.google.com/structured-data/testing-tool/u/0/#url=http%3A%2F%2Fwww.yogabearpc.com
Yoast has added the WebSite schema and it seems unnecessary or even damaging?

A: I wanted to disable this because of the sitelinks searchbox and the fact that I don't have a search function that works globally, just on the blog. Having the search box enabled for me would have undesirable effects.
The easier option may just be to prevent Google using the sitelinks searchbox without having to touch the functions files. You can prevent Google using sitelinks searchbox on your site by using the following meta:
<meta name="google" content="nositelinkssearchbox" />

If you want to disable Yoast's JSON-LD all together then here's a snippet from my blog and the code I use on my site:

SOURCE
How to disable Yoast SEO Schema JSON-LD completely
function bybe_remove_yoast_json($data){
  $data = array();
  return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);

Login to your WordPress dashboard and head over to the editor
  within the tab menu appearance, find your functions file (normally
  named functions.php) and add the code below just before the PHP tag is
  closed at the bottom.

A: Simplest way to completely disable the Yoast SEO schema JSON-LD
Add this line to functions.php file:
add_filter( 'wpseo_json_ld_output', '__return_empty_array' );
Source

A: If you want to disable just Organization or just Website, add this to your theme's functions.php file:
function bybe_remove_yoast_json($data){
    if ( (isset($data['@type'])) && ($data['@type'] == 'Organization') ) {
        $data = array();
    }
    return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);

A: Unless the data Yoast produces is wrong, there is no harm in having it. Quite the contrary, having more structured data is better than having less.
If having it is "unnecessary" depends on your definition of what is necessary. Some consumers might be interested in it, others not.
My guess is that Yoast adds a WebSite entity because of Google’s sitelinks searchbox rich snippet result, which allows Google users to search your site directly from the Google search result.


Q: JQuery not rendering HTML I am using $.get() in my ASP.NET MVC 3 application to get a response from database asynchronously. I get the response returning correctly and based on the response I generate my HTML in a string variable and finally append it to a div already on my markup page. In debug mode it shows me the complete HTML created but it doesn't get rendered in browser.
Here is my sample code
$.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response)
{
    if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '')
    {
        var actions = eval('(' + response + ')');
        var moduleHtml="";
        if (actions.length > 0)
        {
            for (i = 0; i < actions.length; i++)
            {

                moduleHtml += "
";
                moduleHtml += "<input type='checkbox' name='" + ModuleName + "_Actions' value='" + actions[i].ActionID + "' />";
                moduleHtml += "" + actions[i].ActionName + "";
                moduleHtml += "

";
                moduleHtml += "
";
            }

            moduleHtml += "
";
            moduleHtml += "<input type='button' class='inpuButtonAdd' value='Save' /> ";
            moduleHtml += "<input type='button' class='inpuButtonAdd' value='Cancel' /> ";
            moduleHtml += ""
            moduleHtml += "
";

            moduleHtml += "
";

            moduleHtml += "

";
            moduleHtml += "
";
            moduleHtml += "
";
            moduleHtml += "

";

            $("#divModuleDetails").append(moduleHtml); //appending to div
        }
    }
});

What could be causing this?

A: look at this line:
moduleHtml += ""

i think the problem is script still printing only a span but maybe nothing :)
anyway checkout below script optimization i think it should work ;)
    $.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response)
{
    if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '')
    {
        var actions = eval('(' + response + ')');
        var moduleHtml;
        if (actions.length > 0)
        {
            for (i = 0; i < actions.length; i++)
            {

                moduleHtml += "
"
                + "<input type='checkbox' name='"
                + ModuleName
                + "_Actions' value='"
                + actions[i].ActionID
                + "' />"
                + ""
                + actions[i].ActionName
                + ""
                + "

"
                + "
";
            }

           moduleHtml += "
"
            +"<input type='button' class='inpuButtonAdd' value='Save' /> "
            + "<input type='button' class='inpuButtonAdd' value='Cancel' /> "
            +""
            + "
"
            + "
"
            + "

"
            + "
"
            + "
"
            + "

";

            $("#divModuleDetails").append(moduleHtml); //appending to div
        }
    }
});


Q: The Intercept of a categorical multiple regression R is not the mean value? Let's say I have 2 (categorical) variables and one continuous:
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)

When I regress depression on sex (0 or 1), the intercept is 10.0436, what is the mean of sex = 0. Ok!
ds %>% group_by(sex_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=4))
# A tibble: 2 x 2
  sex_dummy `formatC(mean(depression), format = "f", digits = 4)`
      <dbl> <chr>
1      0    10.0436
2      1.00 10.1640

The same thing happens when I regress depression on schooling. The intercept value is 10.4398. The mean of schooling = 0 is the same.
ds %>% group_by(schooling_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=4))
# A tibble: 3 x 2
  schooling_dummy `formatC(mean(depression), format = "f", digits = 4)`
            <dbl> <chr>
1            0    10.4398
2            1.00 9.7122
3            2.00 10.1593

Now, when I compute a model with both variables, why the intercept is not the mean when both groups = 0? The regression **intercept is 10.3796, but the mean when sex = 0, and schooling is = 0 is 10.32548:
ds %>% group_by(schooling_dummy,sex_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=5))
# A tibble: 6 x 3
# Groups: schooling_dummy [?]
  schooling_dummy sex_dummy `formatC(mean(depression), format = "f", digits = 5)`
            <dbl>     <dbl> <chr>
1            0         0    10.32548
2            0         1.00 10.55404
3            1.00      0    9.59305
4            1.00      1.00 9.83139
5            2.00      0    10.21218
6            2.00      1.00 10.10648

When I predict the model when both are 0:
predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0))
       1
10.37956

This result is related to depression (of course...) but still not What I was expecting, since:

(Reference: https://www.theanalysisfactor.com/interpret-the-intercept/)
What is the same for this previous forum post
I aware of my variables are categorical and I'm adjusting my script, as you can reproduce using this code below:
Thanks
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)
mod <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0"))
summary(mod)
ds %>% group_by(sex_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=4))

mod2 <- lm(data=ds, depression ~ relevel(factor(schooling_dummy), ref = "0"))
summary(mod2)
ds %>% group_by(schooling_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=4))

mod3 <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0") +
             relevel(factor(schooling_dummy), ref = "0"))
summary(mod3)
ds %>% group_by(schooling_dummy,sex_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=5))

predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0))

A: Two errors in your thinking (although your R code works so it's not a programming error.
First and foremost you violated your own statement you have not dummy coded schooling it does not have only zeroes and ones it has 0,1 & 2.
Second you forgot the interaction effect in your lm modeling...
Try this...
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)
# if you explicitly make these variables factors not integers R will do the right thing with them
ds$schooling_dummy<-factor(ds$schooling_dummy)
ds$sex_dummy<-factor(ds$sex_dummy)
ds %>% group_by(schooling_dummy,sex_dummy) %>%
    summarise(formatC(mean(depression),format="f", digits=5))
# you need an asterisk in your lm model to include the interaction term
lm(depression ~ schooling_dummy * sex_dummy, data = ds)

The results give you the mean(s) you were expecting...
Call:
lm(formula = depression ~ schooling_dummy * sex_dummy, data = ds)

Coefficients:
                (Intercept)             schooling_dummy1             schooling_dummy2
                  10.325482                    -0.732433                    -0.113305
                 sex_dummy1  schooling_dummy1:sex_dummy1  schooling_dummy2:sex_dummy1
                   0.228561                     0.009778                    -0.334254

and FWIW you can avoid this sort of accidental misuse of categorical variables if your data is coded as characters to begin with... so if your data is coded this way:
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling=c("A","B","C"),
  sex=c("Male","Female")
)

You're less likely to make the same mistake plus the results are easier to read...