text:
Q: How to initialize a Ref> field in objectify to a dummy value I have a collection(arraylist) of Ref `s ,the objectify documentation says that I need to initialize collections for them to be persisted and hence modified in the future.....
Now , Ref points to an object but when I launch my app for the first time I dont have any objects in the data store...so whats the best way for me to initialize a dummy value......
Is my assumption that a Ref<> needs to point to a real object in the data store?

A: Two things:

*

*You should just initialize an empty collection.  You don't need to add anything to it. eg, field = new ArrayList<Ref<Thing>>();

*It's actually not even required that you initialize the collection.  It's just a good idea for reasons that will become apparent if you use the system for a while.


text:
Q: Sticky selection box I am trying to write a sticky selection box using HTML and PHP. I want the selections the user entered before submit to be highlighted after submit is pressed. I have tried a couple different ways and it does not seem to work. Here is the line as I have it now.
<select name="selectBox[]" multiple="multiple" size="5">
<?php
$i=0;

while($temp=mysql_fetch_array($result,MYSQL_NUM))
{
    //echo $temp[1];
?>
    <option value="<?php echo $temp[1] ?>"
        <?php if(isset($_POST[$temp[1]])) {echo "selected";} ?> >
        <?php echo $temp[1] ?> </option>

<?php
    $i++;
}

?>
</select>

I know that the echo "selected" works because I have tried it with just that in the option tag.
Here is the whole code with a slightly different option tag within the selection tags but it still does not worry.

<title>Business Registration</title>

Business Registration

<?php

$user="*********";
$DBserver="localhost";
$password="*********";

$myDatabase='nedwards';
$myTable1='categories';
$myTable2='businesses';
$myTable3='biz_categories';

//connect to the database server.
$con=mysql_connect($DBserver,$user,$password);

$con or die('Could not connect to MySQL: ' . mysql_error());//check connection

mysql_select_db($myDatabase) or die("Unable to select database");//select the databse we will be using
                                                                //check selection

$result = mysql_query("SELECT * FROM $myTable1");//gets the category table.... we will use the fetch_array and take the 2nd element of the array for select box

$submitted=$_POST['submitted'];

if($submitted)
{

    $sql="INSERT INTO $myTable2 (name, address, city, telephone, url) VALUES ('$_POST[bis_name]', '$_POST[addr]', '$_POST[city]', '$_POST[tele]' , '$_POST[url]')";
    mysql_query($sql, $con) or die('Error dude: ' .mysql_error());

//  echo "$_POST[bis_name]";
//  echo "$_POST[addr]";
//  echo "$_POST[city]";

    $chosenTitles=$_POST[selectBox];

    //echo "$_POST[bis_name]";

    foreach ($chosenTitles as $temp)//will run through each title chosen
    {
        //echo "$temp";//for testing

        //get cat id
        $catTitle2IDtemp=mysql_query("SELECT * FROM $myTable1 WHERE title='$temp'", $con);
        $catTitle2ID=mysql_fetch_array($catTitle2IDtemp, MYSQL_NUM);
        $catID=$catTitle2ID[0];//this is the category ID

        //get biz id
        $temp=$_POST[bis_name];
        $bis_name2IDtemp=mysql_query("SELECT * FROM $myTable2 WHERE name='$temp'", $con);
        $bis_name2ID=mysql_fetch_array($bis_name2IDtemp, MYSQL_NUM);
        $bizId=$bis_name2ID[0];//this is the biz ID

        mysql_query("INSERT INTO $myTable3 (business_id, category_id) VALUES ('$bizId', '$catID')");

    }

}

?>

<form name="input" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">

<select name="selectBox[]" multiple="multiple" size="5">
<?php
$i=0;

while($temp=mysql_fetch_array($result,MYSQL_NUM))//gets each row of categroy table "$result" and takes second element of array $tempto select box
{
    //echo $temp[1];
?>

    <option value="<?php echo $temp[1] ?> "    <?php if(in_array($temp[1], $chosenTitles)){echo "selected";}   ?>        > <?php echo $temp[1] ?>   </option>

<?php
    $i++;
}

?>
</select>

Buisness Name
    <input type="text" name="bis_name" value="<?php if($submitted==1){echo $_POST['bis_name'];}?>"/>

Address
<input type="text" name="addr" value="<?php if($submitted==1){echo $_POST['addr'];}?>" />

City
<input type="text" name="city" value="<?php if($submitted==1){echo $_POST['city'];}?>"/>

Telephone
<input type="text" name="tele" value="<?php if($submitted==1){echo $_POST['tele'];}?>"/>

URL	    <input type="text" name="url"  value="<?php if($submitted==1){echo $_POST['url'];}?>"  />

<input type="hidden" name="submitted" value="1">

<input type="Submit" value="Add Business"      />
</form>

<?php
$submitted="0";
$_POST['submitted']="0";
?>

A: You can use in_array php function.
Below is some sample code which will guide you.
<?
    if(isset($_POST['submit']))
    {
        $selectBox = $_POST['selectBox'];
    }
?>
<form name="input" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<select name="selectBox[]" multiple="multiple" size="5">
<option <? if(in_array('one',$selectBox)){ echo 'selected';}?> value="one">one</option>
<option <? if(in_array('two',$selectBox)){ echo 'selected';}?> value="two">two</option>
<option <? if(in_array('three',$selectBox)){ echo 'selected';}?> value="three">three</option>
<option <? if(in_array('four',$selectBox)){ echo 'selected';}?> value="four">four</option>
</select>

<input type="Submit" name="submit" value="Add Business"/>
</form>

A: If I'm reading it right
<option value="<?php echo $temp[1] ?>"
    <?php if(isset($_POST[$temp[1]])) {echo "selected";} ?> >
    <?php echo $temp[1] ?> </option>

produces
<option value="some value"selected> some value </option>

To specify that an option should be selected you need to use the selected attribute:
<option value="some value" selected="selected"> some value </option>

Try this:
<option value="<?php echo $temp[1] ?>"
    <?php if(isset($_POST[$temp[1]])) {echo ' selected="selected"';} ?> >
    <?php echo $temp[1] ?> </option>

redpajama_set_name: RedPajamaStackExchange


text: Q: Remove parts of String? I have a TextView and a String. The String is to collect what Url may be present in the WebView. The TextView displays the Url so that you have an idea on what website you are on. Im trying to have so that it has the root of the Url. Say you are at "Google.ca" it will display "https://www.Google.ca", though I would like it to display "Google.ca". I have searched for a few days regarding this issue and have only found questions regarding, if they know what will be displayed. For me the String "Url" will be changing and you don't know the exact size nor characters. How would I be able to remove just the "https://www." and anything after the ".", this isn't really a issue its more aesthetically pleasing to me.


text:
Q: Saving image with portrait effects matte to PHPhotoLibrary not possible? I'm prototyping simple photo concepts using Apple's AVCam app as a basis. The front camera capture pipeline is set to capture and process both the depth- and portrait-mattes pretty much in a way AVCam app has done it and a high quality portrait matte is being delivered with the AVCapturePhoto object in didFinishProcessingPhoto.
It seems a bare PHAssetCreationRequest addResource doesn't save the portrait matte as image's metadata, as when I read back the stored image from the PHPhotoLibrary and peek into its metadata followed by calls to CGImageSourceCopyAuxiliaryDataInfoAtIndex(), I can see that only key kCGImageAuxiliaryDataTypeDisparity returns data, but keys kCGImageAuxiliaryDataTypeDepth and kCGImageAuxiliaryDataTypePortraitEffectsMatte both return nil.
Edit: tested writing flattened AVCapturePhoto object to a file and reading it back preserves all metadata including the portrait effects matte. However, passing that data object to PHPhotoLibrary asset creation request results in portrait effects matte getting stripped away.
Any idea how the matte could be written through the PHPhotoLibrary API or is this exclusive API only for Apple's Camera app Portrait mode?

A: Mystery was resolved. Here are some notes in case someone makes the same mistakes when e.g. experimenting with AVCam source code.
It turned out the portrait matte was indeed written to PHPhotoLibrary with the image, but reading it back with PHImagePickerController needed some attention. When accessing the image data with NSItemProvider.loadDataRepresentation(forTypeIdentifier: representation) the representation identifier has to be the same format and type the file was saved. For example my photo container was of type .heic. Now, even though NSItemProvider.hasRepresentationConforming(toTypeIdentifier: representation...) listed type identifiers,
UTType.heic
UTType.jpeg

as supported, only the first could load the matte correctly. If I tried to access the data with .jpeg identifier portrait matte was not loaded, but strange error

"Could not create a bookmark: NSError: Cocoa 257 "The file couldn't be
opened because you don't have permission to view it"

kept appearing on Xcode console.
The second mistake was capturing and storing live photo data with portrait matte. It seems possible, but at least iOS Photos app can't handle those photos properly in edit mode and saving the edit always fails in error

"Photo could not be saved, please try again later."

So, don't enable live photo options in capture settings when capturing portrait matte.


text:
Q: Description for category names of Mozilla Shavar blacklist Looking at the Mozilla Shavar blacklist, which is used for tracking protection (ex. in Mozilla Firefox), the services are grouped in several categories:
Email
EmailStrict
Advertising
Content
Analytics
FingerprintingInvasive
FingerprintingGeneral
Social
Cryptomining

Most of them are self-explaining. But for Content I've no clue what it (technically) means. Can someone explain what this category is for and why it is different from Advertising and Analytics?


text:
Q: Proper style to implement control flow in python loop I am not sure if the title of this question is correct or even the right question to ask (sorry if this is a duplicate).
What is the best (most pythonic) way to manage control flow in a loop in python, I specifically want to skip over items in a filter list. Here are my two approaches:
Idea 1:
items=["a","b","c","x","b"]
filterList=["x","y","z"]
for i in items:
    if i in filterList:
        continue

    ... Code for working with i

Idea 2:
items=["a","b","c","x","b"]
filterList=["x","y","z"]
for i in items:
    if i not in filterList:
        ... Code for working with i

Is one of these two styles more pythonic or readable than the other?
Edit 1:
One thing to note is that items will potentially have duplicates, updated code to reflect this.

A: You could use list comprehension:
items = ...
filterList = ...

filtered_items = (i for i in items if i not in filterList)

for i in filtered_items:
   do the thing


text:
Q: calculating the probability of k changeovers when flipping a coin Consider n independent flips of a coin having probability p of landing heads.
Say that a changeover occurs whenever an outcome differs from the one preceding it. For instance,if n = 5 and the outcome is HHTHT, then there are 3 changeovers. If $p=\frac{1}{2}$, what is the probability there are $k$ changeovers.
I'm pretty sure there is a fancy way but what I got is
$$P(\text{k change overs}) =
\begin{cases}
2^{k+1}(\dfrac{1}{2^n}), & 0\leq k<n-1 \\
2^{n-k}(\dfrac{1}{2^n}), &  k=n-1
\end{cases}$$
Would this be one correct way of writing the answer? I basically got this by trying a few sample trials.

A: There are $n-1$ potential changeovers, each equally likely, so this is a binomial problem. Let $C_k$ be the event there are $k$ change-overs.
$$P(C_k) = {n-1\choose k}\dfrac{1}{2^{n-1}}$$
Think about the internal gaps between flips as being a success if a change occurs. The next flip will be the same, or not with equal probability. For example, if $n=4$,
$$P(C_0) = P(HHHH)+P(TTTT) = \dfrac{1}{8} ={4-1\choose 0}\dfrac{1}{2^{4-1}}$$
$$P(C_1) = P(THHH)+ P(HTTT)+P(HHTT)+P(HHHT)+ P(TTHH)+P(TTTH) = \dfrac{3}{8} ={4-1\choose 1}\dfrac{1}{2^{4-1}}$$
$$P(C_2) = P(THTT)+ P(HTHH)+P(TTHT)+P(HHTH)+ P(THHT)+P(HTTH) = \dfrac{3}{8} ={4-1\choose 2}\dfrac{1}{2^{4-1}}$$
$$P(C_3) = P(HTHT)+ P(THTH)= \dfrac{1}{8} ={4-1\choose 3}\dfrac{1}{2^{4-1}}$$

A: This problem can be thought of as an instance of the Stars and bars problem:
We place k changeovers (bars) in between the n-1 spaces between the n coin flips (stars). This can be done in $\binom{n-1}{k}$ ways.
The first throw is either a $\{H,T\}$ in 2 ways.
Once the first throw is decided, the full pattern is decided. The probability of a single pattern is $\frac{1}{2^n}$.
Therefore the total probability of k change-overs is $$\binom{n-1}{k}\times 2 \times \frac{1}{2^n}=\binom{n-1}{k}\times  \frac{1}{2^{n-1}}$$


text:
Q: Proof of a neat pattern in polynomials Let $f_1:\mathbb{R}\to\mathbb{R}$ such that $$f(x) = ax + b\space\space \forall\space x \in \mathbb{R}$$
It can be easily verified that $$f(x)-2f(x-1)+f(x-2)=0 \space \forall \space x \in
\mathbb{R}---(I)$$
Now,$\space$let $f_2:\mathbb{R}\to\mathbb{R}$ such that $$f(x) = ax^2+bx+c \space \forall\space x\space \in \mathbb{R}$$
After some trial and error, I found that $$f(x)-3f(x-1)+3f(x-2)-f(x-3) = 0 \space \forall\space x\space \in \mathbb{R}---(II)$$
One could see the coefficients of terms in the expansion of $(1-x)^2$ being the coefficients of terms in $(I)$ in the same order, and the coefficients of terms in the expansion of $(1-x)^3$ being the coefficients of terms in $(II)$ in the same order.
I tried to continue the above observation:
Let $f_{4}:\mathbb{R}\to\mathbb{R}$ such that $$f(x) = ax^3 + bx^2 + cx + d\space\space \forall\space x \in \mathbb{R}$$
It can be verified that $$f(x)-4f(x-1)+6f(x-2)-4f(x-3)+f(x-4) = 0\space \forall\space x\space \in \mathbb{R}---(III)$$
And voila, the coefficients of terms in the expansion of (1-x)^4 are the coefficient of terms in $(III)$ in the same order.
I have been trying to extend this result in general to $f_{n}$ where $n \in \mathbb{N}$, where $\mathbb{N}$ is the set of natural numbers, have tried to approach this problem via several methods but couldn't get anywhere.
Any hint towards proving the general result(if at all the result is true) will be appreciated
Thank You
PS: $a,b,c,d \in \mathbb{R}$ and $a \neq 0$

A: This article on forward differences will prove helpful, or at least it's my initial take. It will require a little comfort with basic calculus and summation notation, however; I don't know if there's a more elementary angle, this is simply what came to mind.

Recall from calculus: we can define the derivative $f'$ of a function $f$ by
$$f'(x) := \lim_{x \to 0} \frac{f(x+h) - f(x)}{h}$$
We can define a discretized version of this (one someone might use for sequences, for instance), by taking the argument of the limit for $h=1$. We define this "forward difference" operation to be $\newcommand{\D}{\Delta} \D f$:
$$(\D f)(x) \equiv \D f(x) := f(x+1) - f(x)$$
One may ask: what happens if we apply this twice? Well, first, one can show that $\D$ is linear, i.e. for any $\alpha,\beta \in \mathbb{R}$, we have
$$\D (\alpha f+\beta g) = \alpha \D f + \beta \D g$$
(Try proving it for yourself!) Then
$$\begin{align*}
\D^2 f(x)
&= \D (\D f)(x) \\
&= \D \Big( f(x+1) - f(x) \Big)\\
&= \D f(x+1) - \D f(x) \\
&= f(x+2) - f(x+1) - \Big( f(x+1) - f(x) \Big) \\
&= f(x+2) - 2 f(x+1) - f(x)
\end{align*}$$
You might be seeing the relation to your equation. The pattern holds in general: applied $n$ times,
$$\D^n f(x) = \sum_{k=0}^n \binom n k (-1)^{n-k} f(x+k)$$
(Try proving this one for yourself too! Induction may be helpful.)

Now, with this in mind, define $p$ a polynomial of degree $n$:
$$p(x) = \sum_{k=0}^n a_k x^k$$
Find $\D p$:
$$\D p(x) = \sum_{k=0}^n a^k \Big( (x+1)^k - x^k \Big)$$
Note that, using the binomial theorem
$$(x+1)^k - x^k
= -x^k + \sum_{j=0}^k \binom k j x^j$$
If we extract out the $j=k$ term of the sum we get
$$(x+1)^k - x^k
= -x^k + x^k+ \sum_{j=0}^{k-1} \binom k j x^j
= \sum_{j=0}^{k-1} \binom k j x^j$$
Notice what this means: $\D p$ has degree $n-1$.
Thus, $\D^m p$ has degree $n-m$.
If we reach the case $m=n$, then $\D^n p$ is a degree $0$ (constant) polynomial. Of course, if constant, it is easy to see that its forward difference is zero. That is,
$$\D^{\deg(p)+1}p \equiv 0$$
for any polynomial $p$.
(You can frame this in a more formal induction proof if you'd like, but you can see the core of the argument here.)

Your observations are in line with this:

*

*Taking $f_1$ linear, $\D^2 f_1 \equiv 0$

*Taking $f_2$ quadratic, $\D^3 f_2 \equiv 0$

*Taking $f_3$ cubic, $\D^4 f_3 \equiv 0$
and so on.

A: A generating function also works: take $f(x) = x^k$ with $k<n$.  $$\sum_{r=0}^{n} \binom{n}{r} (-1)^r(x-r)^k = \left[\left(\frac{d}{dt}\right)^{\! k} \,  \sum_{r=0}^{n} \binom{n}{r} (-1)^r e^{t(x-r)}\right]_{t=0}=\left[\left(\frac{d}{dt}\right)^{\! k} \, e^{tx}(1-e^{-t})^n\right]_{t=0}.$$ But as $k<n$, this expression will be zero, as at least one of the factors of $(1-e^{-t})$ will survive in every term of the differentiation.

A: By the binomial theorem,
$$f(x)-4f(x-1)+6f(x-2)-4f(x-3)+f(x-4) = ((1 - T^{-1})^4f)(x),$$
where $T$ is the translation operator given by $(Tg)(x) = g(x + 1)$. In the general case, by the binomial theorem, $(1 - T^{-1})^n = \sum_{i = 0}^{n}\binom{n}{i}(-1)^iT^{-i}$, so the $n$-th thing you will write down is $(1 - T^{-1})^nf(x) = \sum_{i = 0}^{n}\binom{n}{i}(-1)^{i}f(x - i)$, and you conjecture that if $f$ is of degree at most $n - 1$, then $(1 - T^{-1})^nf = 0$. This is true because if $f(x)$ is of degree at most $k$, then $(1 - T^{-1})f(x) = f(x) - f(x - 1)$ is of degree at most $k - 1$ (to prove this, it suffices to check this for $f(x) = x^k$, which is easy by the binomial theorem).


text:
Q: Getting value of checked box in array using jquery I have a form which is formatted using a table the code is given below
echo'<form id="change_entry" name="change_entry" >';
echo"
";
echo 'Please select Year and Quarter
';
    $dyear=2014;
    $thisyear=date('Y');
    $diff=$thisyear-$dyear;
echo '<select name="yeardate" id="yeardate">';
for ($i=$dyear;$i<=$thisyear;$i++){ echo'<option class="green" value="'.$i.'"';
            if ($thisyear==$i) {echo 'selected';}
            echo'>'.$i.'</option>'; }
        echo '</select>';

        echo " <select name='qtr' id='qtr'> <option value=''>Select Quarter</option>
      <option value='I'>QTR-I</option> <option value='II'>QTR-II</option> <option value='III'>QTR-III</option> <option value='IV'>QTR-IV</option></select>
";

       echo "

TLD No	Location	Date of Removal	Dose Rate (mGy/h)	Lost
";

                while($row=mysql_fetch_array($data))
                    {
                    $rc++;
                    echo "
";
                    echo "<input type='text' value='".$row['tldno']."'/>	";
                    echo "".$row['location']."	";

                    echo "<input type='text' id='datepicker".$rc. "'name='datepicker'/>	";
                echo "<input size='5' id='dose".$rc."'  value='".$row2['radn_level']."'/>	";
                echo "<input type='checkbox' id='lost".$rc."'  value='Y'/>	";

                    echo "
";
                }

     echo "

";
     echo '
';
     echo '<input type="submit" value="Submit" width="30" />';
     echo '
';

     echo '</form>';

The table gets some data from mysql table and remaining data is entered by user. I submit this data for update/insert to another php script using jquery post. The form data is obtained using following jQuery
jQuery('#change_entry').submit(function (e) {
    e.preventDefault();

    var arr = jQuery('#change_entry tr:gt(0)').map(function () {
        return [jQuery('input', this).map(function () {
            return this.value;
        }).get()];
    }).get();

    var qtr = jQuery('#qtr').val();
    var yeardate = jQuery('#yeardate').val();

    jQuery.post("scripts/tld_change_entry.php", { "records": arr, "yr": yeardate, "qtr": qtr }, function (data) {

        jQuery('#tldlist').html(data);
    });
});

Now the problem is the last  contains a checkbox, whose default value is 'Y' and this value to be taken only if it is checked. But with my script, it is taking all instances of checkbox as 'Y'. I know how to check the checkbox status in jquery. But I do not know how to use it in .get() . Please suggest any method. I can replace the checkbox with a text input, but check box looks better that text input in this case.

A: Changing this part of the code..
return [jQuery('input[type="text"],input[type="checkbox"]:checked', this).map(function() {
   return this.value;
}).get()];

A: You can use this if (this.type != "checkbox" || this.checked) condition in your map() like following.
var arr = jQuery('#change_entry tr:gt(0)').map(function () {
    return [jQuery('input', this).map(function () {
        if (this.type != "checkbox" || this.checked) //added this line
            return this.value;
    }).get()];
}).get();


text:
Q: Strange PHP Warning (Unable to load dynamic library: no-debug-non-zts-20100525) I temporarily set apc.enable_cli=1 in apc.ini, then run php -r "apc_clear_cache();" in the terminal to clear APC cache but this is what I got:
PHP Warning:  PHP Startup: Unable to load dynamic library '/opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mcrypt.so' - /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mcrypt.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mysql.so' - /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mysqli.so' - /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mysqli.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/opt/php5/lib/php/extensions/no-debug-non-zts-20100525/pdo.so' - /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/opt/php5/lib/php/extensions/no-debug-non-zts-20100525/pdo_mysql.so' - /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0

I'm running PHP-FPM 5.4.3, Nginx 1.3.1 and APC 3.1.10 on an Ubuntu Server 12.04 (VPS).
Do you have any idea of what these errors mean?

A: The errors mean that the file /opt/php5/lib/php/extensions/no-debug-non-zts-20100525/mcrypt.so does not exist, while your PHP configuration wants to load it.  Either make the file exist (again?), or modify your PHP configuration to not load the file.  Also, /opt/php5 is not an Ubuntu-standard location for PHP installation, so you've done something custom to the machine -- I'd start by reviewing your notes on what you did there.


text:
Q: How to show time difference over 24 hours between timestamps I have a query that returns speed to response. It works correctly expect for instances when the timediff calculation results is over 24 hours. I get a error of "java.sql.SQLException: Illegal hour value '31' for java.sal.Time type in value"
The number of '31' varies with the variance of hours between the timestamps.
I'm not sure where to precede from here. I tried timestampdiff() but get an error while trying to run the query.
Any comments or suggestions would be much appreciated.
SELECT a.*
FROM
(SELECT
databunker.purchases.id                                           AS 'pur_id',
 databunker.purchases.business                                    AS 'pur_business',
 databunker.purchases.time                                        AS 'pur_time',
 databunker.customers.id                                          AS 'customer_id',
 databunker.customers.phone_number                                AS 'customer_phone_#',
 databunker.customers.is_primary                                  AS 'customer_is_primary',
 map.object_salesforce_id,
 databunker.five9_calls.campaign_name,
 databunker.five9_calls.start_timestamp AS 'start_of_call',
 TIMEDIFF(databunker.five9_calls.start_timestamp, databunker.purchases.time) AS 'speed_to_response'

FROM databunker.purchases
 LEFT OUTER JOIN databunker.customers ON (databunker.purchases.customer_id = databunker.customers.id)
 LEFT OUTER JOIN (SELECT
                    databunker.mappings.object_salesforce_id,
                    databunker.mappings.object_id AS 'map_customer_id'
                  FROM databunker.mappings
                  WHERE databunker.mappings.object_class = 'customer') AS map
   ON (databunker.purchases.customer_id = map.map_customer_id)
 LEFT OUTER JOIN databunker.five9_calls ON (map.object_salesforce_id =
databunker.five9_calls.salesforce_id)
WHERE databunker.purchases.business = 'uma'
     AND databunker.purchases.outcome_type = 'accepted'
     AND databunker.purchases.time >= curdate() - 1

     AND databunker.five9_calls.start_timestamp >= databunker.purchases.time

GROUP BY
 databunker.purchases.id,
 databunker.purchases.business,
 databunker.purchases.time,
 databunker.customers.id,
 databunker.customers.phone_number,
 map.object_salesforce_id,
 databunker.five9_calls.campaign_name,
 databunker.five9_calls.start_timestamp,
 TIMEDIFF(databunker.five9_calls.start_timestamp, databunker.purchases.time)

 ORDER BY databunker.purchases.id, databunker.purchases.time,
 databunker.five9_calls.start_timestamp ASC) a

INNER JOIN

(
SELECT
  databunker.purchases.id AS 'pur_id_2',
  MIN(databunker.five9_calls.start_timestamp) AS 'call_time'

FROM databunker.purchases
  LEFT OUTER JOIN databunker.customers ON (databunker.purchases.customer_id = databunker.customers.id)
  LEFT OUTER JOIN (SELECT
                     databunker.mappings.object_salesforce_id,
                     databunker.mappings.object_id AS 'map_customer_id'
                   FROM databunker.mappings
                   WHERE databunker.mappings.object_class = 'customer') AS map
    ON (databunker.purchases.customer_id = map.map_customer_id)
  LEFT OUTER JOIN databunker.five9_calls ON (map.object_salesforce_id = databunker.five9_calls.salesforce_id)
WHERE databunker.purchases.business = 'uma'
      AND databunker.purchases.outcome_type = 'accepted'
      AND databunker.purchases.time >= curdate() - 1

      AND databunker.five9_calls.start_timestamp >= databunker.purchases.time

GROUP BY
  databunker.purchases.id
) b

ON a.pur_id = b.pur_id_2 AND a.start_of_call = b.call_time

A: There is "time of day" and there is "time span".
MySQL's TIMEDIFF() is returning a "time span" of 31 hours, etc.
Your Java code is expecting a "time of day" which, of course, should not be more than 23:59:59 (ignoring leap seconds).
One workaround is to say
TO_SECONDS(databunker.five9_calls.start_timestamp) -
TO_SECONDS(databunker.purchases.time)

but that won't return (for example) "31:58:47"; instead it will give "115127".
Another workaround is to avoid java.sal.Time and find a library that handles "time spans".


text:
Q: no Task is currently running I am getting an error: no Task is currently running when I attempt to use UnboundedSender and UnboundedReceiver without using tokio::run().
This is the error:
Press Ctrl-C to abort
thread 'receiver thread' panicked at 'no Task is currently running', src/libcore/option.rs:1166:5
stack backtrace:
   0: backtrace::backtrace::libunwind::trace
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.29/src/backtrace/libunwind.rs:88
   1: backtrace::backtrace::trace_unsynchronized
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.29/src/backtrace/mod.rs:66
   2: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:47
   3: std::sys_common::backtrace::print
             at src/libstd/sys_common/backtrace.rs:36
   4: std::panicking::default_hook::{{closure}}
             at src/libstd/panicking.rs:200
   5: std::panicking::default_hook
             at src/libstd/panicking.rs:214
   6: std::panicking::rust_panic_with_hook
             at src/libstd/panicking.rs:477
   7: std::panicking::continue_panic_fmt
             at src/libstd/panicking.rs:384
   8: rust_begin_unwind
             at src/libstd/panicking.rs:311
   9: core::panicking::panic_fmt
             at src/libcore/panicking.rs:85
  10: core::option::expect_failed
             at src/libcore/option.rs:1166
  11: core::option::Option<T>::expect
             at /rustc/dddb7fca09dc817ba275602b950bb81a9032fb6d/src/libcore/option.rs:345
  12: futures::task_impl::with
             at /home/nickhash/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-0.1.29/src/task_impl/mod.rs:46
  13: futures::task_impl::current
             at /home/nickhash/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-0.1.29/src/task_impl/mod.rs:118
  14: futures::sync::mpsc::Receiver<T>::try_park
             at /home/nickhash/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-0.1.29/src/sync/mpsc/mod.rs:902
  15: <futures::sync::mpsc::Receiver<T> as futures::stream::Stream>::poll
             at /home/nickhash/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-0.1.29/src/sync/mpsc/mod.rs:936
  16: <futures::sync::mpsc::UnboundedReceiver<T> as futures::stream::Stream>::poll
             at /home/nickhash/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-0.1.29/src/sync/mpsc/mod.rs:1004
  17: fut2::launch_receiver_thread::{{closure}}
             at src/main.rs:16
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
^C

The code I am running is:
use std:: {thread,time::Duration};
use futures::stream::*;
use futures::prelude::*;

fn launch_sender_thread(tx: futures::sync::mpsc::UnboundedSender<()>) {
    let _ = thread::Builder::new().name("sender thread".to_string()).spawn(move || {
        loop {
            tx.clone().send(());
            thread::sleep(Duration::from_millis(3000));
        }
    });
}
fn launch_receiver_thread(mut rx: futures::sync::mpsc::UnboundedReceiver<()>) {
    let _ = thread::Builder::new().name("receiver thread".to_string()).spawn(move || {
        match rx.poll() {
            Ok(Async::Ready(Some(_))) => {
                println!("thread2: received data");
            },
            Ok(_) => (),
            Err(err) => {
                println!("poll err {:?}",err);
            },
        }
        thread::sleep(Duration::from_millis(1000));
    });
}

fn main() {

    let (sender, receiver) = futures::sync::mpsc::unbounded::<()>();
    launch_receiver_thread(receiver);
    launch_sender_thread(sender);
    println!("Press Ctrl-C to abort");
    thread::sleep(Duration::from_millis(10000000));
}

So, basically I want to send and receive data from one thread to another , but without using the Future object, is this possible?
If it is not possible, then how do I fix this error with a minimal use of Futures crate ? The requirement is to use futures::sync::mpsc::UnboundedSender and futures::sync::mpsc::UnboundedSender for communication.
Cargo.toml:
[package]
name = "fut2"
version = "0.1.0"
edition = "2018"

[dependencies]
futures = { version = "0.1" }

A:
but without using the Future object, is this possible?

It is possible to use UnboundedSender and UnboundedSender with minimum interaction with futures crate, but you have to use futures with tasks. This is not entirely your fault though; the futures documentation and API design aren't very clear about this. In its 0.2 incarnation, there will be a task context explicitly threaded through various API calls. For example, Stream::poll in 0.1.x is defined as:
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error>

In 0.2.x, it is Stream::poll_next:
fn poll_next(
    &mut self,
    cx: &mut Context
) -> Result<Async<Option<Self::Item>>, Self::Error>

So you won't be able to make the same mistake of polling outside of a task.
Until then this works with 0.1.x futures crate:
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use std::thread::{self, JoinHandle};

fn launch_sender_thread(tx: UnboundedSender<()>) -> JoinHandle<()> {
    thread::Builder::new()
        .name("sender thread".to_string())
        .spawn(move || loop {
            let _ = tx.unbounded_send(());
        })
        .unwrap()
}

fn launch_receiver_thread(rx: UnboundedReceiver<()>) -> JoinHandle<()> {
    thread::Builder::new()
        .name("receiver thread".to_string())
        .spawn(move || {
            let mut task = futures::executor::spawn(rx);
            match task.wait_stream() {
                Some(Ok(_)) => println!("thread2: received data"),
                Some(Err(e)) => println!("poll err {:?}", e),
                None => (),
            }
        })
        .unwrap()
}

fn main() {
    let (sender, receiver) = futures::sync::mpsc::unbounded::<()>();
    let recv = launch_receiver_thread(receiver);
    let send = launch_sender_thread(sender);

    println!("Press Ctrl-C to abort");
    recv.join().unwrap();
    send.join().unwrap();
}

Notice, you can drive tx with task as well. It is just simpler to call unbounded_send here.


text:
Q: Set up TeamCity to write Tags to GitHub Repository I have our code in github and teamcity works well pulling changes. Unfortunately when I try and apply the label to the repository I receive the following result:
Labeling process failed: Labelling failed: org.eclipse.jgit.api.errors.JGitInternalException: Updating the ref refs/tags/EDW_Access_Service-1.0.217 to Tag={ object 9f8217173a32c09bbad280439de4edeaebc47e17 type commit tag EDW_Access_Service-1.0.217 tagger PersonIdent[, , Thu Oct 15 14:12:58 2015 +0100] } failed. ReturnCode from RefUpdate.update() was REJECTED
The user that the VCS is configured with has write access to the repository.
I can't see any reason why this would be happening.

A: I found that it works fine if I remove the - from the tag name. It seems this is a banned character.


text:
Q: How do I use query-parameters outside ui-router I have a ui-router-based Angular app, and I want to maintain some state which has nothing to do with routing.
So let's say the URL is #/profile?color=green.  That means the state is "profile" and the color of the app should be green.  If the URL changes to #/profile?color=red, nothing about the state or ng-view or the controller associated with the current route changes, but an entirely separate bit of code should be notified (and it will change the class of the body tag).  That same parameter is available on every possible state; it's orthogonal to the state.
I could just watch $location and parse everything myself, but I am wondering if some facility of ui-router or $state or something would make this easier.
(By the way, to anyone who plans to explain why I don't want to do what I want to do, no, in fact, I do want to do what I want to do, so thanks-kay-bye.)

A: You could definitely accomplish what you're trying to do with $location. I would probably use $stateChangeStart so that you can do less parsing on you're end to accomplish what you're looking for:
$rootScope.$on('stateChangeStart', function(event, toState, toParams) {
  if (toParams.color === 'red') {
    //etc
  }
}

The great part about this solution is that you can listen for these params in this way across any toState which satisfies your requirement that this param is applicable regardless of state.
stateChangeStart documentation


text:
Q: modifying numpy ndarray by index I'm stuck on trying to add values to the numbers column.
import pandas as pd

def twod_array(num):
    data = {"group": [-1, 0, 1, 2],
            'numbers': [[2], [14, 15], [16, 17], [19, 20, 21]],
            }
    df = pd.DataFrame(data=data)
    print(df)
    return 0

Currently it prints this:
   group       numbers
0     -1           [2]
1      0      [14, 15]
2      1      [16, 17]
3      2  [19, 20, 21]

What I'd like to do is to add a value based on the passed input, so for example if I pass 14.5 as a num, this is the output I'd like to see:
   group       numbers
0     -1           [2]
1      0      [14,14.5 15]
2      1      [16, 17]
3      2  [19, 20, 21]

I'm hoping someone can help with this. This is what I have so far but it fails at the insert line with the error "numpy.ndarray" object has no attribute 'insert'.
df = pd.DataFrame({"group": [-1, 0, 1, 2],
        'numbers': [[2], [14, 15], [16, 17], [19, 20, 21]],
        })
arr = df['numbers'].to_list()
num = 14.5

for i, sub_arr in enumerate(arr):
      for j, n in enumerate(sub_arr):
            if arr[i][j]>num:
                  if j!=0:
                    arr[i].insert(j,num)
                  else: arr[i-1].insert(-1 ,num)

df['numbers'] = arr

A: num = 14.5
mask = (df.numbers.apply(min).lt(num) &
        df.numbers.apply(max).gt(num))
index = mask[mask].index[0]
df.numbers.at[index].append(num)
df.numbers.at[index].sort()
print(df)

# Output:
   group         numbers
0     -1             [2]
1      0  [14, 14.5, 15]
2      1        [16, 17]
3      2    [19, 20, 21]

A: Iterate through the df and see if num lies between the first and last value of the numbers column. If it does, use the bisect module to insert num in a sorted fashion.
import bisect
for i in range(len(df)):
  if num >= df.loc[i,'numbers'][0] and num<= df.loc[i,'numbers'][-1]:
    bisect.insort(df.loc[i,'numbers'],num)

print(df)

   group         numbers
0     -1             [2]
1      0  [14, 14.5, 15]
2      1        [16, 17]
3      2    [19, 20, 21]


text:
Q: How to return a dictionary in Python using a text file I'm trying to write a function that returns a dictionary whose keys are pairs of words that appear consecutively in the input file and whose values are lists containing any word that has followed that pair in the file. Ex. Suppose the input file contained only the sentence "This clause is first, and this clause came second.". The resulting dictionary should be: {(this, clause):[is, came], (clause, is):[first], (is, first):[and], (first, and):[this], (and, this):[clause], (clause, came):[second]}.
import string

def predictive(text_file):
    file = open(text_file, encoding='utf8')
    text = file.read()
    file.close()

    punc = string.punctuation + ''"—⎬⎪"⎫1234567890'
    new_text = text
    for char in punc:
        new_text = new_text.replace(char, '')
        new_text = new_text.lower()
    text_split = new_text.split()
    print(text_split)

predictive('gatsby.txt')

I used The Great Gatsby as the text file and stripped away unnecessary punctuation and lowercased the words. I'm not sure what to do next to return what I am looking for but would really appreciate any suggestions or help guiding me in the right way. Thanks!

A: One way to do this, after what you mentioned (sanitising the string)  would be:

*

*Enumerate your splitted string list

*Create a dictionary to hold your results (easier to deal with duplicate indexes)

*Iterate over your enumerated list creating dictionary keys made of concatenated list[idx] + list[idx+1] by space and values of list[idx+3].

Don't forget to check for index out of bounds while in the for loop, otherwise you'll get errors.
Done! You have what you need.

A: Since you've already split the text into words, all you have left to do is iterate over the words looking at the next two words, initialize the value in the dictionary to an empty list using dict.setdefault then append the third word to it:
text = "This clause is first, and this clause came second."
words = text.lower().replace(',', '').replace('.', '').split()

result = {}
for first, second, third in zip(words, words[1:], words[2:]):
    result.setdefault((first, second), []).append(third)
print(result)
# {('this', 'clause'): ['is', 'came'], ('clause', 'is'): ['first'], ('is', 'first'): ['and'], ('first', 'and'): ['this'], ('and', 'this'): ['clause'], ('clause', 'came'): ['second']}

I think you'll find that the hardest part is going to be splitting real-world text into words. Just removing the punctuation like you've done will get you most of the way there, but it's hard to get it completely right. You could try using the nltk library for this but it splits "didn't" as ["did", "n't"] so you'd have to re-join those back into a single word.

A: With zip and defaultdict:
from collections import defaultdict
text = "This clause is first, and this clause came second".lower()
words = text.split()
two_words = zip(words[:-2],words[1:-1])
two_words_values = zip(two_words,words[2:])

twoD = defaultdict(list)

for i,j in two_words_values:
    twoD[i].append(j)

print(twoD)

Output:
defaultdict(<class 'list'>, {('this', 'clause'): ['is', 'came'], ('clause', 'is'): ['first,'], ('is', 'first,'): ['and'], ('first,', 'and'): ['this'], ('and', 'this'): ['clause'], ('clause', 'came'): ['second']})

Default Dictonaries are similar to dictionaries in every sense except they make life a little bit easier by eliminating the need to check if a key is present or not.

Without defaultdict in native python:
text = "This clause is first, and this clause came second".lower()
words = text.split()
two_words = zip(words[:-2],words[1:-1])
two_words_values = zip(two_words,words[2:])

twoD = {}

for i,j in two_words_values:
    if i not in twoD: twoD[i]=[]
    twoD[i].append(j)

print(twoD)

Output:
{('this', 'clause'): ['is', 'came'], ('clause', 'is'): ['first,'], ('is', 'first,'): ['and'], ('first,', 'and'): ['this'], ('and', 'this'): ['clause'], ('clause', 'came'): ['second']}

A: import re
from itertools import islice
from collections import defaultdict

sentence = '''This clause is first, and this clause came second'''
words = re.findall(r'\w+', sentence.lower())

n_adjacent_words = 2
words_dict = defaultdict(list)

for *first_words, next_word in zip(
    *(islice(words, i, None)
      for i in range(n_adjacent_words+1)
     )
):
    words_dict[tuple(first_words)].append(next_word)

>>> words_dict
defaultdict(list,
            {('this', 'clause'): ['is', 'came'],
             ('clause', 'is'): ['first'],
             ('is', 'first'): ['and'],
             ('first', 'and'): ['this'],
             ('and', 'this'): ['clause'],
             ('clause', 'came'): ['second']})


text:
Q: Load Div after Submit Required Fields on PHP Form I have a hidden div I am loading on click of submit button. I also have .notShouldBeBlank on the script for the form. What is the right method so that the php sends results and the hidden div will not load until all required fields are complete? It's currently loading the hidden div and sending results as soon as I click submit. What am I doing wrong?
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$email = $_POST['email'];

$name = stripslashes($name);
$address = stripslashes($address);
$city = stripslashes($city);
$state = stripslashes($state);
$phone = stripslashes($phone);
$email = stripslashes($email);

$to  = 'myemail@thisismywebsite.com ' . ', ';
$to .= $Email;

$from = "$Email ";
$subject = 'Look and Learn: Applicant';
$message = <<<EOF

Look and Learn: Applicant

Name: $name

Address: $address / $city, $state

Phone: $phone

Email: $email

EOF;
//end of message

// Additional headers
$headers .= 'From: Razor Chic of Atlanta <info@thebrlab.com>' . "\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";

mail($to, $subject, $message, $headers);

?>

<!doctype html>

<meta charset="UTF-8" />
<title>Sign Up</title>
<link rel="stylesheet" href="css/sign-up.css">

Sign-Up: Look And Learn Class

<form id="form" action="" name="myContact" onSubmit="return validateForm()" method="post" enctype="multipart/form-data">

Name: *

<input name="name" type="text" size="64" placeholder="Name">

Address: *

<input placeholder="Address" size="100" type="text" name="address" maxlength="100">

City *

<input placeholder="City" name="city" type="text" id="city" maxlength="100" />

State *

<input placeholder="State" name="city" type="text" id="city" maxlength="3" />

Phone: *

<input placeholder="Phone" size="64" type="text" name="phone">

Email: *

<input placeholder="Email address" size="64" type="email" name="email">

<button name="submit" type="submit" id="submit">S  I  G  N    U  P</button>

</form>

Note: * Fields are required

<?php
if($sent){

echo '
';
}
else{
echo '
';
}
?>

<form method="post" action="https://www.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="Razorchicofatlanta@gmail.com">
<input type="hidden" name="item_name" value="Look and Learn: Deposit">
<input type="hidden" name="amount" value="100.00">
<input type="hidden" name="return" value="http://thebrlab.com/razor-chic-of-atlanta/thank-you.html">
<input type="hidden" name="undefined_quantity" value="1">

<input style="background: none" onMouseOver="this.src='images/pay-now-up.png'" onMouseOut="this.src='images/pay-now-down.png'" type="image" src="images/pay-now-down.png" height="41" width="141" border="0" alt="Pay Now" class="button">

</form>

<form method="post" action="https://www.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="Razorchicofatlanta@gmail.com">
<input type="hidden" name="item_name" value="Look and Learn: Balance">
<input type="hidden" name="amount" value="99.00">
<input type="hidden" name="return" value="http://thebrlab.com/razor-chic-of-atlanta/thank-you.html">
<input type="hidden" name="undefined_quantity" value="1">

<input style="background: none" onMouseOver="this.src='images/pay-now-up.png'" onMouseOut="this.src='images/pay-now-down.png'" type="image" src="images/pay-now-down.png" height="41" width="141" border="0" alt="Pay Now" class="button">

</form>

<form method="post" action="https://www.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="Razorchicofatlanta@gmail.com">
<input type="hidden" name="item_name" value="Look and Learn: Full Payment">
<input type="hidden" name="amount" value="199.00">
<input type="hidden" name="return" value="http://thebrlab.com/razor-chic-of-atlanta/thank-you.html">
<input type="hidden" name="undefined_quantity" value="1">

<input style="background: none" onMouseOver="this.src='images/pay-now-up.png'" onMouseOut="this.src='images/pay-now-down.png'" type="image" src="images/pay-now-down.png" height="41" width="141" border="0" alt="Pay Now" class="button">

</form>

A: Your form ID is "form", not "myContact". Change form id to myContact.
Then you have 2 "onsubmit" events, one in jQuery and the other inline (onSubmit). Try to merge them into one to avoid unexpected behaviors.
Also, make sure you return false on your submit event function if the validation fails, so the submit is halted.
Update 1
JavaScript:
$('#myContact').submit(function () {

    $.each($('#myContact .notShouldBeBlank'), function()
    {
        if($(this).val() == ''){
            $(this).after('This field is required.');
            return false;
        }
    });
    /* Uncomment the line below if you really have a validateForm() function */
    // return validateForm()
}

HTML:
<form id="myContact" action="" name="myContact" method="post" enctype="multipart/form-data">


text:
Q: Pull Access accdb query into Excel 2007 error 3265 newbie here. Found the following code on the internet. It has been around for years. I have customized it for my application. Updated reference to MS Office 12.0 access data base engine library. I continually get the 3265 error at the .Parameters line. The query runs fine inside Access and I have been able to pull in a non-parameter query using this code. Have checked spelling ok. The "Rez ID" in the parameter is an alias. The actual heading is AIANHH. Have tried all combinations of the alias and actual heading but still get 3265 at .Parameter
 Don't want to do a push because of specific formatting in Excel. Trying to avoid MS Query because I already have everything working ok in Access. I have numerous queries and don't want to start over with MS Query.The only difference I have noticed is that in Access, the criteria is formatted as: ["Rez ID"] Have tried moving the [] and "" around with no success. Seems like I'm so close to getting this to work but can't get over the hump. Any help would be appreciated.
Sub RunParameterQuery()
'Step 1: Declare your variables
Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim i As Integer
'Step 2: Identify the database and query
Set MyDatabase = DBEngine.OpenDatabase _
("C:\Users\Phil\Documents\Indians\Population & Employment\2010 Population\Census_Data_Set\MS2007_Files\2010_AIANSF_a_1_2_6_8_9_10.accdb")
Set MyQueryDef = MyDatabase.QueryDefs("Reservation_TTRACT")
'Step 3: Define the Parameters
With MyQueryDef
.Parameters("[Rez ID]") = Range("D3").Value
'.Parameters("[CHARITER]") = Range("D4").Value
End With
'Step 4: Open the query
Set MyRecordset = MyQueryDef.OpenRecordset
'Step 5: Clear previous contents
Sheets("Sheet1").Select
ActiveSheet.Range("A6:K10000").ClearContents
'Step 6: Copy the recordset to Excel
ActiveSheet.Range("A7").CopyFromRecordset MyRecordset
'Step 7: Add column heading names to the spreadsheet
For i = 1 To MyRecordset.Fields.Count
ActiveSheet.Cells(6, i).Value = MyRecordset.Fields(i - 1).Name
Next I
MsgBox "Your Query has been Run"
End Sub

A: Ok I figured it out. I had to add a Like statement to the Access Query. I have no Idea why but everything is working now.


text:
Q: Avoid destroying component instance when routing to another component I have an Angular application which consists of 2 components. The main one is a graph which plots data from a json file. Each 5s interval a new point is plotted.
My problem is that when I route to display the second component and then go back to the main one, all the data already plotted is cleared and the component starts from the begining again.
I have researched on the internet but I don't get a clear answer. Basically I want to avoid the main component to destroy on routing so It can continue ploting points (or at least have the same previous amount) even if the component is not displayed at the moment.
Is it possible?

A: You should create your own class that implements RouteReuseStrategy. As an example you may have a look at AppRouteReuseStrategy.
Please note that the class needs to be registered as a provider in app.module.ts.
providers: [
    { provide: RouteReuseStrategy, useClass: AppRouteReuseStrategy },


text:
Q: How do I self join a data.table in a manner like dcast Suppose I have a data.table in "melted" form where I have a key, and identifier and a value
library(data.table)
library(reshape2)
DT = data.table(X = c(1:5, 1:4), Y = c(rep("A", 5), rep("B", 4)), Z = rnorm(9))
DT2 = data.table(dcast(DT, X~Y))

How can I perform that sort of self join inside data.table?
> DT
   X Y           Z
1: 1 A -0.19790449
2: 2 A  0.17906116
3: 3 A  0.01821837
4: 4 A  0.17309716
5: 5 A  0.05962474
6: 1 B -0.24629468
7: 2 B  0.92285734
8: 3 B  0.66002573
9: 4 B -1.01403880
> DT2
   X           A          B
1: 1 -0.19790449 -0.2462947
2: 2  0.17906116  0.9228573
3: 3  0.01821837  0.6600257
4: 4  0.17309716 -1.0140388
5: 5  0.05962474         NA

Aside (mostly for Arun):
Here is a solution I already use for melt (was written with help from Matthew D, so he should have this code), that I think replicates melt completely, and is pretty efficient.  Dcast on the other hand (or should that be dtcast?) is much harder!
melt.data.table = function(data, id.vars, measure.vars,
                           variable.name = "variable",
                           ..., na.rm = FALSE, value.name = "value") {
  if(missing(id.vars)){
    id.vars = setdiff(names(data), measure.vars)
  }
  if(missing(measure.vars)){
    measure.vars = setdiff(names(data), id.vars)
  }

  dtlist = lapply(measure.vars, function(..colname) {
    data[, c(id.vars, ..colname), with = FALSE][, (variable.name) := ..colname]
  })

  dt = rbindlist(dtlist)
  setnames(dt, measure.vars[1], value.name)
  if(na.rm){
    return(na.omit(dt))
  } else {
    return(dt)
  }
}

A: Update: faster versions of melt and dcast are now implemented (in C) in data.table versions >= 1.9.0. Check this post for more info.
Now you can just do:
dcast.data.table(DT, X~Y)

In case of dcast alone, at the moment, it has to be written out completely (as it's not a S3 generic yet in reshape2). We'll try to fix this as soon as possible. For melt, you can just use melt(.) as you'd do normally.

The general idea is this:
setkey(DT, X, Y)
DT[CJ(1:5, c("A", "B"))][, as.list(Z), by=X]

You can name the columns V1 and V2 as A and B using setnames.
But this may not be efficient on large data or when the cast formula is complex. Or rather I should say, it could be much more efficient. We're in the process of finding such an implementation to integrate melt and cast on to data.table. Until then, you could get around this as above.
I'll update this post once we've made significant progress with melt/cast.


text:
Q: android write to disk unreliable - written file.length !=expected.length I have a write method that will write a byte[] to disk. On very few devices I'm running into some strange problems where the written file.length() != byte[].length after a successful write operation.
Code and Problem
The code to write a file to disk
private static boolean writeByteFile(File file, byte[] byteData) throws IOException {
    if (!file.exists()) {
        boolean fileCreated = file.createNewFile();
        if (!fileCreated) {
            return false;
        }
    }

    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bos.write(byteData);
    bos.flush();
    fos.getFD().sync(); // sync to disk as recommended: http://android-developers.blogspot.com/2010/12/saving-data-safely.html
    fos.close();

    if (file.length() != byteData.length) {
        final byte[] originalMD5Hash = md.digest(byteData);

        InputStream is = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[4096];

        while(bis.read(buffer) > -1) {
            md.update(buffer);
        }
        is.close();

        final byte[] writtenFileMD5Hash = md.digest();

        if(!Arrays.equals(originalMD5Hash, writtenFileMD5Hash)) {
            String message = String.format(
                    "After an fsync, the file's length is not equal to the number of bytes we wrote!\npath=%s, expected=%d, actual=%d.  >>  " +
                    "Original MD5 Hash: %s, written file MD5 hash: %s",
                    file.getAbsolutePath(), byteData.length, file.length(),
                    digestToHex(originalMD5Hash), digestToHex(writtenFileMD5Hash));
            throw new GiantWtfException(message);
        }
    }

    return true;
}

I'm running into the if-statement where I compare file length on a few devices.
One example output:
After an fsync, the file's length is not equal to the number of bytes we wrote! path=/mnt/sdcard/.folder/filename, expected=233510, actual=229376 >> Original MD5 Hash: f1d298c0484672c52d9c26d04a3a21dc, written file MD5 hash: ab30660bd2b476d9551c15b340207a8a
I currently see this problem on 5 devices as I'm slowly rolling out the code. Some device data:
Question
Is there anything else I can do or improve?
More stats and observations
Current system version

*

*2.3.5

*2.3.6

Model

*

*N860 (LG)

*GT-I9100G (Samsung)

*GT-S5300 (Samsung)

*GT-S7500 (Samsung)

*LG-VS410PP (LG)

Other stats
In the general crash analytics (from Crittercism) there is always more then enough free disk space at the time the problem happens. Still some (not all) of the devices have thrown IOExceptions around no free disk space at a different point in time.
As always I've never been able to reproduce that problem on any test phone I have.
Assumptions / Observations:
Generally I would expect a IOException when the disk is full. Still all the exceptions that I catch have less bytes written then they should have.
Interestingly enough all the number of bytes that actually have been written to disk are a multiple of 2^15.
EDIT:
I added a MD5 check sum validation that also fails and simplified the example code a little for better readability. It still fails in the wild with different MD5 hashes.

A: philipp, file.length() is the file size as reported by the OS. It might be the space the file takes up on disk or the number of bytes in the file.
If the number returned is size on disk, it is related to the number of clusters that hold the file. For example NTFS generally uses 4KB clusters. If you save a text document with 3 ascii encoded characters in on an NTFS formatted volume, the size of the file is 3 bytes, the size of the file on disk is 4096 bytes. On NTFS with a 4KB cluster all files are a multiple of 4096 bytes on disk. See http://en.wikipedia.org/wiki/Data_cluster for more.
If the number returned is the length of the file in bytes (from the underlying file-system's meta-data) then you should have an exact match to how many bytes you wrote, though I wouldn't bet my life on it.
Android uses YAFFS or EXT4, if that helps at all.
I strongly agree with admdrew, use a hash. MD5 would work great. SHA or even CRC should work fine for this task. As you write bytes to the disk, feed the stream to your hash algorithm as well. Once the file is written, read it back and feed that to your hasher. Compare the results. If you want to be sure the data is clean, file size is not enough.


text:
Q: Convert string to datetime as outcome of an interception between two lines Im trying to get information about on which specific day does my graph intercept with a threshold value (certain hline in this case y=-1). Some of my results are:
(11.805201846946158, -1.0)
(12.99215619183464, -1.0)
(21.33191612908414, -1.0)
(22.633241076423914, -1.0)
(37.00391584924397, -1.0)

I would like to get instead of the 11.8052... value a specific date and time. The graph is plotted in datetime. What do i have to add in my script to print them in time?
spi_avg_1['spi3'].plot(label='SPI 3- monthly')
plt.axhline(y=-1, color='r', linestyle='-', linewidth=0.5)
plt.title('SPI 3-monthly')

yys = [-1]
xx, yy = [], []
xo,yo = [k for k in range(200)],spi_avg_1['spi3']
for i in range(1,len(spi_avg_1['spi3'])):
    for k in yys:
        p1 = np.array([xo[i-1],yo[i-1]],dtype='float')
        p2 = np.array([xo[i],yo[i]],dtype='float')
        k1 = np.array([xo[i-1],k],dtype='float')
        k2 = np.array([xo[i],k],dtype='float')
        if crosses((p2,p1),(k1,k2)):
            seg = line_intersection((p2,p1),(k1,k2))
            print(seg)

A: Dataset:
spi = Dataset('spi3_6_12_1deg_cru_ts_3_21_1949_2012.nc')
lats = spi.variables['lat'][:]
lons = spi.variables['lon'][:]
time = spi.variables['time'][:]
spi3 = spi.variables['spi3'][:]
spi6 = spi.variables['spi6'][:]
spi12 = spi.variables['spi12'][:]

ds = xr.open_dataset('spi3_6_12_1deg_cru_ts_3_21_1949_2012.nc')
ds_mlw = ds.sel(lon=slice(33,37), lat=slice(-18,-13), time=slice("2002-01-01", "2017-11-01"))

spi_avg_1 = ds_mlw.mean(dim=('lon', 'lat'))

The script is as follows:
def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here

def det(a, b):
    return a[0] * b[1] - a[1] * b[0]

div = det(xdiff, ydiff)
    if div == 0:
    return None

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

def near(a, b, rtol=1e-5, atol=1e-8):
    return abs(a - b) < (atol + rtol * abs(b))
def crosses(line1, line2):
"""
Return True if line segment line1 intersects line segment line2 and
line1 and line2 are not parallel.
"""
    (x1,y1), (x2,y2) = line1
    (u1,v1), (u2,v2) = line2
    (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
    e, f = u1-x1, v1-y1
    denom = float(a*d - b*c)
    if near(denom, 0):
    # parallel
       return False
    else:
        t = (e*d - b*f)/denom
        s = (a*f - e*c)/denom
    # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the
    # line segments
        return 0<=t<=1 and 0<=s<=1

 spi_avg_1['spi3'].plot(label='SPI 3- monthly')

plt.axhline(y=-1, color='r', linestyle='-', linewidth=0.5) #threshold spi idicicator of drought

plt.title('SPI 3-monthly')

yys = [-1]
xx, yy = [], []
xo,yo = [k for k in range(200)],spi_avg_1['spi3']

for i in range(1,len(spi_avg_1['spi3'])):
    for k in yys:
        p1 = np.array([xo[i-1],yo[i-1]],dtype='float')
        p2 = np.array([xo[i],yo[i]],dtype='float')
        k1 = np.array([xo[i-1],k],dtype='float')
        k2 = np.array([xo[i],k],dtype='float')
        if crosses((p2,p1),(k1,k2)):
            seg = line_intersection((p2,p1),(k1,k2))
            plt.scatter(seg[0],seg[1],c='red',s=90)
            print(seg)


text:
Q: How do I use XML Schema Definition Tool (Xsd.exe) Seriously I'm confused. I have an .XSD that is made from a class so that I can pass to a webservice. It got it over to the webservice as an XMLSchema object and now I need to make it into a class so that I can make objects out of it on the webservice side. I know that XSD.exe is the answer but I'll be darned if I can puzzle out exactly how to implement this thing. I need it to do this conversion at run time so I need to put the code for it into my project and all the references I've seen to using XSD.exe talk about calling it from the command line. My .XSD is below.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Field">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Name" type="xs:string" />
        <xs:element name="Type" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

In my project this is living in an XMLSchema object. How do I turn it into a class?
-Thank You so much for any help you can give.

A: If you're doing webservices in .NET, you do not need to resort to fiddling with XSD.
There is a wsdl.exe tool if you use the 1st gen webservices stack from .NET, aka .ASMX webservices. There is the svcutil.exe tool that you would use if you are relying on WCF.
Those things generate client-side proxy code, which provide classes that allow webservices clients to invoke web services.  Implicitly they rely on XSD, but you do not need to use the xsd.exe tool directly, nor do you need to deal directly with .xsd files.

A: If you are using .NET 2.0, then simply use "Add Web Reference" and point to the WSDL file of the service. If you are using any later version, then use "Add Service Reference".
Both of these will create the classes you need to communicate with the service, and no need to play with XSD.EXE or even WSDL.EXE.


text:
Q: useState hook always 1 step behind I have seen other questions with the exact same title, but none solved my problem:
This is my code:
import React, { useState } from 'react';
import Validation from './Validation/Validation';
import Char from './Char/Char';

function App() {
  const [textState, textSetState] = useState('');
  const [charsState, charsSetState] = useState([]);

  let inputChange = (event) => {
    textSetState(event.target.value);
    charsSetState(event.target.value.split('').map((char, index) => {
      return <Char char={char} key={index} click={() => { deleteCharHandler(index) }} />
    }));
  }

  const deleteCharHandler = (index) => {
    alert(textState);
  }
  return (

      <input type="text" onChange={(event) => inputChange(event)} />
      <Validation text={textState} />
      {charsState}

  );
}

export default App;

This is the result:

When I click a character, it displays the value from 1 step behind, like the example above.

A: You're putting an array of rendered Char components in your state, then rendering it. There are a number of issues with this approach.

*

*The local copy of the state (charsState) will not be updated immediately; instead React will re-render the component with the new value for state.

*Since you are defining the onClick callback within the function, deleteCharHandler will always be referencing an outdated copy of the state.

*Multiple state hooks being updated in lockstep in this way will cause additional re-renders to happen.

Since the naming in your example is a bit confusing it's hard to tell what the desired behavior is to make good recommendations for how to resolve or refactor.

A: So there are a few things which may or may not be causing an issue so lets just clear a few things up:

*

*You don't need to pass the anonymous function on the input:
<input type="text" onChange={inputChange} /> should suffice

*As with OG state, it's never a good idea to call two setStates simultaneously, so lets combine the two:
const [state, setState] = useState({text: '', char: []});
Once you've updated everything you should be setting one state object onClick.

*Your Char object is using click instead of onClick? unless you are using that as a callback method i'd switch to:
return <Char char={char} key={index} OnClick={() => deleteCharHandler(index)} />
If that doesn't fix your solution at the end, you can simply pass the deleteCharHandler the updated text value instead of re-grabbing the state value

A: I think you need useCallback or to pass textState in parameter. the deleteCharHandler method doesn't change in time with the textState value.
try :
return <Char char={char} key={index} click={() => { deleteCharHandler(index, textState) }} />
...

const deleteCharHandler = (index, textState) => {
    alert(textState);
  }

or :
import React, { useState, useCallback } from 'react';
...
const deleteCharHandler = useCallback(
  (index) => {
    alert(textState);
  }, [textState]);

A: Try this
function App() {
    const [textState, textSetState] = useState('');

    const inputChange = useCallback((event) => {
        textSetState(event.target.value);
    },[])

    function renderChars(){
        return textState.split('').map((char, index) => {
            return <Char char={char} key={index} click={() => { deleteCharHandler(index) }} />
        }));
    }

    const deleteCharHandler = useCallback( (index) => {
         alert(textState);
    }, [textState])

    return (

            <input type="text" onChange={inputChange} />
            <Validation text={textState} />
           {renderChars()}

   );
}


text:
Q: Banach Spaces: Totally Bounded vs. Bounded Are the finite dimensional Banach spaces precisely those ones in which subsets are totally bounded iff they're bounded?

A: I'm assuming a normed space $X$ based on your comments.
If $X$ is an infinite-dimensional normed space, then there exists a sequence $\{ x_{n}\}_{n=1}^{\infty}$ of unit vectors such that $\|x_{m}-x_{n}\| \ge 1/2$ for all $n \ne m$. That's a consequence of the Riesz lemma. I think that answers your question.


text:
Q: Installing plyvel with pip I am getting this error when trying to install plyvel :
  Running setup.py install for plyvel
    Complete output from command /home/eytan/.virtualenvs/env/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-NVZgbQ/plyvel/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-jHZNqS-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/eytan/.virtualenvs/env/include/site/python2.7/plyvel:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/plyvel
    copying plyvel/__init__.py -> build/lib.linux-x86_64-2.7/plyvel
    copying plyvel/_version.py -> build/lib.linux-x86_64-2.7/plyvel
    running build_ext
    building 'plyvel._plyvel' extension
    creating build/temp.linux-x86_64-2.7
    creating build/temp.linux-x86_64-2.7/plyvel
    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c plyvel/_plyvel.cpp -o build/temp.linux-x86_64-2.7/plyvel/_plyvel.o -Wall -g
    cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++
    plyvel/_plyvel.cpp:359:24: fatal error: leveldb/db.h: No such file or directory
     #include "leveldb/db.h"
                            ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

    ----------------------------------------
Command "/home/eytan/.virtualenvs/env/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-NVZgbQ/plyvel/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-jHZNqS-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/eytan/.virtualenvs/env/include/site/python2.7/plyvel" failed with error code 1 in /tmp/pip-build-NVZgbQ/plyvel

Can someone explain what's going on and how can I solve it ?

A: You need to install the leveldb development package.
On deb based distributions:
sudo apt-get install libleveldb-dev

On RPM based distributions:
sudo yum install leveldb-devel

Note that dnf is slowly but surely replacing yum. If your distribution uses dnf (e.g., Fedora 23 and newer), you can just drop it in there instead of yum:
sudo dnf install leveldb-devel

A: Try to run:
sudo apt-get install libleveldb-dev

and then try again to run pip install.
More info: source

A: For centos 6.X
yum install epel-release
yum install leveldb-devel


text:
Q: What are the optimal ways to learn undergraduate level math? I have recently dipped my toes into the topic of Machine Learning / Deep Learning and I would like to understand the underlying mathematical concepts.
I'm looking for an optimal way to learn the basics (mostly what can be found in a typical undergraduate math curriculum).
Going back to university would be the simplest choice but I don't have the time to do so. Another problem with it is that from my experience it is incomparably harder to understand compared to an online guide like this (note that this might only be the case in my country).
What choices do I have (getting certified is a bonus)?
Addendum: My biggest problem with a university was that it is hard to bridge the gap between what I learned in high school and the undergraduate topics. For example, it was hard to grok calculus back then so I chose to go to a teacher and after a few weeks with him, I was like "this is so simple I don't know why I had problems". Going to a math teacher would be the best option in terms of efficiency but a good teacher is more expensive than a university course and does not come with a degree.


text:
Q: Html option and input field not displayed proper I have here a small react app that works fine but when i try to render teh option and input field it doesnt look right
render() {
    return (

                <select onChange={this.makeSelection} name="base" value={this.state.base}>
                  {this.currencies.map(currency => <option key={currency} value={currency}></option>)}
                </select>
                <input value={this.state.value} onChange={this.changeValue}/>

              <select onChange={this.makeSelection} name="other" value={this.state.other}>
                  {this.currencies.map(currency => <option key={currency} value={currency}></option>)}
              </select>
              <input  disabled={true} value={this.state.converted} />

    );

and this is how it looks in the browser- i tried chrome and brave browser
this is a screenshot here
https://imgur.com/jGQW77y
and here is the code:
https://pastebin.com/55SHSSsd

A: You have to pass current element, currency as the content for the option tags:
render() {
return (

      <select
        onChange={this.makeSelection}
        name="base"
        value={this.state.base}
      >
        {this.currencies.map((currency) => (
          <option key={currency} value={currency}>{currency}</option>
        ))}
      </select>
      <input value={this.state.value} onChange={this.changeValue} />

      <select
        onChange={this.makeSelection}
        name="other"
        value={this.state.other}
      >
        {this.currencies.map((currency) => (
          <option key={currency} value={currency}>{currency}</option>
        ))}
      </select>
      <input disabled={true} value={this.state.converted} />

    );
  }

References:
w3schools.com. HTML  Tag. https://www.w3schools.com/tags/tag_option.asp. (accessed November 27, 2020).


text:
Q: How can i send data from my android to a adafruit PN532 card reader via NFC? Im new on this about working with arduino cards and i have a problem, because i have done an application to send a "STRING" from my android phone to another via nfc, and that worked very well... but the thing is when i started to work with a nfc card adafruit pn532, it can't recieve anything and i'd like to know if you can help me or if you have done this before.. thanks!
@Override
protected void onNewIntent(Intent intent) {
    if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
        /*String result = "";
        Toast.makeText(this, "Etiqueta NFC detectada", Toast.LENGTH_SHORT).show();
        result = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
        etiqueta = result;
        mEditText.setText(etiqueta);*/

        Parcelable[] rawMessages = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);

        NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
        mEditText.setText(new String(message.getRecords()[0].getPayload()));

    }}

@Override
public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
    String message = mEditText.getText().toString();
    NdefRecord ndefRecord = NdefRecord.createMime("text/plain", message.getBytes());
    NdefMessage ndefMessage = new NdefMessage(ndefRecord);
    return ndefMessage;
}


text:
Q: select2 ajax : Uncaught TypeError: Cannot read property 'context' of undefined Attempting to do an AJAX call with the Select2 jquery plugin. The query seems to be working, but the issue occurs when ".context===undefined" is called on the "data" object:
Uncaught TypeError: Cannot read property 'context' of undefined
(anonymous function)    @   select2.js:1651
(anonymous function)    @   select2.js:651
$.extend.success         @   select2.js:451
fire                    @   jquery-2.1.4.js:3099
self.fireWith           @   jquery-2.1.4.js:3211
done                    @   jquery-2.1.4.js:8264
(anonymous function)    @   jquery-2.1.4.js:8605

Here is my HTML:

Here is the returned JSON:
[{"WorkOrderId":"b13c3737-c3ce-42d8-95a4-dbd2b6ad766d","WorkOrderNumber":"10033 - 357153","DueDateTime":"6/14/2015 5:21:25 PM","Status":1},{"WorkOrderId":"f9f4f449-53d3-4e93-9162-e970a71ca2b4","WorkOrderNumber":"10241 - 301872","DueDateTime":"6/12/2015 10:56:24 PM","Status":1},{"WorkOrderId":"86782205-15ae-43b8-88a9-2f80a261b350","WorkOrderNumber":"10522 - 728155","DueDateTime":"6/13/2015 11:51:24 AM","Status":1},{"WorkOrderId":"846f38f6-7a0b-4cb2-860f-f54cc6b81250","WorkOrderNumber":"10944 - 757155","DueDateTime":"6/14/2015 1:35:25 PM","Status":1},{"WorkOrderId":"5d22de8c-1995-429c-8431-55363ca318fa","WorkOrderNumber":"11202 - 381180","DueDateTime":"7/30/2015 11:28:02 AM","Status":0},{"WorkOrderId":"b7e0276d-e9c0-4421-93c1-097bbe1bbbe5","WorkOrderNumber":"11497 - 452908","DueDateTime":"6/13/2015 4:22:24 PM","Status":1},{"WorkOrderId":"f11cc30d-877b-48ef-8e8d-dc52ba85fa4a","WorkOrderNumber":"11662 - 554562","DueDateTime":"6/14/2015 12:59:25 PM","Status":1},{"WorkOrderId":"80426f02-3863-448c-99b4-40b88e523899","WorkOrderNumber":"11738 - 431931","DueDateTime":"6/13/2015 8:01:24 AM","Status":1},{"WorkOrderId":"eec0b73a-eaea-464e-b14b-875fda2ec9ed","WorkOrderNumber":"11812 - 751435","DueDateTime":"6/12/2015 9:34:24 PM","Status":1},{"WorkOrderId":"7a824079-8cd2-4212-898a-bcafb6dec397","WorkOrderNumber":"12184 - 456670","DueDateTime":"6/13/2015 1:31:24 AM","Status":1},{"WorkOrderId":"0047ff2f-9e4c-490c-aa8b-9219f3e5da9a","WorkOrderNumber":"12264 - 503344","DueDateTime":"6/13/2015 12:21:24 PM","Status":1},{"WorkOrderId":"28ff159e-5c14-420b-a45a-446e2fb1f981","WorkOrderNumber":"12739 - 515468","DueDateTime":"6/14/2015 1:47:24 AM","Status":1},{"WorkOrderId":"417cc031-9fc1-4cec-a2c4-8c8c0f09f8ef","WorkOrderNumber":"12927 - 517644","DueDateTime":"6/14/2015 8:56:25 PM","Status":1},{"WorkOrderId":"cadfc948-3193-444b-827e-cbf34183b966","WorkOrderNumber":"13349 - 337107","DueDateTime":"6/13/2015 3:02:24 AM","Status":1},{"WorkOrderId":"67c80344-f7a9-411a-a0af-a6f406edf1ae","WorkOrderNumber":"15300 - 667097","DueDateTime":"6/13/2015 4:23:24 AM","Status":1},{"WorkOrderId":"f6929a96-3b24-4a5a-85cb-bfa8a28a4b94","WorkOrderNumber":"15916 - 360186","DueDateTime":"6/14/2015 8:23:24 AM","Status":1},{"WorkOrderId":"4d719616-3c10-43df-a29c-26779c0b1784","WorkOrderNumber":"16111 - 791177","DueDateTime":"6/14/2015 4:41:24 AM","Status":1},{"WorkOrderId":"b53abb8a-0544-4365-9834-bef5f30df984","WorkOrderNumber":"16659 - 604433","DueDateTime":"6/13/2015 2:03:24 PM","Status":2},{"WorkOrderId":"dce8a308-26ff-406d-ae98-47e9f31a45a9","WorkOrderNumber":"16869 - 302808","DueDateTime":"6/13/2015 5:53:24 PM","Status":0},{"WorkOrderId":"24b91d00-0baf-4cc1-a140-db7e5f10813a","WorkOrderNumber":"17052 - 700308","DueDateTime":"6/14/2015 4:51:25 PM","Status":1},{"WorkOrderId":"f9c87a2b-8735-46a0-ada6-9430e7be5f92","WorkOrderNumber":"18095 - 770739","DueDateTime":"6/14/2015 9:59:24 AM","Status":1},{"WorkOrderId":"91cbc26d-4b24-4060-a55b-58ae62696341","WorkOrderNumber":"18189 - 585562","DueDateTime":"6/12/2015 11:29:24 PM","Status":1},{"WorkOrderId":"f552d68a-b754-4fa8-8672-b090358c1fdf","WorkOrderNumber":"18264 - 758315","DueDateTime":"6/14/2015 3:52:25 PM","Status":1},{"WorkOrderId":"2c76a091-2154-4d22-93b2-231daa44e76d","WorkOrderNumber":"18369 - 699494","DueDateTime":"6/14/2015 3:50:24 AM","Status":1},{"WorkOrderId":"2380188c-e461-4a64-9e27-20a5be36e216","WorkOrderNumber":"18405 - 661978","DueDateTime":"6/13/2015 7:45:24 PM","Status":1},{"WorkOrderId":"5d92e775-ea7c-4fe0-8082-25a0b4ef89d4","WorkOrderNumber":"18422 - 795057","DueDateTime":"6/14/2015 11:03:24 AM","Status":1},{"WorkOrderId":"1b9920b2-84a0-4068-8f0b-11c0a749c543","WorkOrderNumber":"18580 - 312167","DueDateTime":"6/12/2015 5:29:24 PM","Status":1},{"WorkOrderId":"71d6d9c7-ad28-4ca3-9548-e63d5fdaf8ff","WorkOrderNumber":"21767 - 361132","DueDateTime":"6/12/2015 2:56:24 PM","Status":2},{"WorkOrderId":"68a95665-08d5-49f2-bc53-9d89b6244900","WorkOrderNumber":"22027 - 771866","DueDateTime":"6/13/2015 12:57:24 AM","Status":1},{"WorkOrderId":"ede4b0f0-c6a8-4b98-a6db-1f63744b2f8a","WorkOrderNumber":"22443 - 431743","DueDateTime":"6/14/2015 12:33:24 AM","Status":1},{"WorkOrderId":"e0290313-f0f2-4002-af50-5d4acda3d58c","WorkOrderNumber":"22610 - 773200","DueDateTime":"6/13/2015 6:54:24 AM","Status":1},{"WorkOrderId":"05f37251-1999-4133-8ca4-db118d5f7297","WorkOrderNumber":"23106 - 781159","DueDateTime":"6/13/2015 9:25:24 PM","Status":1},{"WorkOrderId":"43c7198c-67f5-44e1-b584-4dc7c4449f89","WorkOrderNumber":"23836 - 577156","DueDateTime":"6/13/2015 9:59:24 AM","Status":0},{"WorkOrderId":"9c975a12-75ea-42e9-8826-567f834f14d0","WorkOrderNumber":"24201 - 750775","DueDateTime":"6/14/2015 6:45:25 PM","Status":1},{"WorkOrderId":"dac8af35-79d7-4a9d-9a96-74dff26c5667","WorkOrderNumber":"24250 - 322136","DueDateTime":"6/13/2015 11:03:24 AM","Status":1},{"WorkOrderId":"6aa5e71e-dc57-4317-bca7-e74662db9465","WorkOrderNumber":"25716 - 774762","DueDateTime":"6/14/2015 11:58:24 AM","Status":1},{"WorkOrderId":"077975dd-6971-4286-b645-6cd1537f853f","WorkOrderNumber":"25762 - 612741","DueDateTime":"6/13/2015 8:50:24 PM","Status":1},{"WorkOrderId":"b610e826-a67c-4cb6-98a3-3fdaf2f8860e","WorkOrderNumber":"26363 - 516382","DueDateTime":"6/13/2015 5:54:24 AM","Status":1},{"WorkOrderId":"29493c6e-69c6-4635-8226-58e2007d1efb","WorkOrderNumber":"26992 - 621999","DueDateTime":"6/13/2015 6:47:24 PM","Status":1},{"WorkOrderId":"1e5df10c-4c13-4e28-926b-5e98b836ff88","WorkOrderNumber":"27731 - 590950","DueDateTime":"6/13/2015 3:36:24 PM","Status":2},{"WorkOrderId":"7bf55f76-adae-4cfa-9c12-8415b9559fec","WorkOrderNumber":"28492 - 748391","DueDateTime":"6/14/2015 6:49:24 AM","Status":1},{"WorkOrderId":"0702f4a9-1fd7-4cca-baea-988af03f6b11","WorkOrderNumber":"29635 - 794911","DueDateTime":"6/12/2015 4:51:24 PM","Status":1}]

Here is the code which is failing in "select2.js":
     /**
     * @param initial whether or not this is the call to this method right after the dropdown has been opened
     */
    // abstract
    updateResults: function (initial) {
        var search = this.search,
            results = this.results,
            opts = this.opts,
            data,
            self = this,
            input,
            term = search.val(),
            lastTerm = $.data(this.container, "select2-last-term"),
            // sequence number used to drop out-of-order responses
            queryNumber;

        [...]//omitted for brevity

        // save context, if any
        this.context = (data.context===undefined) ? null : data.context;
        // create a default choice and prepend it to the list
        if (this.opts.createSearchChoice && search.val() !== "") {
            def = this.opts.createSearchChoice.call(self, search.val(), data.results);
            if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
                if ($(data.results).filter(
                    function () {
                        return equal(self.id(this), self.id(def));
                    }).length === 0) {
                    data.results.unshift(def);
                }
            }
        }

        [...]//omitted for brevity
    }

Here is the javascript that hook the ajax with the select2:
   $("#workOrdersLookup").select2(
   {
       ajax:
       {
           data: function (params)
           {
               var query =
               {
                   workOrderNumber: params
               }
               return query;
           },
           type: "GET",
           contentType: "application/json",
           dataType: "json",
           nonBlocking: true,
           url: server_api_base_url + "api/v1/Equipments/" + self.EquipmentId + "/WorkOrders/all",
           results: function (data)
           {
               var results = [];
               $.each(data, function (index, item)
               {
                   results.push(
                   {
                       id: item.WorkOrderId,
                       text: item.WorkOrderNumber,
                       WorkOrderId: item.WorkOrderId,
                       WorkOrderNumber: item.WorkOrderNumber
                   });
               });
               return
               {
                   results: results
               };
           }
       },
       multiple: false,
       placeholder: 'Select workorder',
       dropdownAutoWidth: true,
       minimumInputLength: 1
   });

What is wrong that cause this error?
Searched this error in google and nothing except a forum discussion is related to this.

A: Turned out I was using an up to date way for select2 on an older version of select2.
With the old version of select2, use query: instead of ajax:.
    $("#workOrdersLookup").select2(
    {
        query: function (query) {  /*USING QUERY HERE INSTEAD OF AJAX FIXED MY ISSUE*/
            var data = { results: [] };

            self.Api.GetAllWorkOrders(query.term).done(function (result) {
                $.each(result, function (index, item)
                {
                    data.results.push(
                    {
                        id: item.WorkOrderId,
                        text: item.WorkOrderNumber
                    });
                });

                query.callback(data);
            });
        },
        placeholder: 'Select workorder',
        dropdownAutoWidth: true,
        minimumInputLength: 4
    });


text:
Q: SQLite data input in ion list I have some problem with data input in ion-list. I read some in StackOverflow but my problem doesn't solved. I would like that data from DB input in items on my screen. I am new in AngularJS and Ionic, please help! I am will very grateful if you help solve my problem!
P.S. Sorry for my English.

litedb.js

var db = null;

angular.module('starter.litedb', ['ngCordova'])

// db controller
.controller("LitedbCtrl", function($scope,$cordovaSQLite,$ionicPopup){
    $scope.insert = function(cardnum, datat, eventt, sum, category, total) {
      var query = "INSERT INTO smsdata (cardnum, datat, eventt, sum, category, total) VALUES (?, ?, ?, ?, ?, ?)";
      $cordovaSQLite.execute(db,query, [cardnum, datat, eventt, sum, category, total]).then(function(result){
        console.log("INSERT ID ->" + result.insertId);
      }, function(error){
        console.log(error);
      })
    }
        $scope.selectAll = function(){
        var alldataSMS = [];
      var query = "SELECT * FROM smsdata";
      $cordovaSQLite.execute(db,query,[]).then(function(result){
          if(result.rows.length>0){
            console.log("SELECTED ->" + result.rows.item(0).id + " " +
             result.rows.item(0).category);
             for (var i = 0; i < result.rows.length; i++) {
// cardnum, datat,  eventt, sum, category, total
              alldataSMS.push({
               id: result.rows.item(i).id,
               cardnum: result.rows.item(i).cardnum,
               datat: result.rows.item(i).datat,
               eventt: result.rows.item(i).eventt,
               sum: result.rows.item(i).sum,
               category: result.rows.item(i).category,
               total: result.rows.item(i).total
              })
             }
              $scope.$apply();
          } else {
            console.log("NO ROWS EXIST");
          }

      }, function(error){
          console.log(error);
      })
    }

})
<ion-view view-title="History">
<ion-nav-buttons side="right">
     <button class="button button-icon ion-plus"> </button>
</ion-nav-buttons>
<ion-pane ng-controller="LitedbCtrl">
  <ion-content >
    <button class="button" ng-click="selectAll()">SelectALL</button>
    <ion-list>
     <ion-item ng-repeat="fsdata in alldataSMS">
     <h3>{{fsdata.eventt}}</h3>
     {{fsdata.datat}}
     {{fsdata.sum}}
     {{fsdata.category}}
     {{fsdata.total}}
     </ion-item>
    </ion-list>

  </ion-content>
  </ion-pane>
</ion-view>

app.js
angular.module('starter', ['ionic', 'starter.controllers','starter.chart',
  'starter.litedb'])

.run(function($ionicPlatform, $cordovaSQLite ) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
    // localDB.sync(remoteDB, {live: true});
    db = $cordovaSQLite.openDB({name: "app.db", location: 'default'});
   $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS smsdata (id integer primary key, cardnum text, datat text, eventt text, sum text, category text, total text)");
  });
})

And console log

A: I solved the problem, it was my folt i use another method razer into documentation. Read Github plugin repo
. and my litedb.js

var db = null;

angular.module('starter.litedb', ['ionic','ngCordova'])

// db controller
.controller("LitedbCtrl", function($scope, $ionicPlatform, $cordovaSQLite){

    var db = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function () {
    db.executeSql("CREATE TABLE IF NOT EXISTS smsdata (id integer primary key, cardnum text, datat text, eventt text, sum text, category text, total text)");
}, function (error) {
    console.log('Open database ERROR: ' + JSON.stringify(error));
});

function addItem(cardnum, datat, eventt, sum, category, total) {

    db.transaction(function (tx) {

        var query = "INSERT INTO smsdata (cardnum, datat, eventt, sum, category, total) VALUES (?, ?, ?, ?, ?, ?)";

        tx.executeSql(query, [cardnum, datat, eventt, sum, category, total], function(tx, res) {
            console.log("insertId: " + res.insertId);
            console.log("rowsAffected: " + res.rowsAffected);
        },
        function(tx, error) {
            console.log('INSERT error: ' + error.message);
        });
    }, function(error) {
        console.log('transaction error: ' + error.message);
    }, function() {
        console.log('transaction ok');
    });
}
// addItem('1452', '13.02.2016', 'покупка', '400' ,'Продукты', '800');
// addItem('1452', '15.02.2016', 'зачесление', '1100' ,'Банкомат', '1900');
// addItem('1452', '19.02.2016', 'покупка', '75' ,'Продукты', '1825');
// addItem('1452', '20.02.2016', 'покупка', '290' ,'Здоровье', '1535');
// addItem('1452', '25.02.2016', 'покупка', '950' ,'Развлечения', '585');
// addItem('1452', '29.02.2016', 'покупка', '49' ,'Продукты', '536');

function selAll(){

 $scope.alldataSMS = [];

 db.executeSql("SELECT * FROM smsdata", [], function (result) {
   for(var x = 0; x < result.rows.length; x++) {
  // console.log('cardnum: ' + result.rows.item(x).cardnum +
  //  ' Data: ' + result.rows.item(x).datat +
  //   ' Event: ' + result.rows.item(x).eventt +
  //   ' Sum: ' + result.rows.item(x).sum +
  //   ' category: ' + result.rows.item(x).category +
  //   ' total: ' + result.rows.item(x).total);

   $scope.alldataSMS.push({id:result.rows.item(x).id,
               cardnum:result.rows.item(x).cardnum,
               datat:result.rows.item(x).datat,
               eventt:result.rows.item(x).eventt,
               sum:result.rows.item(x).sum,
               category:result.rows.item(x).category,
               total:result.rows.item(x).total});
  };
}, function(error) {
  console.log('SELECT error: ' + error.message);
});
}

selAll();

function closeDB() {
    db.close(function () {
        console.log("DB closed!");
    }, function (error) {
        console.log("Error closing DB:" + error.message);
    });
}

});


text:
Q: Query search android studio, problemas em listar dados do firebase Alguém poderia me ajudar? O app recupera os dados da child("grupos") na depuração, mas quando eu coloco o nó, por exemplo, child("grupos").child("nome"), o aplicativo da crash e nem na depuração da para ver se está recuperando. O que estou fazendo errado?
Database
https://ibb.co/C1Gy8gs
DEBUG
https://ibb.co/6b8Whw3
Erro usando child("groupos").child("nome");
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
    .activity.SalasActivity$1.search(SalasActivity.java:86)
    .activity.SalasActivity$1.access$000(SalasActivity.java:56)
    .activity.SalasActivity$1$1.onQueryTextChange(SalasActivity.java:78)

public class SalasActivity extends AppCompatActivity {

DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_salas);

        ref = FirebaseDatabase.getInstance().getReference().child("grupos").child("nome");
        recyclerView = findViewById(R.id.rv);
        searchView = findViewById(R.id.searchView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(ref != null){
            ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()){
                        list = new ArrayList<>();

                        for (DataSnapshot ds : dataSnapshot.getChildren())
                        {
                        list.add(ds.getValue(Deal.class));
                        }
                        AdapterClass adapterClass = new AdapterClass(list);
                        recyclerView.setAdapter(adapterClass);
                    }
                    if (searchView != null){
                        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                            @Override
                            public boolean onQueryTextSubmit(String query) {
                                return false;
                            }

                            @Override
                            public boolean onQueryTextChange(String s) {
                                search(s);
                                return true;
                            }
                        });
                    }
                }
                private  void  search(String str){
                    ArrayList<Deal> myList = new ArrayList<>();
                    for (Deal object : list){
                        if (object.getNome().toLowerCase().contains(str.toLowerCase())){
                            myList.add(object);

                        }
                    }
                    AdapterClass adapterClass = new AdapterClass(myList);
                    recyclerView.setAdapter(adapterClass);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(SalasActivity.this,databaseError.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

Deal.class
erro
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: xxx.chat, PID: 11966
    com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type .activity.Deal
    public class Deal {
    private String nome;
    private String id;
    private String membros;

    public Deal() {
    }

    public Deal(String nome, String id, String membros) {
        this.nome = nome;
        this.id = id;
        this.membros = membros;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMembros() {
        return membros;
    }

    public void setMembros(String membros) {
        this.membros = membros;
    }
}

A: Olá, Marc!
Para recuperar o nome, você precisará da key do grupo. Ficaria mais ou menos assim, por exemplo, para obter o nome do grupo
mDatabaseRef.child("grupos")
            .child("-L_KE54XVwBMans6Bh6") // Key do grupo
            .addValueEventListener(new ValueEventListener() {
                 @Override
                 public void onDataChange(DataSnapshot dataSnapshot) {
                     if (dataSnapshot.exists()) {
                       String nome = dataSnapshot.getValue().child("nome");
                     }
                 }
                 @Override
                 public void onCancelled(DatabaseError databaseError) {

                 }
             });

Sempre que um grupo é adicionado na árvore, é adicionado com uma key. Quando precisar recuperar informações dele, precisará saber sua key.
EDIT 1: você precisa adicionar os dados recuperados ao seu ArrayList;
EDIT 2: o que acontece é que você tenta recuperar um campo que não é do tipo que está definido na sua classe Deal, provavelmente o atributo membro. No database, ele aparenta ser um ser um array de objetos ou um tipo de lista (ArrayList ou List). Acredito que a para o seu propósito, seu database não está estruturada de forma correta.
Sugestão
Como seu projeto ainda está no início, sugiro que modifique essa estrutura e separe a lista de membros da child grupos. Quando for criar a lista de membros, use a key da child grupos ao qual ela pertence, por exemplo, para o primeiro grupo

Observe que a key da child  é a mesma do grupo ao qual ele pertence, como sugerido. Veja também, a key de cada membro, pode ser sua própria identificação dentro do database. Então quando quiser recuperar a lista de membros, faça dessa forma
mDatabaseRef.child("membros")
                .child("-L_KE54XVwBMans6Bh6") // Key do grupo
                .addValueEventListener(new ValueEventListener() {
                     @Override
                     public void onDataChange(DataSnapshot dataSnapshot) {
                         if (dataSnapshot.exists()) {
                            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                mMembros.add(snapshot.getValue(Membro.class);
                            }
                         }
                     }
                     @Override
                     public void onCancelled(DatabaseError databaseError) {

                     }
                 });

Há algumas vantagens nisso: fica mais fácil obter a lista de membros, garante que um mesmo membro não seja adicionado duas ou mais vezes no mesmo grupo e você não vai precisar iterar pelos grupos para obter os membros.
Essa reestruturação é a melhor solução para seu problema, pois é mais escalonável. Considere antes de criar as outras parte do seu projeto, ler a documentação do Firebase Database de como estrutura o banco de dados (é um leitura rápida, mas que vai esclarecer alguns pontos importantes).
Espero que isso resolva seu problema!


text:
Q: Why am I getting error 'Cannot read property 'name' of null' when using a parsed string? Here I have a react container that holds an object in a variable called strLoc:
(what var strLoc looks like console logged)

Object {name: "Burj Khalifa", locationLat: "25.197787", locationLong:
  "55.274862"}

I want to use the name property of the object, but when I try to get {strLoc.name}, I get an error message:

Uncaught TypeError: Cannot read property 'name' of null

I don't understand why I can't just pull off the property values to use them? Does the problem have something to do with that the object was a string before (I parsed the string and saved the resulting object in var strLoc) ?
here is my code:
class NoteOutput extends React.Component {
    render() {
        var strLoc = JSON.parse(this.props.location);
        return(

hello

{strLoc.name}

        );
    }
}

function mapStateToProps(state) {
    return {
        location: state.selectedLocation
    };
}

A: its probably because you have the parse in your render() and it tries to show .name of a string/before it gets parsed.
try this:
{strLoc &&
{strLoc.name}
}