text:
Q: How to share image to social media with bitmap? I need to share an image from my RecyclerAdapter because the image does not initially exist, i.e. is loaded within the Activity making use of the adapter. How can I share the bitmap to social media? Every time I click share in my app it says "No apps can perform this action".
feedItemView.setFeedSocialShareClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Share to Social Media

                ImageView imageView = (ImageView) feedItemView.findViewById(R.id.image);
                Drawable mDrawable = imageView.getDrawable();
                Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();

                String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        mBitmap, "Design", null);

                Uri uri = Uri.parse(path);

                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("image");
                share.putExtra(Intent.EXTRA_STREAM, uri);
                share.putExtra(Intent.EXTRA_TEXT, "I found something cool!");
                context.startActivity(Intent.createChooser(share, "Share Your Design!"));
            }
        });

A: try with
 share.setType("image/*");

A: In Kotlin, if your SDK below 29:
where you need give the address of your file!
val share = Intent(Intent.ACTION_SEND)
          share.type = "image/jpeg"
          share.putExtra(Intent.EXTRA_STREAM,Uri.parse(file.path) ) // or Uri.fromFile(file)
          share.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
          share.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
          startActivity(Intent.createChooser(share, "Share Image"))

But if you want cover all SDK , it's better use FileProvider


text:
Q: Get folder next to parent folder in either Path.GetDirectory or Server.MapPath Consider the two paths, one in a solution and the other in IIS:
Solution Path:

*

*C:\Users\userid\Desktop\File\Solution\RootName\ Folder1 \Folder1a\the.aspx

IIS path

*

*C:\inetpub\wwwroot\RootName\webApplication\ Folder1 \Folder1a\the.aspx

Is there a way using Directory or Server or anything at all to get the FIRST folder name after the Parent Directory?
ie in the given above, Folder1 is the first folder after the parent folder.
I can get the opposite, which is the containing folder name from a filepath (in this example, Folder1a) and I can iterate it to get to the answer :
Path.GetFileName(Path.GetDirectoryName(file));
But the problem is, folders can be nested at any amount: (folder1a\folder1a1\folder1a1a...)
How can I get the first folder name after the Parent Directory given a file path?
as an aside,
If there is no foldername (ex. Folder1 does not exist) the answer should output "" (empty)

A: Use .. to go to previous directory, example:
C:\test\..\

is equivalent to:
C:\

Use Directory.GetDirectories to find sub Directories. It has an overload where you can pass search patterns as well:
string[] GetDirectories(string path, string searchPattern)

searchPattern
      Type: System.String
The search string to match against the names of subdirectories in path.
  This parameter can contain a combination of valid literal and
  wildcard characters (see Remarks), but doesn't support regular
  expressions.

A: Try this:
string filename = string.Format("{0}{1}", System.AppDomain.CurrentDomain.BaseDirectory, @"Folder1\Folder1a\the.aspx");

A: Below is what I have tried that works.
Since I simply needed to output the first page after the word, I iterated Path.GetDirectoryName and Path.GetFileName until I could match the root folder.
Ex:
                baseFoldr = "";
                var curFile = Path.GetDirectoryName(file);
                string curName = Path.GetFileName(curFile);

                while (curName.ToLower() != "RootName")
                {
                        curFile = Path.GetDirectoryName(curFile);
                        baseFoldr = curName;
                        curName = Path.GetFileName(curFile);

                }

                return baseFoldr;

I still believe there could be a better answer, though

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that a stastistical distance is a real distance
Show that a stastistical distance is a real distance.

Let $S=(s_{11},s_{22},\dots,s_{pp})$ a vector of sample variances and three vectors $X=(x_1,x_2,\dots,x_p)$, $Y=(y_1,y_2,\dots,y_p)$ and $W=(w_1,w_2,\dots,w_p)$. The statistical distance is defined by
$$D(X,Y)=\sqrt{\frac{(x_1-y_1)^2}{s_{11}}+\frac{(x_2-y_2)^2}{s_{22}}+\dots+\frac{(x_p-y_p)^2}{s_{pp}}}$$
So I want to show that
a) $D(X,Y)=D(Y,X)$
b) $D(X,Y)=0$ if $X=Y$
c) $D(X,Y)>0$ if $X\neq Y$
d) $D(X,Y)\leq D(X,W)+D(W,Y)$
Proof:
a)$$D(X,Y)=\sum_{i=1}^p\frac{(x_i-y_i)^2}{s_{ii}}=\sum_{i=1}^p\frac{(y_i-x_i)^2}{s_{ii}}=D(Y,X)$$
b) If $X=Y$ then $\forall i\qquad x_i=y_i$
$$D(X,Y)=\sum_{i=1}^p\frac{(x_i-y_i)^2}{s_{ii}}=\sum_{i=1}^p\frac{(y_i-y_i)^2}{s_{ii}}=0$$
c) If $X\neq Y$ then there is at least one $x_i\neq y_i$ then for some $i$ $(x_i-y_i)>0$ thus
$$D(X,Y)=\sum_{i=1}^p\frac{(x_i-y_i)^2}{s_{ii}}>0$$
d) Here is the problem, I need to show the triangle inequality and proof the cauchy schwarz inequality, the same argument from here Euclidean distance proof hold in this case?

A: Supposing that the $s_{jj}$ are equal between different random variables, as it seems to be by the wording of the problem, then squaring the formula for triangle inequality we can see that
$$\sum\frac{(x_j-y_j)^2}{s_{jj}}\le \sum\frac{(x_j-z_j)^2}{s_{jj}}+\sum\frac{(z_j-y_j)^2}{s_{jj}}+2\sqrt{\sum\frac{(x_j-z_j)^2}{s_{jj}}\sum\frac{(z_j-y_j)^2}{s_{jj}}}$$
and then observe that
$$2\sqrt{\sum\frac{(x_j-z_j)^2}{s_{jj}}\sum\frac{(z_j-y_j)^2}{s_{jj}}}\ge 2\sum\frac{|z_j-y_j||x_j-y_j|}{s_{jj}}$$
Then comparing term by term
$$\sum\frac{(x_j-y_j)^2}{s_{jj}}\le \sum\frac{(x_j-z_j)^2}{s_{jj}}+\sum\frac{(z_j-y_j)^2}{s_{jj}}+2\sum\frac{|z_j-y_j||x_j-y_j|}{s_{jj}}$$
we can see that
$$(x_j-y_j)^2\le (x_j-z_j)^2+(z_j-y_j)^2+2|z_j-y_j||x_j-z_j|\implies\\
-x_jy_j\le z_j^2-x_jz_j-y_jz_j+|z_j-y_j||x_j-z_j|$$
I left the last statement unfinished. Check if it is true.


text:
Q: Is there any way in magento 2 to prevent user to add more than 1 product in cart I want to set a limit of 1 product in the cart.
Magento 2 C.E provides an option to set a limit of qty of a single product in the cart but that option allows two individual products in the cart.
I want to set vice versa.
Users can add only one product at a time in the cart. user cannot add any other product if he added a product in the cart unless and until he removes the first product or checkout that product.
I am sure there will be a solution for this.

A: Magento2 - How to stop a product from getting added to cart programmatically?
Let me know if this answer Is helpful....! Thanks


text:
Q: Jacoco shows All branches covered with Green mark but shows < 100% in Missed branches. What is wrong here? I have a simple isSubClass function which takes in a List of Classes and a Throwable and returns true if any of the Classes in the list is a subclass of the throwable and false otherwise.
Jacoco shows the function with a green mark saying all braches covered. Yet in the table, it shows Coverage being only 75%
What's wrong here?
private fun isSubClass(exceptionList: List<Class<out Throwable>>, throwable: Throwable): Boolean {
        return exceptionList.any { throwable::class.isSubclassOf(it.kotlin) }
}


text:
Q: getting foreach is not a function when using select multiple in angularjs even if I am not using foreach when I researched many people get this error by using select multiple and I am the same too. You can see the error below. I am not using foreach loop at all. It's going inside angularjs script and in there, it's causing error. I am using select multiple 5 times in the same page, but only this clientele list showing the error. When I compare the array with other arrays which are not causing errors, everything is the same. Any solution from you guys?
clientele array
[
{
    clienteleId:1,
    name:"Hey"

},
{
    clienteleId:2,
    name:"Hey2"

}
]

js code
 <select style="overflow:auto;" multiple class="form-control m-b" size="10" ng-model="selectedClientele"
        ng-options="clientele.name for clientele in availableClienteles"
        ng-dblclick="selectClientele(selectedClientele)">
        <option>Select</option>
 </select>

error

js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38564 TypeError: a.forEach is not a function
    at nh.p.writeValue (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38746)
    at hh.e.$render (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38761)
    at js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38761
    at m.$digest (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38589)
    at m.$apply (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38592)
    at HTMLSelectElement.<anonymous> (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:38726)
    at HTMLSelectElement.dispatch (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:5187)
    at HTMLSelectElement.elemData.handle (js?v=JvBJIyzkDFnuWdUC12a6IwAf_1-tX5vI--RGCM0TLVg1:4995)


text:
Q: BeautifulSoup4 Get "li a" with no text inside li I need help getting some specific anchors from a website. The website has this structure

  This has a link
  1st link

  2nd link

  This also has a link
  1st link

I want to get only the anchors that have no text inside de li.
What is the easiest way to achieve this with BeautifulSoup?

A: You can analyze the elements of soup.contents to determine if only soup objects exist:
from bs4 import BeautifulSoup as soup
d = soup(s, 'html.parser')
results = [i for i in d.find_all('li') if all(not isinstance(c, str) or c == '\n' for c in i.contents)]

Output:
[

  2nd link

]


text:
Q: Dumping many variables in PHP I assure this is a very common situation when you have to test variables (and they are many!), just like this example (I only named vars like this for less-effort-writing sake):
    $variable0='red';
    $variable1='blue';
    $variable2='green';
    $variable3='pink';
    $variable4='purple';
    $variable5='hellow';
    $variable6='foo';
    $variable7='bar';
    $variable8='hi';
    $variable9='bye';

    echo
    '$variable0='.$variable0.'

$variable1='.$variable1.'

$variable2='.$variable2.'

$variable3='.$variable3.'

$variable4='.$variable4.'

$variable5='.$variable5.'

$variable6='.$variable6.'

$variable7='.$variable7.'

$variable8='.$variable8.'

$variable9='.$variable9;

My question is: is there a better way to make this echoing / dumping / printing easier?
Of course, there are other ways of doing the very same presidiary work:
        $x=
    '$variable0='."$variable0\n".
    '$variable1='."$variable1\n".
    '$variable2='."$variable2\n".
    '$variable3='."$variable3\n".
    '$variable4='."$variable4\n".
    '$variable5='."$variable5\n".
    '$variable6='."$variable6\n".
    '$variable7='."$variable7\n".
    '$variable8='."$variable8\n".
    '$variable9='."$variable9"
    echo nl2br($x);

Or:
    $x=<<<HEREDOC
\$variable1=$variable1
\$variable2=$variable2
\$variable3=$variable3
\$variable4=$variable4
\$variable5=$variable5
\$variable6=$variable6
\$variable7=$variable7
\$variable8=$variable8
\$variable9=$variable9;
HEREDOC;
    echo nl2br($x);

But maybe PHP has a function to make this easier?
By the way, all 3 solutions above echoes the very same:
$variable1=blue

$variable2=green

$variable3=pink

$variable4=purple

$variable5=hellow

$variable6=foo

$variable7=bar

$variable8=hi

$variable9=bye;

A: Introducing compact:
var_dump(compact('foo', 'bar', 'baz'));

Note though that I explicitly used three very different variables: $foo, $bar and $baz.
If you actually do literally have $foo1, $foo2 etc, you're really really looking to use an array instead. Dumping that would be trivial too:
$foo    = array();
$foo[0] = 'bar';
$foo[1] = 'baz';
var_dump($foo);

In general, if you have too many variables floating around, your scope is probably too big and you should refactor everything into a number of smaller functions, or your algorithm is more complex than it needs to be, or you should be using arrays or other data structures instead.

A: get_defined_vars() would be able to do so. Might be overkill (all accessable vars will be shown):
print_r( get_defined_vars() );

Return Values: A multidimensional array with all the defined variables*.
*In a function it will only show the local $vars, and those defined as global.
Note:  This does exactly what you're looking for, but the array methods mentioned in other answers would be a better fit logical-wise, see below:

A better way for you to set the values is with an array, this way you 'group' multiple values together:
$color[] = 'red'; // will automatically start with key=0
$color[] = 'blue'; // key=1
$color[] = 'green';// key=2 etc
print_r( $color );
echo $color[1]; // Blue, same as your echo $variable1;

A: You can declare your variables as keys from an array instead
$myarray=Array();

$myarray['variable0']='red';
$myarray['variable1']='blue';
$myarray['variable2']='green';
$myarray['variable3']='pink';
$myarray['variable4']='purple';
$myarray['variable5']='hellow';
$myarray['variable6']='foo';
$myarray['variable7']='bar';
$myarray['variable8']='hi';
$myarray['variable9']='bye';

and print them all with
echo '
';
print_r($myarray);
echo '
';

then, in case you still need to use them as separate variables, doing
extract($myarray)

will create $variable0 to $variable9 in the global context.

A: If you know the upper and lower bounds and all the variables have a similar name you could do the following:
for ($i = 0; $i < $end; ++$i) { echo ${'value_name'. $i}; }

A: Try refactor your code and use arrays
Then you can do print_r or var_dump

A: This should give you the output your looking for:
function get_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return "Variable name not found";
}

function miracle_var_dump($valuesToDump) {

    //For each variable in the $valuesToDump array, print the name and value
    for($i = 0; $i < count($valuesToDump); $i++) {
        echo(get_var_name($valuesToDump[i]) . "=" . $valuesToDump[i] . "
");
    }

}

//Making a call to dump the variables
miracle_var_dump(array($variable0,$variable1,$variable2,$variable3,$variable4,$variable5,$variable6,$variable7,$variable8,$variable9))

Function get_var_name gets the variable name given the variable (taken from one of Jeremey Rutins awsners).

A: //let your variables like this
$variable0='red';
$variable1='blue';
$variable2='green';

//an array to keep all the variable names
$var_names=array();
$var_names[]='$variable0';
$var_names[]='$variable1';
$var_names[]='$variable2';
//etc...

print_var_name($var_names);

function print_var_name($var_names) {
//loop through the array and dump them if they are in $GLOBALS
foreach($GLOBALS as $var_name => $value) {
    if (in_array('$'.$var_name,$var_names)) {
        echo $var_name;
        var_dump($value);
    }
}


text:
Q: XSLT - Get xml from another XML I need to extract an xml inside another one with XSLT fron  field.
<?xml version="1.0" encoding="UTF-8" ?>
<ns:JDBC_SELECT xmlns:ns="namepace/nt">
<row>
<KEY>19</KEY>
<QUEUE_TYPE>2</QUEUE_TYPE>
<EVENT_STATUS>0</EVENT_STATUS>
<EVENT_TYPE>New Work Package Request</EVENT_TYPE>
<CONTENT><?xml version="1.0" encoding="utf-8" standalone="yes"?><event xmlns:ns="namespace/nt" reference="0000000000" source="NBA" target="SAP" timestamp="2013-02-04T14:32:01.836+00:00" type="New Work Package Request" version="1.0" id="19"><new-work-package-request-event><work-order-id>11</work-order-id><personnel-id>ra_a</personnel-id><request-timestamp>2013-02-04T14:32:01.836+00:00</request-timestamp><new-notification-request><type>Z2</type><requirement-code>RI0D</requirement-code><main-work-centre>0102</main-work-centre><planner-group>L00</planner-group><functional-location-id>1024</functional-location-id><short-text>SET UP/REMOVE ISOLATION RUN</short-text><long-text>SET UP/REMOVE ISOLATION RUN, 1024, NORTON FOXLEY (PRV) NORTON FOXLEY Nightline Increase: (l/h)</long-text><personnel-resp-id>12157</personnel-resp-id><cost-centre>3600</cost-centre></new-notification-request><new-work-order-request><type>ZPM2</type></new-work-order-request></new-work-package-request-event></event></CONTENT>
</row>
</ns:JDBC_SELECT>

<xsl:transform xmlns:xsl="namespace/nt" version="1.0">
  <xslutput method="xml"/>
  <xsl:template match="/">
    <xsl:copy-of select="//CONTENT"/>
  </xsl:template>
</xsl:transform>

But not luck.
Any idea?

A: The XML is not valid - it cannot contain a second
<?xml version="1.0" encoding="utf-8"?>

declaration inside an element. As is it won't load.
There is a problem in the XSLT as well - the namespace must be http://www.w3.org/1999/XSL/Transform:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
      <xsl:copy-of select="//CONTENT"/>
    </xsl:template>

</xsl:stylesheet>

Once you get rid of the second <?xml....> declaration in the XML, the above XSLT works, producting this output:
<?xml version="1.0" encoding="utf-8"?>
<CONTENT xmlns:ns="namepace/nt">
  <event reference="0000000000" source="NBA" target="SAP" timestamp="2013-02-04T14:32:01.836+00:00" type="New Work Package Request" version="1.0" id="19" xmlns:ns="namespace/nt">
    <new-work-package-request-event>
      <work-order-id>11</work-order-id>
      <personnel-id>ra_a</personnel-id>
      <request-timestamp>2013-02-04T14:32:01.836+00:00</request-timestamp>
      <new-notification-request>
        <type>Z2</type>
        <requirement-code>RI0D</requirement-code>
        <main-work-centre>0102</main-work-centre>
        <planner-group>L00</planner-group>
        <functional-location-id>1024</functional-location-id>
        <short-text>SET UP/REMOVE ISOLATION RUN</short-text>
        <long-text>SET UP/REMOVE ISOLATION RUN, 1024, NORTON FOXLEY (PRV) NORTON FOXLEY Nightline Increase: (l/h)</long-text>
        <personnel-resp-id>12157</personnel-resp-id>
        <cost-centre>3600</cost-centre>
      </new-notification-request>
      <new-work-order-request>
        <type>ZPM2</type>
      </new-work-order-request>
    </new-work-package-request-event>
  </event>
</CONTENT>


text:
Q: Java JAXB marshall/unmarshall using Java Optionals My applications needs to convert data between Java and XML.
When converting the data, I need to distinguish whether or not the value was present, the value was set explicitly to null or the value had a value.
XML example:
<person><name>Bob</name></person>     <-- element 'name' contains value "Bob"

<person><name nil="true"/></person>   <-- element 'name' was set explicitly to 'nil'/null

<person></person>                     <-- element 'name' is missing

As Java types like 'String' only knows two states (null or not null), I tried to use Java Optionals to solve this.
A mapping between XML and Java Optionals could look like this:
<person></person>                   <=> Optional<String> name = null;

<person><name>Bob</name></person>   <=> Optional<String> name = Optional.of("Bob");

<person><name nil="true"/></person> <=> Optional<String> name = Optional.empty();

I tried to use JAXB for the marshalling and unmarshalling. The idea was that the setter of a field only gets invoked when a value needs to be set explicitly to an value. That means that a value is absent implicitly.

I had a look on other stackoverflow questions like the following, but all of them were incomplete handling the behaviour I need to achieve:
How to generate JaxB-Classes with java.util.Optional?
Using generic @XmlJavaTypeAdapter to unmarshal wrapped in Guava's Optional
Using Guava's Optional with @XmlAttribute
I've been struggling with this problem for two days now. I tried to use the XMLAdapter and GenericAdapter, tried several ways how to annotate the fields and getter/setter with @XmlElement, tried to use @XmlAnyElment with and without lax, but all of them only led to a partial success. Either the nil value was not handeld correctly, the lists were not printed out correctly,  ...
I think every Java webservice with a properly implemented patch operation should have had this problem. (not talking about the "json patch approach" (RFC 6902))
Is there a common way to solve my problem?

A: The following code is able to distinguish empty name from null name.  To make the solution work, I created a PersonList element to contain all of the person elements.  Each Person contains a Name that will have isNil() return true if the element was explicitly set to null by the XML:
Person.java:
import java.util.Optional;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(propOrder = {"name"})
@XmlRootElement(name = "person")
public class Person {

    private Optional<Name> optionalName;

    public Person() {
        optionalName = Optional.<Name>empty();
    }

    public Optional<Name> getOptionalName() {
        return optionalName;
    }

    public Name getName() {
        return (optionalName.isPresent()) ? (optionalName.get()) : (null);
    }

    @XmlElement(name = "name", required = false)
    public void setName(Name name) {
        optionalName = Optional.ofNullable(name);
    }

    @Override
    public String toString() {
        return String.format("Person(optionalName.isPresent() = %s, name = %s)",
                             Boolean.toString(optionalName.isPresent()),
                             ((getName() == null) ? ("null") : (getName().toString())));
    }
}

Name.java:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "name")
public class Name {

    @XmlAttribute(name = "nil")
    private boolean nil;

    @XmlValue
    private String value;

    public Name() {
        nil = false;
        value = null;
    }

    public boolean isNil() {
        return nil;
    }

    public void setNil(boolean torf) {
        this.nil = torf;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.format("Name(nil = %s, value = %s)",
                             Boolean.toString(nil),
                             (value == null) ? ("null"):("\""+getValue()+"\""));
    }
}

PersonList.java:
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "PersonList")
public class PersonList {

    private List<Person> persons;

    public PersonList() {
        persons = null;
    }

    @XmlElement(name = "person")
    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("PersonList(persons = ");
        if(persons == null) {
            sb.append("null");
        }
        else {
            sb.append("[");
            Iterator<Person> iterator = persons.iterator();
            while(iterator.hasNext()) {
                sb.append(iterator.next().toString());
                if(iterator.hasNext()) {
                    sb.append(", ");
                }
            }
            sb.append("]");
        }
        sb.append(")");
        return sb.toString();
    }
}

Main class to demonstrate the solution:
import java.io.ByteArrayInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class XmlOptional {
    public static final int STATUS_OKAY = 0;
    public static final int STATUS_ERROR = -1;

    public static final String XML_DATA = "<PersonList>" +
                                          "<person><name>Bob</name></person>" +
                                          "<person><name nil=\"true\" /></person>" +
                                          "<person></person>" +
                                          "</PersonList>";

    private XmlOptional() {
    }

    private static PersonList loadXml() {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(XML_DATA.getBytes());
            JAXBContext context = JAXBContext.newInstance(PersonList.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            PersonList personList = (PersonList)unmarshaller.unmarshal(bais);
            return personList;
        }
        catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        int status = STATUS_OKAY;

        try {
            PersonList personList = loadXml();
            System.out.format("Xml contained: %s%n", personList);
        }
        catch (Throwable thrown) {
            status = STATUS_ERROR;
            thrown.printStackTrace();
        }
        finally {
            System.exit(status);
        }
    }
}

Sample output:
Xml contained: PersonList(persons = [Person(optionalName.isPresent() = true, name = Name(nil = false, value = "Bob")), Person(optionalName.isPresent() = true, name = Name(nil = true, value = "")), Person(optionalName.isPresent() = false, name = null)])

A: Since I was not able to solve the problem completely by solely using and configuring JAXB properly, I decided to solve it as follows:
(The main goal was to write a subsystem to communicate with an external system based on XML)
As a starting point, I used the XSD schema provided by the target system to communicate with and generated the corresponding (XML)Java classes using JAXB and the XSD file. All the fields in those generated classes were of type JAXBElement<>, in order to be able to hold the 3 states needed (absent, null, someValue).
On the business model side, I used Java classes with Optional<> field types in order to hold the 3 states.
For the mapping, I wrote a mapper which uses reflection to recursively map from JAXB to Java and vice versa. When mapping from Java to JAXB, the mapper used the ObjectFactory to create the JAXBElement objects. (Mapper itself just had about 300 lines of code).
The fields were mapped based on the matching field names.
The most ugly and challenging part was, that the XSD schema file needed to be altered, in order to make JAXB generated classes that uses JAXBElement field types. Therefore I had to manually add the attribute minOccurs="0" nillable="true" to the XML elements, if not already set.
With that solution above, I finally managed to map the XML to Java and vice versa considering the 3 states needed, easily.
Of course, this solution has its drawbacks.
One is the manual modification of the XSD file. Usually bad practice to alter the XSD file provided by the external system, which acts as an interface contract.
For my requirements at the time, the solution worked perfectly. Even changes to the interface contract of the external system could be implemented very easily.

A: You can use some validation in your java class like @NotNull, @Size and so on. Or you can put default value , to be sure , that it will be not null. After that you can create DTOs (Data transfer object) with the recommended Xml annotations and mapped it with the ModelMapper.


text:
Q: Orientation of field at electrostatic boundary In the deduction of boundary conditions of electric field we take a surface and do calculations mathematically.enter image description here

Why do we take the direction of $E$ perpendicular and parallel in same direction (meaning the arrow in respective cases as shown in fig is parallel in direction ) across two surface? How can the deduction based on this assertion be used as a general one. (Meaning why not take the antiparallel case also)? What will happen if the direction are arbitrary.? Deriving the Electrostatic boundary conditions
This link question's last part is related to mine, i just want to know why this specific orientation is taken as it won't be a general one?

A: Its important to understand the Physics rarely depends on the choice / direction of coordinates that you take. Coordinates are a way for humans to comprehend and quantify things.
It doesn't matter which way $E^{above}$ and $E^{below}$ are directed. What matters is once you fix a direction for each vector you should change it mid way between calculations. You will always get the right direction provided you do the calculations right. As a matter of fact, in that particular figure, if the thin sheet is charged, then you will eventually see that the perpendicular components will turn out to be opposite.
What the figures shows is just a convention of vectors being directed along the positive axes.


text:
Q: How Object Masquerading works in Javascript I am having trouble getting this piece of code as to why the ClassA methods get assigned to ClassB. Specifically, I am not able to understand out the inheritance behaviour of first two lines of code in ClassB.
function ClassA(sColor) {
    this.color = sColor;
    this.sayColor = function () {
    alert(this.color);
    };
    this.sayColor1 = function () {
    alert("hi");
    };
}

function ClassB(sColor, sName) {
    this.newMethod = ClassA;
    this.newMethod(sColor);
    delete this.newMethod;
    this.name = sName;
    this.sayName = function () {
    alert(this.name);
    };
}

var objA = new ClassA('red');
var objB = new ClassB('blue', 'Nicholas');
objA.sayColor();
objB.sayColor();
objB.sayColor1();
objB.sayName();

A: You are assigning ClassA to be an instance method in ClassB, that's not inheritance. If you wish ClassB to extend ClassA, you can do this in the following way:
function ClassB(sColor, sName) {
    ClassA.call(this, sColor);
    // do the rest
}

ClassB.prototype = Object.create(ClassA.prototype);

A: I will try a bit to explain what happens in first two lines in ClassB
In the first line, property newMethod refers to function ClassA
    this.newMethod = ClassA;

then, in the second line, the function is being called,
    this.newMethod(sColor);

in this case the function inside ClassA refers to object in ClassB, so all properties of ClassA are added to created object.
and, at last reference is being deleted
    delete this.newMethod;

You can do this, simply by writing ClassA.call(this,sColor);, instead of these three lines

A: The issue is with the way you are implementing inheritance in JS
Object masquerading is done in JS this way:
function ClassA () {

}
function ClassB() {

    this.superclass = ClassA;

    this.superclass();

    delete this.superclass;
}
ClassB.prototype = new ClassA;

Try implementing it this way...
For more reference you can check :
http://www.sitepoint.com/javascript-objects/


text: Q: I am creating a maven project, and thecontent of a MANIFEST.MF does not react to changes in the pom.xml. Where should I look for a mistake? I am creating a maven project, and I am editing the pom.xml to specify the main class, etc. The MANIFEST.MF does not change its content, but I am sure I am writing the appropriate lines in the pom.xml. Is it possible the there is a problem in the settings in Eclipse? (I am doing it in Eclipse, btw)  Where should I look for a mistake?


text:
Q: PIC Bit Masking and Shifting for 4 Bit LCD Control I have a question regarding both masking and bit shifting.
I have the following code:
void WriteLCD(unsigned char word, unsigned commandType, unsigned usDelay)
{
    // Most Significant Bits
    // Need to do bit masking for upper nibble, and shift left by 8.
    LCD_D = (LCD & 0x0FFF) | (word << 8);
    EnableLCD(commandType, usDelay); // Send Data

    // Least Significant Bits
    // Need to do bit masking for lower nibble, and shift left by 12.
    LCD_D = (LCD & 0x0FFF) | (word << 12);
    EnableLCD(commandType, usDelay); // Send Data
}

The "word" is 8 bits, and is being put through a 4 bit LCD interface.  Meaning I have to break the most significant bits and least significant bits apart before I send the data.
LCD_D is a 16 bit number, in which only the most significant bits I pass to it I want to actually "do" something.  I want the previous 12 bits preserved in case they were doing something else.
Is my logic in terms of bit masking and shifting the "word" correct in terms of passing the upper and lower nibbles appropriately to the LCD_D?
Thanks for the help!

A: Looks ok apart from needing to cast "word" to an unsigned short (16 bit) before the shift, in both cases, so that the shift is not performed on a char and looses the data. eg:
LCD_D = (LCD & 0x0FFF) | ((unsigned short) word << 8);


text:
Q: How to set value of two or more different lists of object into one object using java 8 stream? I want to change for loop into stream contains in main method.
This is my main method
List<Model1> list = new ArrayList<>();
                List<Model2> model = Stream.iterate(0, n -> n + 1).limit(10).map(m -> new Model2(m))
                        .collect(Collectors.toList());
                List<Model2> model2 = Stream.iterate(11, n -> n + 1).limit(10).map(m -> new Model2(m))
                        .collect(Collectors.toList());

                list.add(new Model1("a", model));
                list.add(new Model1("b", model2));

                List<Model3> list3=new ArrayList<>();
                for(Model1 m:list) {
                    for(Model2 m2: m.getModel()) {
                        Model3 m3=new Model3();
                        m3.setStr(m.getS1());
                        m3.setValue(m2.getVal());
                        list3.add(m3);
                    }
                }

                list3.stream().forEach(s->
                System.out.println(s.getStr()+"::"+s.getValue()));

below are my model classes
public class Model1 {

        private String s1;

        private  List<Model2> model;
        // getter setter
    }

my next model
 public class Model2 {

        private Integer val;

    //getter setter
    }

Model in which I want to set data
public class Model3 {

        private String str;
        private Integer value;
        // getter setter

    }

The output of my main method  will be :
    a::0
    a::1
    a::2
    a::3
    a::4
    a::5
    a::6
    a::7
    a::8
    a::9
    b::11

I want the same output using Java streams

A: You can do like this:
list.stream()
 .flatMap(m->m.getModel().stream().map(m2->new Model3(m.getS1(),m2.getVal())))
 .collect(Collectors.toList()); // or .collect(Collectors.toCollection(ArrayList::new))

A: If you just want to print the values without copying data into Model3 you can use the following code
list.forEach(m -> m.getModel().forEach(m2 -> System.out.println(m.getS1() + "::" + m2.getVal())))


text:
Q: ImageFactory New Instance Fails I am trying to access a bitmap saved file and perform ObjectDetection on it. I utilize ImageFactory for this, but creating a new instance fails.
val imageFactory1 = ImageFactory.getInstance()
Caused by: java.lang.IllegalStateException: Create new ImageFactory failed!
Caused by: java.lang.ClassNotFoundException: ai.djl.android.core.BitmapImageFactory
Caused by: java.lang.ClassNotFoundException: Didn't find class "ai.djl.android.core.BitmapImageFactory" on path: DexPathList[[zip file "/data/app/com.example.imageclassification2-_snYrn7mbGjXlperEzCKWg==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.imageclassification2-_snYrn7mbGjXlperEzCKWg==/lib/arm64, /data/app/com.example.imageclassification2-_snYrn7mbGjXlperEzCKWg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
Not sure what BitmapImageFactory is, I've never heard about it.

A: The class ImageFactory  can not be found, it looks like you are using the
the DLJ library, make sure you have proper dependencies
Djl for android dependencies
 dependencies {
    implementation platform("ai.djl:bom:0.20.0")

    implementation "ai.djl:api"
    // TODO: remove djl android package version in 0.21.0
    implementation "ai.djl.android:core:0.20.0"
    runtimeOnly "ai.djl.pytorch:pytorch-engine"
    runtimeOnly "ai.djl.android:pytorch-native:0.20.0"
    runtimeOnly "ai.djl.android:onnxruntime:0.20.0"
}


text:
Q: Surprised over notation in fundamental theorem So I'm looking into the fundamental theorem of calculus and I'm a bit weirded out by the notation used in part two.
$$ \int_{a}^b f(t) dt = G(B)-G(a)$$
Why don't we say $F(b)-F(a)$? We are just talking about the anti-derivative of $a$ and $b$, right?

A: $G$ is any anti-derivative. The distinction here is important because if a function $f(x)$ has one anti-derivative $F(x)$, then $G(x) = F(x) + C$ is also an anti-derivative for $f$ for any constant $C$. So, there are many, and any one of them suffices to compute the definite integral $\int_a^b f(x)\;dx$.

A: It is usually written with $F(b) - F(a)$ as you say, for example on Wikipedia and Mathworld.
However, while $F$ usually denotes the antiderivative of $f$, this is not neccesarily true ($f$ and $F$ may be completely unrelated depending on the context). You could specify $G' = f$ and instead use the notation you have written. But if the book hasn't (EDIT: I see now that it did), I understand your confusion.

A: The author defines a specific function $F(x)$ by $F(x) = \int_a^xf(x)dx$ and shows that it is an antiderivative of $f(x)$.
He does not assume or claim that it is the only antiderivative, so he doesn't say "the" antiderivative.
He then goes on to handle the case for any other antiderivative that might exist, calling it $G(x)$ just to give it a name in order to state the result.
Note that your calling $F$ "the" antiderivative is incorrect in that sense. I understand what you mean (and everybody else does too), and the result stated shows that it doesn't matter which antiderivative you choose as long as you are subtracting two values of it, which causes the arbitrary constant to disappear in the end. The real content is that all of the antiderivatives, in the end, only differ by a constant.

A: To elaborate on what has already been said, the notation $F(x) = \int_a^x f(t) dt$ means the following: sketch a  graph of $f$, and find the area under the part of the graph that starts at an input value of $a$ and ends at an input value of $x$.  The area you compute is $F(x)$.
For example, you can figure out that $\int_1^x 2t dt = x^2 - 1$ by just sketching the function and using the formula for the area of trapezoids.  So in ths example, $f(x) = 2x$, and $F(x)$ in part 1 of the theorem has to be the function $F(x) = x^2-1$.
The second part of the theorem says that if you want to find $\int_a^b f(x) dx$, that is, the area under the graph of $f$ starting at an input value of $a$ and ending at an input value of $b$, you can do the following: choose any antiderivative $G(x)$, for $f(x)$, and then take $G(b) - G(a)$. The result is the area you seek to find.  For example, suppose you want to find $\int_2^3 x^2 dx$.  Again, $f(x) = 2x$, but you can take $G(x)$ to be $x^2 - 1$ or $x^2 + 3$ or $x^2$, since all of these functions have $2x$ as their derivative.  No matter which one of these you choose, $G(3) - G(2)$ will give you the area under the graph of $f(x) = 2x$ from $x = 2$ to $x = 3$.


text:
Q: How can I run tasks on multi process using WorkManager? Background
My application has two process. One(main process) is generally handling UI related jobs. And the other one(remote process) is taking care various types of jobs. Both processes have different tasks, resources and roles. So, each process can run their scheduled job on their own context. Also, every jobs SHALL run on their scoped process.
Problem
BTW, I tried to schedule a job using WorkManager(v2.1.0) on the remote process, but it was triggered on the main process. Because WorkManager register jobs to SystemJobService, and its target process is main.
I tried to configure the target Service, but I couldn't. How can I configure it?


text:
Q: Insert html text into .odt OpenOffice document with C# Please, help anyone who worked with OpenOffice Writer document in C#. How can insert an HTML formated text into the document? The following code:
((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getStart().
    setString("The <b>first line </b> in the newly created text document.\n\n");

inserts exactly The <b>first line </b> in the newly created text document.
I need to insert "The first line in the newly created text document"
Any solution?

A: If you want to insert formatted text - then you need to change the (paragraph/character) properties.
As you seen already OOo not react on HTML tags  ;-)


text:
Q: Mysql Error in Installation of Pimcore Xampp Ubuntu 18.04 I have try to install Pimcore "Advanced Demo Package (E-Commerce, PIM, MDM, DAM, ...)" package and it'll return me following error,
9/10 [=========================>--]  90%
 Trying to install assets as relative symbolic links.

 --- ------------------------------------------ ------------------
      Bundle                                     Method / Error
 --- ------------------------------------------ ------------------
  ✔   PimcoreAdminBundle                         relative symlink
  ✔   PimcoreCoreBundle                          relative symlink
  ✔   PimcoreEcommerceFrameworkBundle            relative symlink
  ✔   OutputDataConfigToolkitBundle              relative symlink
  ✔   Web2PrintToolsBundle                       relative symlink
  ✔   PimcoreCustomerManagementFrameworkBundle   relative symlink
  ✔   ObjectMergerBundle                         relative symlink
 --- ------------------------------------------ ------------------

 [OK] All assets were successfully installed.

 [ERROR] The following errors were encountered during installation

 * **An exception occurred while executing 'SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'':**

Warning: Error while sending QUERY packet. PID=11521

I can see this issue happen because it'll not select database first, without selecting database it'll try to run SHOW FULL TABLES WHERE Table_type = 'BASE TABLE' command.
After installation i can see it not create system admin account as well.
Is there any solution for this?

A: I have found solution to this, I hope my experience is helpful to others.
I have remove xampp installation and manually install apache,mariadb 10.01, mysql 5.7, php 7.1.
Now I can install without any issue. I hope this'll helpful to others as well.
Thanks,

A: Another nice way of getting pimcore installed locally is to use docker ;)
https://github.com/dpfaffenbauer/pimcore-docker-compose
At the time of writing there is some issue with permissions, so it would require a
chown -R www-data: .
after all steps have been followed. But should be pretty simple to install on ubuntu. I recommend docker if you work on multiple projects, it keeps dependencies/services separated, so no need to worry about php/mysql versions and etc.


text:
Q: Why it's not replacing? public class SecretPhrase
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        String phrase= "Go Team"; //replace phrase with asterisks
        phrase=phrase.replace("**","****");
        System.out.println(phrase);
    }
}

Why is phrase not being replaced with anything? I want the entire String to be full of *.

A: Documentation of replace function:
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
Parameters:
target The sequence of char values to be replaced
replacement The replacement sequence of char values
Returns:
The resulting string


text:
Q: Iterating Neeman's forcing In the paper, "Forcing with sequences of models of two types," (MR3201836), Neeman claims that, using a supercompact and a weakly compact above, one can force with his pure side conditions poset twice to obtain the tree property at $\omega_2$ and $\omega_3$.
Question 1: Are the details of this written up anywhere?
Question 2: Does the second stage add reals?  (For a fairly simple reason?)

A: I believe that Neeman's claim was in error.  This preprint contains a kind of counterexample.
Version 1 of the paper, available under the link on the arxiv, contains a detailed attempt to prove Neeman's claim based on my discussions with him.  After writing it all up, I thought about the argument again and started to worry that there were some gaps/circularities in the proof of the main technical lemma, Lemma 32, and a mistake in the argument for the tree property at $\kappa$ near the end.  (The copy of $\omega^{<\omega}$ I built isn't dense.)  After struggling to correct it, I gave up and started thinking in the other direction.
His claim included an answer to question 2 in the negative; the second stage should not add reals. My counterexample is to the published claim conjoined with that unpublished subclaim.  But maybe a completely different argument from what Neeman told me may prove the original claim.  The question is, what is that "special argument" for preserving $\omega_1$?
I told Neeman about this work, and he said that a modification of the forcing that directly avoids my counterexample should work.  (A Laver function is incorporated to bound the ordertypes of Magidor models.)  He says he will write it up.


text:
Q: mapping ajax data to jquery I am having the json data as
data.json file
 {

  "response":[
        {"id":1,"name":"Crime","rel":4},
        {"id":2,"name":"Murder","rel":5},
        {"id":3,"name":"Horror","rel":6},
        {"id":4,"name":"Comedy","rel":1},
       {"id":5,"name":"Novel","rel":2,}
     ]
  }

and the ajax call is..
 document.onreadystatechange = function () {
   if (document.readyState == "interactive") {
      $.ajax({
           url: "data.json",
           type: "GET",
           dataType: "json",
         success: function (response) {
           "use strict";
            main(response);
          }
  });
 }
}

and as I want the rel attribute of each item am trying with jquery mapping
    $.fn.tagcloud = function(options) {

       var opts = $.extend({}, $.fn.tagcloud.defaults, options);
      var tagWeights = this.map(function(){
      return $(this).attr("rel");
    });

how can i get response into the above function and
 where am getting tagWeights empty so how can I retreive tag weights
 and am trying make it into array
 tagWeights = jQuery.makeArray(tagWeights).sort(compareWeights);

So how can I get the attribute "rel" data

A: Problem here you are using JSON not XML or DOM. So avoid using attr() of jquery function.
You can try like this inside main function.
var tagWeights = response.map(function(item){
     return item.rel;
 });

tagWeights.sort(compareWeights);


text:
Q: server-side css selectors I am creating a tool that will check dynamically generated XHTML and validate it against expected contents.
I need to confirm the structure is correct and that specific attributes exist/match. There may be other attributes which I'm not interested in, so a direct string comparison is not suitable.
One way of validating this is with XPath, and I have implemented this already, but I would also like something less verbose - I want to be able to use CSS Selectors, like I can with jQuery, but on the server - within CFML code - as opposed to on the client.
Is there a CFML or Java library that allows me to use CSS Selectors against an XHTML string?

A: I've just released an open source project which is a W3C CSS Selectors Level 3 implementation in Java. Please give it a try. I was looking for the same thing and decided to implement my own engine. It's inspired by the code in WebKit etc.
http://github.com/chrsan/css-selectors/tree

A: I don't know of a Java library itself, but there is a Ruby library called Hpricot that does exactly what you're looking for. In conjunction with the Ruby implementation on the Java platform, JRuby, it should be relatively straightforward to call Ruby methods from your Java code (using BSF, JSR-222 Scripting APIs, or an internal API).
Are you using Coldfusion 8? Coldfusion 8, being based on Java 6, supports JSR-222 Scripting APIs "javax.scripting".
Take a look at this blog entry on embedding PHP within CFML. You should be able to do the same with Ruby. There is ZIP file example code linked from this blog posting, and if you crack open the CFML, you'll see a good example of embedding Ruby within CFML.
Although it might take a bit of work to make all the pieces work together, but with a bit of investment, it should give you the robust parsing/CSS selector querying that you're looking for.

A: Hpricot is definetly a fantastic solution if the JRuby-route is open to you.
Wrt. XPath being the "correct" way to access XML documents... sorry but this is rubbish. There are numerous ways to access elements of an XML document: DOM traversal, XPath, XQuery, CSS selectors to name a few. XPath is certainly popular but CSS selectors are very very powerful, assuming your XML document has HTML semantics.

A: If you can use PHP within your CFML (as mentioned above), you could take advantage of this excellent "jQuery for PHP" library, phpQuery
Full CSS selector support, manipulation functions, traversing, etc. It should work great for what you need.
Hope it helps.

A: There is a theoretical difference between the server and client. To a web browser, the document is a living DOM hierarchy. To your server code it's merely an XML document of whatever type. XPath is the "correct" way to access elements of an XML document.
So unless you have a serious performance problem with your current XPath solution, or it doesn't actually work correctly, I suggest you stick with it. Trying something too clever brings the risk of breaking something that's working.
If you find the XPath to be too verbose and ugly to leave sitting around, or want more power to re-use the tool in different cases, or just can't resist trying to do something clever, then you could try writing a utility that compiles a given CSS selector into an XPath. You could then call this in one line whenever you needed.

A: it may be easier to use cQuery.com - cQuery.com is an API based 'Content Query Engine' to extract content from live websites by using CSS.
You can using it programatically in you application.


text:
Q: I can't seem to pass an array of objects as prop (console logs 1 object, [object object] instead) I am new to React js and I am trying to pass my data(dummy_data) as props from App.js to PieChart.js so that I can access the data from PieChart.js. dummy_data is an array of objects, dummy_data={[object Object] [object Object] ... [object Object]}.
I am confused as to why I am only able to see 1 object pair from my console log in PieChart, [object Object]. What do I need to do to pass the dummy_data object array to my PieChart function in PieChart.js?
I have tried the passing of a normal array the syntax , but my console log in PieChart.js still shows me the same output [object Object]. Am I using the syntax wrongly?
App.js
import React from "react";
import axios from "axios";

// imports
import PieChart from './components/piechart'; // Piechart for dashboard

/*
Info:
"data" contains all MongoDB data read from /api call, which uses find({ }) to search MongoDB for all data.
"data" is an array of objects in the format Data: { [object object], [object object] ... [object object] }
getInOutEnv(item) {} is used to map the "data" retrieved from /api call. The resulting response allows me to
access each object in "data" as "item" and accessing the object's properties using item (item.environment and item.lightlevel)
*/

// app class
class App extends React.Component {

  // Accessing values/var from functions
  dummy = []; // store response data from /api (server/MongoDB)
  dummy_final = []; // store previous data of dummy and check to see if they hold the same values
  map = [];   // store data in mapped format to be able to access object properties (e.g. trythis.env and trythis.lightlv)

  getInOutEnv(item) {
    console.log( 'obj - ' + [item.environment,item.lightlevel].join(" ") );
    let inOut = {env: item.environment, lightlv: item.lightlevel};
    return (inOut);
  }

  getData() {
    axios.get('/api')
      .then((response) => {
        const data = response.data; //contains all the data from MongoDB
        console.log('---------- <Get Data> ----------');
        console.log(`data : ${data}`);
        console.log(`map : ${this.map}`);
        // try 1
        this.dummy = data;  // data and dummy are an array of objects -> Data: { [object object] [object object] ... [object object]}
        console.log(`[dummy] ${this.dummy}`);
        let map = this.dummy.map(this.getInOutEnv);
        console.log('----- accessing obj properties -----')
        if (JSON.stringify(this.dummy) !== JSON.stringify(this.dummy_final)) {
          console.log(`[dummy] ${JSON.stringify(this.dummy)}`);
          console.log(`[dummy_final] ${JSON.stringify(this.dummy_final)}`); // check if difference between dummy and dummy_final
          ...
            //increase count of lightlv
            switch(trythis.lightlv) { // 6 cases 'Bright', 'Dark', 'Normal', 'VerySunny', 'Outcast', 'Sunny'
              ...
            }
          }
          // set dummy to dummy_final, so this loop will not trigger unless new data is fetched to dummy from /api (MongoDB)
          this.dummy_final = this.dummy;
          console.log(`[new dummy_final] ${JSON.stringify(this.dummy_final)}`);
        } else {
          console.log('[Data stored is up to date] Values of MongoDB matches current data stored in dummy_final');
          console.log(`[Current Env Indoor] ${this.envCount_Indoor}`);  // check count of env indoor
          console.log(`[Current Env Outdoor] ${this.envCount_Outdoor}`);  // check count of env outdoor
          console.log(`[Current Env Mismatched Field Names] ${this.envCount_Error}`);  // check count of mismatched Field Names
        }
      })
      .catch(() => {
        alert('Error in retrieving data');
      });
  }

  render() {

    this.getData();
    console.log(`[testingData] ${this.dummy_final}`);

    return(

          Pie Chart
          <PieChart dummy_final={this.dummy_final}/>

    )
  }
}

export default App;

PieChart.js
import React from "react";
import { Pie, Doughnut } from 'react-chartjs-2';
import { Chart, ArcElement } from "chart.js";
Chart.register(ArcElement);

// chart background colour for env
const bgcolour_env = [
    'rgba(255, 99, 132, 0.2)',  //colour 1...
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'   //last colour
]

const hover_env = [
    'rgba(255, 99, 132, 0.8)',  //colour 1...
    'rgba(54, 162, 235, 0.8)',
    'rgba(255, 206, 86, 0.8)',
    'rgba(75, 192, 192, 0.8)',
    'rgba(153, 102, 255, 0.8)',
    'rgba(255, 159, 64, 0.8)'
]

// chart background for lightlevel

const data = {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: bgcolour_env,
        hoverBackgroundColor: hover_env
    }]
}

function PieChart({dummy_final}) {
  let data1 = [];
  data1 = dummy_final;
  console.log(`dummy_final : ${dummy_final}`);
  //console.log(`data1 : ${JSON.stringify(data1)}`);

  return (

        test
        <Doughnut
        data={data}
        options={{
          title:{
            display:true,
            text:'Average Rainfall per month',
          },
          legend:{
            display:true,
            position:'right'
          }
        }}
        />

  );
}

export default PieChart;

A: UPDATE!
I realised that using setState here would actually be easier to pass the data and is the more ideal way of passing my data since it is part of the React Lifecycle (still have no clue how to pass a promise's returned data).
App.js
import React from "react";
import axios from "axios";

// import from components
import PieChart from './components/piechart'; // Piechart for dashboard

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      environment: '',
      lightlevel: '',
      data_form: []
    };
  }

  // Accessing values/var from functions
  dummy = []; // store response data from /api (server/MongoDB)
  dummy_final = []; // store previous data of dummy and check to see if they hold the same values

  getData() {
    return axios.get('/api')
      .then((response) => {
        const data = response.data; //contains all the data from MongoDB
        this.dummy = data;
        console.log(`[data] : ${data}`);
        console.log(`[check dummy] ${this.dummy}`);
        console.log('---------- <Get Data> ----------');
        // Checking if dummy and dummy_final have the same data. If they do, do not retrieve data. If not retreieve and set data.
        if (JSON.stringify(this.dummy) !== JSON.stringify(this.dummy_final)) {
          this.setState({
            data_form: this.dummy
          });
          console.log('Reached');
          this.dummy_final = this.dummy;
          console.log(`[dummy_final] ${this.dummy_final}`);
        } else {
          console.log('Data up to date');
          console.log(`[Current Data] ${this.dummy_final}`);
        }
      })
      .catch(() => {
        alert('Error in retrieving data');
      });
  }

  render() {

    this.getData();

    console.log(`[state data] ${this.state.data_form}`);

    //JSX
    return(

          Pie Chart
          <PieChart data_form={this.state.data_form}/>

    )
  }
}

export default App;

Since you cannot call upon useEffect in Class Component, I just used a conditional statement to compare this.dummy and final_dummy after assigning this.dummy to my response.data from my /api call, at the start since this.dummy will be assigned response.data, the conditional statement returns false, thereby triggering the function to setState with this.dummy as the data and assigning this.dummy to this.dummy_final. After which since calling a useState will result in an infinite render loop, I fixed this with the conditional statement such that will since this.dummy is now = this.dummy_final, the condition is false and will not trigger the setState conditional block, thereby preventing an infinite loop. (This method is basically just replicating useEffect hook in Component Class without encapsulating a functional component)
PieChart.js
import React from "react";

function PieChart(props) {
  console.log(`data_form : ${props.data_form}`);
  ...

  return (

        ...

  );
}

export default PieChart;

Hope this helps anyone who ran into the same issue starting React without an experience.
Feel free to leave some links to some useful information about the latest React workflow. I would greatly appreciate it, Cheers!

A: About useEffect, if you'd look the link that I left on my comment, you'd see that it combines two class methods componentDidMount and componentDidUpdate, actually it has componentWillUnmount there too, try something like this:
import React from "react";
import axios from "axios";

import PieChart from './components/piechart'; // Piechart for dashboard

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      environment: '',
      lightlevel: '',
      data_form: [],
    };
  }

  getData() {
    axios.get('/api')
      .then((response) => {
        const data = response.data; //contains all the data from MongoDB
        this.setState({
          data_form: data,
        });
      })
      .catch((error) => alert('Error in retrieving data', error));
  }

  componentDidMount() {
    this.getData();
    console.log(`did mount [state data] ${this.state.data_form}`);
  }

  componentDidUpdate() {
    this.getData();
    console.log(`did update [state data] ${this.state.data_form}`);
  }

  render() {
    return(

        Pie Chart
        <PieChart data_form={this.state.data_form}/>

    )
  }
}

export default App;

Can't test it myself without the project, but I think it should work.
UPDATE: (SAME CODE WITH FUNCTIONAL COMPONENTS)
import React, { useEffect, useState } from "react";
import axios from "axios";

// import from components
import PieChart from './components/piechart'; // Piechart for dashboard

function App()  {
  const [dataForm, setDataForm] = useState([]);

  getData() {
    axios.get('/api')
      .then(({ data }) => {
        setDataForm(data);
      })
      .catch((error) => alert('Error in retrieving data', error));
  }

  useEffect(() => {
    getData()
    console.log(`will be called once on first render [state data]: ${dataForm}`);
  }, [])

  return (

      Pie Chart
      <PieChart data_form={dataForm}/>

  )
}

export default App;


text:
Q: XML, Soap and XPATH query with multiple instance of node I am working with some XML, not really technically inclined and been trying to figure this out from reading various sources on the internet but getting nowhere fast.
I have the below XML:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Header>
      <XXXSoapHeader xmlns="http://XXX.com/optima/webservices">
         <AuthenticationString>?</AuthenticationString>
      </XXXSoapHeader>
   </soap:Header>
   <soap:Body>
      <SubmitMultipleCalcMarginRequestResponse xmlns="http://XXX.com/optima/webservices">
         <SubmitMultipleCalcMarginRequestResult>
            <TaskExecutionSubmitInfo>
               <taskExecutionId>74457</taskExecutionId>
               <description>Calc LIVE BROKER margin : Account WebServiceTest_Account1(435) : Business Date (12-Feb-2007)</description>
            </TaskExecutionSubmitInfo>
            <TaskExecutionSubmitInfo>
               <taskExecutionId>74458</taskExecutionId>
               <description>Calc LIVE BROKER margin : Account WebServiceTest_Account2(436) : Business Date (12-Feb-2007)</description>
            </TaskExecutionSubmitInfo>
         </SubmitMultipleCalcMarginRequestResult>
      </SubmitMultipleCalcMarginRequestResponse>
   </soap:Body>
</soap:Envelope>

And have been using the below to extract info from the nodes:
//*[name() = 'taskExecutionId']

Which returns:
<?xml version="1.0" encoding="UTF-8"?>

<root xmlns="http://XXX.com/optima/webservices">
  <taskExecutionId>74457</taskExecutionId>
  <taskExecutionId>74458</taskExecutionId>
</root>

But what can I do if I want to return just the second taskExecutionId? Or the first? I have tried appending with a [n] but this doesn't to work. Any ideas?

A: To get the the N th instance of something in the whole XML document, you can use this XPath:
(//*[name() = 'taskExecutionId'])[N]

The parentheses are necessary.  Without them, you'd be selecting the N th taskExecutionId under its particular parent.


text:
Q: detect fragmented contour for a shape with opencv Suppose I have images of shapes in which some of them have fragmented contours and some of them are normal and healthy. Now consider I am getting an image and I have to decide which category it belongs. How can I decide? I used connectedComponents from opencv but for both of them it will output two regions.

img = cv2.imread('sample.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
numLabels, labels = cv2.connectedComponents(img_gray)

Does it have some other workaround or am I doing it wrong?
(Shapes can be anything: circle, triangle, rectangle, ...)


text:
Q: Paypal Api Redirection Headers issue I am working Paypal with using API.  I am getting error like this. I searched in Google.. i got only one suggestion regarding paypal api credentials. but the below code is working in another server. can anybody tell me what may be the reason.Thanks inadvance
        Error : Security header is not valid
        Array
        (
            [TIMESTAMP] => 2014%2d02%2d10T16%3a09%3a39Z
            [CORRELATIONID] => 6df53789eb1fb
            [ACK] => Failure
            [VERSION] => 76%2e0
            [BUILD] => 9605603
            [L_ERRORCODE0] => 10002
            [L_SHORTMESSAGE0] => Security%20error
            [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
            [L_SEVERITYCODE0] => Error
        )

A: One of the following maybe..
- You are in sandbox mode with a live account or vice versa
- You have extra spaces before or after the account credentials


text:
Q: Dynamic reload of items in select many component I want to achieve sth similar to http://www.primefaces.org/showcase/ui/pprSelect.jsf but i need a collection of double-combos, so i wrapped it in ui:repeat
I need on the backend check which element from collection of double-combos was changed and what I need to reload. For communication is used p:ajax as in the example, but AjaxBehaviorEvent not bring me any idea of index of element ( i mean index of double-combos element generated by ui:repeat)
My client code, the idea is to update bean:selectedIndex everytime when a ajax event will be raised ( on change value of selectOneMenu ), and value of bean:selectedIndex will be set as index of changed selectOneMenu
private List<State> productStates
private int selectedIndex;
private List<Group> groups;
private Map<Integer, Collection<Device>> availableDevicesMap;

<ui:repeat var="state" value="#{bean.productStates}" varStatus="iter">

    <p:selectOneMenu id="devGroup" value="#{state.group}">
        <f:selectItems value="#{bean.groups}"  />
            <p:ajax  update="refreshable"  process="devGroup, @this"  listener="#{bean.refreshDevicesForState}" >
                    <f:setPropertyActionListener target="#{bean.selectedIndex}" value="#{iter.index}"/>
            </p:ajax>
    </p:selectOneMenu>

    <!-- THIS WILL BE UPDATED -->
    <h:panelGroup id="refreshable">
            <p:selectManyButton  id="devices" value="#{state.devices}" >
                <f:selectItems value="#{bean.availableDevicesMap[status.index]}"   />
            </p:selectManyButton>
    </h:panelGroup>
</ui:repeat>

Backend which doesn't work as expected. setPropertyActionListener is not invoked and selectOneMenu component hasn't got selected group as value
public refreshDevicesForState(AjaxBehaviorEvent e) {
        SelectOneMenu menu = (SelectOneMenu)e.getComponent();
    // this value is not as selected on frontend
        Group group = (Group)menu.getValue();

    // selectedIndex will not be set, so I assume that setPropertyActionListener didn't invoked
    availableDevicesMap.put(selectedIndex, group.getDevices());
}

I tried also with code below which works but in my opinion it is ugly
// id will be grandpaId:parentId:index:myId
String selectedIndex = IdHelper.getIdPart(e.getComponent().getClientId(), -2);
State state = productStates.get(Integer.parseInt(selectedIndex));

I am using latest primefaces on glassfish and Mojarra as jsf reference implementation
Thank you for any help
In more general sense:
I have list of objects on backed bean, lets say Cars
List<Car> cars

on frontent I iterate over them and create select brand and select model combos for every car. When user select brand for i.e 4th car i want to get to know on backend that 4th car will be changed and i will reload list of available model for this one car

 <ui:repeat var="state" value="#{bean.cars}" >
    <p:selectOneMenu id="brands"/>// select brand

    <p:selectOneMenu "models"/>// show available models depends on selected brand
 </ui:repeat>

How to handle it correct in the JSF world ?

A: My first suggestion is to use converter for Group.
SelectOneMenu cannot set custom class, only with the help of a converter. (an example is at autocomplete: http://www.primefaces.org/showcase/ui/autoCompletePojo.jsf)
Second, in your bean handler, productStates variable contains already the selected values (of selectOneMenus). You can use it easier, than access it from the event.
If the values of selectOneMenus depend on State, you have to modify this:
<f:selectItems value="#{bean.groups}"  />

to be able to express which group values should be displayed.
If you want debug it (without eclipse debugging), you can use messages, for example:
add this to xhtml:
<p:growl id="msgs" showDetail="true"/>

and in bean:
public refreshDevicesForState(AjaxBehaviorEvent e) {

 ...
 FacesMessage msg = new FacesMessage("Selected", "any debug info" + productStates.get(0).getGroup());
 FacesContext.getCurrentInstance().addMessage(null, msg);

}

I modified my answer, according to your mods. I would do it this way:
xhtml:
<ui:repeat var="state" value="#{bean.productStates}" varStatus="iter">

 <p:selectOneMenu id="devGroup#{iter.index}" value="#{state.group}"
        valueChangeListener="#{bean.updateSubProperty}" immediate="true">
  <f:selectItems value="#{bean.groups}"  />
  <f:attribute name="index" value="#{iter.index}" />
 </p:selectOneMenu>

 <p:selectOneMenu id="subDevGroup#{iter.index}">
  ...
 </p:selectOneMenu>
</ui:repeat>

bean:
 public void updateSubProperty(ValueChangeEvent vce) {
  String index = vce.getComponent().getAttributes().get("index").toString();
  int i = Integer.parseInt(index); //this is the index of the selected selectOneMenu
  ///...

  //update sub selectOneMenu
  RequestContext.getCurrentInstance().update("subDevGroup" + index);
 }


text:
Q: Files Continually Fail to Open in Multiple Programs For the last week, I've not been able to open files in Xcode. I'm looking to learn why it isn't working, and how to fix it.
I've posted two questions in stack overflow here and here, and received good advice, but no solution.
Additionally, I have another program here which opens files just fine with no issues... I have no idea why one is opening files, and the other isn't. (Reminder, NONE of my recent programs are opening files.)
{Update: checking above program before this post, NOW it fails, saying the files don't exist... This program was running yesterday and I made no changes to it. I promise it was working... So why am I having file issues suddenly?}
Just to be sure, I've:

*

*Gone to Build Phases >> Copy Files >> Add File, adding both files to Absolute Path

*Checked the spelling of the files and my code

Here is a simple program that should open a text file, then print the contents, which are "testing 1 2 3" - except it doesn't:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {

    fstream inFile;

    string words;

    inFile.open("test.txt");
    if (!inFile) {
        cout << "Failure." << endl;
        exit(1);
    }

    getline(inFile, words);

    cout << words << endl;

    return 0;
}

This program fails every time (as do my others).
Here is my output:
Failure.
Program ended with exit code: 1
Setting a breakpoint at the statement  inFile.open("test.txt");, I get:
Printing description of inFile:
(std::__1::fstream) inFile = {
  std::__1::basic_iostream<char, std::__1::char_traits<char> > = {
    std::__1::basic_istream<char, std::__1::char_traits<char> > = {
      std::__1::basic_ios<char, std::__1::char_traits<char> > = {
        std::__1::ios_base = {
          __fmtflags_ = 4098
          __precision_ = 6
          __width_ = 0
          __rdstate_ = 0
          __exceptions_ = 0
          __rdbuf_ = 0x00007fff5fbff4f8
          __loc_ = 0x00007fff7b718c30
          __fn_ = 0x0000000000000000
          __index_ = 0x0000000000000000
          __event_size_ = 0
          __event_cap_ = 0
          __iarray_ = 0x0000000000000000
          __iarray_size_ = 0
          __iarray_cap_ = 0
          __parray_ = 0x0000000000000000
          __parray_size_ = 0
          __parray_cap_ = 0
        }
        __tie_ = 0x0000000000000000
        __fill_ = -1
      }
      __gc_ = 0
    }
    std::__1::basic_ostream<char, std::__1::char_traits<char> > = {
      std::__1::basic_ios<char, std::__1::char_traits<char> > = {
        std::__1::ios_base = {
          __fmtflags_ = 4098
          __precision_ = 6
          __width_ = 0
          __rdstate_ = 0
          __exceptions_ = 0
          __rdbuf_ = 0x00007fff5fbff4f8
          __loc_ = 0x00007fff7b718c30
          __fn_ = 0x0000000000000000
          __index_ = 0x0000000000000000
          __event_size_ = 0
          __event_cap_ = 0
          __iarray_ = 0x0000000000000000
          __iarray_size_ = 0
          __iarray_cap_ = 0
          __parray_ = 0x0000000000000000
          __parray_size_ = 0
          __parray_cap_ = 0
        }
        __tie_ = 0x0000000000000000
        __fill_ = -1
      }
    }
  }
  __sb_ = {
    std::__1::basic_streambuf<char, std::__1::char_traits<char> > = {
      __loc_ = (__locale_ = 0x00007fff7b718c30)
      __binp_ = 0x0000000000000000
      __ninp_ = 0x0000000000000000
      __einp_ = 0x0000000000000000
      __bout_ = 0x0000000000000000
      __nout_ = 0x0000000000000000
      __eout_ = 0x0000000000000000
    }
    __extbuf_ = 0x0000000102001000 ""
    __extbufnext_ = 0x0000000000000000
    __extbufend_ = 0x0000000000000000
    __extbuf_min_ = ""
    __ebs_ = 4096
    __intbuf_ = 0x0000000000000000
    __ibs_ = 0
    __file_ = 0x0000000000000000
    __cv_ = 0x00007fff7b718a40
    __st_ = (__mbstate8 = "", _mbstateL = 0)
    __st_last_ = (__mbstate8 = "", _mbstateL = 0)
    __om_ = 0
    __cm_ = 0
    __owns_eb_ = true
    __owns_ib_ = false
    __always_noconv_ = true
  }
}
(lldb)

And setting a breakpoint at if(!inFile) ... I get (looks that exact same to me):
  Printing description of inFile:
  (std::__1::fstream) inFile = {
  std::__1::basic_iostream<char, std::__1::char_traits<char> > = {
    std::__1::basic_istream<char, std::__1::char_traits<char> > = {
      std::__1::basic_ios<char, std::__1::char_traits<char> > = {
        std::__1::ios_base = {
          __fmtflags_ = 4098
          __precision_ = 6
          __width_ = 0
          __rdstate_ = 4
          __exceptions_ = 0
          __rdbuf_ = 0x00007fff5fbff4f8
          __loc_ = 0x00007fff7b718c30
          __fn_ = 0x0000000000000000
          __index_ = 0x0000000000000000
          __event_size_ = 0
          __event_cap_ = 0
          __iarray_ = 0x0000000000000000
          __iarray_size_ = 0
          __iarray_cap_ = 0
          __parray_ = 0x0000000000000000
          __parray_size_ = 0
          __parray_cap_ = 0
        }
        __tie_ = 0x0000000000000000
        __fill_ = -1
      }
      __gc_ = 0
    }
    std::__1::basic_ostream<char, std::__1::char_traits<char> > = {
      std::__1::basic_ios<char, std::__1::char_traits<char> > = {
        std::__1::ios_base = {
          __fmtflags_ = 4098
          __precision_ = 6
          __width_ = 0
          __rdstate_ = 4
          __exceptions_ = 0
          __rdbuf_ = 0x00007fff5fbff4f8
          __loc_ = 0x00007fff7b718c30
          __fn_ = 0x0000000000000000
          __index_ = 0x0000000000000000
          __event_size_ = 0
          __event_cap_ = 0
          __iarray_ = 0x0000000000000000
          __iarray_size_ = 0
          __iarray_cap_ = 0
          __parray_ = 0x0000000000000000
          __parray_size_ = 0
          __parray_cap_ = 0
        }
        __tie_ = 0x0000000000000000
        __fill_ = -1
      }
    }
  }
  __sb_ = {
    std::__1::basic_streambuf<char, std::__1::char_traits<char> > = {
      __loc_ = (__locale_ = 0x00007fff7b718c30)
      __binp_ = 0x0000000000000000
      __ninp_ = 0x0000000000000000
      __einp_ = 0x0000000000000000
      __bout_ = 0x0000000000000000
      __nout_ = 0x0000000000000000
      __eout_ = 0x0000000000000000
    }
    __extbuf_ = 0x0000000102001000 ""
    __extbufnext_ = 0x0000000000000000
    __extbufend_ = 0x0000000000000000
    __extbuf_min_ = ""
    __ebs_ = 4096
    __intbuf_ = 0x0000000000000000
    __ibs_ = 0
    __file_ = 0x0000000000000000
    __cv_ = 0x00007fff7b718a40
    __st_ = (__mbstate8 = "", _mbstateL = 0)
    __st_last_ = (__mbstate8 = "", _mbstateL = 0)
    __om_ = 0
    __cm_ = 0
    __owns_eb_ = true
    __owns_ib_ = false
    __always_noconv_ = true
  }
}
(lldb)

A: Short answer is, my project was broken because it was trying to run a project in a path where a previous project already existed. Once I deleted both completely, and started anew, my program worked just fine.
While I made no changes to the original project, I started a new project in the same directory, which then caused all my issues.


text:
Q: Template selection area is not visible on page editor sidebar in wordpress twentty sixteen default theme Template selection area is not visible on page editor sidebar in wordpress twentty sixteen default theme
    <?php
/**
 * Template Name:Zoho testAPI
 *
 *
 *
 *
 */

echo phpinfo();
?>

A: Twenty Sixteen does not contain any post type templates by default, thus no template selection is shown.
Adding a custom foo.php file to the wp-content/themes/twentysixteen folder with the following content works just fine and reveals the template selection meta box (title: "Page Attributes"):
<?php
/**
 * Template Name: Foo Bar
 * Template Post Type: post, page
 */

 // Do some stuff…

It also works for pages only using Template Name without Template Post Type:
<?php
/**
 * Template Name: Foo Bar
 */

 // Do some stuff…


text: Q: Flutter Firestore Cached Netwok Image Time I have a social media app and I get photos from firebase and show them on my home screen. In this process, I use Cached Network Image to load photos faster and the photos are successfully cached. What I'm wondering is whether these cached photos automatically clean themselves after a certain time, if they do, after how much time has passed. If it doesn't clean, what should I do for it to automatically clean itself?


text:
Q: problem with updating state with useState and prev state My code is like this:

const [registryFormState, setRegistryFormState] = useState({
    email: null,
    username: null,
    password: null,
    confirmPassword: null,
  });

  const changeFormHandler = (value, inputIdentify) => {
    switch (inputIdentify) {
      case 'email':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          email: value,
        }));
      case 'username':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          username: value,
        }));
      case 'password':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          password: value,
        }));
      case 'confirmPassword':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          confirmPassword: value,
        }));
      default:
        return;
    }
  };

but when i change just email and console.log() the registryFormState, all the properties value change with the same value

A: You can use registryFormState to destructure instead of prevState like so:
import React from "react";

export default function Lol() {
  const [registryFormState, setRegistryFormState] = React.useState({
    email: null,
    username: null,
    password: null,
    confirmPassword: null
  });

  const changeFormHandler = (value, inputIdentify) => {
    switch (inputIdentify) {
      case "email":
        setRegistryFormState({
          ...registryFormState,
          email: value
        });
        break;
      case "username":
        setRegistryFormState({
          ...registryFormState,
          username: value
        });
        break;
      case "password":
        setRegistryFormState({
          ...registryFormState,
          password: value
        });
        break;
      case "confirmPassword":
        setRegistryFormState({
          ...registryFormState,
          confirmPassword: value
        });
        break;
      default:
        break;
    }
  };

  return (
    <div>
      <input onChange={e => changeFormHandler(e.target.value, "email")} />
      <input onChange={e => changeFormHandler(e.target.value, "username")} />
      <input onChange={e => changeFormHandler(e.target.value, "password")} />
      <input
        onChange={e => changeFormHandler(e.target.value, "confirmPassword")}
      />
      <button onClick={() => console.log(registryFormState)}>Submit</button>
    </div>
  );
}


text:
Q: SIMPLE :: XCOPY NOT PRODUCING OUTPUT IN .bat I'm a mortgage loan guy in Seattle, WA and I frequently set up a folder hierarchy into which I save a client's documents and as they come in to me.  I've been creating these manually for years and I'd like to save the 3 to 4 minutes it takes to set these up by using a batch file.
So...  I have a default set of folders, some of which contain a couple of small Adobe PDFs.  What I'd like to do (and cannot make happen) is to run a batch file that would facilitate some custom remarks or input from me during the batch so that with a click and a couple of keystrokes, I have an organized folder setup for a new client within seconds rather than minutes.
I've written the following but it isn't producing any output folders or files.
______not sure character terms show correctly - see linked images below for actual______
@echo off
::Ask
echo Your Source Path:
set INPUT1=
set /P INPUT1=Type input:

echo Your Destination Path:
set INPUT2=
set /P INPUT2=Type input:

C:\WINDOWS\system32\xcopy.exe /e /v %INPUT1% %INPUT2%

My responses were:
to the first prompt "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014"
to the second prompt "E:\DV8333 MY DOCUMENTS\001 CLIENTS\"
I have verified that xcopy.exe is in fact located as indicated above.
I'm on XP SP3
My actual paths and .bat file are shown in the linked image for clarity.
http://www.avidrecording.com/images/01.png
Thanks in advance, much appreciated.

A: @Rem save this as a .bat file and run
@echo off
set /P source=Enter Source Folder:
echo %Source%
set /P destination=Enter Destination Folder:
echo %destination%
xcopy %source% %destination% /v /i /e

A: Fundamentally, your problem appears to be that the xcopy command can't figure out which of the data it is receiving is parameters and which switches and which superfluous because you have spaces in your directorynames.
Fortunately, the cure is simple. "quote your parameters"
C:\WINDOWS\system32\xcopy.exe /e /v "%INPUT1%" "%INPUT2%"

Now - the path to xcopy.exe is probably superfluous - as is the extension, so
xcopy /e /v "%INPUT1%" "%INPUT2%"

is more than likely all you'd need.
(I'd caution to experiment with a throw-away destination until you've perfected your method. I use a RAMDISK...)
Also, if you're copying a template, then there's no apparent reason for all the folderol about inputting Input1. If you have more than one template set, set up a separate batch and shortcut  for each one with a fixed template path, eg
xcopy /e /v "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014" "%INPUT2%"

Note the use of quotes to defeat the evil spaces.
Next, your destination could be built, but may contain spaces. For instance, you may have a client to which you wish to refer as "037 - Fred Nurk". Now it's a pain to have to type in the full path, so make it easy. Just type in the 037 - Fred Nurk part and let batch fill in the rest.
xcopy /e /v "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014" "E:\DV8333 MY DOCUMENTS\001 CLIENTS"\"%input2%"\

Note that this will append the input as a directory under E...001 clients. Note that the strings are concatenated and the double-quotes are there solely to tell batch "here be a string that may contain spaces."
If this works, and there's no reason why it wouldn't (does for me...) then all you'd need to do is enter the client details and the template would be copied to a new directory. Now actually playing around with the data in the files that are copied so that they are customised - well, at the price, that would be worthy of another question...

A: @echo off
echo Backing up file
set /P source=Enter source folder:
set /P destination=Enter Destination folder:
set /P Folder name=Enter Folder name
set xcopy=xcopy // Set the switches as per your need
%xcopy% %source% %destination%
pause


text:
Q: Firebase: get more information about attendees attending an event With Firebase (Web) I am trying to get useful information from my event
My database structure:
{
    users:
        "abc": {
            birthday: "21/07/1998",
            firstname: "Maxime",
            lastLogin: "30/07/2018"
        },
        "def": {
            birthday: "12/03/1973",
            firstname: "John",
            lastLogin: "12/04/2018"
        },
    },

    events: {
        "df16s5dfs21er6zf5f1ze-": {
            title: "Some great event",
            members: [
                "abc",
                "def"
            ]
        }
    }
}

What I try to obtain in Javascript is an object containing all my events, the members of those events and some more information about those members. So for example:
{
    "df16s5dfs21er6zf5f1ze-": {
        title: "Some great event",
        members: {
            "abc": {
                firstname: "Maxime",
                lastLogin: "30/07/2018"
            },
            "def": {
                firstname: "John",
                lastLogin: "12/04/2018"
            }
        }
    }
}

As you can see the only things that have been added is "firstname" and "lastLogin" that should be fetched directly from the "users" node.
I tried multiple things in Javascript, without success :(
Does anybody has a good example of a solution that can handle this situation?
My code at the moment:
let refEvents   = firebase.database().ref("/events");
let refUsers    = firebase.database().ref("/users");

refEvents
    .once('value')
    .then((snapEvents) => {
        snapEvents.forEach((snapEvent, kEvent) => {
            let event = snapEvent.val();
            // Iterate on event.members and write this info into event.members[key_member] = memberData;
        });
    });

EDIT:
I tried the following, I think I am just missing async(s) / await(s)
    refEvents
    .once('value')
    .then((snapshot) => {
        let events = snapshot.val();

        for(kEvent in events) {
            console.log(kEvent, "Is an event");
            let event = events[kEvent];

            for(member in event.members) {
                console.log(member, "Is a member of event", kEvent);
                refUsers.child(member).child("/profile").once('value', (userProfile) => {
                    console.log("userProfile", userProfile);
                });
            }
        }

        console.log("final events", events);
        dispatch({ type: FETCH_EVENTS_S, payload: cleanNewEvents(snapshot.val()) });
    })
    .catch((err) => {
        dispatch({ type: FETCH_EVENTS_F, payload: err.message });
    });

The problem here is that the 'userProfile' logs are coming after execution of the loop.

A: How to handle this case
Fetch events
export const fetchEvents = async () => {
    let finalEvents = {};
    let events = await getEvents();
        events = events.val();

    for(kEvent in events) {
        let event   = events[kEvent];
        let members = await getMembers(event.members);

        event.members = members;

        finalEvents[kEvent] = event;
    }

    return finalEvents;
}

Get events function
const getEvents = () => {
    return firebase
        .database()
        .ref("events")
        .once("value");
}

Get members for one event
const getMembers = async (members) => {
    let profiles = {};

    for(member in members) {
        let profile             = await getProfile(member);
        let { username , image } = profile.val();

        if(!image) image = "";

        profiles[member] = { username, image };
    }

    return profiles;
}

Get profile of one member
const getProfile = (kUser) => {
    return firebase
        .database()
        .ref("users")
        .child(kUser)
        .child("profile")
        .once("value");
}


text:
Q: Enable Sound button in Notification Channel In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.
In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable
Let me show my code for notification :
    var intent = Intent(mContext, HomeActivity::class.java)
    intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
    var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

    var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
            .setContentTitle(mContext.getString(R.string.app_name))
            .setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
            .setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setSound(uri)
            .setSmallIcon(R.drawable.ic_app_icon)
            .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
            .setVibrate(longArrayOf(0, 100, 1000, 300))
            .setAutoCancel(true)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
        channel.description = "NOTIFICATION_DESCRIPTION"
        channel.lightColor = Color.LTGRAY
        channel.enableVibration(true)
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

        val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
        channel.setSound(uri, attributes)
        var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    var notificationManager = NotificationManagerCompat.from(mContext)
    notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())

I am also set channel.setSound(uri, attributes) in cannel but sound not coming
Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?
Plz help

A: I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.
First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.
Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);

    if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.

        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        CharSequence name = "MyChild";
        String description = "All MyChild messages";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        notificationChannel.setDescription(description);
        notificationChannel.enableVibration(true);
        notificationChannel.setSound(sound, audioAttributes);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }

A: I'm facing same issue and still didn't get satisfying answer, but till that time we can workaround it like so:
final Uri NOTIFICATION_SOUND = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
RingtoneManager.getRingtone(context, NOTIFICATION_SOUND).play();

You need to call this after:
notificationManager.notify(notificationId, notification);

This way you will always get sound playing even if "allow sound" was turned off for your App, and the sound played will be from the system not media (expected behavior from the notifications).
And to avoid having two sounds playing at once (for the devices that don't have this issue), you can turn the sounds off like so:
1- For the Builder:
notificationBuilder.setContentTitle(title)
    .set.....
    .set.....
    .setSound(null);

2- For the channel:
channel.setSound(null, null);

A: mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)

This line of code is worked for me it enables all notification settings.


text:
Q: Copy files from one AWS account's S3 bucket to another AWS account's S3 bucket + using NodeJS How to copy files from source AWS account's S3 bucket into destination S3 bucket which is on a different AWS account using NodeJS ?
i.e, from S3 in AWS  Account A to S3 in AWS Account B

A: Did you try the copyObject method?
Use Bucket and Key to indicate the destination and CopySource to indicate the source object. Make sure your creds have permission to both read the source object and write the destination object.
Ideally, improve the security of your copy by asserting the AWS account ID of the destination bucket in ExpectedBucketOwner, if you know it.
Here's an untested example:
const s3 = new AWS.S3();

const params = {
  Bucket: 'destbucket',
  CopySource: 'srcbucket/srcfolder/file.txt',
  Key: 'destfolder/file.txt'
};

const result = await s3.copyObject(params).promise();

If you need to assume a role that allows access to both buckets, then use some variant of this code to get STS credentials and an S3 client object:
const sts = new AWS.STS({ region: 'us-west-2' });

const role_params = {
  RoleArn: 'arn:aws:iam::1234567890:role/yourrole',
  RoleSessionName: 'optional-name',
  ExternalId: 'some-optional-value',
  DurationSeconds: 3600,
};

const res = await sts.assumeRole(role_params).promise();

const cred_params = {
  accessKeyId: res.Credentials.AccessKeyId,
  secretAccessKey: res.Credentials.SecretAccessKey,
  sessionToken: res.Credentials.SessionToken,
};

const s3 = await new AWS.S3(cred_params);

To understand the permissions needed for cross-account S3 access, see How can I provide cross-account access to objects that are in Amazon S3 buckets?


text:
Q: How to get the data from dynamically table I have a dynamically table I need to get the date from it any place in the script.....
the table
$('#update_panel').html('Loading Date....');

$.ajax({
    url: '/Home/GetCountries',
    type: 'GET',
    datatype: 'Json',
    success: function (data) {
        if (data.length > 0) {
            var $data = $('

').addClass('table table-responsive table-striped');
            var header = "

Country ID	Country

";
            $data.append(header);

            $.each(data, function (i, row) {
                var $row = $('
');
                $row.append($('').html(row.CountryId));
                $row.append($('').html(row.CountryName));
                $row.append($('').html("Edit | Delete"));
                $data.append($row);
            });

            $('#update_panel').html($data);
        }

I tried it but it didn't work
    $("#mytable tr").click(function () {

        var countryId = $(this).find('td').eq(1).text().trim();
        alert(countryId);
    });

How to reach the table in the Dom?
Thanks in Advance

A:    $.ajax({
                url: '/Home/GetCountries',
                type: 'GET',
                datatype: 'Json',
                success: function (data)
                {
                    if (data.length > 0)
                    {
                        // HERE I HAVE APPLIED 'id' ATTRIBUTE TO TABLE
                        var $data = $('

').addClass('table table-responsive table-striped');
                        var header = "

Country ID	Country

";
                        $data.append(header);
                        $.each(data, function (i, row)
                        {
                            var $row = $('
');
                            $row.append($('').html(row.CountryId));
                            $row.append($('').html(row.CountryName));
                            $row.append($('').html("Edit | Delete"));
                            $data.append($row);
                        });
                        $('#update_panel').html($data);
                    }
                }
            });
            //USE 'on' EVENT WHEN YOU WANT TO TRIGGER EVENT ON DYNAMIC DOM
            $("#update_panel").on("click", "#mytable tr", function ()
            {
                // IT WILL SELECT ALL 'td' CHILDREN OF CLICKED 'tr' ELEMENT.
                // THEN WE USED .first() SO IT WILL SELECT ONLY FIRST 'td' ELEMENT
                var countryId = $.trim($(this).children("td").first().text());
                alert(countryId);
            });

A: Seems like your table did't have an id #mytable. Change $("#mytable tr").click(function () { into :
$('#update_panel').on('click','.table tr',function () {...});

Or simply adding id #mytable into table
 $('

')

And register it handler using .on like so :
$('#update_panel').on('click','#mytable tr',function () {...});

A: Here is some observations and a possible solution:

*

*Your dynamic table is missing the ID (mytable)

*Once it is added your code should work fine. See the code below,

var data = [];
var row1 = {};
row1.CountryId = "100";
row1.CountryName = "USA";
data.push(row1);

var row2 = {};
row2.CountryId = "101";
row2.CountryName = "Germany";
data.push(row2);

if (data.length > 0) {
            var $data = $('

').addClass('table table-responsive table-striped');
            var header = "

Country ID	Country

";
            $data.append(header);

            $.each(data, function (i, row) {
                var $row = $('
');
                $row.append($('').html(row.CountryId));
                $row.append($('').html(row.CountryName));
                $row.append($('').html("Edit | Delete"));
                $data.append($row);
            });

            $('#update_panel').html($data);
  }

$("#mytable tr").click(function () {

        var countryId = $(this).find('td').eq(0).text().trim();
        alert(countryId);
  });