text:
Q: How to solve problems that have many distinct levels (they are recursive) in c I would like to know how to handle problems where there is a process which is used in many different 'levels' of a problem in c, preferable in an 'idiomatic' way.I know I did not explain this well enough, so let me give an example:
Consider the general problem of making a game solver, which is supposed to print the best next move.I think that it should check all possible moves in a for loop and see if it is a winning move(in this round) if it is, return the move, otherwise check every possible move the opponent can play against your move (for loop) and call the function to find the best move again.
However, I find that this approach has some limitations, such as performance (the program will spend it's time running boilerplate code required to call the functions etc)
and limited flexibility , since the function will have to find a method to communicate with the caller how good a move was found.That is, if it could be done at all.
bestmove()
{
  for (;i<maxmove;i++)
   {
    if(checkifwinning(moves[i])) return;
    for (;n<maxopponentmove;n++)
     {
      bestmove();
     }
   }

I have been messing with haskell for a while now, so I am afraid that my mind is set on seeking recursive solutions.I hope that you can show me a way to write this function in a 'c native' way.

A: The C language permits recursive functions. However, it has no notion of tail-recursive calls (but in some occasions, recent GCC compilers are able to optimize some tail-recursive calls into purely iterative machine code).
When coding recursive functions you should avoid too deep recursion and too big local call frames (so use heap memory).

A: I think what you really need is a branch-and-bound like algorithm: keep a list of "open" moves (i.e., not yet considered) and a list of "closed" moves (i.e., already considered). In C this would best be implemented having two queues (open and closed). Then you would have an algorithm as follows:
while (open is not empty)
{
   pop gameState from open
   if (gameState in closed)
      continue;
   push gameState to closed
   for (eachMove)
   {
       computeNewState();
       addStateToOpen();
   }
}

There are several advantages to this compared to a recursive approach:

*

*you are sure that every game state is only considered once

*you do not "overwhelm" the stack

A: You are talking about searching a game tree to find a best move; you could use a standard algorithm like minimax.  Your approach seems to be a depth-first search of the tree which terminates at the first winning move found; note that this won't find the shortest path to a winning move nor does it guard against the opponent's winning.
There are ways to speed up the searching of game trees such as alpha-beta pruning.  Such a standard algorithm is the way to go - much better than worrying about the overhead of calling functions in C, etc.  C function calls are not expensive.  Beware of such "optimizations" when writing C code - the optimizer is likely to be better at such things anyway.  At the very least, first write a version in the most straightforward way so you have something to benchmark against.  Your job is to find a good algorithm.


text:
Q: Does time complexity get affected in a map function with index for a large array I have a map function which loops a large array (hundreds of products) and displays a list of products. I would like to display an additional element after the 2nd product. I have added a condition which checks for index where index == 1 and displays the elements. But I am assuming that it would affect time complexity and performance. This is within a react component. The function looks similar to this.
{products.map((product, index) => (
    <>
        <Product
            product={product}
        />
        {index == 1 &&
Test
}
    </>
))}

Please let me know if this would affect the performance.
Thanks in advance.

A: That does not impact the time complexity at all - you're looping through the array of length n once per item, so it's a linear time complexity O(n). I'm fairly certain it wouldn't impact performance, && short-circuits so it would only be running index == 1 for the rest of the indices. A potentially more performant way to do it would be to handle the first two items outside of the loop, then slice(2) to get the rest of the array and just run map on that without the if statement.
But in short, that if statement will not noticeably affect performance, and the time complexity is only really affected by how much you're looping through the array (in this case, you're only looping through each element once so it's O(n)).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Json Result From MVC With Ajax Is Not Showing My Ajax block looks like so:
    $('#btnTest').click(function(){
      $.getJSON('/User/ViewMessages',function(result) {
            // TODO: update the DOM with the items
            $("table#tblMessages").append("
"+result.MESSAGETEXT+"	"+result.DATESENT+"	");
      });
    });

My Action in my Controller looks like such:
        public ActionResult ViewMessages()
    {
        var recipient = Convert.ToInt32(HttpContext.Session["User_Id"]);
        var query = (from m in context.Messages
                     from rec in context.Recipients
                     where rec.RECIPIENT == recipient
                     where rec.MESSAGEID == m.MESSAGEID
                     select new
                     {
                         m.MESSAGETEXT,
                         m.DATESENT
                     }).ToList();
        return Json(query.ToList());
    }

When Debugging, my query variable returns:
{ MESSAGETEXT = "seresr", DATESENT = {9/15/2011 11:06:45 AM} }
The thing is, my table is added with "undefined" for both my  values. Where have i gone wrong? I have already added the maproute as well, but I'm still out of luck.

A: It looks like you're returning a list, which will be represented in JSON as an array.  So your result object is a JavaScript array rather than a single object.  To loop through all the items and add a table row for each, try something like this:
$.getJSON('/User/ViewMessages', function(result) {
    for (var i in result) {
        var row = result[i];
        $("table#tblMessages").append("
" + row.MESSAGETEXT
            + "	" + row.DATESENT + "	");
    }
});


text:
Q: Insert Data to DB without Page Refresh using JQuery, Inserts single rows multiple times I m using jquery and php to insert data into db after fetching it from table.
However, although the insert without page refresh using jquery works fine, but it inserts the last fetched row multiple times.
So far my code :
Index :
<?php
   $sqlproduct = "SELECT * FROM products ORDER BY id DESC LIMIT 0,2";
   $resultproduct = $conn->query($sqlproduct);
   if ($resultproduct->num_rows > 0) {
   while($rowproduct = $resultproduct->fetch_assoc()) {
      $p_id = $rowproduct["id"];
      $p_name = $rowproduct["name"];
      $p_c_id = $rowproduct["c_id"];
      $p_v_id = $rowproduct["v_id"];
      $p_image = $rowproduct["image"];
      $p_price = $rowproduct["price"];
?>
<form action="addtocart" method="post"  id="myform">
     <input type="hidden" id="pid" name="pid" value="<?php echo $p_id; ?>" />
     <input type="hidden" id="uid" name="uid" value="<?php echo $u_id; ?>" />
     <input type="hidden" id="quantity" name="quantity" value="1" />
     <input type="hidden" id="price" name="price" value="<?php echo $p_price; ?>" />
     <input type="hidden" id="vid" name="vid" value="<?php echo $p_v_id; ?>" />
         <button id='insert' class="add-cart-btn">
              <i class="icon-basket"></i>
         </button>
</form>
<?php } } else { } ?>

<script>
        $("form").submit(function(e){
            e.preventDefault();
            $.post(
                'addtocart.php',
                {
                    pid: $("#pid").val(),
                    uid: $("#uid").val(),
                    vid: $("#vid").val(),
                    quantity: $("#quantity").val(),
                    price: $("#price").val()
                },
                function(result){
                    if(result == "success"){
                        $("#result").val("Values Inserted");
                    } else {
                        $("#result").val("Error");
                    }
                }
           );
        });
    </script>

addtocart.php
<?php
    define('HOST','localhost');
    define('USERNAME', 'username');
    define('PASSWORD','password');
    define('DB','dbname');

    $con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);

    $p_id = $_POST['pid'];
    $u_id = $_POST['uid'];
    $v_id = $_POST['vid'];
    $price = $_POST['price'];
    $quantity = $_POST['quantity'];

    $sql = "insert into cart (p_id, u_id, v_id, price, quantity) values ('$p_id','$u_id','$v_id','$price','$quantity')";

    if(mysqli_query($con, $sql)){
        echo 'success';
    }
?>

I understand that it has something to do with LIMIT and OFFSET i used to fetch product details.
I even tried altering the ID values inside HTML form and the script #id's
Form fields
<input type="hidden" id="pid<?php echo $p_id;?>" name="pid" value="<?php echo $p_id; ?>" />
<input type="hidden" id="uid<?php echo $p_id;?>" name="uid" value="<?php echo $u_id; ?>" />
<input type="hidden" id="quantity<?php echo $p_id;?>" name="quantity" value="1" />
<input type="hidden" id="price<?php echo $p_id;?>" name="price" value="<?php echo $p_price; ?>" />
<input type="hidden" id="vid<?php echo $p_id;?>" name="vid" value="<?php echo $p_v_id; ?>" />

And Script ID's
pid<?php echo $p_id;?>: $("#pid<?php echo $p_id;?>").val(),
uid<?php echo $p_id;?>: $("#uid<?php echo $p_id;?>").val(),
vid<?php echo $p_id;?>: $("#vid<?php echo $p_id;?>").val(),
quantity<?php echo $p_id;?>: $("#quantity<?php echo $p_id;?>").val(),
price<?php echo $p_id;?>: $("#price<?php echo $p_id;?>").val()

This time, it didn't even passed the values to addtocart page.
OR
JavaScript code find the element within the context
<script>
        $("form").submit(function(e){
            e.preventDefault();
            $.post(
                'addtocart.php',
                {
                    pid: $(this).find("input[name='pid']").val(),
                    uid: $(this).find("input[name='uid']").val(),
                    vid: $(this).find("input[name='vid']").val(),
                    quantity: $(this).find("input[name='quantity']").val(),
                    price: $(this).find("input[name='price']").val()
                },
                function(result){
                    if(result == "success"){
                        $("#result").val("Values Inserted");
                    } else {
                        $("#result").val("Error");
                    }
                }
           );
        });
    </script>

This time, it didn't even passed the values to addtocart page.
Any help is appreciated..

A: Your HTML elements are re-using the same id values.  So when you select an element by that id, such as here:
$("#pid").val()

You're trying to target multiple elements, by what is supposed to be a unique identifier, and get back a single value.  Logically that can't work, and is against HTML standards so the behavior is undefined.
For your current setup, where each iteration of the loop has its own form, you don't need the id values and can just target the form elements by name.  For example, remove the id from each element:
<input type="hidden" name="pid" value="<?php echo $p_id; ?>" />

And in the JavaScript code find the element within the context of the submitting form:
$(this).find("input[name='pid']").val()

Or you may even just be able to serialize the form, if the element names all match what you need.  Something like this:
$.post('addtocart.php',
    $(this).serialize(),
    function(result) {
        //...
});


text:
Q: Retrieve rows where specific columns are different between rows I have the following SQL to obtain both highest (max) and 2nd highest dated rows. There are some cases in the data where the only difference in the 'OLD ROW' and 'NEW ROW' is the effective date. What I would like to do is only show the old and new rows per EMPLID where either the BANK_CD and/or the ACCOUNT_NUM are different between the 'old' and 'new' rows.
   WITH CTE AS (
 SELECT A.EMPLID
 , C.VENDOR_ID
 , B.FIRST_NAME
 , B.LAST_NAME
 , A.BANK_CD
 , A.ACCOUNT_NUM
 , A.ACCOUNT_TYPE
 , A.PRIORITY
 , A.LAST_UPDATE_DATE
 , A.EFFDT
 , MAX(A.LAST_UPDATE_DATE) OVER(PARTITION BY A.EMPLID) AS MAX_UPDATE_DATE
 , ROW_NUMBER() OVER(PARTITION BY A.EMPLID
  ORDER BY A.EFFDT DESC
  , D.EFFDT DESC) AS RN
  FROM PS_DIRECT_DEPOSIT D INNER JOIN PS_DIR_DEP_DISTRIB A ON A.EMPLID = D.EMPLID
   AND A.EFFDT = D.EFFDT INNER JOIN PS_EMPLOYEES B ON B.EMPLID = A.EMPLID INNER JOIN PS_GHS_DIR_DEP_VND C ON C.EMPLID = A.EMPLID
     INNER JOIN PS_DIR_DEP_DISTRIB E ON E.EMPLID = A.EMPLID AND E.EFFDT = A.EFFDT AND E.PRIORITY = A.PRIORITY
 WHERE B.EMPL_STATUS NOT IN ('T','R','D')
   AND ((A.DEPOSIT_TYPE = 'P'
   AND A.AMOUNT_PCT = 100)
    OR A.PRIORITY = 999
    OR A.DEPOSIT_TYPE = 'B')
   AND D.EFF_STATUS = 'A' )

 SELECT CASE WHEN RN = 1 THEN 'NEW ROW' WHEN RN = 2 THEN 'OLD ROW' END AS
 'ROW_TYPE' , *
 FROM CTE
 WHERE RN IN (1, 2)
 AND MAX_UPDATE_DATE >= GETDATE() - 8

Here is an example of output I am getting now:
ROW_TYPE    EMPLID     VENDOR_ID    FIRST_NAME    LAST_NAME    BANK_CD    ACCOUNT_NUM    ACCOUNT_TYPE    PRIORITY    LAST_UPDATE_DATE    EFFDT       MAX_UPDATE_DATE    RN
NEW ROW     12345      XYZ123       John          Smith        111111122  45678          C               999         03/12/2019          03/12/2019  03/12/2019         1
OLD ROW     12345      XYZ123       John          Smith        111111122  45678          C               999         10/25/2017          10/25/2017  10/25/2017         2
NEW ROW     47831      A86464       Samm          Bulle        754566654  98865          C               999         03/12/2019          06/08/2018  03/12/2019         1
OLD ROW     47831      A86464       Samm          Bulle        754566654  45678          C               999         10/25/2017          06/08/2018  10/25/2017         2
NEW ROW     32456      KG4561       Kilo          Renne        875123311  32146          C               300         09/02/2018          09/02/2018  09/02/2018         1
OLD ROW     32456      KG4561       Kilo          Renne        971215477  78131          C               310         12/21/2017          12/21/2017  12/21/2017         2

In the above example, I would NOT want to output the first two set of EMPLID rows (top 4 rows) as they have the same BANK_CD and ACCOUNT_NUM between the old and new row. The last set of rows I would want to keep in my output as you can see the BANK_CD and ACCOUNT_NUM are different (either could be though to be included).
I tried adding an self join for PS_DIR_DEP_DISTRIB and then adding in the WHERE clause where AND (A.BANK_CD <> E.BANK_CD OR A.ACCOUNT_NUM <> E.ACCOUNT_NUM) as follows:
   WITH CTE AS (
 SELECT A.EMPLID
 --, C.VENDOR_ID
 , B.FIRST_NAME
 , B.LAST_NAME
 , A.BANK_CD
 , A.ACCOUNT_NUM
 , A.ACCOUNT_TYPE
 , A.PRIORITY
 , A.LAST_UPDATE_DATE
 , A.EFFDT
 , MAX(A.LAST_UPDATE_DATE) OVER(PARTITION BY A.EMPLID) AS MAX_UPDATE_DATE
 , ROW_NUMBER() OVER(PARTITION BY A.EMPLID
  ORDER BY A.EFFDT DESC
  , D.EFFDT DESC) AS RN
  FROM PS_DIRECT_DEPOSIT D INNER JOIN PS_DIR_DEP_DISTRIB A ON A.EMPLID = D.EMPLID
   AND A.EFFDT = D.EFFDT INNER JOIN PS_EMPLOYEES B ON B.EMPLID = A.EMPLID INNER JOIN PS_GHS_DIR_DEP_VND C ON C.EMPLID = A.EMPLID
 ---ADDING SELF JOIN BELOW---
     INNER JOIN PS_DIR_DEP_DISTRIB E ON E.EMPLID = A.EMPLID AND E.EFFDT =
     A.EFFDT AND E.PRIORITY = A.PRIORITY
 WHERE B.EMPL_STATUS NOT IN ('T','R','D')
   AND ((A.DEPOSIT_TYPE = 'P'
   AND A.AMOUNT_PCT = 100)
    OR A.PRIORITY = 999
    OR A.DEPOSIT_TYPE = 'B')
   AND D.EFF_STATUS = 'A'
---ADDING NEW WHERE CONDITION BELOW---
   AND (E.ACCOUNT_NUM <> A.ACCOUNT_NUM OR E.BANK_CD <> A.BANK_CD ))
 SELECT CASE WHEN RN = 1 THEN 'NEW ROW' WHEN RN = 2 THEN 'OLD ROW' END AS 'ROW_TYPE'
 , *
  FROM CTE
  WHERE RN IN (1, 2)
  AND MAX_UPDATE_DATE >= GETDATE() - 8

When I make the above changes though, I do not get any data returned at all. What am I doing wrong?
3/20/19 Edit:
Following Tarek's suggested answer below, I seem to be missing some rows that I would expect to be in the final output. It appears that the new fields added BANK_CD_prev and ACCOUNT_NUM_prev are returning NULL values in the rows I am expecting them to be displayed, hence why the final query isnt retrieving them. How can this be dealt with?
ROW_TYPE    EMPLID    FIRST_NAME    LAST_NAME   BANK_CD       ACCOUNT_NUM     ACCOUNT_TYPE  PRIORITY    LAST_UPDATE_DATE       EFFDT        MAX_UPDATE_DATE  RN    BANK_CD_prev   ACCOUNT_NUM_prev
NEW ROW     56789     Test          User        874556411     54765           C             999         2019-02-28             2019-02-28   2019-02-28       1     NULL           NULL
OLD ROW     56789     Test          User        874556411     98451           C             999         2017-10-09             2017-10-09   2017-10-09       1     874556411      54765
NEW ROW     56789     Sampl         Test        756561623     46331           C             999         2018-03-12             2018-03-12   2018-03-12       1     NULL           NULL
OLD ROW     56789     Test          User        756561623     46331           C             999         2015-05-18             2015-05-18   2015-05-18       1     756561623      46331

Please note the above is running the query without the final conditions for ( AND BANK_CD <> BANK_CD_prev AND ACCOUNT_NUM <> ACCOUNT_NUM_prev just so I could see why I was missing some rows. You can see in this case the first EMPLID's two rows where the ACCOUNT_NUM is different and therefore I should be outputting both rows. The 2nd EMPLID (last two rows) is a little different in that the BANK_CD and ACCOUNT_NUM are the same for both rows, so I wouldn't expect this to be output (which it's not, so that is correct) but is still showing the NULL's as in the first set of rows.
3/20/19 Edit 2:  You can see that the BANK_CD_COUNT and ACCOUNT_NUM_COUNT have some strange numbers in them that I think is causing a problem.
ROW_TYPE    EMPLID  FIRST_NAME  LAST_NAME   BANK_CD     ACCOUNT_NUM  ACCOUNT_TYPE   PRIORITY    LAST_UPDATE_DATE    EFFDT        MAX_UPDATE_DATE    RN   BANK_CD_COUNT  ACCOUNT_NUM_COUNT
NEW ROW     812682  Test        User        031308302   8675309      C              999         2019-03-09          2019-03-09   2019-03-09          1   1101            1
OLD ROW     812682  Test        User        231379393   0001236408   C           999            2018-04-11          2018-03-03   2019-03-09          2   476            1

This link contains Create Table and Insert scripts for anyone who could help replicate this.
https://pastebin.com/cZLhMmet

A: One way to do it is to use LEAD and LAG functions. We'll need both here.
Here is your original query, which I formatted and commented out the filter by date.
WITH
CTE
AS
(
    SELECT
        A.EMPLID
        ,C.VENDOR_ID
        ,B.FIRST_NAME
        ,B.LAST_NAME
        ,A.BANK_CD
        ,A.ACCOUNT_NUM
        ,A.ACCOUNT_TYPE
        ,A.PRIORITY
        ,A.LAST_UPDATE_DATE
        ,A.EFFDT
        ,MAX(A.LAST_UPDATE_DATE) OVER (PARTITION BY A.EMPLID) AS MAX_UPDATE_DATE
        ,ROW_NUMBER() OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS RN
    FROM
        PS_DIRECT_DEPOSIT D
        INNER JOIN PS_DIR_DEP_DISTRIB A
            ON A.EMPLID = D.EMPLID
            AND A.EFFDT = D.EFFDT
        INNER JOIN PS_EMPLOYEES B ON B.EMPLID = A.EMPLID
        INNER JOIN PS_GHS_DIR_DEP_VND C ON C.EMPLID = A.EMPLID
        INNER JOIN PS_DIR_DEP_DISTRIB E
            ON E.EMPLID = A.EMPLID
            AND E.EFFDT = A.EFFDT
            AND E.PRIORITY = A.PRIORITY
    WHERE
        B.EMPL_STATUS NOT IN ('T','R','D')
        AND
        (
            (
                A.DEPOSIT_TYPE = 'P'
                AND A.AMOUNT_PCT = 100
            )
            OR A.PRIORITY = 999
            OR A.DEPOSIT_TYPE = 'B'
        )
        AND D.EFF_STATUS = 'A'
)
SELECT
    CASE
        WHEN RN = 1 THEN 'NEW ROW'
        WHEN RN = 2 THEN 'OLD ROW'
    END AS 'ROW_TYPE'
    ,*
FROM CTE
WHERE
    RN IN (1,2)
    --AND MAX_UPDATE_DATE >= GETDATE() - 8
;

This query returns the following result based on your sample data:
+----------+---------+-----------+------------+-----------+----------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+
| ROW_TYPE | EMPLID  | VENDOR_ID | FIRST_NAME | LAST_NAME | BANK_CD  | ACCOUNT_NUM | ACCOUNT_TYPE | PRIORITY |    LAST_UPDATE_DATE     |          EFFDT          |     MAX_UPDATE_DATE     | RN |
+----------+---------+-----------+------------+-----------+----------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+
| NEW ROW  |  097432 | 3471B     | H          | Adam      | 09146115 |    13404891 | C            |      999 | 2016-06-10 00:00:00.000 | 2016-06-10 00:00:00.000 | 2016-06-10 00:00:00.000 |  1 |
| OLD ROW  |  097432 | 3471B     | H          | Adam      | 09146115 |    13404891 | C            |      999 | 2016-06-10 00:00:00.000 | 2014-11-05 00:00:00.000 | 2016-06-10 00:00:00.000 |  2 |
| NEW ROW  |  100765 | 1272B     | V          | Milo      |  2358414 |      040925 | S            |      310 | 2014-03-05 00:00:00.000 | 2011-04-27 00:00:00.000 | 2014-03-05 00:00:00.000 |  1 |
| OLD ROW  |  100765 | 1272B     | V          | Milo      |  2358414 |      040925 | S            |      300 | 2014-03-05 00:00:00.000 | 2001-08-23 00:00:00.000 | 2014-03-05 00:00:00.000 |  2 |
| NEW ROW  | 1045632 | 3870A     | V          | Olo       |  2345794 |   179410860 | C            |      999 | 2018-08-16 00:00:00.000 | 2018-08-16 00:00:00.000 | 2018-08-16 00:00:00.000 |  1 |
| OLD ROW  | 1045632 | 3870A     | V          | Olo       |  2345794 |   179410860 | C            |      310 | 2011-02-25 00:00:00.000 | 2011-02-25 00:00:00.000 | 2018-08-16 00:00:00.000 |  2 |
| NEW ROW  |   21345 | 12345A    | J          | Smith     |  0224547 |    59167824 | C            |      999 | 2019-02-28 00:00:00.000 | 2019-02-28 00:00:00.000 | 2019-02-28 00:00:00.000 |  1 |
| OLD ROW  |   21345 | 12345A    | J          | Smith     |  0224547 |      591678 | C            |      999 | 2017-11-08 00:00:00.000 | 2017-10-17 00:00:00.000 | 2019-02-28 00:00:00.000 |  2 |
| NEW ROW  |   26110 | 1272B     | S          | Sams      |  8208302 |      822328 | C            |      999 | 2019-02-08 00:00:00.000 | 2019-02-08 00:00:00.000 | 2019-02-08 00:00:00.000 |  1 |
| OLD ROW  |   26110 | 1272B     | S          | Sams      |  8208302 |      822328 | C            |      315 | 2014-03-05 00:00:00.000 | 2012-07-30 00:00:00.000 | 2019-02-08 00:00:00.000 |  2 |
+----------+---------+-----------+------------+-----------+----------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+

I included it here, so you can see the difference with the below.
Here is the new query with added LEAD and LAG functions (we need both to get the previous and next rows) with extra filter in the WHERE clause.
LEAD and LAG return NULL when they reach the end of the window. For example, LAG (prev value) would return NULL for the first row of the window, since there is no "previous" row yet.
So, for the first row (rn=1) we need to compare its value with the "next".
For the second row (rn=2) we need to compare its value with the "prev".
Final query
WITH
CTE
AS
(
    SELECT
        A.EMPLID
        ,C.VENDOR_ID
        ,B.FIRST_NAME
        ,B.LAST_NAME
        ,A.BANK_CD
        ,A.ACCOUNT_NUM
        ,A.ACCOUNT_TYPE
        ,A.PRIORITY
        ,A.LAST_UPDATE_DATE
        ,A.EFFDT
        ,MAX(A.LAST_UPDATE_DATE) OVER (PARTITION BY A.EMPLID) AS MAX_UPDATE_DATE
        ,ROW_NUMBER() OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS RN

        ,LAG(A.BANK_CD) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS BANK_CD_prev
        ,LEAD(A.BANK_CD) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS BANK_CD_next
        ,LAG(A.ACCOUNT_NUM) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS ACCOUNT_NUM_prev
        ,LEAD(A.ACCOUNT_NUM) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC, D.EFFDT DESC) AS ACCOUNT_NUM_next
    FROM
        PS_DIRECT_DEPOSIT D
        INNER JOIN PS_DIR_DEP_DISTRIB A
            ON A.EMPLID = D.EMPLID
            AND A.EFFDT = D.EFFDT
        INNER JOIN PS_EMPLOYEES B ON B.EMPLID = A.EMPLID
        INNER JOIN PS_GHS_DIR_DEP_VND C ON C.EMPLID = A.EMPLID
        INNER JOIN PS_DIR_DEP_DISTRIB E
            ON E.EMPLID = A.EMPLID
            AND E.EFFDT = A.EFFDT
            AND E.PRIORITY = A.PRIORITY
    WHERE
        B.EMPL_STATUS NOT IN ('T','R','D')
        AND
        (
            (
                A.DEPOSIT_TYPE = 'P'
                AND A.AMOUNT_PCT = 100
            )
            OR A.PRIORITY = 999
            OR A.DEPOSIT_TYPE = 'B'
        )
        AND D.EFF_STATUS = 'A'
)
SELECT
    CASE
        WHEN RN = 1 THEN 'NEW ROW'
        WHEN RN = 2 THEN 'OLD ROW'
    END AS 'ROW_TYPE'
    ,*
FROM CTE
WHERE
    RN IN (1,2)
    AND
    (
        (
            rn = 1
            AND BANK_CD <> BANK_CD_next
        )
        OR
        (
            rn = 1
            AND ACCOUNT_NUM <> ACCOUNT_NUM_next
        )

        OR

        (
            rn = 2
            AND BANK_CD <> BANK_CD_prev
        )
        OR
        (
            rn = 2
            AND ACCOUNT_NUM <> ACCOUNT_NUM_prev
        )
    )
    --AND MAX_UPDATE_DATE >= GETDATE() - 8
;

Final result
+----------+--------+-----------+------------+-----------+---------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+--------------+--------------+------------------+------------------+
| ROW_TYPE | EMPLID | VENDOR_ID | FIRST_NAME | LAST_NAME | BANK_CD | ACCOUNT_NUM | ACCOUNT_TYPE | PRIORITY |    LAST_UPDATE_DATE     |          EFFDT          |     MAX_UPDATE_DATE     | RN | BANK_CD_prev | BANK_CD_next | ACCOUNT_NUM_prev | ACCOUNT_NUM_next |
+----------+--------+-----------+------------+-----------+---------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+--------------+--------------+------------------+------------------+
| NEW ROW  |  21345 | 12345A    | J          | Smith     | 0224547 |    59167824 | C            |      999 | 2019-02-28 00:00:00.000 | 2019-02-28 00:00:00.000 | 2019-02-28 00:00:00.000 |  1 | NULL         | 0224547      | NULL             | 591678           |
| OLD ROW  |  21345 | 12345A    | J          | Smith     | 0224547 |      591678 | C            |      999 | 2017-11-08 00:00:00.000 | 2017-10-17 00:00:00.000 | 2019-02-28 00:00:00.000 |  2 | 0224547      | NULL         | 59167824         | NULL             |
+----------+--------+-----------+------------+-----------+---------+-------------+--------------+----------+-------------------------+-------------------------+-------------------------+----+--------------+--------------+------------------+------------------+

A: I would just add the following analytics functions to your CTE to return the predecessor:
LAG(A.BANK_CD) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC) AS BANK_CD_prev,
LAG(A.ACCOUNT_NUM) OVER (PARTITION BY A.EMPLID ORDER BY A.EFFDT DESC) AS ACCOUNT_NUM_prev

Then you just need to reference that in your main query and you are done
FROM CTE
WHERE RN IN (1, 2)
AND MAX_UPDATE_DATE >= GETDATE() - 8
AND BANK_CD <> BANK_CD_prev
AND ACCOUNT_NUM <> ACCOUNT_NUM_prev

please reply, if that solved your problem. As you did not provide an example to test on it is hard to tell.
EDIT: I mean: use that solution with your initial approach without the self join at all. it will not help you on your problem.


text:
Q: How to retrieve dynamic value from Django settings.py in a Celery Task? My Django rely on Celery and Celerybeat to spawn tasks. I have 3 systemd services/units:

*

*myapp.service (gunicorn daemon)

*celery-myapp.service (celery worker(s))

*celerybeat-myapp.service (celerybeat daemon)

I have an environment variable MY_SECRET defined in my main "myapp.service" service (systemd unit).
I can't get this value from settings.py or directly environment variable in my tasks (tasks.py), but I can retrieve this value smoothly from my view (views.py) using settings.py or environment variable directly.
Do I need to replicate environment variable MY_SECRET defined in myapp.service to celery-myapp.service and celerybeat-myapp.service so that I could grab this value from my Celery tasks? How can I retrieve MY_SECRET value i, my Celery task?
myapp.service
[Unit]
Description=My App
After=network.target
Wants=celery-myapp.service
Wants=celerybeat-myapp.service

[Service]
User=myapp
Group=nginx
Environment=MY_SECRET=1234
WorkingDirectory=/opt/myproject/
ExecStart=/opt/myproject/env/bin/gunicorn --workers 3 --log-level debug --bind unix://opt/myproject/myapp.sock myaproject.wsgi:application

[Install]
WantedBy=multi-user.target

Environment variable is referenced in my Django project 'settings.py' along with other settings I intended to use within the application:
settings.py
# Populated with environment variable defined by systemd unit
MY_SECRET = os.environ.get('MY_SECRET')
# Static value
MY_URL= 'http://127.0.0.1'

From my view I can get value defined as environment variable MY_SECRET from settings.py and directly from environment:
views.py
def my_view(request):
    from django.conf import settings as project_settings

    my_secret_env = os.environ.get('MY_SECRET')
    my_secret_setting = project_settings.MY_SECRET
    my_url_setting = project_settings.MY_URL

   return render(request,'mypage.html',{
       'my_secret_env': my_secret_env,
       'my_secret_setting': my_secret_setting,
       'my_url_setting': my_url_setting,
   )

mypage.html
    {% block page_content %}

my_secret_env: {{ my_secret_env }}

my_secret_setting: {{ my_secret_setting }}

my_url_setting: {{ my_url_setting }}

    {% endblock %}

From my task I can't get value defined as environment variable MY_SECRET from settings.py nor directly from environment.
On the other hand, static value from settings.py is properly retrieved:
tasks.py
@shared_task
def task_mytask():
    from django.conf import settings as project_settings

    my_secret_env = os.environ.get('MY_SECRET')
    my_secret_setting = project_settings.MY_SECRET
    my_url_setting = project_settings.MY_URL

    # No value displayed
    print(my_secret_env)
    # No value displayed
    print(my_secret_setting)
    # Value displayed properly
    print(my_url_setting)

@periodic_task(run_every=timedelta(seconds=60))
def task_myperiodictask():
    task_mytask.delay()

A: Not sure what your goal is here, but you should never pass your secrets around willy nilly. However, if you want to, you may have to pass them as args from where you are calling the task. Like so:
task.py
@shared_task()
def task_mytask(my_secret_env, my_secret_setting):
    ...

views.py
task_mytask.apply_async(args=[my_secret_env, my_secret_setting])

Also, you could try setting an environment variable and try calling that.
export MY_SETTING = 1234


text:
Q: Reducing Rails Queries (N+1?) So in my past application, I was somewhat familiar with using .includes in Rails, but for some reason I'm having a bit of a difficult time in my current scenario.
Here's what I'm working with:
    # If non-existent, create. Otherwise, update.
    existing_data = Page.all
    updated_data = {}
    new_records = []
    @latest_page_data.each do |key, value|
      existing_record = existing_data.find_by(symbol: key)
      if existing_record != nil
        updated_data[existing_record.id] = value
      else
        new_records << Page.new(value)
      end
    end

    if !new_records.empty?
      Page.import new_reocrds
    end
    if !updated_data.empty?
      Page.update(updated_data.keys, updated_data.values)
    end
  end

The problem that I'm having is that the .find_by portion of the code results in a query every single iteration of @latest_page_data. I guess I would think that existing_data would hold all of the data it needs in memory, but obviously it doesn't work that way.
So next, I tried something like this:
# If non-existent, create. Otherwise, update.
existing_data = Page.includes(:id, :symbol)
updated_data = {}
new_records = []
@latest_currency_data.each do |key, value|
  existing_record = existing_data.find_by(symbol: key)

but then rails throws an error, stating:

ActiveRecord::AssociationNotFoundError (Association named 'id' was not
  found on Page; perhaps you misspelled it?):

so I can't use this example to find the id and symbol attributes.
I tried to take out :id in the Page.includes method, but I need to be able to get to the ID attribute in order to update the respective record later down in the code.
I've also saw some other posts pertaining to this topic, but I think the problem I may be running into is I'm not dealing with associations (and I believe that's what .includes is for? If this is the case, is there any other way that I can reduce all of the queries that I'm submitting here?

A: The includes method is used to preload associated models. I think what you are looking for is a select. Modifying your code to use select, do this :
existing_data = Page.select(:id, :symbol).load
updated_data = {}
new_records = []
@latest_currency_data.each do |key, value|
  existing_record = existing_data.find_by(symbol: key)
  if existing_record
    updated_data[existing_record.id] = value
  else
    new_records << Page.new(value)
  end
end

The drawbacks of using select over pluck is that since Rails constructs an object for you, so it is slower than a pluck. Benchmark: pluck vs select

A: Rather than trying to figure out a way to do it in Rails (since I'm not familiar with the 100% correct/accurate Rails way), I just decided to use .pluck and convert it into a hash to get the data that I'm looking for:
existing_data = Page.pluck(:id, :symbol)
existing_data = Hash[*existing_data.flatten]
updated_data = {}
new_records = []
@latest_currency_data.each do |key, value|
  if existing_data.values.include? key
    id = existing_data.find{|k,v| v.include? key}[0]
    updated_data[id] = value
  else
    new_records << Page.new(value)
  end
end

If anyone has a better way, it'd be gladly appreciated. Thanks!


text:
Q: How to pass Information in one page and Retrieve it in another? Hello I'm learning php but I'm hard stuck on what the next step should be.
I have a multidimensional array:
$fruits=array(
    array(
        "name"=>"The Banana",
        "color"=> "Yellow",
        "information"=>"bananas have lots of fiber."),
    array(
        "name"=>"The Strawberry",
        "color"=> "Red",
        "information"=>"strawberries have lots of vitamin."),
;

I'm able to show the array with my for each function
function show_fruits($fruits){
    foreach($fruits as $fruit)
        echo $fruit[name]."<br>".$fruit[color];
}

But now I want to pass the information into a new single page where it also shows the "information" key depending on the selection.
I was trying to use $_GET and embed the URL into my function but I was only getting "the" in the url result.
If anyone have better idea or how to proceed I would greatly appreciated!

A: You can store it in the $_SESSION global variable

A: you can use $_SESSION if you want to pass the array from a page to an other, and include if you want to pass the function


text:
Q: Jquery binding events Why does the handler bound to an event of an element fire the wrong result?  I would expect the click event of Div1 below to popup a dialog stating 'div1' but it popup's 'div2'.
I am new to this and I am scratching my head to work out why this is happening.  I would appreciate any help to explain.
Cheers,
Alex
<!DOCTYPE html>

<title>TestEvents</title>

div1; click here to show expected result: 'TabName: div1'

div2; click here to show expected result: 'TabName: div2'

A: it seems a classic closure problem, because when you click on div (any) i variable has already reach the end of for loop (so it always prints the last value). Try to change like so
function TestWhatIsGoingOn(myObjToTest) {
    for (i in myObjToTest) {
       (function(i) {
           $('#' + myObjToTest[i].TabName).click(function() { TestResult('TabName: ' + myObjToTest[i].TabName); });
       )(i);
    }
}

A: Your problem is in this section of code:
for (i in myObjToTest) {
    $('#' + myObjToTest[i].TabName).click(function() {
        TestResult('TabName: ' + myObjToTest[i].TabName);
    });
}

The trouble is that the value of i is not hard-coded into this section.  When the function runs, it will see what the current value of i is.  Since you have since incremented it to refer to your second tab, this function will always refer to the second tab.  This feature of Javascript is called a closure -- it closes in the value of i.
The easiest way around this is to use jQuery to bind to more than one object at once, and then evaluate based on the object clicked on:
$(document).ready(function(){
    $('div').click(function(){
        alert('TabName: ' + this.id);
    });
});

This will do everything you want your code in the question to do.
In a real-world situation, you would probably need to give the divs a common class (e.g. toClick) and then use a jQuery class selector ($('.toClick')).


text:
Q: Trigger Compare Old and New AccountOwner of a Contact I am having trouble comparing the old and new owner of the Account associated with the contact to achieve #6 of the requirement.
Can someone please suggest how I satisfy condition #6 in the logic.
I am trying to write a Trigger to achieve the following
// When a Contact is created or updated -
// Send an email to the Contact on behalf of the AccountOwner
// Create a follow up task for the AccountOWner
// Save the email and task as an Activity

// If contact inserted
// Check following conditions
  /*

  1. Account Id not null  - checked

  2. Contact Email not null - checked

  3. Account Shipping Address =='USA' - checked

  4. Account Status == Active  - checked

  5. Account Record Type == 'MarketingAccount' - checked

  6. AccountOwner != 'Guest' AND AccountOwner == ContactOwner AND AccountOwner = 'user in marketing profile'   - having trouble

  */

// If contact updated
  // listen to only this event (Account Owner changed from 'Guest' to 'user in Marketing profile')

  // Check following conditions

  1. Account Id not null  - checked

  2. Contact Email is not null - checked

  3. Account Shipping Address IS IN 'USA' - checked

   4. Account Status == Active  - checked

   5. Account Record Type == 'MarketingAccount' = checked

  6. Account owner ! = 'Guest' AND AccountOwner == ContactOwner AND AccountOwner = 'user in marketing profile' AND (PreviousAccountOwner != Current Account OWner) AND  (PreviousAccountOwner == 'Guest' AND  CurrentAccountOwner == 'User in Marketing Profile' )  // having trouble

   public with sharing class HelperContactTrigger{

      public static List<Contact> sendEmail(List<Contact>Contacts,Map<id,Contact> oldMapContact,Map<ID,Contact> newMapContact ) {

      Id recordTypeId =  Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Marketing_Account').getRecordTypeId();

     // Get Old and New Contact record
     Contact oldContact = Trigger.oldMapContact.get(Id);
     Contact newContact = Trigger.newMapContact.get(Id);

    // Get the email template
    EmailTemplate et = [Select Id from EmailTemplate where Name=:'Marketing: New Contact Email'];

    // Create instance of Messaging.SingleEmailMessage
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

    // Prepare a list of all contacts that should receive an email based on conditions for insert and update

    // Contact is Updated

    for (Contact con: Contacts){

        Contact oldContact = oldMapContact.get(con.Id);
        Contact newContact = newMapContact.get(con.Id);

        if(con.AccountId != null && con.Email != null && con.Account.Dealer_Status__c == 'Active' && con.Account.ShippingCountry =='USA' && con.Account.RecordTypeId == recordTypeId && (con.Account.Owner.Name != 'Guest' && con.Owner.Name==con.Account.Owner.Name ) ) {

            //initialize messaging method
            Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

            //set object Id
            singleMail.setTargetObjectId(con.Id);

            //set template Id
            singleMail.setTemplateId(et.Id);

            //flag to trueto insert activity history
            // Check if this is default, if yes -- remove this line

            singleMail.setSaveAsActivity(true);

            //add mail
            emails.add(singleMail);
        }
    }

    //send mail
    Messaging.sendEmail(emails);

    return Contacts;

 }

}

 ***************************

trigger ContactTrigger on Contact (after insert, after update) {

 if (Trigger.isAfter) {
    if (Trigger.isInsert || Trigger.IsUpdate ) {
        HelperContactTrigger.sendEmail(Trigger.New,Trigger.oldMap,Trigger.newMap);
    }
 }

}

A: I think your problem is that in your Contact Trigger, the Trigger.New list only contains Contact field info. You cannot access parent object fields directly, you need to query them first.
i.e, in your code, con.Account.Owner.Name will return null. You need to query the Account.Owner.Name so that it returns the actual value stored there.
To Access the values of the Parent Account field for the contacts in Trigger.New, you will need to perform an SOQL query. I would store the returned records in a Map or a List and then use this to check against your criteria in #6
See these resources:
https://developer.salesforce.com/forums/?id=906F00000008sxRIAQ
Need clarification on Trigger.new
Access parent object field in apex trigger


text:
Q: How do I hide specific user profile fields? I am using a membership plugin which pulls default WordPress user profiles to a directory. I want to hide these fields from my registered site users. I have searched for plugins and found nothing that lets me "pick and choose". I also read this answer but it doesn't address my needs.
In a perfect world (and in my wishful thinking) I would like to be able to know if there are a "list" of user profile fields and some code I could use to hide them. An example of this idea of a "list" of fields is in this forum post on wordpress.org.


text:
Q: Internal Server Error after adding multiple cron jobs I was adding multiple cron jobs from my cpanel. After about 10 minutes I got an email
execl: couldn't exec `/bin/sh'
execl: Resource temporarily unavailable

And after that I am continously getting this error:
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@********.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
Apache Server at www.******.com Port 80

I have already removed all the cron jobs. But still I am getting the error. Please help. Thanx in advance!


text:
Q: Hide div after second animation CSS I have a little problem in my code. I'm trying to make my text disappear after the second animation, which is the first animation in "div.textoe" (input text on the page) and the second animation is in the "div.textoee". What I want to do is clear the text of the page after the second animation, but it does not happen in my code, what am I doing wrong?
$(".textoe").on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function(){
    $('.textoe').addClass('textoee');
    $('.textoee').removeClass('textoe');
});
$(".textoee").on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function(){
    alert('Hide text');
});

http://jsfiddle.net/w55dN/1/

A: You need to use event delegation since the class you want to target in the binding is added dynamically:
$(document).on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', '.textoee' ,function(){
    alert('Hide text');
});


text:
Q: Media queries css not overiding the properties of different pixel ratio, once it applies , once it wont? enter image description hereI am applying css properties at different width pixels . Parent properties overriding the child width properties . Ex max-width 425px , max-width 375px. Once it applies , and works fine but later it doesn't work. In developer tool i find the strike to the css properties.

A: The most common error is not paying attention to your styles cascading arrangement.
Meaning, the base requirement for this to work is You to have the following hierarchy:
/* base CSS styles */
html {
    font-size: 10px; // Generic style
}

@media (max-width: 425px) {
    /* css for 425px and below */
}

@media (max-width: 375px) {
    /* css for 375px and below */
}

No matter if you are working in a single file, or using imports of some kind, your main styles always come first then your media queries must be stacking down from the highest width to the lowest.


text:
Q: Versioning when binary AND text files are involved? I have a project where I need to maintain changes to both the text and binary files.  I have a couple of options:

*

*Use patches

*Use a versioning system like git or hg.

For my purposes, patches are a better option if it was only text files.  However, since there are images that might be replaced/added/deleted, which is the best way to go?
Is there a clean diff/patch utility that can take care of binary differences as well (without me having to specify it is binary -- I should be able to diff the entire directory and not individual files, which I can't with bash's diff in binary mode) and use them as patches?  If not, which versioning system is a cleaner option when it comes to binary files?

A: Both Git and Mercurial can easily handle both text and binary files. Use whichever you prefer. And yes, a VCS is the right choice.

A: Mercurial has the notion of patch queue (with the mq extension enabled), largely inspired by quilt.
This allows you to manage your patches in several ways:

*

*Use a single patch queue and have all your patch order sequentially in it

*Use several patch queues, with the qqueue command, and have patches grouped by whatever criteria fits you.

As a bonus, as patches queues are really patch files, you can easily change their order and even move/copy them from one queue to another (have a look in your .hg directory to find the patch queues).
You can find a lot more of usefull information about managing patch queues at Steve Losh's tutorial on mercurial queue.

A: If you don't like a VCS as such, try using a ftp server containing patches. Version numbers can be used as directory names. This system can be backed with a script, which applies patches sequentially based on directory names.
In the project I'm working on, database patches are applied in this manner. However, they are maintained inside a VCS. A file can be used to maintain the current version, which will be read by the script to decide which patch to apply.


text:
Q: Why is my mock call giving me an "Cannot read property 'then' of undefined" I'm pretty sure this has something to do with the call being async but that's about as far as my brain can get.
The calling function is:
const { messageNodeResponse } = require('../../../app/lib/message-node-response');

jest.mock('../../../app/lib/am-api.js');

describe('message node response', () => {
  it('should check for message node prompt.', async () => {
    const req = {
      session:
      {
        payload: {
          callbacks: [{
            type: 'NameCallback',
            output: [{ name: 'prompt', value: 'resendExpiredOTP' }],
            input: [{ name: 'IDToken1', value: '' }],
          },
          {
            type: 'NameCallback',
            output: [{ name: 'prompt', value: 0 }],
            input: [{ name: 'IDToken2', value: '' }],
          }],
        },
      },
    };
    const res = await messageNodeResponse(req, 'registration');
    expect(res.statusCode).toEqual(200);
  });
});

The function being tested (in message-node-response.js):
const messageNodeResponse = (req, api) => {
  const requestBody = req.session.payload;
  requestBody.callbacks[1].input[0].value = 0;
  const apiCall = assignApi(api);
  return apiCall(req, requestBody)
    .then((result) => {
      logger.debug(result.data);
      req.session.payload = result.data;
    }).catch((err) => {
      throw err;
    });
};

module.exports = { messageNodeResponse };

Running the unit test gives me the following error: "TypeError: Cannot read property 'then' of undefined" referring to the line "return apiCall(req, requestBody)".
As requested, am-api.js:
const axios = require('axios');
const { v1: uuid } = require('uuid');

const post = async (url, data, req) => axios.post(
  url,
  data,
  {
    headers: {
      'Content-Type': 'application/json',
      'Accept-API-Version': 'protocol=1.0,resource=2.1',
      language: req.cookies.lng ? req.cookies.lng : 'en',
      ...(req.session.clientId) && { 'client-id': req.session.clientId },
      ...(req.session.id) && { 'session-id': req.session.id },
      ...((req.headers['correlation-id']) && { 'correlation-id': req.headers['correlation-id'] }) || { 'correlation-id': uuid() },
      ...(req.headers['user-agent']) && { 'User-Agent': req.headers['user-agent'] },
      ...(req.headers['x-forwarded-for']) && { 'X-Forwarded-For': req.headers['x-forwarded-for'] },
    },
  },
);

const registrationApi = async (req, data) => {
  const url = `${process.env.AM_API_URL}${process.env.AM_REALM_PATH}/authenticate?service=${process.env.AM_REGISTRATION_TREE_NAME}&authIndexType=service&authIndexValue=${process.env.AM_REGISTRATION_TREE_NAME}`;
  return post(url, data, req);
};

const authenticationApi = async (req, data) => {
  const url = `${process.env.AM_API_URL}${process.env.AM_REALM_PATH}/authenticate?service=${process.env.AM_AUTHENTICATION_TREE_NAME}&authIndexType=service&authIndexValue=${process.env.AM_AUTHENTICATION_TREE_NAME}`;
  return post(url, data, req);
};

const passwordResetApi = async (req, data) => {
  const url = `${process.env.AM_API_URL}${process.env.AM_REALM_PATH}/authenticate?service=${process.env.AM_PASSWORD_RESET_TREE_NAME}&authIndexType=service&authIndexValue=${process.env.AM_PASSWORD_RESET_TREE_NAME}`;
  return post(url, data, req);
};

const accountRecoveryApi = async (req, data) => {
  const url = `${process.env.AM_API_URL}${process.env.AM_REALM_PATH}/authenticate?service=${process.env.AM_ACCOUNT_RECOVERY_TREE_NAME}&authIndexType=service&authIndexValue=${process.env.AM_ACCOUNT_RECOVERY_TREE_NAME}`;
  return post(url, data, req);
};

module.exports = {
  registrationApi,
  authenticationApi,
  passwordResetApi,
  accountRecoveryApi,
};

A: the current jest implementation (v27.5) does only use the synchronous function  definitions when auto-mocking.
furthermore, the default returning value is undefined for the mocked functions.
to define your mocks correctly it's possible to use the second jest.mock() function argument which is the module factory.
jest.mock('../../../app/lib/am-api.js', () => ({
  registrationApi: () => Promise.resolve({ data: 42 }),
  authenticationApi: () => Promise.resolve({ data: 42 }),
  passwordResetApi: () => Promise.resolve({ data: 42 }),
  accountRecoveryApi: () => Promise.resolve({ data: 42 })
}));

the other option for you is to use the mockAxios module without mockinп your api file itself.


text:
Q: Updating Tk label using Thread use Thread;
use warnings;
use Tk;

my $x = 10;
my $mw = new MainWindow;
$mw->Label(-text => 'honeywell')->place(-x => $x, -y => 50);
my $thr = new Thread \&sub1;

sub sub1 {
  for ($i = 0 ; $i < 20 ; $i++) {
      $x += 20;
      sleep(2);
      $mw->update;
    }
}

MainLoop;

I am trying to update the label so that the text appears going down.I want to implement it using thread.But the text os not sliding down.Can anyone plz help me?

A: Try this code:
use strict;
use warnings;

use Tk;

my $x = 10;

my $mw = new MainWindow;
my $label = $mw->Label(-text => 'honeywell')->place(-x => $x, -y => 50);

$mw->repeat(2000, \&sub1);

sub sub1 {
    return if $x >= 400;
    $x += 20;
    $label->place(-x => $x, -y => 50);
    $mw->update;
}

MainLoop;

A: I don't think that this will ever work (using Thread or threads).
place uses the content of $x and does not bind the variable $x. So changing the variable after the initial placement won't do anything to the label.


text:
Q: Name Problems when running linear model and waldtest in function environment I have a problem trying to encapsulate a linear model and waldtest in a function. When you run the wald test it can no longer tell where the data is. This happens both when the lm and waldtest are in the same function and when the lm is in a function and waldtest is in the global (or a different function) environment.
Minimal working example
# Loading Packages
library(lmtest)
# Loading Data
x <- sin(1:100)
y <- 1 + x + rnorm(100)
dd = data.frame(x = x, y = y)
form = "y ~ x"

When I do the regression and waldtest outside a function there is no problem:
# Doing Regression outside function
Model1 = lm(formula = form, data = dd)
waldtest(Model1)

When I do the regression and waldtest inside a function there are errors:
# Doing Regression inside function
reg = function(form, FrameOfData){
  Model = lm(formula = form, data = FrameOfData)
  print(waldtest(Model))
}
reg(form, FrameOfData = dd)
# Error in is.data.frame(data) : object 'FrameOfData' not found

Changing the above waldtest command to print(waldtest(Model2, data = dd)) is also unsuccessful returning # Error in modelUpdate(objects[[i - 1]], objects[[i]]) : original model was of class "lm", updated model is of class "data.frame"
The one workaround I can find is to choose a global dataframe name to match the function name (in the above case run FrameOfData = dd before running reg function) but I don't want to do this for the application I have in mind.
Other questions on Stack Overflow
The most similar question I can find is this one:
Regression with Heteroskedasticity Corrected Standard Errors
where this problem does not arise as the linear regression is run in the global environment.
Desired Solution
Is there anyway to run the lm command and then change the object's attributes to point to the global dataframe's true name? Otherwise is there a way to tell the waldtest command the global dataframe's true name?

A: 1) do.call In function reg replace the line that defines Model with:
Model <- do.call("lm", list(formula = form, data = FrameOfData))

1a) A variation:
Model <- do.call("lm", list(formula = form, data = substitute(FrameOfData)))

2) with Alternately, this would work:
Model <- with(FrameOfData, lm(formula = form))

3) eval Yet another possibility is this:
Model <- eval(substitute(lm(formula = form, data = FrameOfData)))

although using eval tends to be frowned upon.
3a) Here is a variation:
reg <- function(form, FrameOfData) {
  eval(substitute(waldtest(lm(formula = form, FrameOfData)),
         list(form = form, FrameOfData = FrameOfData)))
}

Note: There are potential problems with most of the above.  The following based on (1) should work and (3a) works in this case too but the corresponding code for all the others will fail:
set.seed(123)

rm(x, y, dd, form)

fn <- function() {
    x <- sin(1:100)
    y <- 1 + x + rnorm(100)
    dd = data.frame(x = x, y = y)
    form = "y ~ x"
    reg(form, FrameOfData = dd)
}

reg <- function(form, FrameOfData){
  Model <- do.call("lm", list(formula = form, data = FrameOfData))
  waldtest(Model)
}
fn()


text:
Q: Setting a WPFDataGrid columnheader to a TextBlock I have a DataGrid with AutoGenerateColumns=True.
I want to set the ColumnHeaders to a TextBlock so the heading text can wrap.
I have:
Private Sub OnAutoGeneratingColumn(sender As System.Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs)
....
    Dim tb As New TextBlock
    tb.TextWrapping = TextWrapping.Wrap
    tb.Text = SomeText
    e.Column.Header = tb
End Sub

In other code, I can see that the ColumnHeader is actualy a TextBlock, and doing
Dim sHeader as String = DirectCast(dgtc.Header, TextBlock).Text

returns SomeText back.
But, the Grid Does not display any text in the header!  If on the other hand I set
e.Column.Header = SomeText

The headings show OK.
What am I missing?
I know there are some answers for this on the site but I could not find any for AutoGenerateColumns = True.


text:
Q: Jasper reports Server and GWT integration I ve installed Jasper Reports Server and i want to develop a GWT application to call the jasper server web services as : Login , Running a report in the server, listing reports, View User .... I 've implemented web services in java through the Jasper Soft web services guide for example for authentitcation :
public static void connect(String URL,HttpClient httpclient)
{
    serverURL = URL;
    //report path

                    HttpClient client = httpclient;

                    // Setting Login URL in a POST method
                    String loginURL = serverURL+"rest/login";

                    PostMethod postMethod = new PostMethod(loginURL);

                    // Set authentication parameters
                    postMethod.addParameter("j_username", "jasperadmin");
                    postMethod.addParameter("j_password", "jasperadmin");
                    int statusCodeL;
                    try {
                        statusCodeL=client.executeMethod(postMethod);

                        if (statusCodeL != HttpStatus.SC_OK) {
                            System.out.println("Login failed: " + postMethod.getStatusLine());
                            return;
                        }
                    }catch (HttpException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

But i can t explore those web services when developing with GWT framework Which is no compatible with HTTPClient, even when using the Request Builder the authentication failed.
My question is HOW TO INTEGRATE JASPER REPORTS SERVER INTO GWT APPLICATION ?

A: I also had to implement the Jasper Report integration at my company. And yes, I also had difficulties. We ended up only using the Jasper Report Library to generate our report and we did the rest ourselves (listing reports, storing generated reports, etc...).

A: It is possible to use GWT. In the HttpServlet, have that call the Jasper APIs. Then the HttpServlet can return the results of the Jasper call to GWT. I put a comment that links to where the answer is.


text:
Q: Switch two values without temp storage I write this code to switch two values without temp storage and it works well, but when I try to use the same style to do other things, it doesn't work as I expected.
                `
 #include <iostream>
 using namespace std;

 int main(){
   int i=100,j=200;
   //expect swich i and j
   i=j+i-(j=i);
   cout<<i<<"   "<<j<<endl;

   //expect j=100 and i=300
   i=j+(j=i);
   cout<<i<<"   "<<j<<endl;
 }

result is:
200    100
400    200

so why doesn't the second (j=i) work?
can we just have a discussion about this situation? no one will maintain such code, including me.

A: This is undefined behaviour (UB). The operands to + can be evaluated in any order. The intent of your code relies on one particular order being chosen but your compiler is choosing the other evaluation order. Unlucky for you.
This experience should be enough to persuade you to avoid writing code like this. As soon as you start causing side effects in expressions you must be careful to avoid UB. Don't be afraid of using a local temp variable when swapping. And be even less afraid of using the swap routine built into the standard library.
One final point. The fact that you don't declare a variable does not mean that the generated code will not make use of a variable. It may be in a register, but so what, where do you think a compiler is going to put your temp int in a swap function?

A: You could use the XOR swap :
i ^= j; j ^= i; i ^= j;
It's false economy on today's processors however.

A: As you give it your "method" has undefined behavior.

Between the previous and next sequence point an object shall have its
  stored value modified at most once by the evaluation of an
  expression. Furthermore, the prior value  shall be read only to
  determine the value to be stored.

Practically speaken, you don't have any guarantee that the evaluation of y gives you the old value or the new value. A compiler could chose any of those.
Theoretically undefined behavior means that your code might eat your harddrive or spend all your money.
All this for a doubtful optimization that makes your code unreadable. Don't do cruft like that.

A: Probably, your assumption about order of evaluation is wrong.
i=j+(j=i);

IIRC, it is not specified (for C++ I'm confident about this, see C++ standard §1.9 (15)).
If (j=i) is evaluated before j (after the equals sign) is evaluated, the result will be different than if you do it vice versa.
In short, please use std::swap() if you're using C++. This will clearly state your intent (and will allow implementers of the standard library to use optimizations).

A: try something like this :
a = a+b;
b = a-b;
a = a-b;

A: With arithmetic operations you can get overflow.
There is bits swap algorithm also:
a = a^b
b = a^b
a = a^b


text:
Q: How to write rows asynchronously in Spark Streaming application to speed up batch execution? I have a spark job where I need to write the output of the SQL query every micro-batch. Write is a expensive operation perf wise and is causing the batch execution time to exceed the batch interval.
I am looking for ways to improve the performance of write.

*

*Is doing the write action in a separate thread asynchronously like shown below a good option?

*Would this cause any side effects because Spark itself executes in a distributed manner?

*Are there other/better ways of speeding up the write?
// Create a fixed thread pool to execute asynchronous tasks
val executorService = Executors.newFixedThreadPool(2)
dstream.foreachRDD { rdd =>
  import org.apache.spark.sql._
  val spark = SparkSession.builder.config(rdd.sparkContext.getConf).getOrCreate
  import spark.implicits._
  import spark.sql

  val records = rdd.toDF("record")
  records.createOrReplaceTempView("records")
  val result = spark.sql("select * from records")

  // Submit a asynchronous task to write
  executorService.submit {
    new Runnable {
      override def run(): Unit = {
        result.write.parquet(output)
      }
    }
  }
}

A: 1 - Is doing the write action in a separate thread asynchronously like shown below a good option?
No. The key to understand the issue here is to ask 'who is doing the write'. The write is done by the resources allocated for your job on the executors in a cluster. Placing the write command on an async threadpool is like adding a new office manager to an office with a fixed staff. Will  two managers be able to do more work than one alone given that they have to share the same staff? Well, one reasonable answer is "only if the first manager was not giving them enough work, so there's some free capacity".
Going back to our cluster, we are dealing with a write operation that is heavy on IO. Parallelizing write jobs will lead to contention for IO resources, making each independent job longer. Initially, our job might look better than the 'single manager version', but trouble will eventually hit us.
I've made a chart that attempts to illustrate how that works. Note that the parallel jobs will take longer proportionally to the amount of time that they are concurrent in the timeline.

Once we reach that point where jobs start getting delayed, we have an unstable job that will eventually fail.
2- Would this cause any side effects because Spark itself executes in a distributed manner?
Some effects I can think of:

*

*Probably higher cluster load and IO contention.

*Jobs are queuing on the Threadpool queue instead of on the Spark Streaming Queue. We loose the ability to monitor our job through the Spark UI and monitoring API, as the delays are 'hidden' and all is fine from the Spark Streaming point of view.

3- Are there other/better ways of speeding up the write?
(ordered from cheap to expensive)

*

*If you are appending to a parquet file, create a new file often. Appending gets expensive with time.

*Increase your batch interval or use Window operations to write larger chunks of Parquet. Parquet likes large files

*Tune the partition and distribution of your data => make sure that Spark can do the write in parallel

*Increase cluster resources, add more nodes if necessary

*Use faster storage

A:
Is doing the write action in a separate thread asynchronously like shown below a good option?

Yes. It's certainly something to consider when optimizing expensive queries and saving their results to external data stores.

Would this cause any side effects because Spark itself executes in a distributed manner?

Don't think so. SparkContext is thread-safe and promotes this kind of query execution.

Are there other/better ways of speeding up the write?

YES! That's the key to understand when to use the other (above) options. By default, Spark applications run in FIFO scheduling mode.
Quoting Scheduling Within an Application:

By default, Spark's scheduler runs jobs in FIFO fashion. Each job is divided into "stages" (e.g. map and reduce phases), and the first job gets priority on all available resources while its stages have tasks to launch, then the second job gets priority, etc. If the jobs at the head of the queue don't need to use the whole cluster, later jobs can start to run right away, but if the jobs at the head of the queue are large, then later jobs may be delayed significantly.
Starting in Spark 0.8, it is also possible to configure fair sharing between jobs. Under fair sharing, Spark assigns tasks between jobs in a "round robin" fashion, so that all jobs get a roughly equal share of cluster resources. This means that short jobs submitted while a long job is running can start receiving resources right away and still get good response times, without waiting for the long job to finish. This mode is best for multi-user settings.

That means that to make a room for executing multiple writes asynchronously and in parallel you should configure your Spark application to use FAIR scheduling mode (using spark.scheduler.mode property).
You will have to configure so-called Fair Scheduler Pools to "partition" executor resources (CPU and memory) into pools that you can assign to jobs using spark.scheduler.pool property.
Quoting Fair Scheduler Pools:

Without any intervention, newly submitted jobs go into a default pool, but jobs' pools can be set by adding the spark.scheduler.pool "local property" to the SparkContext in the thread that's submitting them.


text:
Q: Get Cell value from selected row gridview I have a GridView that has 7 columns. 6 of the columns have LinkButtons.
What I want to do is,  get the data value that is in the 1st column and put that in a Label elsewhere on  my page when one of those LinkButons is clicked.
For example the first column has a value that looks like this: 01:00 - 02:00.
Here is what I have so far: My GridView is named gvappts
I have added this property:OnRowDataBound="gvappts_DataBound"
And inside gvappts on one of my LinkButtons I have added Command and Command Arguments:<asp:LinkButton id="lbd1" runat="server" Text='<%#(Eval("Day1"))%>' CommandName="GetData" CommandArgument='<%# Container.DataItemIndex %>'/>
Because I want to Select the current row.
In my .cs I have this:
protected void gvappts_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
    {
        if (e.CommandName == "GetData")
        {
            //Get rowindex
            int rowindex = Convert.ToInt32(e.CommandArgument);
            //Get Row
            GridViewRow gvr = gvappts.Rows[rowindex];
            //Set the label value
            lblTimeSelected.Text = gvr.Cells[0].Text;
        }
    }

I do not get any errors when clicking the buttons, but no value is returned. What am I overlooking?

A: Try this.
 GridViewRow gvr = gvappts.Rows[rowindex];
 Label myLabel  = gvr.FindControl("MyLabel Id") as Label ;
 lblTimeSelected.Text = myLabel.Text;


text:
Q: How to Skip a Test if an element is not present in Cypress I am writing a test in which if I land on a page and if any records are available, I need to click on three dots buttons near the record. But I should skip the test if no records are available on the page.
cy.get('body')
    .then(($body) => {

        if ($body.find('.ant-empty-description').length) {

            cy.log('Element not found. Skip the Test')

        }
        else {
            cy.xpath("//tbody[@class='ant-table-tbody']//tr[" + rowNumber + "]//td[4]//button//em").click()
        }
    })

I am using an approach in which if 'No Record found' message is present, I need to skip the test else click on the button present near the record.

A: Sometimes it's necessary to test conditionally, but using <body> as a base element is a mistake IMO.
<body> is always on the page, but the table data may not be if fetched from an API.
The test will always run faster than the API, always see the empty row placeholder.
Pattern to use
Add an intercept() and wait for the API to respond.
Use the table rows as base element for conditional check - there will always be at least one row (but it may be the "No records" row).
cy.intercept(...).as('tableData')

...

cy.wait('@tableData')

cy.get('tbody tr').then($rows => {   // may be only one "No record" row

  const noData = $rows.text().includes('No Record found')

  if (!noData) {
    $rows.eq(rowNumber).find('td').eq(4]).find('button').click()
  }
})

A: You can use mocha's .skip() functionality. Please note that you'll have to use function() instead of arrow functions.
it('test', function() {
  cy.get('body')
    .then(function($body) {
      if ($body.find('.ant-empty-description').length) {
        cy.log('Element not found. Skip the Test')
        this.skip()
      } else {
        cy.xpath("//tbody[@class='ant-table-tbody']//tr[" + rowNumber + "]//td[4]//button//em").click()
      }
    })
})

That being said, I agree with @jjhelguero -- using skips in this way is an anti-pattern for testing. Ideally, you should control whether or not an element will appear on the webpage, and use your test setup to manipulate the page into having/not having the element.


text:
Q: Does a Visual Studio debug build contain any personal information? I'm wondering about privacy and personal information that's contained in the debug files created by Visual Studio.
I have a project that I have compiled for both debug and release, and I have to zip basically the whole directory tree that contains the solution, the source, the pdbs, etc. and make it available.
I'm wondering what type of information will be released by doing this, other than source and binaries obviously.
Thanks!

A: Done correctly you will not release any personal information by doing this.
Things to watch out for:

*

*Sensitive information in paths. If you keep your source files in My Documents folder, your Windows user name will be leaked in .pdb files, as it embeds full source file paths. I recommend copying solution to directory c:\dev\project (or similar) and rebuilding there.

*Don't publish .suo, .user files, as these may contain sensitive information, and are generated by studio automatically for each user

*Look out for sensitive information that may be in app.config files
One more suggestion: don't publish any intermediate files (usually in obj directory). These will not help recipients in any way, but may contain personal information.


text:
Q: Trouble using readline() user input with survfit function I tried looking at past answers, but couldn't find an exact answer. I'm relatively new to R so bear with me.
I'm doing quite a few functions where user input is neccesary. I've gathered that the best way to enter user text is by readlines()
Now the function that i'm mostly concerned with is survfit.
Reproducible example 1
library (survival)
Survival <- sample (0:100, 100, rep=TRUE)
STATUS <- sample (0:1, 100, rep=TRUE)
variable <- sample (0:1, 100, rep=TRUE)
data <- data.frame(Survival, STATUS, variable )

Graphdata <- survfit(Surv(Survival, STATUS) ~ variable, data=data)
plot <- plot(Graphdata)

What I want to do
In the survfit function I want to replace the variable with readline() and make the "variable" user inputted.
For example:
Graphdata <- survfit(Surv(Survival, STATUS) ~ readlines(), data=data)

However, it seems that putting a placeholder won't work because the function is calling data directly from "data" and ignoring the placeholder completely.
I suspect there is a really basic work around.
Cheers

A: This should work.
varA <- sample (0:1, 100, rep=TRUE)
varB <- sample (0:1, 100, rep=TRUE)
varC <- sample (0:1, 100, rep=TRUE)
data <- data.frame(Survival, STATUS, varA, varB, varC)

chosenvar <- readline("\nWhat independent variable do you want to fit?\n")

if(!(chosenvar %in% names(data))) stop(paste("Predictor must be one of", paste(names(data), collapse=", ")))
Graphdata <- survfit(formula(paste("Surv(Survival, STATUS) ~", chosenvar)), data=data)
plot <- plot(Graphdata)


text:
Q: Набор битов данных о цвете с экрана монитора в массив c# есть код для создания скриншота экрана.
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width , Screen.PrimaryScreen.Bounds.Height );
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
printscreen.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

В частности меня интересует момент с классом Graphics и методом CopyFromScreen
В документации говориться, что:
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

Метод CopyFromScreen - Выполняет перемещение набора битов данных о цвете с экрана на поверхность рисования объекта Graphics.
Вопрос следующий. Каким образом можно получить этот набор битов сразу в виде массива и не производить лишние манипуляции с графикой?
Спасибо.


text:
Q: PayPal Advanced hosted checkout not honoring NOSHIPPING option I have a site that is using PayPal Advanced with Layout C, where it uses an iframe to present payment options for either paying with PayPal, or entering a credit card number and paying. When clicking the Checkout with PayPal button, it goes to a payment page on PayPal. It seems that PayPal must be doing some testing of a new checkout process, because I am randomly receiving one of two different screens (shown below).
Up until recently, I've been seeing and testing with Checkout Page A. I have been sending my transactions without a shipping address, using the NOSHIPPING parameter to tell PayPal that's okay. All was good. Now, with Checkout Page B, it gives me an error when I don't send the shipping address:
Field format error: 10727-The field Shipping Address1 is required

If I go ahead and send an address, then all works fine. Anybody know why this new page is not honoring the NOSHIPPING parameter? As I said, it's exactly the same transaction details/process for both pages -- it's PayPal who is deciding which process to show me as a user on a random basis.
Checkout page A:

Checkout page B:

Details of Secure Token request:
USER[7]=xxxxxxx&VENDOR[8]=xxxxxxxx&PARTNER[6]=PayPal&PWD[15]=xxxxxxxxxxxxxxx&CREATESECURETOKEN[1]=Y&SECURETOKENID[32]=62afb751dead4d2abf191c5226dd8f21&TRXTYPE[1]=S&NOSHIPPING[1]=1&ALLOWNOTE[1]=0&INVNUM[17]=ST-BATCH-23-C8903&USER1[4]=xxxx&USER6[2]=xx&USER5[4]=xxxx&AMT[5]=30.52&BILLTOFIRSTNAME[4]=John&BILLTOLASTNAME[8]=Doexxxxx&ERRORURL[46]=**myurl**&RETURNURL[46]=**myurl**&CANCELURL[46]=**myurl**&SILENTPOSTURL[50]=**myurl**&URLMETHOD[4]=POST&

Details of response to my RETURNURL after logging into PayPal with my paypal account to make a payment:
AVSZIP=N&TYPE=S&BILLTOEMAIL=**myemail**&BILLTOLASTNAME=Doe&BILLTONAME=John&LASTNAME=Doe&PNREF=EUYPC2C6821D&TENDER=P&EMAIL=**myemail**&METHOD=P&BILLTOFIRSTNAME=John&AMT=30.52&TRANSTIME=2014-08-28+12%3a51%3a33&INVOICE=ST-BATCH-23-C8903&NAMETOSHIP=JOh+Doe&USER5=xxxx&BILLTOCOUNTRY=US&RESPMSG=Field+format+error%3a+10727-The+field+Shipping+Address1+is+required&COUNTRY=US&TAX=0.00&FIRSTNAME=John&AVSDATA=NNN&USER6=xxxx&SECURETOKEN=QpJEHzD0O1EGZJLoy3PAHxAEU&SECURETOKENID=62afb751dead4d2abf191c5226dd8f21&INVNUM=ST-BATCH-23-C8903&AVSADDR=N&NAME=John+Doe&USER1=xxxx&HOSTCODE=10727&RESULT=7&TRXTYPE=S

A: I understand you are having issues with the NOSHIPPING parameter when being directed through our new checkout flow. I am having issues recreating the error 10727 in my own testing. Would you please provide the API request you are using in your Secure Token call (minus any personal information)? Also, please provide a sample of one of the responses containing the 10727 error message? If you would feel more comfortable, you can file a ticket at paypal.com/MTS and we can communicate directly.
^EW
Update
PayPal has resolved this issue and the NOSHIPPING parameter works as intended now.


text:
Q: Logarithm on infinite tensor products continuous? Denote $V:=\mathbb{R}^d$ and consider the Cartesian product $V^\infty:=\prod_{k=0}^\infty V^{\otimes k}$ together with its canonical projections $\pi_k : V^\infty\rightarrow V^{\otimes k}, (v_0, v_1, \ldots)\mapsto v_k$, where $V^0:=\mathbb{R}$ and each factor space $V^{\otimes k}$ is equipped with the usual (Euclidean) tensor norm $\|\cdot\|_k$ inherited from $V$.
Define the space
$$\tag{1}E \,:=\,\left\{v\in V^\infty \ \middle| \ \sum_{k\geq 0}\|\pi_k(v)\|_k\cdot\lambda^k<\infty, \ \forall\,\lambda>0\right\}$$
and endow it with the locally convex topology induced by the family of norms $\|v\|_\lambda:=\sum_{k\geq 0}\|\pi_k(v)\|_k\lambda^k$, $\lambda>0$.
For each $v\equiv(v_k)\in V^\infty$ with $v_0=1$, define the (formal) logarithm $\log(v)$ as
$$\tag{2} \log(v)\, := \, \sum_{k\geq 1}\frac{(-1)^{k-1}}{k}(v-1)^{\otimes k}.$$
Question: Is it true that $v\mapsto\log(v)$ is continuous as a map from (the subspace) $E_1:=\{v\equiv(v_k)\in E\mid v_0=1\}$ to $E$?
Continuity w.r.t. the product topology on $E$ is trivial (as $\pi_k\circ\log$ is a polynomial for each $k\geq 0$), but the required case seems less clear. Any hints or references are appreciated.


text:
Q: Filter after multiple values ionic I'm doing a project on an online library and I have a modal page that allows you to search for books through 3 inputs, title, author and year. how do I filter the books through these 3 inputs?
my modal.html:
    <ion-content padding>
      <ion-list>
      <ion-item>
        <ion-label color="primary" >Title</ion-label>
        <ion-input placeholder="Insert the title"  [(ngModel)]="searchTerm"  name="titlebook" ></ion-input>
        </ion-item>
        <ion-item>
        <ion-label color="primary">Author</ion-label>
        <ion-input placeholder="Insert the Author"  name="authorbook" ></ion-input>
      </ion-item>
      <ion-item>
          <ion-label color="primary">Year</ion-label>
        <ion-input type="number" placeholder="Insert the Years" name="anno"></ion-input>
        </ion-item>
       </ion-list>
    <ion-buttons text-center>
    <button  ion-button color="secondary" (click)="searchTitle()">save
    </ion-buttons>

my json example (100 books):
    {
        "id":"3",
        "author": "Dante Alighieri",
        "country": "Italy",
        "imageLink": "images/the-divine-comedy.jpg",
        "language": "Italian",
        "link": "https://en.wikipedia.org/wiki/Divine_Comedy\n",
        "pages": 928,
        "title": "The Divine Comedy",
        "year": 1315
      },

A: Here is a simple way to do it:
Bind a change event on your three inputs like this: <ion-input (ionChange)="filterItems()"></ion-input>.
Add your filterItems() function to your modal controller:
filterItems() {
    this.books.filter((item) => {
        // the condition inside here, decides whether the item will be shown or not
        return item.title.toLowerCase().includes(this.title.toLowerCase) && item.author.toLowerCase().includes(this.author.toLowerCase());
    });
}

Now you are matching for the title and the author. Of course you need to bind your ion-input's with ngModel.
And you can output your books using *ngFor in your template.
Care! The function will return false, when the inputs are empty. Maybe you need to change the condition a little bit for your needs.


text:
Q: How to echo a variable containing an unescaped dollar sign in bash If I have a variable containing an unescaped dollar sign, is there any way I can echo the entire contents of the variable?
For example something calls a script:
./script.sh "test1$test2"
and then if I want to use the parameter it gets "truncated" like so:
echo ${1}
test1
Of course single-quoting the varaible name doesn't help.  I can't figure out how to quote it so that I can at least escape the dollar sign myself once the script recieves the parameter.

A: The variable is replaced before the script is run.
./script.sh 'test1$test2'

A: by using single quotes , meta characters like $ will retain its literal value. If double quotes are used, variable names will get interpolated.

A: The problem is that script receives "test1" in the first place and it cannot possibly know that there was a reference to an empty (undeclared) variable. You have to escape the $ before passing it to the script, like this:
./script.sh "test1\$test2"

Or use single quotes ' like this:
./script.sh 'test1$test2'

In which case bash will not expand variables from that parameter string.

A: As Ignacio told you, the variable is replaced, so your scripts gets ./script.sh test1 as values for $0 and $1.
But even in the case you had used literal quotes to pass the argument, you shoudl always quote "$1" in your echo "${1}". This is a good practice.


text:
Q: Find the value of $\mathbb{E}(X_1+X_2+\ldots+X_N)$ of i.i.d random variables $X_i$s.
Let $ X_1,X_2,X_3 ,\ldots$ be a sequence of i.i.d. random variables with mean $1$. If $N$ is a
  geometric random variable with the probability mass function $\mathbb{P}(N=k)=\dfrac{1}{2^k}$;
  $k=1,2,3,\ldots$ and it is independent of the $X_i$'s, then $\mathbb{E}(X_1+X_2+\ldots+X_N)=$?

My work:
Since mean of $X_i$s are $1$, so $\frac{X_1+X_2+\ldots+X_N}{N}=1$. Hence $\mathbb{E}(X_1+X_2+\ldots+X_N)=\mathbb{E}(N)=\sum_{k=1}^{\infty}k\mathbb{P}(N=k) = \sum_{k=1}^\infty \dfrac{k}{2^k}=2$.
Is my solution correct? Is this the right process to do it? Help please. Thanks.

A: Only a way to solve it correctly. In the answers of Ant and André it is explained what you did wrong.
If $S_N:=X_1+\cdots+X_N$ then:
$$\mathbb ES_N=\sum_{k=1}^{\infty}\mathbb E(S_N\mid N=k)\Pr(N=k)$$
Observe that  $\mathbb E(S_N\mid N=k)=\mathbb ES_k=\mathbb EX_1+\cdots+\mathbb EX_k=k$.
I leave the rest to you.

Edit
To explain why  $\mathbb E(S_N\mid N=k)=\mathbb ES_k$, observe that $\left\{ S_{N}\in A\wedge N=k\right\} =\left\{ S_{k}\in A\wedge N=k\right\} $ for any measurable $A$, leading to:$$\Pr\left(S_{N}\in A|N=k\right)=\frac{\Pr\left(S_{N}\in A\wedge N=k\right)}{\Pr\left(N=k\right)}=\frac{\Pr\left(S_{k}\in A\wedge N=k\right)}{\Pr\left(N=k\right)}=\Pr\left(S_{k}\in A\right)$$
The last equation is a consequence of the fact that $N$ and $S_k$ are independent. So the distribution of $S_N$ under condition $N=k$ is the same as the distribution of $S_k$.

A: No, your process does  not make any sense. Even if the mean of $X_k$ is $1$, this does not mean that $$\frac {X_1 + \dots + X_N}{N} = 1$$
for some $N$.
This is a huge misunderstanding; I'll try to briefly explain why is it so.
Random variables are not numbers
When talking about a random variable, you're talking about a function. When you write $X_1$, what you mean is $X_1(\omega)$; that is, it takes a different value for different $\omega$. As such, you cannot expect $X_1(\omega) + \dots + X_N(\omega) = N(\omega)$ to hold! The left hand side depends on the particular $\omega$, as does the right hand side. Since they are independent, this equation cannot hold for any $N$ (random variable or not)
Relationship between mean and expectation
Your confusion probably stems from the fact that if $x_i$ are numbers, then we call their "mean" (or more properly average) the number $\frac 1n\sum_{i=1}^n x_i $. Clearly you can do the same with random variables (and the result will again be a random variable, not a number) to get to
$$\frac 1n\sum_{i=1}^n X_i(\omega)$$
(note that in this context I am assuming $n$ constant, different than $N(\omega)$ random variable)
A priori, this value has no relationship whatsover with the abstract integral $E[X_1]$ (which is what we call the mean of the random variable). They are completely different things defined in completely different ways! For instance, $E[X_1]$ only depends on $X_1$ while the other is an average of many random variables.
One discovers, after some work, that if the random variables $X_i$ are independent and indentically distributed with mean $\mu \in \mathbb R$, then $$\frac 1n \sum_{i=1}^n X_i \to \mu$$
(the limit is taken a.s. and in $L^1$).
So you if you take a lot of iid random variables and you take their average, the result is still a random variable, but it's "very close" to a constant, and that constant is precisely the mean $\mu$. As $n \to \infty$, it will be "equal" to the constant $\mu$. This is called the Law of Large Numbers and it's the justification as of why we call $E[X_1]$ "mean" in the first place, but you should remember how things are defined and not get confused by words
How to solve the problem
Now, if instead of $N(\omega)$ we simply had $n$, the problem was easy; use linearity of expectation to find that
$$E(X_1 + \dots + X_n) = E(X_1) + \dots + E(X_n) = n$$
If $N(\omega)$ is a random variable, clearly you cannot do the same; you need to use the tower property of conditional expectation to write that
$$E(X_1 + \dots + X_N)  = E(E(X_1 + \dots + X_n \mid N = n) ) = E(N) = \sum_{k=1}^\infty \frac k{2^k} = 2$$

A: The calculation is incompletely justified, and one should not write $\frac{X_1+\cdots+X_N}{N}=1$.
Observe that $E(X_1+\cdots+X_N\mid N=k)=k$. This is because the $X_i$ and $N$ are independent, so for fixed $k$, we are just looking at $X_1+\cdots +X_k$, and by the linearity of expectation, the expectation of the sum is $(k)(1)$.
By the Law of Total Expectation,
$$E(X_1+\cdots+X_N)=\sum_1^\infty E(X_1+\cdots+X_N\mid N=k)\Pr(N=k).$$ Thus we conclude that
$$E(X_1+\cdots+X_N)=\sum_1^\infty k2^{-k},$$
and you calculated this sum correctly.

A: By Wald's identity (basic version),
$$E\left[ \sum_{i=1}^{N} X_i\right] = E[N] E[X_1]$$
where
$$E[N] = \sum_{k=1}^{\infty} \frac{k}{2^k}$$
$$E[X_1] = 1$$


text:
Q: How to check intersection between rectangle and TextureRegion LibGDX? I don't know if it's possible, but I want to check it like this because I'm using some animated elements and some non animated elements. I was wondering how I would go about doing this. Thanks.

A: If you are using Box2D you would create 2 bodies and trigger an event when there is a contact between the two.
One would be a Dynamic body and the other one would be a StaticBody.
more information  here> https://github.com/libgdx/libgdx/wiki/Box2d

A: I ended up using another rectangle as a hit box that I set to the same moving coordinates as my TextureRegion.


text:
Q: Searching spotify user's music library for particular genre I am developing third party app on spotify platform. In that, user have to select spotify user's music library playlist (top 100 songs by Spotify user). So, I am trying to search spotify library for particular genre.
I am using SPSearch with Query genre:pop. But for some generics like "rock" it return nil.
I am using latest build of cocoalibspotify. Please can somebody tell how to get Spotify user track list or playlist for particular genre?

A: The full advanced search documentation can be found here.
Note that this will search the entire Spotify catalog, not just the user's own library. There's currently no built-in way to only search the user's library at this time.


text:
Q: Is there a way to only print part of a JSON string in JavaScript I have JSON data which I have gotten from weather api. Within the data I would like to be able to display the weather for each hour.

     "hour": [
                    {
                        "time_epoch": 1621897200,
                        "time": "2021-05-25 00:00",
                        "temp_c": 8.4,
                        "temp_f": 47.1,
                        "is_day": 0,
                        "condition": {
                            "text": "Partly cloudy",
                            "icon": "//cdn.weatherapi.com/weather/64x64/night/116.png",
                            "code": 1003
                        },
                        "wind_mph": 22.1,
                        "wind_kph": 35.6,
                        "wind_degree": 319,
                        "wind_dir": "NW",
                        "pressure_mb": 1011.0,
                        "pressure_in": 30.3,
                        "precip_mm": 0.0,
                        "precip_in": 0.0,
                        "humidity": 87,
                        "cloud": 37,
                        "feelslike_c": 4.1,
                        "feelslike_f": 39.4,
                        "windchill_c": 4.1,
                        "windchill_f": 39.4,
                        "heatindex_c": 8.4,
                        "heatindex_f": 47.1,
                        "dewpoint_c": 6.3,
                        "dewpoint_f": 43.3,
                        "will_it_rain": 0,
                        "chance_of_rain": "0",
                        "will_it_snow": 0,
                        "chance_of_snow": "0",
                        "vis_km": 10.0,
                        "vis_miles": 6.0,
                        "gust_mph": 32.9,
                        "gust_kph": 52.9,
                        "uv": 1.0
                    },
                    {
                        "time_epoch": 1621900800,
                        "time": "2021-05-25 01:00",
                        "temp_c": 8.3,
                        "temp_f": 46.9,
                        "is_day": 0,
                        "condition": {
                            "text": "Partly cloudy",
                            "icon": "//cdn.weatherapi.com/weather/64x64/night/116.png",
                            "code": 1003
                        },

From the above JSON data I would like to get the time. For some reason the date and time are given within the JSON.
As shown below I am able to get both the date and time from the JSON but I would only like to display the time. Is there any way that I can do this?

  $.ajax({
      type: "GET",
      url: api + "forecast.json?key=" + apiKey + "&q=" + position.coords.latitude+ "," + position.coords.longitude,
      dataType: 'json',
      timeout: 0,
      success: (parsed_json) => {
        console.log(parsed_json);
        const time = parsed_json['forecast']['forecastday'][0]['hour'][0]['time'];

        const timeText = document.getElementById("title");
        timeText.innerText = time;

      }
    });

A: The simplest solution would be to split on blank sign
basic example:
const timeOnly = "2021-05-25 00:00".split(" ")[1];

your case:
const dateAndTime = parsed_json['forecast']['forecastday'][0]['hour'][0]['time'];
const timeOnly = dateAndTime.split(" ")[1];


text:
Q: What's the best way to structure a Users table in DynamoDB? I'm trying to build a Users table and get my head around how to model data in DynamoDB.
I have two basic access patterns to start with.

*

*Get a user by id.

*Get a user by email.

But I want to keep the table flexible so that later on I can store alternative login methods for a user and access those later.
Does the table below make sense?
It allows me to a getItem on the main table by user id pk: user#123, sk: USER and getItem on the gsi by email pk: USER, sk: email#joe@gmail.com.
I'm concerned that the gsi won't be able to effectively partition the data.
| pk       | sk_gsi1pk | gsi1sk                |
| -------- | --------- | --------------------- |
| user#123 | USER      | email#joe@gmail.com   |
| user#456 | USER      | email#sarah@gmail.com |
| user#789 | USER      | email#bob@gmail.com   |

A: A couple things here.

*

*You can't do a getItem on a GSI. You can query it, but it does not guarantee uniqueness like the table's partition and sort do.

*What you're doing there is reasonable. I question whether you need to include email# in front of the email address. If they are using a different form of login it wouldn't be the same anyway (e.g. joe@gmail.com != joe). It's also not clear that you need the sort key on the table, unless you expect to store other records for the user, using the same partition key value.


text:
Q: Usage of SQLiteOpenHelper.getWritableDatabase According to http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase%28%29

Once opened successfully, the database is cached, so you can call this
  method every time you need to write to the database.

Consider the following snippet:
SQLiteDatabase db1 = openHelperImplObj.getWritableDatabase();
// do something with db1
SQLiteDatabase db2 = openHelperImplObj.getWritableDatabase();
// do something with db2
db2.close();
// do something with db1
db1.close();

I presume the second call to getWritableDatabase() will return the same cached DB (the db1), wouldn't the line db2.close() cause any issue to db1 operations that happen afterward? If so, what is the recommended way to avoid such problem since the second call may happen anywhere, i.e. in a different function or even in different class.

A: When you open a data base by using db  openHelperImplObj.getWritableDatabase();
then following thing check
1>If database is not created then it create database and open it for write mode else created first then open.
2>Second and most important what i have observed if data base is already created then it opened it but if its open already it do nothing, That means it occupy the old instance of data
base that open DB already until you close it.Thats why its better practice to close DB once it
use over
Hope you got


text:
Q: Ag grid: How to add a row with sorting order I have been trying an issue like while adding the row into ag grid, it is always adding in bottom of the grid without sort order.
I would like to add the row with sorting order here the example what is happening when I add the row,
Actual results is
4
5
6
1 => Newly added row without sorting.

Expected result is
1 => Newly added row with sorting.
4
5
6

This is the syntax using from Ag-grid.
const addedRow = this.gridOptions.api.updateRowData({ add: [view.data]});
      addedRow.add[0].setSelected(true);

Any expert advice
No sort(Default: Loading the data as per the array order)
8
4
9
1 => Added new Row
Ascending
1 => Added new Row
4
8
9
Descending
9
8
4
1 => Added new Row

A: You can set the sort order of your grid using the gridApi.
In the onGridReady callback, set the following sort:
onGridReady(params) {
      this.gridApi = params.api;

      var sort = [
          {
            colId: "id",
            sort: "asc"
          }
        ];
        this.gridApi.setSortModel(sort);
    }

Then when you've added your new row, it will be automatically order by the id field in ascending order.
Take a look at this StackBlitz example.


text:
Q: "Google Maps is tracking your location" blue status bar Have a strange bug, we use Google Maps SDK in our iOS app and ever since iOS 8.3 we have been getting the annoying "Google Maps is tracking your locaton" blue flashing status bar when we launch our app. It doesn't always happen though, it seem random. Has anyone else run into this? If so, have you found a way to prevent this from happening?  Thanks!
UPDATE:
Haven't seen this in iOS 8.4 so I am going to assume this was a bug in the OS.


text:
Q: Is there a way to put NLog.config information inside of my app.config file? Is there a way to put NLog.config information inside of my app.config file?  This way I can have one config file instead of two.  It could look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <nlog>
    <targets>...</targets>
    <rules>...</rules>
  </nlog>
</configuration>

Please let me know if this is a duplicate.

A: Of course that you can put the configuration in your app.config file.
You just need to use the NLog.Config.ConfigSectionHandler so you need to write
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <nlog>
    <targets>...</targets>
    <rules>...</rules>
  </nlog>
</configuration>

as described  in the NLog documentation in the Configuration file format section.


text:
Q: creating vue-cli3 project on git-bash I'm trying to follow https://alligator.io/vuejs/demistifying-vue-webpack/ . Based on this I tried:
$ vue init webpack-simple demistify-project

 Command vue init requires a global addon to be installed.
 Please run yarn global add @vue/cli-init and try again.

So I tried:
$ yarn global add @vue/cli-init
yarn global v1.12.3
[1/4] Resolving packages...
warning @vue/cli-init > vue-cli > coffee-script@1.12.7: CoffeeScript on NPM
has moved to "coffeescript" (no hyphen)
warning @vue/cli-init > vue-cli > metalsmith > gray-matter > coffee-
s cript@1.12.7: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

warning "@vue/cli-init@3.2.0" has no binaries
Done in 15.69s.

then:
$ vue init webpack-simple demistify-project

 Command vue init requires a global addon to be installed.
 Please run yarn global add @vue/cli-init and try again.

How do I get this working?

A: You're trying to use a vue-cli 2 command with a vue-cli 3 version.
Since version 3, the command to initialize a new project has changed so to do what you want you're not going to write vue init webpack-simple project but instead vue create project


text:
Q: Gitlab configured with SSH keys still asks for password I am trying to avoid typing the password every time I want to pull or push from a gitlab repository. Therefore I followed https://docs.gitlab.com/ee/ssh/ but still, now every time I want to pull something it still asks me to provide the password for my remote gitlab repository.
Any clue on how to fix this issue?

A: Are you sure you are using the SSH link for your repository? It is like: git@gitlab.com:YOUR-USER/YOUR PROJECT.git