text:
Q: How can i get a project from Git including dependencies? I am using Git for the first time. There is a project on Git that i need to do a "get latest".
Now this solution has other project dependencies. So do i need to do a git clone on each project to my local machine or is there a switch in the git clone that can fetch the project and all other projects it depends on ?

A: You need to check the nature of those dependencies:

*

*source dependencies, which means your project repository could reference as "submodule" (or possibly subtree) other project source code.

*binary dependencies, which means your project includes a file (which has nothing to do with Git) telling your compiler how to fetch said binaries:

*

*pom.xml for Maven artifact dependencies

*package.json for npm dependencies

*requirements.txt for python dependencies

*... and so on, depending on the nature of your project

In the former case, if submodules are involved, you would see a .gitmodules file listing the external repositories.
A simple git clone --recurse-submodules would be enough to clone all repositories involved.
The OP Debbie.S confirms in the comments:

My solution is a Visual Studio 2091 solution and in the solution under Dependencies->Projects, there is the name of the project it depends on.
Now I thought I could clone from Git in one go and retrieve the entire solution with all dependencies, obviously not as it has not been set up that way.
So I need to clone each individual project from Git until submodules are introduced from now on.


text:
Q: Parse HTTP access log in order to get all request with 429 respond within one sec Typical access.log file from nginx
000.00.000.001 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 429 1157 "data..."
000.00.000.002 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 200 741 "-" "data..."
000.00.000.001 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.001 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.001 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.001 - - [28/Jun/2021:06:37:02 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.003 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.003 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.003 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.003 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.003 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.004 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.004 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."
000.00.000.004 - - [28/Jun/2021:06:37:03 +0100] "POST /abc/cba/ HTTP/1.1" 429 741 "-" "data..."

The question is how could I get all IP addresses from the log file that had response code 429 and are made within one sec any time. I am trying to find a solution with awk but no success yet if somebody could give a hint.
The output for a given example would be:
28/Jun/2021:06:37:02:
000.00.000.001
28/Jun/2021:06:37:03:
000.00.000.003

*

*only IP that made more or equal of 5 request

*have response status 429

*group by seconds if there is something show in response any time not a specific second

A: Is this what you're trying to do?
$ awk -F'[[ ]+' '$9==429{print $4, $1}' file | uniq -c | awk '$1>4{print $2 ":\n" $3}'
28/Jun/2021:06:37:02:
000.00.000.001
28/Jun/2021:06:37:03:
000.00.000.003

If the content within the first set of quotes (e.g. "POST /abc/cba/ HTTP/1.1") isn't always 3 space-separated strings as in your sample input then just tweak it to this:
$ awk -F'[[ ]+' '{sub(/"[^"]*"/,"")} $6==429{print $4, $1}' file | uniq -c | awk '$1>4{print $2 ":\n" $3}'
28/Jun/2021:06:37:02:
000.00.000.001
28/Jun/2021:06:37:03:
000.00.000.003

If you prefer an awk-only solution for some reason:
$ awk -F'[[ ]+' '$9==429{cnt[$4":\n"$1]++} END{for (key in cnt) if (cnt[key]>4) print key}' file
28/Jun/2021:06:37:02:
000.00.000.001
28/Jun/2021:06:37:03:
000.00.000.003

All of the above scripts will work just using mandatory POSIX tools in any shell on every Unix box.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP embedded image not showing on web browser I'm sending an e-mail newsletter in PHP. Inside the PHP I have something like
<?php
//define the receiver of the email
set_time_limit(0);
$to='123@gmail.com';
$subject = 'test';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers='MIME-Version: 1.0' . "\r\n";
$headers .= "From: 123@gmail.co.id\r\nReply-To: 123@gmail.co.id";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: text/html; boundary=\"PHP-mixed-".$random_hash."\"";

ob_start(); //Turn on output buffering

include ("contents.php");

$message = ob_get_clean();

//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

and this is contents.php file
<?php
// A few settings
$img_file = 'tes.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '';
?>

When I open the email with android smartphone, the image is being displayed. However, when I open it with web browser or outlock, no image is shown. I'm not sure if it's about the proxy that Gmail uses for security reasons or if it's something else. Either way, I'd like to know if anyone ever came across this and if so, how it was solved.

A: How to investigate.
It's possible Gmail is prepending the src attribute of the img tag with its CDN endpoint. To verify what is actually in the src attribute, select the image element and inspect it in developer tools:
Image in Chrome Developer Tools
It may look something like https://ci6.googleusercontent.com/proxy/...#data: image/gif... which is not a valid URL.
Plan A.
If Gmail is looking for a URL to the file and not a data URI, you could upload the file to Amazon S3 and point to it in the src attribute.
Plan B.
Try this:
echo '
';

Instead of:
echo '';


text:
Q: Foreach dentro de outro array no php Como eu posso gerar com o php esse array para fazer uma transação de pagamento pelo Pagseguro?
$params = array(
        'email'                     => $PAGSEGURO_EMAIL,
        'token'                     => $PAGSEGURO_TOKEN,
        'creditCardToken'           => $creditCardToken,
        'senderHash'                => $senderHash,
        'receiverEmail'             => $PAGSEGURO_EMAIL,
        'paymentMode'               => 'default',
        'paymentMethod'             => 'creditCard',
        'currency'                  => 'BRL',
        // 'extraAmount'               => '1.00',

        'itemId1'                   => '0001',
        'itemDescription1'          => 'PHP Test',
        //'itemAmount1'               => $numero,
        'itemAmount1'               => '1.00',
        'itemQuantity1'             => 1,

        'itemId2'                   => '0002',
        'itemDescription2'          => 'PHP Test2',
        //'itemAmount2'               => $numero,
        'itemAmount2'               => '1.00',
        'itemQuantity2'             => 1,

        'reference'                 => 'REF1234',
        'senderName'                => $senderName,
        'senderCPF'                 => $senderCPF,
        'senderAreaCode'            => 83,
        'senderPhone'               => $senderPhone,
        'senderEmail'               => $senderEmail,
        'shippingAddressStreet'     => $shippingAddressStreet,
        'shippingAddressNumber'     => $shippingAddressNumber,
        'shippingAddressDistrict'   => $shippingAddressDistrict,
        'shippingAddressPostalCode' => $shippingAddressPostalCode,
        'shippingAddressCity'       => $shippingAddressCity,
        'shippingAddressState'      => $shippingAddressState,
        'shippingAddressCountry'    => 'BRA',
        'shippingType'              => 1,
        'shippingCost'              => '1.00',
        'installmentQuantity'       => 1,
        'installmentValue'          => '3.00',
        'creditCardHolderName'      => 'Chuck Norris',
        'creditCardHolderCPF'       => '54793120652',
        'creditCardHolderBirthDate' => '01/01/1990',
        'creditCardHolderAreaCode'  => 83,
        'creditCardHolderPhone'     => '999999999',
        'billingAddressStreet'     => 'Address',
        'billingAddressNumber'     => '1234',
        'billingAddressDistrict'   => 'Bairro',
        'billingAddressPostalCode' => '58075000',
        'billingAddressCity'       => 'João Pessoa',
        'billingAddressState'      => 'PB',
        'billingAddressCountry'    => 'BRA'
    );

Note que precisa repetir de acordo com o numero de produtos essa parte
        'itemId1'                   => '0001',
        'itemDescription1'          => 'PHP Test',
        //'itemAmount1'               => $numero,
        'itemAmount1'               => '1.00',
        'itemQuantity1'             => 1,

        'itemId2'                   => '0002',
        'itemDescription2'          => 'PHP Test2',
        //'itemAmount2'               => $numero,
        'itemAmount2'               => '1.00',
        'itemQuantity2'             => 1,

Os produto vem de um array
foreach($product_list_array as $item)
{
    echo $item->product_price;
    echo $item->product_id;
    echo $item->product_quantity;
    echo $item->product_desc;

}

Como eu faria para colocar esse foreach dentro do $params=array(...) junto com as demais informações da compra?
Ficaria assim?
<?php

$params = array();

$params['email']  = $PAGSEGURO_EMAIL;
$params['token']  = $PAGSEGURO_TOKEN;

foreach($product_list_array as $index => $item)
{
    $item = 'itemId' . $index;
    $params[$item]  => $item->product_id,
    $params['itemDescription1'] = $item->product_desc,
    $params['itemAmount1'] = $item->product_price,
    $params['itemQuantity1'] = $item->product_quantity,
}

$params['billingAddressState'] => 'PB';
$params['billingAddressCountry'] => 'BRA';

$header = array('Content-Type' => 'application/json; charset=UTF-8;');
    $response = curlExec($PAGSEGURO_API_URL."/transactions", $params, $header);
    $json = json_decode(json_encode(simplexml_load_string($response)));

?>

está dando erro

A: $params['email']  = $PAGSEGURO_EMAIL;
$params['token']  = $PAGSEGURO_TOKEN;
...

foreach($product_list_array as $index => $item)
{
    $item = 'itemId' . $index;
    $params[$item]  = $item->product_id;
    $params['itemDescription1'] = $item->product_desc;
    $params['itemAmount1'] = $item->product_price;
    $params['itemQuantity1'] = $item->product_quantity;
}

...
$params['billingAddressState'] = 'PB';
$params['billingAddressCountry'] = 'BRA';


text:
Q: Why does new data to an async pipe not cause data to rerender? I've been reading a lot of background on Angular/ReactJS and trying to get a good understanding of the lifecycle hooks and how it all plays together, but something that still confuses me is the following scenario.
Say you have a someService and in that service you define a BehaviorSubject called someBehaviorSubject. It is defined inside someService as:
public someBehaviorSubject= new BehaviorSubject<someInterface[]>([]);

That behavior subject is then subscribed to someAPIcall(argument: string): void. someService.someAPIcall is defined as:
someAPIcall(argument: string): void {
  this.http.get<someInterface[]>(argument).subscribe(this.someBehaviorSubject);
}

someInterface is defined as:
interface someInterface {
  data: string
}

Say there is a parent component called someParent and a child called someChild. someParent has two buttons which call:
someService.someAPIcall("A");

and
someService.someAPIcall("B");

respectively. someChild has the following in a template:
<div*ngFor="let data of someService.someBehaviorSubject | async">
  {{data}}
</div>

In my observations, when you click button A or button B in someParent, the data correctly renders either dataset A or B. However, if you click the other button after the first set of data has rendered it does not rerender the data with the new dataset. I expected that it would with the async pipe being directly subscribed to the BehaviorSubject. I don't understand why the data isn't redrawn?

A: In order to update the BehaviorSubject value you need to use the next() function which will push the new value into the BehaviorSubject.
Example:
someAPIcall(argument: string): void {
  this.http.get<someInterface[]>(argument).subscribe(data =>
{
   this.someBehaviorSubject.next(data);
});}

For more information about RxJS subjects, consider checking the documentation.


text:
Q: Yet another Least Squares matrix derivation I understand the solution to the well known Least squares as explained in the following post
Least-squares solution to a matrix equation?
We solve for β so that below expression has minimal value.
$\mathbf(Y−Xβ)′ × (Y−Xβ)$
In above, lets assume that we have N samples each with D features

*

*Y is N*1

*X is N*D

*β is D*1

I am wondering how the derivation steps would change had we assumed Y output shape is 1 * N

*

*Y is N*1

So the equation for Y would be
$\mathbf Y = β'X'$
and not
$\mathbf  Y = Xβ $
as in the original derivation.
Again, while I completely understand the steps in the original derivation, I could not solve if I had assumed  Y = β′X′
$\mathbf  (Y−β′X′)′×(Y−β′X′)$
Expanding the above for derivative wrt β yields below  - but I couldn't proceed further
$\mathbf  Y′Y  − Y′β′X′ - XβY - Xββ′X′ $
For academic interest, I like to understand if it at all possible to solve for β this route and the steps

A: In brief, the steps to solve a least squares problem are
$$\eqalign{
y &= X\beta \quad\implies
\min_\beta\,\|X\beta-y\|^2 \quad\implies
\beta = (X^TX)^{-1}X^Ty \\
}$$
The decision to use $Y=y^T$ instead of $y$
has no effect on these steps, i.e.
$$\eqalign{
Y^T &= X\beta \quad\implies
\min_\beta\,\|X\beta-Y^T\|^2 \quad\implies
\beta = (X^TX)^{-1}X^TY^T \\
}$$
The approach can be summarized as:
$\quad$Substitute the new $Y^T$ variable where ever the original $y$ variable appears.
Make this substitution in every expression, every formula, and every derivative.


text:
Q: Make scrolling a sticky element higher priority than changing the element position Suppose I have a side nav, I want the side nav to be sticky so that it scrolls along with the user. However the side nav is not of a fixed height: when a user opens an item on the nav with sub items then it expands vertically to show the sub items.
Once a submenu expands, or I suppose on a small screen, the menu may not fit on one screen like before. The solution for a user would be to scroll down the page to see the bottom of the nav and select their chosen link. However now that the side menu is sticky, the menu will rather scroll with them when the scroll down. It's only once the user reaches the bottom of the content that the menu will then find the end of it's container and stay so the user can access the bottom of the menu.
Here is a code pen I forked that illustrates the issue. The content is massive and the side nav only slightly larger than the screen height.

.sidebar {
  width: 25%;
  height: 120vh;
  min-height: 400px;
  overflow: auto;
  position: -webkit-sticky;
  position: sticky;
  top: 3em;
}

.main {
  width: 60%;
  height: 2000vh;
  min-height: 1000px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.main,
.sidebar {
  border: 5px solid #222;
  background-color: white;
  border-radius: 10px;
  color: #222;
  padding: 15px;
}

.wrapper {
  display: flex;
  justify-content: space-between;
}

body {
  padding: 3%;
  background-color: #ccc;
  font-size: 20px;
  box-sizing: border-box;
  font-family: Lato, sans-serif;
}

code, pre {
  background-color: #ccc;
  padding: 0 3px;
  border-radius: 5px;
}

.bottom {
  position: absolute;
  bottom: 0;
}

Main content

Scroll down the page!

You made it!

Sticky sidebar

I will follow you! But should wait til you hit my bottom when scrolling down before following down. If you are scrolling up, I should wait for you to hit my top before following.

What can I do? I would love a pure CSS version for performance reasons. I dont want to limit the height of the nav because that means the vast majority of the users will need to rethink how they use the nav, by scrolling on the nav directly rather than on the content like they are used to.
I have found a JS library called sticky kit that creates the exact effect I am looking for, the scrollable sticky element example in particular. However it has not been updated in 2 years and I don't want to rely on a jquery plugin that likely will not work as web standards change.
There is a middle ground option, where I use JS to change the CSS sticky direction on scroll - like this pen. But there is a terrible jerkiness when you switch directions.

A: So from what I have studied, this is just not part of the spec for sticky at this time - you need to use a bit of JS.
However how much JS can be minimized if you instead use the JS to control the sticky positioning. I forked that JS pen I posted at the end of my question and worked on it to find a very minimal solution with very little JS, that tries to avoid too many calculations on the scroll event listener.

window.onscroll = function (e) {
  if (window.scrollY < this.prevScrollY) {
    // Track position state of nav
    // 1 == stuck to top
    // 0 == absolute positioning
    // -1 == stuck to bottom
    this.stick_pos = scrollUpwards(this.stick_pos);
  } else {
    this.stick_pos = scrollDownwards(this.stick_pos);
  }
  this.prevScrollY = window.scrollY;
}

function scrollUpwards(stick_pos) {
  // If the element is already stuck to the top then we are fine
  if(stick_pos === 1) return stick_pos;
  // Figure out where the new window will be after scroll
  let aside = $("aside").get(0);
  let aboveAside = aside.getBoundingClientRect().top > 0;
  // If we are going above the element then we know we must stick
  // it to the top
  if (aboveAside){
    $("aside").css("position", "sticky")
      .css("top", 0)
      .css("bottom", '')
      .css("align-self", "flex-start");
    return 1;
  }
  // If it will still be below the top of the element, then we
  // must absolutely position it to its current position - if it already is absolutely positioned then we do nothing
  if (stick_pos == 0) return stick_pos;

  // Undo the stick to the bottom
  // First get the current position
  $("aside")
    .css("top", aside.offsetTop)
    .css("position", "absolute")
    .css("bottom", '')
    .css("align-self", "");
  return 0;
}

function scrollDownwards(stick_pos) {
  /*
  let aside = $("aside").get(0);
  let aboveAside = aside.offsetTop >= window.scrollY;
  let browser_bottom = window.scrollY + window.innerHeight;
  let aside_bottom = aside.offsetTop + aside.offsetHeight;
  let belowAside = browser_bottom >= aside_bottom;
  if (aboveAside) {
    //console.log("stick to bottom");
    $("aside").css("top", '');
    $("aside").css("bottom", 0);
    $("aside").css("align-self", "flex-end");
  }
  */
  // If the element is already stuck to the bottom then we are fine
  if(stick_pos === -1) return stick_pos;
  // Figure out where the new window will be after scroll
  let aside = $("aside").get(0);
  let browser_bottom = window.innerHeight;
  let aside_bottom = aside.getBoundingClientRect().top + aside.offsetHeight;
  let belowAside = browser_bottom > aside_bottom;
  // If we are going below the element then we know we must stick
  // it to the bottom.
  if (belowAside){
    $("aside").css("position", "sticky")
      .css("top", '')
      .css("bottom", 0)
      .css("align-self", "flex-end");
    return -1;
  }
  // If it will still be above the bottom of the element, then we
  // must absolutely position it to its current position - if it already is absolutely positioned then we do nothing
  if (stick_pos == 0) return stick_pos;

  // Undo the stick to the top
  // First get the current position
  // $("aside").css("position", "absolute")
  // .css("top", aside.offsetTop);
  $("aside")
    .css("top", aside.offsetTop)
    .css("position", "absolute")
    .css("bottom", '')
    .css("align-self", "");
  return 0;
}
div#section {
  /* begin: irrelevant styling */
  margin: 5em auto;
  padding: 0.625rem;
  max-width: 300px;
  font-family: sans-serif;
  font-size: 18px;
  line-height: 1.5em;
  text-align: justify;
  background-color: #dbe4ee;
  /* end: irrelevant styling */
  display: flex;
  justify-content: space-around;
}
div#section div#nav-container {
  position: relative;
  display: flex;
  min-width: 2em;
}
div#section div#nav-container aside {
  position: sticky;
  align-self: flex-start;
  width: 2em; /* Magic number, must be same width as the aside nav */
  /* begin: irrelevant styling */
  background-color: #81a4cd;
  color: white;
  text-align: center;
}
div#section div#nav-container aside div {
  padding: 0 .3em;
}
div#section article {
  margin-left: 0.5em;
}
div#section article p {
  margin: 0;
}
div#section article p + p {
  margin-top: 1.5em;
}

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

Perferendis ut iusto voluptatem ex temporibus aut autem amet. Sit vero in soluta. Est officia asperiores tenetur vel quam nostrum eum facere. Sed totam quasi libero at facilis doloremque. Non aut velit odio. Tempora dolore sunt recusandae sed quia
      sunt.

Voluptatem optio asperiores dolorem voluptatem. Ipsa alias perspiciatis doloribus est nisi ut. Fuga aut et vitae consequatur dolor corrupti aut minima.

Facilis et ut eligendi. Excepturi labore asperiores vero. Perferendis porro sunt molestiae. In sit dolorem eum esse sit inventore est. Atque perspiciatis commodi nihil.

Consequatur ipsa id repellendus voluptatem perspiciatis temporibus. Praesentium eveniet nemo laudantium inventore similique impedit nihil esse. Maiores iste commodi molestiae quas odit nihil ex corrupti. Illum id amet non vero.

Voluptas soluta itaque et. Aperiam quasi sint eos ullam. Assumenda facilis omnis alias numquam. Odio quia esse vel et minima soluta architecto. Qui saepe consequatur aut rerum. Et et aut voluptatibus inventore.

Perferendis ut iusto voluptatem ex temporibus aut autem amet. Sit vero in soluta. Est officia asperiores tenetur vel quam nostrum eum facere. Sed totam quasi libero at facilis doloremque. Non aut velit odio. Tempora dolore sunt recusandae sed quia sunt.

Voluptatem optio asperiores dolorem voluptatem. Ipsa alias perspiciatis doloribus est nisi ut. Fuga aut et vitae consequatur dolor corrupti aut minima.

Facilis et ut eligendi. Excepturi labore asperiores vero. Perferendis porro sunt molestiae. In sit dolorem eum esse sit inventore est. Atque perspiciatis commodi nihil.

Consequatur ipsa id repellendus voluptatem perspiciatis temporibus. Praesentium eveniet nemo laudantium inventore similique impedit nihil esse. Maiores iste commodi molestiae quas odit nihil ex corrupti. Illum id amet non vero.

Voluptas soluta itaque et. Aperiam quasi sint eos ullam. Assumenda facilis omnis alias numquam. Odio quia esse vel et minima soluta architecto. Qui saepe consequatur aut rerum. Et et aut voluptatibus inventore.

Its not ideal compared to a CSS solution but its pretty zippy and seems stable. I'm all ears for improvements and will be cleaning it up on the codepen. For one this solution makes use of magic numbers (the width of the aside container and the aside must be held the same, since the aside will be absolutely positioned during interim scrolls). This could be solved with a css variable I suppose.


text:
Q: What is the best way to test for object equality - without overriding Equals & GetHashCode, or implementing IEquatable? I'd like to check for equality among two objects that have no Public Properties.  However, I don't want to override the Equals & GetHashCode method, or implement IEquatable.  For example, consider the following code:
class Program
{
    static void Main(string[] args)
    {
        Guid id = Guid.NewGuid();
        string personName = "MyName";
        MyClass object1 = new MyClass(id, personName);
        MyClass object2 = new MyClass(id, personName);
        //This returns false, but I'd like it to return true:
        Console.WriteLine(object1.Equals(object2));
        //[edit]...by using, for example:
        Console.WriteLine(ObjectsAreEqual(object1, object2));
    }
}

class MyClass
{
    private Guid _id;
    private string _personName;
    public MyClass(Guid id, string personName)
    {
        _id = id;
        _personName = personName;
    }
}

I know the standard method is to override Equals & GetHashCode, but for various reasons, I don't want to change any code in the class.  Plus, there are no public properties, so I can't compare these.  Is there any other way of implementing this?
For example, via reflection?  Or perhaps by serialising the Objects to JSON, and comparing the resulting strings?
Thanks.

A: You could create a custom IEqualityComparer<T> implementation that uses reflection:
var comparer = new MyClassEqualityComparer();
Console.WriteLine(comparer.Equals(object1, object2));

// ...

public class MyClassEqualityComparer : EqualityComparer<MyClass>
{
    private static readonly string[] _names = { "_id", "_personName" };

    private static readonly FieldInfo[] _infos =
        typeof(MyClass).GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                       .Where(fi => _names.Contains(fi.Name))
                       .ToArray();

    public override bool Equals(MyClass x, MyClass y)
    {
        return _infos.All(fi => object.Equals(fi.GetValue(x), fi.GetValue(y)));
    }

    public override int GetHashCode(MyClass obj)
    {
        unchecked
        {
            int hash = 31;
            foreach (FieldInfo fi in _infos)
            {
                object val = fi.GetValue(obj);
                hash = (hash * 17) + ((val == null) ? 0 : val.GetHashCode());
            }
            return hash;
        }
    }
}

A: You can't change the result of the Equals instance method without overriding it. So you'll need to use IEqualityComparer<T> which needs to be passed explicitly to the code that requires equality checks. Luckily most built in collections accept such an equality comparer as a parameter to their constructor.
Implementing IEqualityComparer<T> with reflection seems to be your only option if you don't want to change the original class in any way.
You can get the FieldInfo using GetField("_personName",BindingFlags.NonPublic) and then call GetValue on it to get the value.
void Main()
{
        Guid id = Guid.NewGuid();
        string personName = "MyName";
        MyClass object1 = new MyClass(id, personName);
        MyClass object2 = new MyClass(id, personName);
        //This returns false, but I'd like it to return true:
        Console.WriteLine(object1.Equals(object2));
        //[edit]...by using, for example:
        Console.WriteLine(MyClassEqualityComparer.Instance.Equals(object1, object2));
}

public class MyClass
{
    private Guid _id;
    private string _personName;
    public MyClass(Guid id, string personName)
    {
        _id = id;
        _personName = personName;
    }
}

public class MyClassEqualityComparer:IEqualityComparer<MyClass>
{
  private static FieldInfo personNameField=typeof(MyClass).GetField("_personName",BindingFlags.Instance|BindingFlags.NonPublic);
  private static FieldInfo idField=typeof(MyClass).GetField("_id",BindingFlags.Instance|BindingFlags.NonPublic);

  public bool Equals(MyClass o1,MyClass o2)
  {
    if(o1==o2)
      return true;
    if(o1==null||o2==null)
      return false;
    string name1=(string)personNameField.GetValue(o1);
    string name2=(string)personNameField.GetValue(o2);
    if(name1!=name2)
      return false;
    Guid id1=(Guid)idField.GetValue(o1);
    Guid id2=(Guid)idField.GetValue(o2);
    return id1==id2;
  }

  public int GetHashCode(MyClass o)
  {
    if(o==null)
      return 0;
    string name=(string)personNameField.GetValue(o);
    Guid id=(Guid)idField.GetValue(o);
    return name.GetHashCode()^id.GetHashCode();
  }

  private MyClassEqualityComparer()
  {
  }

  public static readonly IEqualityComparer<MyClass> Instance=new MyClassEqualityComparer();
}

A: You could add a member function to MyClass and check the private fields there:
class MyClass
{
    private Guid _id;
    private string _personName;
    public MyClass(Guid id, string personName)
    {
        _id = id;
        _personName = personName;
    }

    public bool IsEqual(MyClass otherInstance)
    {
        return (_id == otherInstance._id && _personName == otherInstance._personName);
    }
}

or add extension method if you can't change the MyClass implementation, and compare using reflection as CodeInChaos described:
static class MyClassExtensions
{
    public static bool IsEqual(this MyClass myInstance, MyClass otherInstance)
    {
       // Reflection goes here - read all private field from myInstance
       // and otherInstance and compare them
    }
}


text:
Q: Parsing JSONArray when no key is present using restassured i am using restassured to test my rest APIs and I have a scenario where my rest API returns a JSONArray without any key value like below. While browsing through multiple questions i havent seen similar JSONArray handled without key value. Verifying such a JSON is supported by RestAssured ?
[
    "Test_1 Bundle_01",
     "Test_2 Bundle_02",
     "Test_3 Bundle_03"
    ]

A: Found a way to do this by using jsonpath.
List<String> newlist = JsonPath.with(response.asInputStream()).get("$");
System.out.println(newlist.get(0).toString());

By using jsonpath and storing the response in a list of string, individual string can be accessed easily.


text:
Q: How to use OCR module in a pdftron node js app? I want to use OCR module in my node app, but I don't see full documentation on that. There are some code snippets available for the functionality but I am not sure how to add the module in a node app (I didn't find any npm packages for the OCR module). I am using the @pdftron/pdfnet-node in my app.

A: You will first need to download the OCR module from the PDFTron website.
Once you have downloaded and extracted the module to a directory where your program can access it, you will need to call the addResourceSearchPath() method to pass the location of the module to the SDK.
Please see the OCR sample here for reference.


text:
Q: Is there any way to use Spring MVC 3.1 (particullary, RedirectAttributes) with Spring 3.0.5? It's so frustating, but I cannot upgrade Spring core to 3.1, only MVC.
The thing is that I need to use Flash Attributes after a redirect.
Or maybe there's a "howto" to do the same as RedirectAttributes, in Spring 3.0.
Thank you so much!

A: You can just implement it yourself.
For the flash request attributes, add them to the session with a special flag attribute (a prefix in their string key value), like REDIRECT_HAPPENING_<attributeName>.
Then create an interceptor that checks if you have any attributes named that way in the session. If you do, add them as request attributes (and remove them from the session - you can do this in postHandle()), otherwise return.


text:
Q: Is there a specific reason for not being able to assign values in 2D vector unlike of 1D vector I understand that we can insert values in 2D vector as  vec[i].push_back(value) but I was trying to insert value in the 2D vector as  vec[i][j] = value , but it was giving the error :
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Ideally when we use a 1D vector we can assign values like  a[i] = value . But in 2D vectors why does C++ not allow assignment of values in 2D vector like this.
#include<iostream>
#include<vector>
using namespace std;
int main(){
    vector<vector<int>> v;
    int i,j,n = 3,m = 4,num;
    for(i=0;i < n;i++){
        for(j=0;j<m;j++){
            cin>>num;
            v[i][j] = num;
        }
    }
    for(i=0;i < n;i++){
        for(j=0;j<m;j++){
            cout<<v[i][j]<<" ";
        }
        cout<<endl;
    }
}

If it was a 2D array. We could do this operaion. But, why not in a vector. Can you please refer me a material to read about it ?


text:
Q: Is there any way to permanently crop a PDF without decreasing its quality? I scanned a document and would like to crop out around half of the image.
I can crop using Preview or using Adobe Acrobat Pro. But neither program permanently crops the file. The file size never decreases.

*

*I tried using "Remove Hidden Information" on Adobe Acrobat Pro which was able to permanently crop the file. After the process completed, I clicked Save which opened a new Save As prompt. So, I re-saved the document, but the file size grew tenfold. No idea why.

*I tried exporting to Optimized PDF on Adobe Acrobat Pro and the PDF was still not permanently cropped.

*I tried exporting to Reduced Size PDF on Adobe Acrobat Pro and the PDF was permanently cropped, but the image quality was decreased.
Are there seriously no options to remove the cropped area without exporting the file as TIFF and importing the TIFF files to create a new PDF file or ->Print->Save As PDF? I don't want to do these because the image quality will decrease.
And why is such a basic task so difficult?

A: Cropping (in Acrobat) is non-destructive, as you noted.
If you really want to permanently cut away parts of your scan, it would be better to open the file in an image processing software, do the cutting away (aka cropping) there and resave as PDF (or TIFF, and then bring back to Acrobat for a PDF).
If you do not change the image resolution, the image quality will remain.


text:
Q: how to render a data table from XML file in codeIgniter? I am new in codeIgniter.
I want to render a data table from an external XML file.
Suppose I have an external xml file which is having
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<defect-data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <record>
        <DefectID>40580</DefectID>
        <Status>Open</Status>
        <DetectedOn>42110</DetectedOn>
        <AssignedTo>Bimal kumar</AssignedTo>
        <AssignedToCTSOff>Amit</AssignedToCTSOff>
    </record>
    <record>
        <DefectID>41580</DefectID>
        <Status>Close</Status>
        <DetectedOn>42110</DetectedOn>
        <AssignedTo>eve ram</AssignedTo>
        <AssignedToCTSOff>Sourav</AssignedToCTSOff>
    </record>
</defect-data>

I want to render this XML in html data table.
Is there any readymade way in codeIgniter to achieve this?
thanks in advance

A: No.  CodeIgniter provides help with converting strings into XML safe strings, but nothing for parsing it the other way round.
However, PHP does have SimpleXML which can be used to parse XML for you to use.  You can use that within CodeIgniter to manipulate the XML as you need.


text:
Q: Strange behavior from V8's usage of v8::EmbedderHeapTracer I'm having a bit of a hard time with using the v8::EmbedderHeapTracer API with V8 version 6.3.
My issue is the following sequence of events happening in the following order:

*

*V8 will call TracePrologue.

*V8 will register a V8 reference for embedder field pointer with RegisterV8References.

*Optional: I have tried both calling and not calling RegisterExternalReference on the object the embedder field is stored in here.  Intuitively, I would expect this to be redundant information, as V8 has already detected it as reachable, but I have tried calling it out of paranoia.

*I will add pointer to my frontier (e.g. the stack for DFS traversal of the embedder heap).

*V8 will then run the SetWeak callback on the v8::Persistent<v8::Object> that it just registered before.  This will cause me to delete the object.

*Note that neither EnterFinalPause nor TraceEpilogue have been called yet.

*pointer is removed from the frontier, and I attempt to expand it.  This results in a heap use after free (detected by ASan).

Is objects that are determined to be reachable being deleted within the same GC cycle something that I should have to be worried about?  I would have thought that anything that has RegisterExternalReference called on it would be kept alive until at least the next GC cycle.
Additional information:
ASan dump:
=================================================================
==184290==ERROR: AddressSanitizer: heap-use-after-free on address 0x60c0001687c0 at pc 0x0000053ad97e bp 0x7f36d0676f30 sp 0x7f36d0676f28
READ of size 8 at 0x60c0001687c0 thread T30 (MainWebModule)
    #0 0x53ad97d in cobalt::script::v8c::V8cHeapTracer::AdvanceTracing(double, v8::EmbedderHeapTracer::AdvanceTracingActions) out/linux-x64x11-v8_debug/../../cobalt/script/v8c/v8c_heap_tracer.cc:76:16
    #1 0x675d8e2 in v8::internal::LocalEmbedderHeapTracer::Trace(double, v8::EmbedderHeapTracer::AdvanceTracingActions) out/linux-x64x11-v8_debug/../../v8/src/heap/embedder-tracing.cc:45:26
    #2 0x67975e7 in v8::internal::MarkCompactCollector::ProcessEphemeralMarking(bool) out/linux-x64x11-v8_debug/../../v8/src/heap/mark-compact.cc:1847:46
    #3 0x678ed88 in v8::internal::MarkCompactCollector::MarkLiveObjects() out/linux-x64x11-v8_debug/../../v8/src/heap/mark-compact.cc:2558:7
    #4 0x678d983 in v8::internal::MarkCompactCollector::CollectGarbage() out/linux-x64x11-v8_debug/../../v8/src/heap/mark-compact.cc:525:3
    #5 0x66ab63d in v8::internal::Heap::MarkCompact() out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1684:29
    #6 0x66a835f in v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1557:9
    #7 0x66a6c48 in v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1216:11
    #8 0x66a4b78 in v8::internal::Heap::CollectAllGarbage(int, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1069:3
    #9 0x66a4725 in v8::internal::Heap::HandleGCRequest() out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:993:5
    #10 0x659cb9a in v8::internal::StackGuard::HandleInterrupts() out/linux-x64x11-v8_debug/../../v8/src/execution.cc:480:23
    #11 0x710ac22 in v8::internal::__RT_impl_Runtime_StackGuard(v8::internal::Arguments, v8::internal::Isolate*) out/linux-x64x11-v8_debug/../../v8/src/runtime/runtime-internal.cc:306:34
    #12 0x710a4f3 in v8::internal::Runtime_StackGuard(int, v8::internal::Object**, v8::internal::Isolate*) out/linux-x64x11-v8_debug/../../v8/src/runtime/runtime-internal.cc:296:1
    #13 0x7f36af5047a3  (<unknown module>)

0x60c0001687c0 is located 0 bytes inside of 120-byte region [0x60c0001687c0,0x60c000168838)
freed by thread T30 (MainWebModule) here:
    #0 0x2308fd2 in operator delete(void*) (out/linux-x64x11-v8_debug/cobalt+0x2308fd2)
    #1 0x3b532d1 in cobalt::dom::KeyboardEvent::~KeyboardEvent() out/linux-x64x11-v8_debug/../../cobalt/dom/keyboard_event.h:99:29
    #2 0x238f94c in base::RefCounted<cobalt::script::Wrappable>::Release() const out/linux-x64x11-v8_debug/../../base/memory/ref_counted.h:91:7
    #3 0x24ced4f in scoped_refptr<cobalt::script::Wrappable>::~scoped_refptr() out/linux-x64x11-v8_debug/../../base/memory/ref_counted.h:249:13
    #4 0xb928ca2 in cobalt::script::v8c::WrapperPrivate::~WrapperPrivate() out/linux-x64x11-v8_debug/../../cobalt/script/v8c/wrapper_private.h:86:3
    #5 0xb9285ba in cobalt::script::v8c::WrapperPrivate::Callback(v8::WeakCallbackInfo<cobalt::script::v8c::WrapperPrivate> const&) out/linux-x64x11-v8_debug/../../cobalt/script/v8c/wrapper_private.h:38:5
    #6 0x667f45c in v8::internal::GlobalHandles::PendingPhantomCallback::Invoke(v8::internal::Isolate*) out/linux-x64x11-v8_debug/../../v8/src/global-handles.cc:848:3
    #7 0x6680408 in v8::internal::GlobalHandles::DispatchPendingPhantomCallbacks(bool) out/linux-x64x11-v8_debug/../../v8/src/global-handles.cc:813:16
    #8 0x668084b in v8::internal::GlobalHandles::PostGarbageCollectionProcessing(v8::internal::GarbageCollector, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/global-handles.cc:869:18
    #9 0x66a8a7b in v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1601:37
    #10 0x66a6c48 in v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) out/linux-x64x11-v8_debug/../../v8/src/heap/heap.cc:1216:11
    #11 0x65bdfc9 in v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) out/linux-x64x11-v8_debug/../../v8/src/factory.cc:91:3
    #12 0x710c27d in v8::internal::__RT_impl_Runtime_AllocateInNewSpace(v8::internal::Arguments, v8::internal::Isolate*) out/linux-x64x11-v8_debug/../../v8/src/runtime/runtime-internal.cc:322:31
    #13 0x710b9c3 in v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) out/linux-x64x11-v8_debug/../../v8/src/runtime/runtime-internal.cc:315:1
    #14 0x7f36af5047a3  (<unknown module>)
    #15 0x7f36af5513fb  (<unknown module>)
    #16 0x7f36af5be594  (<unknown module>)
    #17 0x7f36af5b583e  (<unknown module>)
    #18 0x7f36af5be594  (<unknown module>)
    #19 0x7f36af5b583e  (<unknown module>)
    #20 0x7f36af5be594  (<unknown module>)
    #21 0x7f36af5bb818  (<unknown module>)
    #22 0x7f36af5040fe  (<unknown module>)
    #23 0x6599b9a in v8::internal::(anonymous namespace)::Invoke(v8::internal::Isolate*, bool, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, int, v8::internal::Handle<v8::internal::Object>*, v8::internal::Handle<v8::internal::Object>, v8::internal::Execution::MessageHandling) out/linux-x64x11-v8_debug/../../v8/src/execution.cc:146:13
    #24 0x6598454 in v8::internal::(anonymous namespace)::CallInternal(v8::internal::Isolate*, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, int, v8::internal::Handle<v8::internal::Object>*, v8::internal::Execution::MessageHandling) out/linux-x64x11-v8_debug/../../v8/src/execution.cc:182:10
    #25 0x6597dd6 in v8::internal::Execution::Call(v8::internal::Isolate*, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, int, v8::internal::Handle<v8::internal::Object>*) out/linux-x64x11-v8_debug/../../v8/src/execution.cc:192:10
    #26 0x54a5627 in v8::Function::Call(v8::Local<v8::Context>, v8::Local<v8::Value>, int, v8::Local<v8::Value>*) out/linux-x64x11-v8_debug/../../v8/src/api.cc:5449:7
    #27 0xb96677e in cobalt::dom::V8cEventListener::HandleEvent(scoped_refptr<cobalt::script::Wrappable> const&, scoped_refptr<cobalt::dom::Event> const&, bool*) const out/linux-x64x11-v8_debug/gen/bindings/browser/source/cobalt/dom/v8c_event_listener.cc:90:20
    #28 0x3a2962b in cobalt::dom::EventListener::HandleEvent(scoped_refptr<cobalt::dom::Event> const&, cobalt::dom::EventListener::Type) const out/linux-x64x11-v8_debug/../../cobalt/dom/event_listener.cc:95:7
    #29 0x3a1e705 in cobalt::dom::EventTarget::FireEventOnListeners(scoped_refptr<cobalt::dom::Event> const&) out/linux-x64x11-v8_debug/../../cobalt/dom/event_target.cc:200:31

previously allocated by thread T30 (MainWebModule) here:
    #0 0x23083d2 in operator new(unsigned long) (out/linux-x64x11-v8_debug/cobalt+0x23083d2)
    #1 0x24b530b in cobalt::browser::WebModule::Impl::InjectKeyboardEvent(scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&) out/linux-x64x11-v8_debug/../../cobalt/browser/web_module.cc:791:7
    #2 0x253ca5e in base::internal::RunnableAdapter<void (cobalt::browser::WebModule::Impl::*)(scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&)>::Run(cobalt::browser::WebModule::Impl*, scoped_refptr<cobalt::dom::Element> const&, base::Token const&, cobalt::dom::KeyboardEventInit const&) out/linux-x64x11-v8_debug/../../base/bind_internal.h:317:12
    #3 0x2556929 in base::internal::InvokeHelper<false, void, base::internal::RunnableAdapter<void (cobalt::browser::WebModule::Impl::*)(scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&)>, void (cobalt::browser::WebModule::Impl*, cobalt::dom::Element*, base::Token const&, cobalt::dom::KeyboardEventInit const&)>::MakeItSo(base::internal::RunnableAdapter<void (cobalt::browser::WebModule::Impl::*)(scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&)>, cobalt::browser::WebModule::Impl*, cobalt::dom::Element*, base::Token const&, cobalt::dom::KeyboardEventInit const&) out/linux-x64x11-v8_debug/../../base/bind_internal.h:966:14
    #4 0x25565d6 in base::internal::Invoker<4, base::internal::BindState<base::internal::RunnableAdapter<void (cobalt::browser::WebModule::Impl::*)(scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&)>, void (cobalt::browser::WebModule::Impl*, scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&), void (base::internal::UnretainedWrapper<cobalt::browser::WebModule::Impl>, scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit)>, void (cobalt::browser::WebModule::Impl*, scoped_refptr<cobalt::dom::Element>, base::Token, cobalt::dom::KeyboardEventInit const&)>::Run(base::internal::BindStateBase*) out/linux-x64x11-v8_debug/../../base/bind_internal.h:1571:12
    #5 0x2322063 in base::Callback<void ()>::Run() const out/linux-x64x11-v8_debug/../../base/callback.h:412:12
    #6 0x25d3932 in MessageLoop::RunTask(base::PendingTask const&) out/linux-x64x11-v8_debug/../../base/message_loop.cc:548:21
    #7 0x25d41f9 in MessageLoop::DeferOrRunPendingTask(base::PendingTask const&) out/linux-x64x11-v8_debug/../../base/message_loop.cc:560:5
    #8 0x25d451e in MessageLoop::DoWork() out/linux-x64x11-v8_debug/../../base/message_loop.cc:744:13
    #9 0x25f1e1b in base::MessagePumpDefault::Run(base::MessagePump::Delegate*) out/linux-x64x11-v8_debug/../../base/message_pump_default.cc:31:31
    #10 0x25d2648 in MessageLoop::RunInternal() out/linux-x64x11-v8_debug/../../base/message_loop.cc:491:10
    #11 0x25d23f4 in MessageLoop::RunHandler() out/linux-x64x11-v8_debug/../../base/message_loop.cc:463:3
    #12 0x265e81f in base::RunLoop::Run() out/linux-x64x11-v8_debug/../../base/run_loop.cc:47:10
    #13 0x25d0cbc in MessageLoop::Run() out/linux-x64x11-v8_debug/../../base/message_loop.cc:363:12
    #14 0x26f2398 in base::Thread::Run(MessageLoop*) out/linux-x64x11-v8_debug/../../base/threading/thread.cc:159:17
    #15 0x26f28a3 in base::Thread::ThreadMain() out/linux-x64x11-v8_debug/../../base/threading/thread.cc:212:5
    #16 0x26e58bc in base::(anonymous namespace)::ThreadFunc(void*) out/linux-x64x11-v8_debug/../../base/threading/platform_thread_starboard.cc:44:13
    #17 0x2d1f982 in (anonymous namespace)::ThreadFunc(void*) out/linux-x64x11-v8_debug/../../starboard/shared/pthread/thread_create.cc:73:10
    #18 0x7f37370ab183 in start_thread /build/eglibc-ripdx6/eglibc-2.19/nptl/pthread_create.c:312

Thread T30 (MainWebModule) created by T0 here:
    #0 0x22c381d in __interceptor_pthread_create (out/linux-x64x11-v8_debug/cobalt+0x22c381d)
    #1 0x2d1f489 in SbThreadCreate out/linux-x64x11-v8_debug/../../starboard/shared/pthread/thread_create.cc:124:12
    #2 0x26e5504 in base::(anonymous namespace)::CreateThread(unsigned long, SbThreadPriority, int, bool, char const*, base::PlatformThread::Delegate*, unsigned long*) out/linux-x64x11-v8_debug/../../base/threading/platform_thread_starboard.cc:59:21
    #3 0x26e5787 in base::PlatformThread::CreateWithOptions(base::PlatformThread::PlatformThreadOptions const&, base::PlatformThread::Delegate*, unsigned long*) out/linux-x64x11-v8_debug/../../base/threading/platform_thread_starboard.cc:142:10
    #4 0x26f195e in base::Thread::StartWithOptions(base::Thread::Options const&) out/linux-x64x11-v8_debug/../../base/threading/thread.cc:96:8
    #5 0x24bb450 in cobalt::browser::WebModule::WebModule(GURL const&, base::ApplicationState, base::Callback<void (cobalt::layout::LayoutManager::LayoutResults const&)> const&, base::Callback<void (GURL const&, std::string const&)> const&, base::Callback<void (base::TimeDelta)> const&, base::Callback<void ()> const&, cobalt::media::CanPlayTypeHandler*, cobalt::media::WebMediaPlayerFactory*, cobalt::network::NetworkModule*, cobalt::math::Size const&, float, cobalt::render_tree::ResourceProvider*, float, cobalt::browser::WebModule::Options const&) out/linux-x64x11-v8_debug/../../cobalt/browser/web_module.cc:1226:11
    #6 0x23495ab in cobalt::browser::BrowserModule::Navigate(GURL const&) out/linux-x64x11-v8_debug/../../cobalt/browser/browser_module.cc:519:25
    #7 0x2343f7c in cobalt::browser::BrowserModule::BrowserModule(GURL const&, base::ApplicationState, base::EventDispatcher*, cobalt::account::AccountManager*, cobalt::browser::BrowserModule::Options const&) out/linux-x64x11-v8_debug/../../cobalt/browser/browser_module.cc:372:3
    #8 0x23124f7 in cobalt::browser::Application::Application(base::Callback<void ()> const&, bool) out/linux-x64x11-v8_debug/../../cobalt/browser/application.cc:614:11
    #9 0x230cb48 in (anonymous namespace)::StartApplication(int, char**, char const*, base::Callback<void ()> const&) out/linux-x64x11-v8_debug/../../cobalt/browser/main.cc:78:25
    #10 0x230c0b2 in void cobalt::wrap_main::BaseEventHandler<&(anonymous namespace)::PreloadApplication, &(anonymous namespace)::StartApplication, &(anonymous namespace)::HandleStarboardEvent, &(anonymous namespace)::StopApplication>(SbEvent const*) out/linux-x64x11-v8_debug/../../cobalt/base/wrap_main_starboard.h:74:7
    #11 0x230b214 in SbEventHandle out/linux-x64x11-v8_debug/../../cobalt/browser/main.cc:105:1
    #12 0x2d246b4 in starboard::shared::starboard::Application::DispatchAndDelete(starboard::shared::starboard::Application::Event*) out/linux-x64x11-v8_debug/../../starboard/shared/starboard/application.cc:307:3
    #13 0x2d23685 in starboard::shared::starboard::Application::DispatchStart() out/linux-x64x11-v8_debug/../../starboard/shared/starboard/application.cc:194:3
    #14 0x2d2242b in starboard::shared::starboard::Application::RunLoop() out/linux-x64x11-v8_debug/../../starboard/shared/starboard/application.cc:382:5
    #15 0x2d228b8 in starboard::shared::starboard::Application::Run(starboard::shared::starboard::CommandLine) out/linux-x64x11-v8_debug/../../starboard/shared/starboard/application.cc:111:10
    #16 0x277ca1f in starboard::shared::starboard::Application::Run(int, char**) out/linux-x64x11-v8_debug/../../starboard/shared/starboard/application.h:166:12
    #17 0x277c849 in main out/linux-x64x11-v8_debug/../../starboard/linux/x64x11/main.cc:31:26
    #18 0x7f37360cff44 in __libc_start_main /build/eglibc-ripdx6/eglibc-2.19/csu/libc-start.c:287

SUMMARY: AddressSanitizer: heap-use-after-free out/linux-x64x11-v8_debug/../../cobalt/script/v8c/v8c_heap_tracer.cc:76:16 in cobalt::script::v8c::V8cHeapTracer::AdvanceTracing(double, v8::EmbedderHeapTracer::AdvanceTracingActions)
Shadow bytes around the buggy address:
  0x0c18800250a0: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
  0x0c18800250b0: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c18800250c0: fa fa fa fa fa fa fa fa fd fd fd fd fd fd fd fd
  0x0c18800250d0: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
  0x0c18800250e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 fa
=>0x0c18800250f0: fa fa fa fa fa fa fa fa[fd]fd fd fd fd fd fd fd
  0x0c1880025100: fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa fa
  0x0c1880025110: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fa
  0x0c1880025120: fa fa fa fa fa fa fa fa fd fd fd fd fd fd fd fd
  0x0c1880025130: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
  0x0c1880025140: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==184290==ABORTING

Log output (logging GC cycle begin/end, object marking, and the weak callback running):
$ cat log.txt | grep -P '(Begin|End|0x60c000199540)'
[0204/150945:INFO:v8c_heap_tracer.cc(53)] Begin GC cycle 1
[0204/151001:INFO:v8c_heap_tracer.cc(37)] 0x60c000199540 got registered by RegisterV8References during GC cycle 1
[0204/151001:INFO:v8c_heap_tracer.cc(172)] 0x60c000199540 got marked during GC cycle 1
[0204/151001:INFO:wrapper_private.h(78)] 0x60c000199540 is dying in GC cycle 1
==190737==ERROR: AddressSanitizer: heap-use-after-free on address 0x60c000199540 at pc 0x0000053ad9de bp 0x7fe4ebb76270 sp 0x7fe4ebb76268
READ of size 8 at 0x60c000199540 thread T30 (MainWebModule)
0x60c000199540 is located 0 bytes inside of 120-byte region [0x60c000199540,0x60c0001995b8)

A: With the default configuration V8 marks wrappers, i.e., objects pointing into embedder memory, incrementally.
The requirements are

*

*An v8::EmbedderHeapTracer implementation figuring out (transitive) liveness of V8 wrappers based on references passed to it from V8.

*Consistency mechanisms, .e.g., write barriers, when DOM is mutated during incremental marking.

*Informing V8's young generation garbage collector to keep v8::Persistent alive during incremental marking.

3 is probably subtle. The steps involved are:

*

*Register a callback for Scavenges using Isolate::AddGCPrologueCallback

*Visit weak persistent handles using Isolate::VisitWeakHandles

*Mark weak persistents as active using v8::PersistentBase<T>::MarkActive
Steps 2 and 3 can be omitted when turning off incremental tracing of wrappers using the flag incremental_marking_wrappers.


text:
Q: RFC-822 DateTime Formatting in PHP with Database I have a date field on my database. the date format as following.
June 17, 2013

Im using the format as
date("F j, Y");

So my question is there a way that i can display this date in RFC-822 format using php? or do i need to start saving the date in RFC-822 format from now on? Thanks in advance.

A: Using the following syntax, you can display current time in RFC822 Format.
$date = new DateTime('2000-01-01');
echo $date->format(DateTime::RFC822);

A: Neither.
From now on you have to start using format supplied by database.
You have to understand the difference between storage format and display formatting. It's different matters. When storing data in mysql, you have to follow mysql rules. So, instead of June 17, 2013 you have to store 2013-06-17.
And then convert at output to whatever format required - not limited to a single one but whatever format is demanded by destination.

A: None of the other answers worked for me, so this is what worked... to take a date in PHP and output it in RFC822:
date("D, d M Y G:i:s T", strtotime($date));

Hope that helps others.

A: As was pointed out your best bet is to change the way you are storing your dates to something other then a string.  date("Y-m-d", strtotime($date)) can assist you in this endeavor.
But to solve the immediate need you can utilize use strtotime, date and the DATE_RFC822 constant to get you what you are looking for.
echo date(DATE_RFC822, strtotime($value));

See First example on php date documentation

A: As @ashleedawg and others mentioned in some comments the simplest solution that works:
date("D, d M Y H:i:s O", strtotime($date));

Mind the "H" and the "O" ;)
Thanks!

A: If you want to date format something in PHP for RFC-822 , then just do this...
date('r', strtotime($date))

'r'  » RFC 2822 formatted date   Example: Thu, 21 Dec 2000 16:01:07 +0200

Source: PHP.net: DateFormat
But, as other stated, you don't want to store this in your database!  However, you'll need to use r for other things, like XML-RSS date time formats...

All date-times in RSS conform to the Date and Time Specification of RFC 822... (Source: RSS 2.0 Specification.)

A: date_format(date(your database field), '%D, %j %M %t')
and what type of format you want just see the link
date and time format for Mysql

A: You can save it as TimeStamp in database and  show it RFC822 format
date(DATE_RFC822, time());

A: This is the only solution that worked for me:
date("D, d M Y H:i:s T", strtotime($date));

Other examples above that didn't work include using the DATE_RFC822 format specifier, which puts out a 2-digit year, instead of 4 digits. Then the other suggestion to use G:i:s for time doesn't work because G specifies no leading zeroes, so you'll get 2:00:00 instead of 02:00:00.

A: don't use T at the end but an "O", it works for me


text:
Q: MongoDB Match Engine in Javascript Context:
I have a nodejs app which is inserting documents to a mongoDB.
I have users who create custom queries to this mongodb to find documents. I also use change streams to live feed updates to them.
I'm using the mongodb 3.6.2 nodejs driver.
Question:
It could be possible for me to remove the change streams if I could check if the document I was inserting matched one of my user's queries.
For example, let's say a user was interested in documents that matched the query { "foo": "bar" }. If I insert a document { "baz": 1, "foo": "bar" }, I could send that document down the wire to the user and not need to rely on my change stream to listen for the insert.
Is there any way for me (in javascript) to match an object against a query so that I don't need to rely on my change stream?
EDIT

*

*minimongo might be an option for me? It looks like they're just using lodash after transforming the selector.

*I could also use the minimongo package from meteor.js which the above was inspired / forked from. var matcher = new Minimongo.Matcher({a: {$gt: 5}}); if (matcher.documentMatches({a: 7})) ...

A: I ended up going with minimongo
import minimongo from 'minimongo';

const query = { ... }
const docForInsert = { ... }

const found = minimongo.utils.processFind([docForInsert], query)

if (found?.length) {
   ...
}


text:
Q: ListView Adapter Crashes Activity As in the subcjet. When I comment listView.setAdapter(adapter); it just shows another activity:
This is whole onCreate:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista__klas);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        klasy = getResources().getStringArray(R.array.klasy);

        ListView listView = (ListView)findViewById(R.id.lista_klas);
        adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_lista__klas);
        listView.setAdapter(adapter);
    }

And here log from logcat when I press button which starts this activity:
11-20 13:14:53.085    1494-1780/system_process I/ActivityManager﹕ START {cmp=pl.krasiniak.krachapp_beta/.Lista_Klas} from pid 3975
11-20 13:14:53.335    3975-3975/pl.krasiniak.krachapp_beta D/AndroidRuntime﹕ Shutting down VM
11-20 13:14:53.335    3975-3975/pl.krasiniak.krachapp_beta W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a521f8)
11-20 13:14:53.345    3975-3975/pl.krasiniak.krachapp_beta E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.krasiniak.krachapp_beta/pl.krasiniak.krachapp_beta.Lista_Klas}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2079)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
            at android.app.ActivityThread.access$600(ActivityThread.java:132)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4575)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at pl.krasiniak.krachapp_beta.Lista_Klas.onCreate(Lista_Klas.java:34)
            at android.app.Activity.performCreate(Activity.java:4465)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
            at android.app.ActivityThread.access$600(ActivityThread.java:132)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4575)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
            at dalvik.system.NativeStart.main(Native Method)
11-20 13:14:53.355    1494-1675/system_process W/ActivityManager﹕ Force finishing activity pl.krasiniak.krachapp_beta/.Lista_Klas
11-20 13:14:53.355    1494-1675/system_process W/ActivityManager﹕ Force finishing activity pl.krasiniak.krachapp_beta/.MainActivity
11-20 13:14:53.865    1494-1509/system_process W/ActivityManager﹕ Activity pause timeout for ActivityRecord{40ef3f48 pl.krasiniak.krachapp_beta/.Lista_Klas}
11-20 13:14:54.065    3215-3215/com.cyanogenmod.trebuchet W/Adreno200-EGLSUB﹕ SetSwapInterval() interval: 0 not set
11-20 13:14:54.105    1494-1506/system_process I/ActivityManager﹕ No longer want com.android.keychain (pid 3950): hidden #16
11-20 13:15:04.105    1494-1509/system_process W/ActivityManager﹕ Activity destroy timeout for ActivityRecord{40ebf3c0 pl.krasiniak.krachapp_beta/.MainActivity}
11-20 13:15:04.105    1494-1509/system_process W/ActivityManager﹕ Activity destroy timeout for ActivityRecord{40ef3f48 pl.krasiniak.krachapp_beta/.Lista_Klas}

I'm sure array isn't empty. Thank you for answers, greetings :)

A: The code cannot be correct:
setContentView(R.layout.activity_lista__klas);

// ...

ListView listView = (ListView)findViewById(R.id.lista_klas);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_lista__klas);

The same layout is used for both content view and array adapter. When the two-argument constructor of ArrayAdapter is used, the resource id must resolve to a single TextView. The findViewById() call implies it is a more complex layout with a ListView.
If I understand your intention correctly, do the following:

*

*Make sure activity_list__klas contains a ListView with the specified id lista_klas so that the findViewById() returns non-null.

*Change the layout resource id of the adapter constructor to a resource file that contains a single TextView that represents your list row. Or change to another constructor overload that allows you to specify the TextViews where array items are mapped.

*Provide some data to the adapter to actually show something.

A: Try this. Add third parameter
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.activity_lista__klas,klasy);

If this did not work. Please paste your layout file too.

A: I'm guessing your problem is here:
ListView listView = (ListView)findViewById(R.id.lista_klas);

Check that you have a ListView with this ID and that listView is not null.
Also, when you create the adapter you need to pass the ArrayAdapter a layout file that contains a single TextView to use to display each list item. You've passed the same layout that you've used in setContentView which (I assume) is the complete layout for your activity.


text:
Q: How to clear the inputs in function using React bootstrap typeahead I am trying the clear the inputs in the function using following code.
import {Typeahead} from 'react-bootstrap-typeahead';

type requestState={
  value:string[]
}

class Data extends Component<{},requestState> {
  constructor(props){
    super(props);
    this.state = {
      value: [],
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.typeahead.getInstance().clear();
  }

  render() {
    return(
      <Typeahead
        ref={(ref) => this.typeahead = ref}
        id="data"
        labelKey="data"
        multiple={true}
        options={this.state.values}
        placeholder="Choose a data.."
        onChange={(e) => this.handleChange(e)}
      />
    );
  }
}

export default Data;

When I try using this code to clear the inputs at once, I am getting following error: "Property 'typeahead' does not exist on type 'Data'".
Could someone help me how to define typeahead property and what changes have to do to get this working.

A: This is a react ref issue and you just need to define the ref for use first.
Using classical definition:
class Data extends Component<{},requestState> {
  constructor(props){
    super(props);
    this.state = {
      value: [],
    }
    this.handleChange = this.handleChange.bind(this);

    this.typeahead = null;
  }

  handleChange(e) {
    this.typeahead.getInstance().clear();
  }

  render() {
    return(
      <Typeahead
        ref={(ref) => this.typeahead = ref}
        id="data"
        labelKey="data"
        multiple={true}
        options={this.state.values}
        placeholder="Choose a data.."
        onChange={(e) => this.handleChange(e)}
      />
    );
  }
}

Using React.createRef
class Data extends Component<{},requestState> {
  constructor(props){
    super(props);
    this.state = {
      value: [],
    }
    this.handleChange = this.handleChange.bind(this);

    this.typeahead = createRef<Typeahead>();
  }

  handleChange(e) {
    this.typeahead.current.getInstance().clear();
  }

  render() {
    return(
      <Typeahead
        ref={this.typeahead}
        id="data"
        labelKey="data"
        multiple={true}
        options={this.state.values}
        placeholder="Choose a data.."
        onChange={(e) => this.handleChange(e)}
      />
    );
  }
}

Refs and the DOM

A: This Changes worked for me in typescript to clear the inputs using React Bootstrap Typeahead
 import React, { Component } from 'react';
 import {Typeahead} from 'react-bootstrap-typeahead';

 class Data extends Component<{},requestState> {
 typeahead = React.createRef<Typeahead>();
 constructor(props){
 super(props);
   this.state = {
    value: [],
   }
   this.handleChange = this.handleChange.bind(this);

   }

  handleChange(e) {
    this.typeahead.current.state.selected= []
  }

  render() {
   return(
    <Typeahead
    ref={this.typeahead}
    id="data"
    labelKey="data"
    multiple={true}
    options={this.state.values}
    placeholder="Choose a data.."
    onChange={(e) => this.handleChange(e)}
    />
  );
 }
}
export default Data;


text:
Q: how does asp.net url routing\directing works? I was handed over an CLASSIC asp.net site.
I have troubles figuring out the url direction methods.
For exmaple:
      http://localhost/siteName/Story/1/some+title
no .aspx or other extension.
I know MVC routing and I worked a bit with webforms but can't remember there was routing.
I appreciate any kind of assistance. Even what to look for.
Thanks in advance!

A: ASP.NET MVC attempts to abstract the file type and file locations away from the user.
In many cases, ASP.NET MVC applications do not modify the routing defaults.
In this case, you typically see this:
The Route = SiteName/Controller/Route/OptionalParameters
In your case, you can find the files like so:
In the siteName Project, look for the view (html,css,js) in the Views/Story folder.
Look for the server code in the Controller/StoryController.cs file.
The routing definition can be in one of two places:
Pre-MVC4: global.asax
MVC 4 and above: App_Start/RouteConfig.cs


text:
Q: JavaScript Функция и console.log() Почему два подобных экземпляра кода, которые, по логике, должны иметь одинаковые исходные результаты, дают разные исходные результаты?
function rectangleArea(width, height) {
 console.log(width * height);
}

rectangleArea(5, 7)
//Output 35

и
function rectangleArea(width, height) {
 console.log(width * height);
}

console.log(rectangleArea(5, 7))
// prints 35 и undefined

A: Функция, которая не возвращает ничего, на самом деле по умолчанию возвращает undefined. Так что во втором примере консоль в виде возвращаемого значения получает его и выводит.
Если надо результат напечатать в консоли, то надо этот результат вернуть из функции. А этим занимается ключевое слово return (что  в переводе с английского будет "вернуть"), а не console.log


text:
Q: AWK variable retains its value after piping output into it from system() I want to print the line containing the IP address (may be absent) from the output of: ifconfig $1
Nothing should be printed (output should be empty) if the command returns nothing.
Here's the command I am using:
echo -e "wlan2 \n eth3" | awk '{
                          command = "ifconfig " $1 " | grep \"inet addr\" ";

                          command | getline output;
                          print $1 output;
                               }'

Output:
wlan2          inet addr:192.168.0.104  Bcast:192.168.0.255  Mask:255.255.255.0
eth3          inet addr:192.168.0.104  Bcast:192.168.0.255  Mask:255.255.255.0

In this case, wlan2 has an IP, eth3 does not have an IP. But the same line gets printed for eth3.
Question: How to find out if the output of the command is nothing? Or make sure that variable output does not retain its previous value in subsequent iterations?

A: Assuming that you do have a genuine reason to do this in awk (at the moment, it looks like you could do this using the shell), you need to make a couple of changes:
awk '{ command = "ifconfig " $1 " | grep \"inet addr\" " }
     command | getline output > 0  { print $1, output }
     { close(command) }'

By checking the return value of getline, we can only print the line when it is successful. It is also important to use close so that the pipe isn't left open, as this will lead to problems with larger inputs or repeated lines.
It seems like piping to grep within awk is a bit of an anti-pattern, so you might be better off doing the pattern matching in awk itself:
awk '{ command = "ifconfig " $1
     while (command | getline output > 0) if (output ~ /inet addr/) print $1, output }
     { close(command) }'

A while loop is used to read all of the output of ifconfig. If a match is found, the line is printed.


text:
Q: Login token with React I'm in the process of wiring up Log In functionality with React and am running into issues with user session tokens.
Problem:
I'm able to successfully login and create a user session token (verified via console), however, once I refresh the page after successful login, it redirects me back to the log in page as if I do not have a token.
Why is this token issue appearing? Is it even a token issue?
I've coded react so that if !token, then direct to Log In form, and if there is a token, then redirect to placeholder ('account')
import React, { Component } from 'react';
import { Form, Container, Button, Spinner } from 'react-bootstrap'
import { getFromStorage, setInStorage } from '../utils/storage'

export default class LoginUser extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      token: '',
      logInError: '',
      logInEmail: '',
      logInPassword: '',
    }

    this.onChangeLogInEmail = this.onChangeLogInEmail.bind(this);
    this.onChangeLogInPassword = this.onChangeLogInPassword.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.logout = this.logout.bind(this);

  }

  componentDidMount() {
    const obj = getFromStorage('OI_Login')
    if (obj && obj.token) {
      const { token } = obj
      // verify token
      fetch('http://localhost:5001/users/verify?token' + token)
        .then(res => res.json())
        .then(json => {
          if (json.success) {
            this.setState({
              token,
              isLoading: false
            })
          } else {
            this.setState({
              isLoading: false
            })
          }
        })

    } else {
      this.setState({
        isLoading: false,
      })

    }
  }

  // ON CHANGE
  onChangeLogInEmail(e) {
    this.setState({
      logInEmail: e.target.value
    })
  }

  onChangeLogInPassword(e) {
    this.setState({
      logInPassword: e.target.value
    })
  }

  logout(e) {
    e.preventDefault()
    this.setState({
      isLoading: true,
    })
    const obj = getFromStorage('OI_Login')
    if (obj && obj.token) {
      const { token } = obj
      // verify token
      fetch('http://localhost:5001/users/logout?token' + token)
        .then(res => res.json())
        .then(json => {
          if (json.success) {
            this.setState({
              token: '',
              isLoading: false,
              logInError: ''
            })
          } else {
            this.setState({
              isLoading: false
            })
          }
        })

    } else {
      this.setState({
        isLoading: false,
      })
    }
  }

  onSubmit(e) {
    e.preventDefault()
    const {
      logInEmail,
      logInPassword
    } = this.state

    this.setState({
      isLoading: true,
    })

    //post request to backend
    fetch('http://localhost:5001/users/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: logInEmail,
        password: logInPassword
      }),
    }).then(res => res.json())
      .then(json => {
        if (json.success) {
          setInStorage('OI_Login', { token: json.token })
          this.setState({
            logInError: json.message,
            isLoading: false,
            logInEmail: '',
            logInPassword: '',
            token: json.token
          })
        } else {
          this.setState({
            logInError: json.message,
            isLoading: false
          })
        }
      })

  }

  render() {
    const {
      isLoading,
      token,
      logInError,
      logInEmail,
      logInPassword,
    } = this.state

    if (isLoading) {
      return (
        <>

            <Spinner animation="border" />

        </>
      )
    }

    if (!token) {
      return (
        <>
          <Container>

Log In

            <Form>
              <Form.Group>
                <Form.Label>Email</Form.Label>
                <Form.Control
                  required
                  type="email"
                  id="email"
                  value={logInEmail}
                  onChange={this.onChangeLogInEmail}
                />
              </Form.Group>
              <Form.Group>
                <Form.Label>Password</Form.Label>
                <Form.Control
                  required
                  type="password"
                  id="password"
                  value={logInPassword}
                  onChange={this.onChangeLogInPassword}
                />
              </Form.Group>

                {
                  (logInError) ? (

{logInError}

                  ) : (null)
                }

              <Form.Group>
                <Button variant="btn btn-primary" onClick={this.onSubmit} type="submit">Log In</Button>
              </Form.Group>
            </Form>
            Register
          </Container>
        </>
      )
    }

      return (
        <>

Account

          <Button variant="danger" onClick={this.logout}>Log Out</Button>
        </>
      )

  }

}

Token storage
export function getFromStorage(key) {
  if (!key) {
    return null
  }

  try {
    const valueStr = localStorage.getItem(key)
    if (valueStr) {
      return JSON.parse(valueStr)
    }
    return null
  } catch (err) {
    return null
  }
}

export function setInStorage(key, obj) {
  if (!key) {
    console.error('Error: Key is missing')
  }

  try {
    localStorage.setItem(key, JSON.stringify(obj))
  } catch (err) {
    console.error(err)
  }

}

A: You need to save the token to the cookie when you got it.
And get the token from the cookie after page refreshing.


text:
Q: Monomorphism between abelian groups and quotient group Could someone help me with the following question?
Let be $A,B$ two abelian groups and $f:A\rightarrow{B}$ a monomorphism between them. What should we understand when we write the quotient group $A/B$? (we don't know if $B$ is a subgroup of $A$)
Thanks.


text:
Q: Tkinter add entry on basis of an answer of a OptionMenu I'm using TKinter (I'm new with GUI tools), and I would like to know if it is possible to add (or activate) a entry with base on the answer of a option menu. Below is a part of the code
from Tkinter import *

win=Tk()

Label(win, text="Is This a Data Cube?",font='20').grid(row=14, column=0,sticky=W)
DataCubeValue = StringVar(win)
DataCubeValue.set("False")
DataCube = OptionMenu(win,DataCubeValue,"True","False")
DataCube.grid(row=15, column=0,sticky=W)

If the answer is True is choosen I would like to display this:
Label(win, text="X and Y values (x,y)",font='20').grid(row=14, column=1,sticky=W)
XYValue = StringVar(win)
XYValue.set("10,7")
XY =  Entry(win,textvariable=XYValue)
XY.grid(row=15, column=1,sticky=W)

A: A central idea of GUI programming is to register code to be executed in reaction of user actions. Such code is usually named callback (the toolkit call it back depending on user actions on the interface).
You can bind to DataCubeValue changes with the following line. callback method (to be defined before) will be cause each time the value of DataCubeValue change.
DataCubeValue.trace("w", callback)

In the callback method, you can either choose to place the block of code with Label and Entry instantiation, but think that callback will be called every time the user change the OptionMenu value. You could either deactivate the OptionMenu once the user used it, but I would advise to  instantiate your widgets in the initial run, and just display or hide them from the callback.
def callback(*args):
    if DataCubeValue.get() == "True":
        label.grid(row=14, column=1,sticky=W)
        XY.grid(row=15, column=1,sticky=W)
    else:
        label.grid_forget()
        XY.grid_forget()


text:
Q: Ajax not capturing php contact form script I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:

                <form id="form" action="php/email.php" class="contactForm"
method="post">

                        <input type="text" class="form-control" name="name"
placeholder="Your Name" required="">

                        <input type="email" class="form-control"
name="email" placeholder="Your Email" required="">

                        <textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>

                    <input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">

                </form>

And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$success = "

Submission successful

Thank you for contacting us!

";

$to = "email@email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;

if(isset($_POST['g-recaptcha-response'])){
      $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
      echo '
Please check the the captcha form.
';
      exit;
    }
    $secretKey = "";
    $ip = $_SERVER['REMOTE_ADDR'];

$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
    $responseKeys = json_decode($response,true);

if (mail($to, $subject, $txt, $headers)) {
    echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>

What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.

A: Ok, I figured it out. I added  to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?

A: Change
$('#form').on('submit', function(e)

To
$('#form').on('submit', function(event)

Because you use
event.preventDefault();


text:
Q: Android ads doen't show up I've just finished developping my application and now I'm trying to make test ads show up in my application but it doesn't work, I've already added the required code to the gradle
Manifest
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.pc.wolrdwidefacts">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">

I've copying just the first part of the manifest because it's too long.
XML file
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/alcohol1"
tools:context=".alcohol1">
<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

<Button
    android:id="@+id/next_btn"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="218dp"
    android:background="@drawable/next" />

<Button
    android:id="@+id/menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/menu" />
   </RelativeLayout>

Acitivity code
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alcohol1);

    MobileAds.initialize(this,
            "ca-app-pub-3940256099942544/6300978111");

    mAdView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);


text:
Q: ActionScript - Clearing Graphics With JointStyle.MITER Bug? I've come across an undesirable effect of using JointStyle.MITER when clearing/redrawing graphics.
My project involves managing custom line graphics with both round and sharp edges, which is why I would like to use a miter joint style.
When the line thickness is greatly increased, even the round areas of the line are affected by the miter style.  While I find this unfortunate, it's understandable and not the bug I'm referring to.  the bug(?) occurs when decreasing the line thickness doesn't completely clear the graphics, as instructed to do so by the code each time the thickness changes, leaving artifacts of the line graphics where the line once was.  Artifacts are also left by sharp edges, not just rounded corners.
I'm using Flash Player version 10.1.53.64 on Mac OS X Snow Leopard (10.6.4).
You can test this by running my sample code below.  use the left and right keyboard arrows change the thickness of the stroke of a round rect.
Update:  The graphics artifacts are superficial.  Dragging the shape over their location after they appear will remove them.  Code updated with dragging functionality.
package
{
import flash.display.CapsStyle;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;

public class StrokeWidth extends Sprite
    {
    private var roundRect:Sprite = new Sprite();
    private var strokeThickness:Number = 6;

    public function StrokeWidth()
        {
        addEventListener(Event.ADDED_TO_STAGE, init);
        }

    private function init(evt:Event):void
        {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownEventListener);
        roundRect.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventListener);
        roundRect.addEventListener(MouseEvent.MOUSE_UP, mouseEventListener);

        drawRoundRect();
        roundRect.x = roundRect.y = 100;
        addChild(roundRect);
        }

    private function drawRoundRect():void
        {
        roundRect.graphics.clear();
        roundRect.graphics.lineStyle(strokeThickness, 0x000000, 1.0, true, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER);
        roundRect.graphics.beginFill(0xFF0000);
        roundRect.graphics.drawRoundRect(0, 0, 400, 200, 100);
        }

    private function mouseEventListener(evt:MouseEvent):void
        {
        switch  (evt.type)
                {
                case MouseEvent.MOUSE_DOWN: roundRect.startDrag();  break;
                case MouseEvent.MOUSE_UP:   roundRect.stopDrag();
                }
        }

    private function keyDownEventListener(evt:KeyboardEvent):void
        {
        switch  (evt.keyCode)
                {
                case Keyboard.LEFT:     strokeThickness -= 1;       break;
                case Keyboard.RIGHT:    strokeThickness += 1;
                }

        drawRoundRect();
        }
    }
}

A: interesting.  the problem was caused because the lineStyle's scale mode was set to none:
LineScaleMode.NONE

changing it to normal fixes the problem:
LineScaleMode.NORMAL

A: what about re-creating the shape?


text:
Q: How to generate all possible combinations Folder Prey has
    "Deer.txt",
    "Antelope.txt",
    "Rabbit.txt"
Folder Predator has
    "Shark.txt",
    "Bear.txt",
    "Cougar.txt"
Folder Habitat has
    "Forest.txt",
    "Ocean.txt",
    "Desert.txt"

How do I generate all 27 possible combinations using a .bat file?
The tricky part is the number of Folders is not static.  Someone may add a Folder Food later, or remove Folder Habitat.
Could a .bat file be written to handle this?
The output would be:
Deer_Shark_Forest
Deer_Shark_Ocean
Deer_Shark_Desert
Deer_Bear_Forest
Deer_Bear_Ocean
Deer_Bear_Desert
Deer_Cougar_Forest
Deer_Cougar_Ocean
Deer_Cougar_Desert
Antelope_Shark_Forest
Antelope_Shark_Ocean
Antelope_Shark_Desert
Antelope_Bear_Forest
Antelope_Bear_Ocean
Antelope_Bear_Desert
Antelope_Cougar_Forest
Antelope_Cougar_Ocean
Antelope_Cougar_Desert
Rabbit_Shark_Forest
Rabbit_Shark_Ocean
Rabbit_Shark_Desert
Rabbit_Bear_Forest
Rabbit_Bear_Ocean
Rabbit_Bear_Desert
Rabbit_Cougar_Forest
Rabbit_Cougar_Ocean
Rabbit_Cougar_Desert

Assure you this is not a homework question.
I'd like to write it as a batch file.

A: You can do this with the following batch file:
@echo off
setlocal enabledelayedexpansion
set first_pass=yes
copy nul temp2.txt > nul
for /d %%D in (*) do (
    for %%F in ("%%D"\*) do (
        if !first_pass! == yes (
            echo %%~nF >> temp2.txt
        ) else (
            for /f "delims=" %%L in (temp1.txt) do (
                echo %%~nF_%%L >> temp2.txt
            )
        )
    )
    set first_pass=no
    del temp1.txt 2> nul
    rename temp2.txt temp1.txt
)

This creates a file named temp1.txt.
(Of course the script can trivially be modified to use a different filename
and/or to display the results on the screen.)
This is the output I got:
Antelope_Bear_Desert
Antelope_Bear_Forest
Antelope_Bear_Ocean
Antelope_Cougar_Desert
Antelope_Cougar_Forest
Antelope_Cougar_Ocean
Antelope_Shark_Desert
Antelope_Shark_Forest
Antelope_Shark_Ocean
Deer_Bear_Desert
Deer_Bear_Forest
Deer_Bear_Ocean
Deer_Cougar_Desert
Deer_Cougar_Forest
Deer_Cougar_Ocean
Deer_Shark_Desert
Deer_Shark_Forest
Deer_Shark_Ocean
Rabbit_Bear_Desert
Rabbit_Bear_Forest
Rabbit_Bear_Ocean
Rabbit_Cougar_Desert
Rabbit_Cougar_Forest
Rabbit_Cougar_Ocean
Rabbit_Shark_Desert
Rabbit_Shark_Forest
Rabbit_Shark_Ocean

Notes:

*

*Obviously, this uses the * wildcard,
and so the order of the output depends on the order
in which Windows expands the wildcard.
On my system, given alphabetic directory entries,
* is expanded in alphabetic order.
This may be different on systems that use languages other than English,
and/or it may be changeable by configuration setting.
For the purpose of the next two bullets,
I will assume that alphabetic order is used.

*Within each folder, the names are in alphabetic order;
e.g., Antelope before Deer, etc…, Bear before Cougar, etc…, etc…

*In accordance with your desired output specified in your question,
the folders are output in reverse alphabetic order;
i.e., Prey_Predator_Habitat.

*Either of the above can be changed (although not elegantly).

*

*setlocal enabledelayedexpansion lets us handle variables in loops.

*copy nul temp2.txt > nul creates the second temporary working file.
The > nul suppresses the normal 1 file(s) copied. status message.

*for /d %%D in (*) do loops through all the folders
in the current directory.
The variable %%D will sequentially take on the values
Habitat, Predator, and Prey —
or whatever folders are in the current directory
when you run the batch file.

*for %%F in ("%%D"\*) do loops through all the files in directory %%D;
i.e., the directory we're currently looking at from the outer loop.
The variable %%F will sequentially take on values such as
Habitat\Desert.txt, Habitat\Forest.txt, and Habitat\Ocean.txt.
The quotes allow this to work even if the directory name contains space(s).
If there are other files in the folder, they will be included, too.
If you want to look only at .txt files,
change the for statement to for %%F in ("%%D"\*.txt) do.

*!first_pass! is just the variable first_pass.
It would normally be written %first_pass%,
but we need to use this syntax because we're in a loop.
(This works only because we enabled it,
with setlocal enabledelayedexpansion.)

*first_pass is yes while we are processing the first directory;
i.e., Habitat.
In this case we just write the filename to the temp2.txt file;
so, when the for %%F in ("%%D"\*) do loop completes, temp2.txt
will containDesertForestOceanbecause %%~nF
evaluates to only the base file name part of the file pathname in %%F.
If you want to include the .txt extensions,
use %%~nxF instead of %%~nF.

*Spoiler alert: when we execute the outer (for /d %%D)
for the second and third (etc.) time, first_pass is no
and temp1.txt is the temp2.txt from the previous pass.

*So, on the second and third (etc.) passes,
we execute for /f "delims=" %%L in (temp1.txt) do,
which loops through the lines in temp1.txt,
setting %%L to the contents of the lines.
"delims=" is an options string that specifies that the lines
should not be broken into words.
This allows this batch file to work even if the file names contain space(s).

*For example, on the second pass (%%D=Predator) of the outer loop,
when we do the first pass (%%F=Predator\Bear.txt) of the second loop,
temp1.txt is as shown above for temp2.txt, and temp2.txt is empty.

*For each line (%%L) from temp1.txt,
we do echo %%~nF_%%L >> temp2.txt,
which writes the current filename, an underscore _,
and the current line (from temp1.txt) into temp2.txt (appending).
Thus, after the first pass (Bear) of the second loop,
including a complete run of the third loop, temp2.txt
will containBear_DesertBear_ForestBear_Ocean
The second pass (Cougar) of the second loop will append
Cougar_DesertCougar_ForestCougar_Oceanto temp2.txt,
and so on.

*By the time we reach the third pass (%%D=Prey) of the outer loop,
temp1.txt is the temp2.txt from the previous pass,
containing nine lines (six of which are shown above).
Then the same thing happens (with different values) as before;
%%F gets set to Prey\Antelope.txt,
and so every line in temp1.txt gets copied to temp2.txt
with Antelope_ prepended, and we get

Antelope_Bear_DesertAntelope_Bear_ForestAntelope_Bear_Ocean
Antelope_Cougar_DesertAntelope_Cougar_Forest       ︙

*As foreshadowed, when we finish the second loop,
and get to the end of the first loop,
we set first_pass to no,
delete the current temp1.txt
(if any; if it doesn't exist yet, suppress the error message),
and rename temp2.txt to temp1.txt.

So, we end up with a file 27 lines long
(Num(Habitat) × Num(Predator) × Num(Prey)).
You can add and remove folders and files,
because nothing is hard-coded in the script —
not even the number of folders.

*

*If there is a folder (e.g., Job_Titles) that contains no files,
then there will be no output (because 3 × 0 × 3 × 3 = 0).
In fact,
in this case, the above batch file produces a bunch of error messages,
and either an empty temp1.txt file (expected behavior) or no file at all.
This can of course be fixed.

*This script has been designed to handle file or directory names
that contain space(s),
and has been tested in that situation (and it seems to work correctly),
but there may be some edge cases that I didn't consider.

*Inevitably, the output will be ambiguous
if any of the file names contain _ (underscore).
For example, Antelope_Mountain_Lion_Forest is ambiguous.

A: You can use PowerShell:
$categories = gci -Directory | % {$_.Name}
Function AddCombos([int]$catPos, $root) {
    gci ".\$($categories[$catPos])\*.txt" | % {
        $memberTitle = [IO.Path]::GetFileNameWithoutExtension($_.Name)
        If ($catPos -eq ($categories.Length - 1)) {
            $root + $memberTitle
        } Else {
            AddCombos ($catpos + 1) ($root + $memberTitle + '_')
        }
    }
}
AddCombos 0 ''

First, this script gets the names of all the categories (e.g. "Prey") and puts them in the $categories list. It then defines a recursive function. AddCombos gets all the files in the category indexed by $catPos. If it's not on the last category, it outputs the completed string. Otherwise, it calls itself after adding the current member (e.g. "Deer") to the work-in-progress string and incrementing $catPos to indicate that the next category should be looked at. After defining that function, the script calls it starting at the first category (index 0) and with an empty string as the work-in-progress.
Note that the order of the categories is determined alphabetically. Since the folder names aren't used in the output, you can name them such that they'll be done in the order you desire. The script uses the text files' titles in the output, but if you want to control the order of those by renaming the files, you can change the $memberTitle = line to this:
$memberTitle = (gc $_)[0]

That takes the first line of each file's contents instead of its title.
This script can handle any number of categories and any number of members in each category.
To run it, save it as a .ps1 file and follow the instructions in the Enabling Scripts section of the PowerShell tag wiki. Then you can run it from a batch file like this:
powershell .\myscript.ps1

A: @echo off
    setlocal enableextensions disabledelayedexpansion

    for %%t in ("%temp%\%random%%random%%random%.tmp") do (
        >"%%~ft" echo(*
        for /d %%d in (*) do >nul 2>&1 dir /a-d "%%d" && for /f "tokens=* delims=*" %%l in ('
            type "%%~ft" ^& ^>"%%~ft" break
        ') do for %%f in ("%%d\*") do (
            >>"%%~ft" (if "%%~l"=="" (echo(%%~nf) else (echo %%l_%%~nf))
        )
    ) & type "%%~ft" & del "%%~ft"

It will generate a temporary file (referenced by %%t) where to concatenate the output lines.
For each directory (%%d) the temporary file is readed, cleared and for each line (%%l) in the temporary file it is echoed again with each file (%%f) under the current folder concatenated
Once all the files names have been concatenated, the temporary file is sent to console and removed.