text:
Q: Execute a function after two (or more) ajax request succeed I need to perform two independent ajax requests and a function to be executed after both of them succeed. I can obviously send the first request, then send the second one when the first one succeeds and finally execute the function when the second request succeeds. But is there a way to execute them separately and execute the function when both of them succeed?
i.e. I could have the following requests:
var jqxhr1 = $.post( "example1.php", function() {
  alert( "first success" );
})
var jqxhr2 = $.post( "example2.php", function() {
  alert( "second success" );
})

and the following function:
function myfunction() {
  alert( "function success" );
}

A: You just need to use $.when In the case where multiple Deferred objects
var jqxhr1 = $.post( 'example1.php');
var jqxhr2 = $.post( 'example2.php');

$.when(jqxhr1, jqxhr2).then(function( response1, response2 ) {
   console.log('both requests succeed, do staff here')
});

Hope this will be helpful.

A: As many commented under your question the best way is to use Promises. As I see you are using jQuery so I will post you my answer using jQuery. So the basic setup will be:
html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

<button id="one">Send 2 ajax</button>

<script src="script.js"></script>
</body>
</html>

example1.php:
<?php
echo json_encode($_POST['button']);

example2.php:
<?php
sleep(5);
echo json_encode($_POST['button']);

And javascript file:
$( document ).ready( function () {

    var $button1 = $( '#one' );

    $button1.on( 'click', function ( e ) {
        e.preventDefault();

        $.when(
            $.ajax( {
                url: "example1.php",
                type: "post",
                data: { button: "some data" }
            } ),
            $.ajax( {
                url: "example2.php",
                type: "post",
                data: { button: "some data" }
            } ) ).done( function ( a1, a2 ) {
            console.log( a1 );
            console.log( a2 );
        } );

    } )

} );

Explanation: $.when() is used when you want to wait until several ajax request are successful. So in my example done() is executed  after 5 seconds when two ajax request are successful. First and second params is returned values from first and second ajax call. You can read more about it in link I provided above. Returned data is like this:
Array[3]
    0:""Some data from AJAX 1""
    1:"success"
    2:Object
    length:3
    __proto__:Array[0]

Array[3]
    0:""Some data from AJAX 2""
    1:"success"
    2:Object
    length:3
    __proto__:Array[0]

example1.php and example2.php are very simple - they just send json back to javascript. Except that example2.php simulates ajax response timeout of 5 seconds.
P.S.: Code above is working example, which I'm running on my local machine.

A: You can declare a variable called requestsCompleted and asign it a value of zero. Every time a request is completed, add 1 to the variable, and when its equal to two, execute the function
Edit: As @Pogrindis pointed out, the best way is to use Promise.all() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)

A: Just use something like this:
 var count = 0;

    while (count < 2){
     //do ajax call
         //on success increment counter
         //on error just log and continue

    //you can put a timeout here and just do 'return' after if you wish
    }

    functionCall();


text:
Q: Responsive design / scaling modules according to resolution I added the following module to joomla "Left right image slideshow" this can be found at http://www.gopiplus.com/extensions/2011/07/left-right-image-slideshow-joomla-module/#comments
in this module the available customize settings is the following:
Width (px):  |___| <----textbox
Height (px):  |____| <----textbox
This works fine the only problem is that if I open it on another computer with a different screen resolution the imageview is too big or too small. After doing some research I found that I need to use "%" instead of px, but in this case as you can see in the picture the textbox is only for px. In this case how can I change my imageview to adjust when the resolution changes?
Please help?

A: It's hardcoded to be px in the file /modules/mod_left_right_image_slideshow/tmpl/left-right-image-slideshow-gallery.js.
The best solution would probably be to contact the developer of the module and suggest him supporting your wish. Or just use a different module from the huge list of available slideshow modules: http://extensions.joomla.org/extensions/photos-a-images/slideshow.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Yes or no function, arguments, and return void to cout So I'm fairly new to c++ and programming in general, so just for learning purposes, I am trying to extend the use of functions, but I'm not sure what do create for the arguments of my yesorno(). I created this and thought it would work, but as I understand, it always prints the return of '0' (which is also unwanted, but I understand why it does it currently) but does nothing with the variables and ends the program. Does anyone have anything that would spare me a remote crash course on everything I'm doing wrong?
#include <iostream>

int main()
{
    int yesorno_input = NULL;
    std::cout << yesorno();
    if (yesorno_input == 1)
    {
        std::cout << "yes";
    }
    else
    {
        std::cout << "no";
    }
    std::cin.get();
}

int yesorno()
{
    int yesorno_input = NULL;
    char choice;
    std::cout << "Y\\N";
    std::cin >> choice;
    if (choice == 'y')
        int yesorno_input = 1;
    else if (choice == 'n')
        int yesorno_input = 0;
    else
        std::cout << "...";
    std::cin.get();
    return 0;
}

A: The thing is you want to get the result back from the yesorno() right.?
And in your program you have made some mistakes like as noted in below code.
And as you want to have a parametrized function yesorno() try following:
#include <iostream>
int yesorno(char); // declaration of function yesorno

int main()
{
    int yesorno_input = NULL;
    char choice;

    // here you want to get input from user right?
    std::cout << "Y\\N";
    std::cin >> choice;

    // here you want to get the value by passing char as a parameter right?
    // so pass the char as a parameter to function yesorno

    yesorno_input  = yesorno(choice);

    // print the answer
    std::cout << yesorno_input;

    // Check for the return value by using switch statement
    // we can use if...else ladder too but it is convenient to use switch statement
    switch(yesorno_input)
    {
      case 0:
        std::cout << "No";
        break;
      case 1:
        std::cout << "yes";
        break;
      default:
        std::cout << "Invalid Input";
    }
    std::cin.get();
}

int yesorno(char choice)
{
    // you dnt need these things as you are passing value to the function
    //int yesorno_input = NULL;
    //char choice;
    //std::cout << "Y\\N";
    //std::cin >> choice;

    // just check here for the values and enjoy the output
    if (choice == 'y')
        return 1;
    else if (choice == 'n')
        return 0;
    else
        return -1;
}

Hope this will help you

A: Corrected version of your code. Learn to DEBUG your code. This way you will learn the fun of programming. You should know the significance of each line in your code.
#include <iostream>

int yesorno(){
  int yesorno_input = NULL;
  char choice;
  std::cout << "Y\\N";
  std::cin >> choice;
  if (choice == 'y')
    yesorno_input = 1;
  else if (choice == 'n')
    yesorno_input = 0;
  else
    std::cout << "...";
  std::cin.get();
  return yesorno_input;
}

int main()
{
  int yesorno_input = NULL;
  yesorno_input = yesorno();
  if (yesorno_input == 1)
  {
    std::cout << "yes";
  }
  else
  {
    std::cout << "no";
  }
  std::cin.get();
  return 0;
}

A: int main()
{
    int yesorno_input = yesorno();
    if (yesorno_input == 1)
    {
       std::cout << "yes";
    }
else
{
    std::cout << "no";
}
}

int yesorno()
{

std::cout << "Y\\N";
std::cin >> choice;
if (choice == 'y' || choice == 'Y')
    return 1;
else if (choice == 'n' || choice == 'N')
   return 0;

}

In your code, at the end of yerorno() function you use return 0; statement. This  causes whatever the input is, return 0 to called line.
In order to correct this:
You have to use your return value of the yesorno function in order to use the choice. You can do this with yesorno_input = yesorno();


text:
Q: Not able to open "Project Structure" in Android studio I have created new project in studio. Code works fine without any issue.
But I am facing issue on opening Project Structure.
On click on File -> Project Structure, it's not showing Project Structure dialog
but, in bottom of studio, it's showing error like below
4:16:06 PM IllegalArgumentException:
Multiple entries with same key: 24.0.0 rc4=24.0.0 rc4 and 24.0.0 rc4=24.0.0 rc4

Can any body know how to solve this issue.
My Android studio version 2.1.2

A: Check your SDK location and installed needed libraries.


text:
Q: TypeScript: Multiple constructor implementations are not allowed I have an Object where I use it in multiple services, and each one should take some parameters, so I create two constructors, but TypeScript did not allow me to do this. My example is:
class User {
    id: number;
    username: string;
    password: string;
    email: string;
    firstName: string;
    lastName: string;
    roles: string[];

    constructor(username: string, password: string){
        this.username = username;
        this.password = password;
    }

    constructor(id: number, username: string, firstname: string, lastname: string, roles: string[]){
        this.id = id;
        this.username= username;
        this.firstname= firstname;
        this.lastname= lastname;
        this.roles = roles;
    }
    //.. and maybe another constructor also
}

Is there a trick to solve this issue, please?

When I use the optional ? in constructors for example:
constructor(
    public id?: number,
    public username?: string,
    public email?: string,
    public password?: string,
    public firstName?: string,
    public lastName?: string,
    public roles?: string[]) {
}

and when I get my data from backend:
this.service.usersList().subscribe(users => {
  console.log(users);
  this.dataSource.data = users;
});

The roles is set in the password and not in the roles failed:
{
  "id": 1,
  "username": "user1",
  "email": "user1@email.com",
  "password": [
    "USER",
    "MODR"
  ]
}

For that I'm not sure about this trick.

Maybe I was not precise, but I use this method to parse my data:
static fromJson(item: Object): any {
    return new User(
        item['id'],
        item['username'],
        item['email'],
        item['roles']
    );
}

For that, when I create a constructor with optional, it will set the attributes in order of my call.

A: You can't use multiple constructors, but you can add a few optional parameters and verify if it exists, like the following:
class User {
    id: number;
    username: string;
    password: string;
    email: string;
    firstname: string;
    lastname: string;
    roles: string[];
    // The "?" says that its optional parameter
    constructor(id?: number, username?: string, firstname?: string,
        lastname?: string, roles?: string[], password?: string) {
        if (id) { // if id exists , you can implement the first constructor
            this.id = id;
            this.username = username;
            this.firstname = firstname;
            this.lastname = lastname;
            this.roles = roles;
        }
        if (password) { // if password exists : you can implement the second one
            this.username = username;
            this.password = password;
        }
    }
}

Your response should be like this before this works fine:
static fromJson(item: Object): any {
    return new User({
        id : item['id'],
        username : item['username'],
        email : item['email'],
        roles : item['roles']
    });
}

So your constructor should be like this:
constructor(user: any){
    if (user.id) { // if id exists , you can implement the first constructor
        this.id = user.id;
        this.username = user.username;
        this.firstname = user.firstname;
        this.lastname = user.lastname;
        this.roles = user.roles;
    }
    if (user.password) { // if password exists : you can implement the second one
        this.username = user.username;
        this.password = user.password;
    }
}

Or if you don't want to do that, you can set the response regarding the order, like this:
static fromJson(item: Object): any {
    return new User(
        item['id'],
        item['username'],
        undefined,
        item['email'],
        undefined,
        undefined,
        item['roles']
    );
}

A: I found the solution:
What happened?
When you create a constructor with optional parameters and try to call this constructor, it will set the attributes with the order of call. For that, when I call:
new User(
    item['id'],
    item['username'],
    item['email'],
    item['roles']
);

The roles in set in the firstName or password.
Solution
To solve this, it's required to change the order or parameters in the constructor:
constructor(
    public id?: number,
    public username?: string,
    public email?: string,
    public roles?: string[],

    public password?: string,
    public firstName?: string,
    public lastName?: string) {
}

Or if you won't change the order, just use undefined for example:
new User(
    item['id'],
    item['username'],
    undefined,
    item['email'],
    undefined,
    undefined,
    item['roles']
);

Until you arrive to the position of your attribute.

A: Use:
export class A {
   constructor() {
      // Something here
   }
   secondConstructor() {
      // Something here
      return this;
   }
}

And then you use just like this:
const a = new A();
const a2 = new A().secondConstructor();


text:
Q: MarkLogic migration I have a MarkLogic server on an ec2 linux 7. I want to migrate it to a linux 6. I moved the ebs to the new linux 6 and mounted it on /var/opt/MarkLogic.
I am able to start MarkLogic and access the admin page using web. All looked great until I started getting errors today. I am new to MarkLogic.
500: Internal Server Error
XDMP-LEXVAL: db:database-id("") -- Invalid lexical value ""
 In /MarkLogic/Admin/lib/nav-format.xqy on line 181
 In get-databases("")

$icon = ""
$databases = <databases xsi:schemaLocation="http://marklogic.com/xdmp/database database.xsd" xml:lang="zxx" timestamp="14682485897919660" xmlns="http://marklogic.com/xdmp/database" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><database><database-name>Documents</database-name><database-id>1...</databases>
$g = <database xmlns="http://marklogic.com/xdmp/database"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><database-name>8080-canonicalHL7-modules</database-name><databas...</database>

In /MarkLogic/Admin/lib/nav-format.xqy on line 884
   In database-nav("database", "summary", (), "")
$section = "database"
$panel = "summary"
$param = ()
$icon = ""

In /MarkLogic/Admin/lib/nav-format.xqy on line 2353
   In printNav("database", "summary", (), "")
$section = "database"
$panel = "summary"
$param = ()
$icon = ""
$sec = "database"
$start-time = xs:dayTimeDuration("PT0.001535S")

In /MarkLogic/Admin/lib/database-summary-form.xqy on line 123
  In
databaseSummaryPage(<databases xsi:schemaLocation="http://marklogic.com/xdmp/database database.xsd" xml:lang="zxx" timestamp="14682485897919660" xmlns="http://marklogic.com/xdmp/database" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><database><database-name>Documents</database-name><database-id>1...</databases>, ())

$datanode = <databases xsi:schemaLocation="http://marklogic.com/xdmp/database database.xsd" xml:lang="zxx" timestamp="14682485897919660" xmlns="http://marklogic.com/xdmp/database" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><database><database-name>Documents</database-name><database-id>1...</databases>
$msgs = ()

In /database-summary.xqy on line 17

A: Looks like in your moving data around you've corrupted your on-disk configuration setup and/or data so now it has an empty string database id, which is choking some admin code which doesn't expect that to ever be able to happen.  It's not a code issue, it's that the configuration data on disk isn't entirely consistent.  Maybe you moved some data but not all.  Maybe you did all this data moving while the server was running.  I can't tell from here.
You say you're new to MarkLogic, so this is probably just a dev server, so my advice would be to simply start fresh.


text:
Q: MS10-070 causing problems with Asp.NET MVC AntiForgery tokens? KB2418241, KB2416473, and KB2416451 all reference http://www.microsoft.com/technet/security/bulletin/MS10-070.mspx
After installing this patches on our Windows Server 2003 machines last Friday, we have been getting a significantly increased rate of errors of the sort:
System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not
supplied or was invalid. ---> System.Web.HttpException: Validation of viewstate MAC
failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey>
configuration specifies the same validationKey and validation algorithm. AutoGenerate
cannot be used in a cluster. ---> System.Web.UI.ViewStateException: Invalid viewstate.

The setup is as follows:

*

*The web applications are running in a web cluster, with the NLB settings to Client Affinity: Single.

*There are redirects between two separate web applications, and both of their machineKey elements are identical using explicit validationKey and decryptionKey elements.

*The validation method is set to "SHA1" and the decryption method is set to "AES"
(Furthermore, no redeployments of the applications have taken since well before the microsoft updates were installed).
These errors could of course be caused by actual CSRF attacks, but I find it unlikely given the volume and the spike corresponding with installation of the updates.
Are there any known issues with this update that could be causing this?  (and even better, any known workarounds?)

A: This problem was indeed caused by the security update.  The update changed the way things are validated by additionally signing the encrypted data.  This included the AntiForgeryToken cookie.
If the user restarts their browser or otherwise clears all session cookies, the problem goes away.
This was also noted in a comment at http://weblogs.asp.net/scottgu/archive/2010/09/27/asp-net-security-update-shipping-tuesday-sept-28th.aspx
After installing the patch, I was quite freaked out to find requests to my site
failing  - 500s.  But only in one browser.  To sum up: If you have an MVC site,
and are using Html.AntiForgeryToken() - any existing browser sessions will need
to be closed and reopened so that the session cookie that was generated before
the patch was applied, for that antiforgery token, can be killed.   Your existing
users may need to be informed of this - I can't see anyway to change the name of that
cookie.

You can also run into this problem when upgrading from MVC 1 to MVC 2:
http://weblogs.asp.net/james_crowley/archive/2010/03/18/beware-upgrade-to-asp-net-mvc-2-0-with-care-if-you-use-antiforgerytoken.aspx
In both cases, a workaround if you can't force your users to restart their browser requires editing the application code and redeploying.  You can edit the application so that when the exception occurs, you clear the AntiForgeryToken cookie from the incoming request, and then reissue the token cookie by calling Html.AntiForgeryToken(). However, in doing so, you must take care that you only do it in the appropriate places (e.g. the error page or other page that does not modify data) - otherwise, you lose all the protection from CSRF attacks, which is the whole reason of using the antiforgery token in the first place.


text:
Q: Callback for Cancel in Framework7 swipeout? I use framkework7 swipeout to delete products in my app.
When i swipe to left or right it remains in that position; than a dialog with cancel and ok is showing.
If i press ok > it removes the product
on cancel only the dialog is hidding, the product
 remains swiped.
Can't find no callback to hide/swipe back to right my product.
This is my code:

    ....

        Delete

$('.deleted-callback').on('swipeout:deleted', function() {
    deleteProduct($(this).data('id'));
});

Is this a bug or it's just me? Any help with that please?
Thanks

A: For this swipeout to close on cancel you need to do add data-close-on-cancel="true" to anchor tag.

...

...

        Delete


text:
Q: Error when loading some pages on Android 4.1.2 I have problem with loading some pages (that use JavaScript I think) via WebView.
When I loaded the page I got an error:
12-16 15:07:11.037: A/libc(1639): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 1654 (WebViewCoreThre)

My code:
webView=(WebView)findViewById(R.id.test);

webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());

webView.loadUrl("http://www.zumi.pl");

When I set webView.getSettings().setJavaScriptEnabled(false); everything is loading but looks bad, so I don't want to block JavaScript.
I noticed the problem is only on Android 4.1.1. If I run it on 2.3 and 4.2 everything works perfectly.
Does anyone have an idea how can I solve that?

A: This will disable the 3D accelerated parts of leaflet which will probably make it work but lower performance. This isn't a fix, but should at least work around it for now
mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);


text:
Q: W3C CSS Validator error with required attribute I'm getting the following error in the W3C CSS 3 Validator:

Unknown pseudo-element or pseudo-class :required

Required is a HTML5 input attribute. My CSS works in IE10, Google Chrome and Firefox.
This is my CSS:
#reserved input:required {background:#eaeae6;}
#reserved select:required {background:#eaeae6;}

This is my HTML code:
<section id="reserved">
    <select id="hab" name="hab" title="Study or Apartment" required>
    <input type="text" id="name" name="name" maxlength="50" style="width: 200px;" title="Name and Surname" required/>
</section>

Doesn't W3C recognize the required attribute like a standard?

A: CSS3 includes the Selectors Level 3 API. Selectors 3 does not include the :required selector.
:required was introduced in Selectors Level 4. Browsers support it, but it isn't part of the CSS3 specification and so will fail in a CSS3 validator.

A: Thanks for your answer lonesomeday.
I change my css and create a class instead of the required pseudo-class like this:
#reserved .required-class {background: #eaeae6;}

<input class="required-class" type="email" id="email" name="email" pattern="[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{1,5}" style="width: 200px;" title="email" required/>

With this change, now I've passed the W3C Validator :D


text:
Q: Get formatted values from custom Form Request - Laravel 5.6 I`m using custom form request to validate all input data to store users.
I need validate the input before send to form request, and get all validated data in my controller.
I have a regex function ready to validate this input, removing unwanted characters, spaces, allow only numbers and etc.
Would to get all data validated in controller, but still have no success.
Input example:

$cnpj= 29.258.602/0001-25
How i need in controller:

$cnpj= 29258602000125
UsuarioController

class UsuarioController extends BaseController
{
    public function cadastrarUsuarioExterno(UsuarioStoreFormRequest $request)
  {
     //Would to get all input validated - no spaces, no!@#$%^&*, etc
     $validated = $request->validated();

     dd($data);
  }
...
}

UsuarioStoreFormRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

class UsuarioStoreFormRequest extends FormRequest
{

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{

    return [
        'cnpj' => 'required|numeric|digits:14',
    ];
}

Custom function to validate cnpj

function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
    return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
    $soma += $cnpj{$i} * $j;
    $j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
    return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
    $soma += $cnpj{$i} * $j;
    $j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
}

A: You could use the prepareForValidation method in your FormRequest. This way your input would be modified and replaced in the request before it is validated and you can normally retrieve it in the controller with $request->get('cnpj'); after the validation was successful.
public function prepareForValidation()
{
    $input = $this->all();

    if ($this->has('cnpj')) {
        $input['cnpj'] = $this->get('cnpj'); // Modify input here
    }

    $this->replace($input);
}

A: You could extend the validated function in UsuarioStoreFormRequest as follows
/**
 * Get the validated data from the request.
 *
 * @return array
 */
public function validated()
{
    $validated = parent::validated();

    //Add here more characters to remove or use a regex
    $validated['cnpj'] = str_replace(['-', '/', ' ', '.'], '', $validated['cnpj']);

    return $validated;
}

A: Do it like this:
$string = "29.258.602/0001-25";
preg_match_all('!\d+!', $string, $matches);
return (implode("",$matches[0]));

Hope its help


text:
Q: $n$-player version of Zermelo's Theorem Zermelo's Theorem states that "Every finite zero-sum 2-player game is determined (one of the two players has a winning strategy)." I was wondering if anyone has investigated the generalization of this theorem to more than 2-player games. A proof, reference, or counterexample to this theorem for more than 2-players would be an answer that I am looking for.
Thanks!

A: That is actually not what Zermelo has shown, ase explained here.
A winning strategy is not even defined for other games.
What is closely related to how many people (wrongly) believed Zermelo has shown such a thing is Kuhn's "algorithm": In games of perfect information, one gets a Nash equilibrium by backward induction (that also satisfies subgame perfection). One gets a unique Nash equilibrium this way, when no player is indifferent between any two plays.

A: I am no expert, but it seems to me that with at least three players things get messy.
Consider the following trivial game with players $A,B,C$: the first two moves of $A,B$ are irrelevant, and then $C$ chooses between two options where payoffs are $(1,-1,0)$ (i.e. $A$ wins) and $(-1,1,0)$ (i.e. $B$ wins), and the game ends there. Then, the fate of $A$ and $B$ depend on the decision by $C$, who has no particular incentive to choose either, so surely there is no hope for a winning strategy for anyone. Would that be a counterexample you are looking for?


text:
Q: SICP stream integrator In SICP chapter 3.5 the code for a integrator is given
(define (solve f y0 dt)
  (define y (integral dy y0 dt))
  (define dy (stream-map f y))
  y)

a signal-processing system for solving the differential equation dy/dt=f(y)
where f
is a given function. The figure shows a mapping component, which applies f
to its input signal, linked in a feedback loop to an integrator in a manner very similar to that of the analog computer circuits that are actually used to solve such equations.

What is the real life useage of the given program?


text:
Q: Check if an array of integers forms a palindrome? So the question requires us to check if the entered elements in an array form a palindrome or not.
For eg, if an array has 134, 21, 12, 431, the output should declare that this is a palindrome.
I tried my best to keep my program simple and the logic used looks right to me. But it still isn't giving me the correct output. For eg, I input the size as 4 and then entered 134, 21, 12, 431. As per my code, I think it should print  "It is a palindrome." but instead there's no ouput on the console.
would be great if somebody can help me with this.
#include <iostream>
using namespace std;

int main()
{
    int size;
    cout << "Enter the size of array: " << endl;
    cin >> size;
    int arr[size];
    cout << "Enter the element: " << endl;

    for (int i=0; i<size; i++)
    {
        cin >> arr[i];
    }

    int arr2[size/2];
    for (int i=0; i<((size/2)-1); i++)
    {
        int reverse=0;
        while (arr[i]!=0)
        {
            int rem;
            rem = arr[i]%10;
            reverse=((reverse*10)+rem);
            arr[i]=arr[i]/10;
        }
        arr2[i]=reverse;
    }

    for (int i=0; i<((size/2)-1); i++)
    {
        if(arr2[i]==arr[size-1-i])
        {
            if(i==(size/2)-1)
            {
                cout << "It is a palindrome." << endl;
            }
        }
        else
        {
            cout << "Array is not a palindrome." << endl;
        }
    }
}

A: You can check whether the count of non-repeated couples is 1 or 0.
 bool isPalindrome(std::vector<int>& vec) {
        int max = *(std::max_element(vec.begin(), vec.end()));
        std::vector<int> tmp(max + 1, 0);
        for (int i = 0; i < vec.size(); ++i) {
            ++tmp[vec[i]];
        }
        int odd = 0;
        for (int i = 0; i < tmp.size(); ++i) {
            if (tmp[i] % 2 == 1) {
                ++odd;
            }
        }
        return (odd == 1 || odd == 0);
    }


text:
Q: Retrieve one item per group from one tabel with mysql I have a table with tweets from different users where I'd like to select the latest tweet per person. What sql do I use to retrieve these?
twitter_username   tweet       date
stevdobb           tweet one   2013-06-07 12:00
stevdobb           tweet two   2013-06-09 12:00
stevdobb           tweet three 2013-06-05 12:00
other_username     tweet four  2013-06-10 12:00

A: You can get create a subquery to find the latest date by user
select twitter_username, max(date) from tweets group by twitter_username

Then you can use this subquery to get the required tweets
select tweets.* from tweets join (
   select twitter_username, max(date) max_date
   from tweets group by twitter_username
) latest on
latest.twitter_username = tweets.twitter_username and
latest.max_date = tweets.date

A: try
SELECT twitter_username,tweet FROM your_table
GROUP BY `twitter_username` ORDER BY `date` DESC

GROUP BY is usually used with aggregate functions, but without them, only the first matching record is shown. If you order it by date desc, it is the latest one.


text:
Q: How to detect "slot filling" in Watson Assistant response I noticed that Watson Assistant's response has no way to detect if slot filling is occurring.  You can see "context" if output context was set according to their example:
{
  "output": {
    "generic": [
      {
        "response_type": "text",
        "text": "Hello! What can I do for you?"
      }
    ],
    "intents": [
      {
        "intent": "hello",
        "confidence": 0.9281370162963867
      }
    ],
    "entities": []
  },
  "context": {
    "global": {
      "system": {
        "turn_count": 1,
        "user_id": "55cd47b1-3847-430b-ba28-1739e0654576"
      },
      "session_id": "55cd47b1-3847-430b-ba28-1739e0654576"
    },
    "skills": {
      "main skill": {
        "system": {
          "state": "eyJzZXNzaW9uX2lkIjoiNTVjZDQ3YjEtMzg0Ny00MzBiLWJhMjgtMTczOWUwNjU0NTc2Iiwic2tpbGxfcmVmZXJlbmNlIjoibWFpbiBza2lsbCIsImFzc2lzdGFudF9pZCI6ImViM2RmZGRlLTJkNDUtNDBmYS05NDZlLTk2ODVmNTU2NzhhOSIsImluaXRpYWxpemVkIjp0cnVlLCJkaWFsb2dfc3RhY2siOlt7ImRpYWxvZ19ub2RlIjoicm9vdCJ9XSwibGFzdF9icmFuY2hfbm9kZSI6ImdyZWV0aW5nX29wdGlvbl8zIn0="
        }
      }
    }
  },
  "user_id": "55cd47b1-3847-430b-ba28-1739e0654576"
}

However, in the response that comes when slot filling is occurring there is no way to see that there is something similar to open context.
{
  "output": {
    "intents": [
      {
        "intent": "action_36417_intent_42985",
        "confidence": 1
      }
    ],
    "entities": [],
    "generic": [
      {
        "response_type": "text",
        "text": "Lite Plan: $10/month and Premium with Tech Support: $99/month."
      }
    ]
  },
  "user_id": "64e28440-84e2-4246-bfad-34daab1b92e5"
}

So in this case, you just have to advise the conversation designer to always put output context?
The reason this is important is because I need to detect whether slot filling or open context exists in order to know if the next message should go to the same bot or not.

A:
The reason this is important is because I need to detect whether slot filling or open context exists in order to know if the next message should go to the same bot or not.

I believe this is the crux of your question. As in most implementations multiple skills would not be used in such a fashion. So checking for slot filling is redundant.
For your issue, just have a step that fires after all slots are filled and use that to trigger when to talk to another bot.


text:
Q: Манипулирование DOM в JavaScript работает не корректно Всем привет! Снова столкнулся со странной проблемой, теперь связанной с JavaScript. Есть страница, на ней простенький JavaScript, также подключён jQuery.
function initTooltips() {
$(window).load(function() {
    $('.tt-trigger').each(function() {
        var index = $(this).data('tooltip');
        var pPos = $(this).position();
        var pWidth = $(this).outerWidth();
        var pHeight = $(this).outerHeight();

        $('.tooltip.tt[data-tooltip="' + index + '"]').css({
        width: pWidth + 'px',
        top: (pPos.top + pHeight) + 'px',
        left: (pPos.left) + 'px' // pPos.left = 0, 150, 300 ..
        });
    });
});

$(window).resize(function() {
    $('.tt-trigger').each(function() {
        var index = $(this).data('tooltip');
        var pPos = $(this).position();
        var pWidth = $(this).outerWidth();
        var pHeight = $(this).outerHeight();

        $('.tooltip.tt[data-tooltip="' + index + '"]').css({
        width: pWidth + 'px',
        top: (pPos.top + pHeight) + 'px',
        left: (pPos.left) + 'px'
        });
    });
});
};

$(function() {
    initTooltips();
});

Итак, код перестаёт работать ($(this).position().left начинает на все итерации выдавать 0) в трёх ситуациях: если я выношу код из load и resize в отдельную функцию, если я выношу код за пределы $(window).load() (document не так уж и ready, видимо) или если я перехожу с этой страницы на какую-то другую, а затем возвращаюсь кнопкой браузера "Назад" (начинает работать после обновления страницы).
Например, такой код уже не работает (но ошибок в консоль не выдаёт, просто все нужные переменные равны нулю):
function foo() {
    $('.tt-trigger').each(function() {
        var index = $(this).data('tooltip');
        var pPos = $(this).position();
        var pWidth = $(this).outerWidth();
        var pHeight = $(this).outerHeight();

        $('.tooltip.tt[data-tooltip="' + index + '"]').css({
        width: pWidth + 'px',
        top: (pPos.top + pHeight) + 'px',
        left: (pPos.left) + 'px' // pPos.left = 0, 0, 0 ..
        });
    });
};
function initTooltips() {
    $(window).load( foo() );
    $(window).resize( foo() );
};

$(function() {
    initTooltips();
});

То есть поведение очень странное, но я не вижу причин для этого. Заранее спасибо за помощь.

A: Ну вот, это другое дело.
Вы совершенно правильно поместили одинаковый повторяемый код в отдельную функцию. Но теперь Вам надо не вызывать Ваш обработчик, a передавать ссылку на него:
function initTooltips() {
    $(window).load( foo );
    $(window).resize( foo );
};


text:
Q: android - Анимация "лесенка"в GridView Здравствуйте, у меня есть GridView размером 6*6. Мне нужно сделать анимацию "лесенка" при старте активности. Застрял на самой анимации. Вот по такому порядку айтемов должна происходить анимация. Начинается с верхнего левого угла, заканчивается в нижнем правом.
1
2,7
3,8,13
4,9,14,19
5,10,15,20,25
6,11,16,21,26,31
12,17,22,27,32
18,23,28,33
24,29,34
30,35
36

Очень глупо по отдельности анимировать все по порядку. Хочу создать цикл, но написав for уставился в мигающий курсор и туплю. Как это можно сделать?
Насчёт адаптера, вообще, тупик. Он же перебирает все по порядку, слева-направо, а мне-то нужна лесенка.

A:         for (int i = 1; i < 37; i++) {
        if (i == 1) {
            Log.i("TAG", "i :   - " + i);
        }
        else if (i == 2) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5));
        }
        else if (i == 3) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10));
        }
        else if (i == 4) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15));
        }
        else if (i == 5) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20));
        }
        else if (i == 6) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20) + " , " + (i + 25));
        }
        else if (i == 12) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20));
        }
        else if (i == 18) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15));
        }
        else if (i == 24) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10));
        }
        else if (i == 30) {
            Log.i("TAG", "i :   - " + i + " , " + (i + 5));
        }
        else if (i == 36) {
            Log.i("TAG", "i :   - " + i);
        }
    }

С помощью switch
   for (int i = 1; i < 37; i++) {
        switch (i) {
            case 1:
                Log.i("TAG", "i :   - " + i);
                break;
            case 2:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5));
                break;
            case 3:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10));
                break;
            case 4:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15));
                break;
            case 5:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20));
                break;
            case 6:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20) + " , " + (i + 25));
                break;
            case 12:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20));
                break;
            case 18:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15));
                break;
            case 24:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10));
                break;
            case 30:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5));
                break;
            case 36:
                Log.i("TAG", "i :   - " + i);
                break;
        }
    }

С помощью switch немного короче
      for (int i = 1; i < 37; i++) {
        switch (i) {
            case 1:
            case 36:
                Log.i("TAG", "i :   - " + i);
                break;
            case 2:
            case 30:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5));
                break;
            case 3:
            case 24:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10));
                break;
            case 4:
            case 18:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15));
                break;
            case 5:
            case 12:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20));
                break;
            case 6:
                Log.i("TAG", "i :   - " + i + " , " + (i + 5) + " , " + (i + 10) + " , " + (i + 15) + " , " + (i + 20) + " , " + (i + 25));
                break;
        }
    }

Результат
I/TAG: i :   - 1
I/TAG: i :   - 2 , 7
I/TAG: i :   - 3 , 8 , 13
I/TAG: i :   - 4 , 9 , 14 , 19
I/TAG: i :   - 5 , 10 , 15 , 20 , 25
I/TAG: i :   - 6 , 11 , 16 , 21 , 26 , 31
I/TAG: i :   - 12 , 17 , 22 , 27 , 32
I/TAG: i :   - 18 , 23 , 28 , 33
I/TAG: i :   - 24 , 29 , 34
I/TAG: i :   - 30 , 35
I/TAG: i :   - 36


text:
Q: How do I determine an open file's size in Python? There's a file that I would like to make sure does not grow larger than 2 GB (as it must run on a system that uses ext 2).  What's a good way to check a file's size bearing in mind that I will be writing to this file in between checks?  In particular, do I need to worry about buffered, unflushed changes that haven't been written to disk yet?

A: os.fstat(file_obj.fileno()).st_size should do the trick.  I think that it will return the bytes written.  You can always do a flush before hand if you are concerned about buffering.

A: Though this is an old question, I think that Isak has the simplest solution. Here's how to do it in Python:
# Assuming f is an open file
>>> pos = f.tell()  # Save the current position
>>> f.seek(0, 2)  # Seek to the end of the file
>>> length = f.tell()  # The current position is the length
>>> f.seek(pos)  # Return to the saved position
>>> print length
1024

A: I'm not familiar with python, but doesn't the stream object (or whatever you get when opening a file) have a property that contains the current position of the stream?
Similar to what you get with the ftell() C function, or Stream.Position in .NET.
Obviously, this only works if you are positioned at the end of the stream, which you are if you are currently writing to it.
The benefit of this approach is that you don't have to close the file or worry about unflushed data.

A: You could start with something like this:
class TrackedFile(file):
    def __init__(self, filename, mode):
        self.size = 0
        super(TrackedFile, self).__init__(filename, mode)
    def write(self, s):
        self.size += len(s)
        super(TrackedFile, self).write(s)

Then you could use it like this:
>>> f = TrackedFile('palindrome.txt', 'w')
>>> f.size
0
>>> f.write('A man a plan a canal ')
>>> f.size
21
>>> f.write('Panama')
27

Obviously, this implementation doesn't work if you aren't writing the file from scratch, but you could adapt your __init__ method to handle initial data.  You might also need to override some other methods: writelines, for instance.
This works regardless of encoding, as strings are just sequences of bytes.
>>> f2 = TrackedFile('palindrome-latin1.txt', 'w')
>>> f2.write(u'A man a plan a canál '.encode('latin1')
>>> f3 = TrackedFile('palindrome-utf8.txt', 'w')
>>> f3.write(u'A man a plan a canál '.encode('utf-8'))
>>> f2.size
21
>>> f3.size
22

A: Or, if the file is already open:
>>> fsock = open('/etc/hosts', 'rb').read()
>>> len(fsock)
444

That's how many bytes the file is.

A: Perhaps not what you want, but I'll suggest it anyway.
import os
a = os.path.getsize("C:/TestFolder/Input/1.avi")

Alternatively for an opened file you can use the fstat function, which can be used on an opened file. It takes an integer file handle, not a file object, so you have to use the fileno method on the file object:
a = open("C:/TestFolder/Input/1.avi")
b = os.fstat(a.fileno()).st_size

A: Most reliable would be create a wrapping class which would check file's size when you open it, track write and seek operations, count current size based on those operations and prevent from exceeding size limit.


text:
Q: White question mark while trying to get user's Facebook profile picture in Android I store app-scoped-ids in my database, hoping to fetch profile pictures from them via the graph API.
This code:
String url = "https://graph.facebook.com/" + mate.getFacebookId() + "/picture?type=large";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = null;
    HttpEntity entity = null;

    try {

        response = httpClient.execute(httpGet);

    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response != null) {
        entity = response.getEntity();
    }

    byte[] data = null;
    try {
        data = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    if (data != null) {

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    }

    return bitmap;

...does not work and returns a white question mark, why?
The url 'https://graph.facebook.com/800397776713349/picture?type=normal' works just fine in chrome.

A: The semicolon on this line is missing:
String url = "https://graph.facebook.com/" + mate.getFacebookId() + "/picture?type=large"

It looks like you're using an invalid Facebook ID. Check that mate.getFacebookId() is returning a valid ID. When I use a valid ID, I'm able to return the image successfully inside an AsyncTask:
Use inside Main thread (onCreate, onActivityCreated, etc.):
GetImage retrieve = new GetImage((ImageView)findViewById(R.id.yourimageview));
retrieve.execute();

GetImage:
class GetImage extends AsyncTask<String, Void, Bitmap>
{
    private ImageView view;

    public GetImage(ImageView view)
    {
        this.view = view;
    }

    @Override
    protected Bitmap doInBackground(String... params)
    {
        //Your exact code goes here
    }

    @Override
    protected void onPostExecute(Bitmap b)
    {
        view.setImageBitmap(b);
    }

}


text:
Q: Dask DataFrame for fitting Keras model I have a Dask DataFrame that I want to use for fitting a Keras autoencoder model:
DataFrame:
import dask.dataframe as dd
input_df = dd.read_csv(file_path)
input_df.dtypes

_2          float64
_3          float64
_4          float64
_5          float64 ...
Keras model:
autoencoder = Sequential()
autoencoder.add(Dense(dense[0], input_shape=(dense[0],), activation = 'relu' ))
autoencoder.add(Dense(dense[1], activation = 'relu' ))
autoencoder.add(Dense(dense[2], activation = 'relu' ))
autoencoder.add(Dense(dense[3], activation = 'relu' ))
autoencoder.add(Dense(dense[0], activation = 'relu' ))

autoencoder.compile(loss='mse',
          optimizer='adam',
          metrics=['mse'])

When I pass the DataFrame for fitting:
autoencoder.fit(input_df, input_df,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                validation_split = val_split)

I get the error:
TypeError                                 Traceback (most recent call last)
<ipython-input-23-d0480d8a460d> in <module>()
      3                     epochs=epochs,
      4                     verbose=1,
----> 5                     validation_split = val_split)

~/anaconda3/envs/py36/lib/python3.6/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    950             sample_weight=sample_weight,
    951             class_weight=class_weight,
--> 952             batch_size=batch_size)
    953         # Prepare validation data.
    954         do_validation = False

~/anaconda3/envs/py36/lib/python3.6/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    799                 for (ref, sw, cw, mode) in
    800                 zip(y, sample_weights, class_weights,
--> 801                     feed_sample_weight_modes)
    802             ]
    803             # Check that all arrays have the same length.

~/anaconda3/envs/py36/lib/python3.6/site-packages/keras/engine/training.py in <listcomp>(.0)
    797             sample_weights = [
    798                 standardize_weights(ref, sw, cw, mode)
--> 799                 for (ref, sw, cw, mode) in
    800                 zip(y, sample_weights, class_weights,
    801                     feed_sample_weight_modes)

~/anaconda3/envs/py36/lib/python3.6/site-packages/keras/engine/training_utils.py in standardize_weights(y, sample_weight, class_weight, sample_weight_mode)
    522     else:
    523         if sample_weight_mode is None:
--> 524             return np.ones((y.shape[0],), dtype=K.floatx())
    525         else:
    526             return np.ones((y.shape[0], y.shape[1]), dtype=K.floatx())

~/anaconda3/envs/py36/lib/python3.6/site-packages/numpy/core/numeric.py in ones(shape, dtype, order)
    201
    202     """
--> 203     a = empty(shape, dtype, order)
    204     multiarray.copyto(a, 1, casting='unsafe')
    205     return a

TypeError: 'float' object cannot be interpreted as an integer

Would appreciate some help! Thanks!


text:
Q: MySQL query to linq I have MySQL query
SELECT  Task_Number, BM_Number, BU, Status
FROM
    eng_effort
    INNER JOIN eng_task on eng_effort.Eng_Task_ID = eng_task.Eng_Task_ID
where Status = "In Progress" and User_ID = "7"
group by Task_Number;

How do i write it in linq. please help.

A: Using the LINQ syntax, you can write something like this:
var query = (from effort in context.eng_effort
            join task in context.eng_task on effort.Eng_Task_ID equals task.Eng_Task_ID
            where task.Status == "In Progress" && task.User_ID == "7"
            select new { task.Task_Number, ... })
            .GroupBy(a => a.Task_Number);

Also, are you sure User_ID is a text column?
With the extension method syntax:
context.eng_effort
    .Join(
        context.eng_task,
        effort => effort.Eng_Task_ID,
        task => task.Eng_Task_ID,
        (effort, task) => (effort, task)) // Using a ValueTuple here
    .Where(et => et.task.Status == "In Progress" && et.task.User_ID == "7")
    .Select(et => new { et.task.Task_Number, ... })
    .GroupBy(a => a.Task_Number);

Or you could perform a Perform grouped join.


text:
Q: insertion in the description of external affiliate product url in the single_product.php page of woocommerce add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
 global $product;
// Get product id
 $product_id = $product->get_id();

 // Get url
 $url = $product->add_to_cart_url();
 // Only for single product pages
 if( ! is_product() ) return $content;

 // Set the limit of words
 $limit = 13;

 if (str_word_count($content, 0) > $limit) {
     $arr = str_word_count($content, 2);
     $pos = array_keys($arr);
     $text = '
' . substr($content, 0, $pos[$limit]) . ".....continua la lettura
";
     $content = force_balance_tags($text); // needded
 }
 return $content;
}

The code works, in the single product page it displays the url ($url), but when I open the home page of the website I no longer see the content.
What am I doing wrong?
thank you


text:
Q: Destructor array stack tiwer hanoi c++ double pointer I try to push element into the stack but it shownd that there is an error of space amount. The capacity upgraded if the length is bigger than the capacity. Does somebody know how to correct this error? I think that this may come from the destructor, but I am not so sure about this.
ArrayStack.cpp
#include "ArrayStack.h"

ArrayStack::ArrayStack()
{
   maxCapacity = DEFAULT_CAPACITY;
   this->tab = new int* [DEFAULT_CAPACITY];
   this->topElement = 0;
   this->length = 0;
}

ArrayStack::~ArrayStack()
{
    for (int i = 0; i < maxCapacity; i++)
    {
        delete tab[i];
    }
    delete[] tab;
}

void ArrayStack::push(int element)
{
    this->length++;
    while (this->maxCapacity <= this->length) {
        maxCapacity += DEFAULT_CAPACITY;

        int** temp = new int* [maxCapacity];
        for (int i = 0; i < maxCapacity; i++)
        {
            temp[i] = tab[i];
        }
        delete tab;
        this->tab = temp;
    }

    this->tab[this->length] = new int (element);
    this->topElement = element;

}

void ArrayStack::pop()
{
    if (isEmpty())
    {
        throw Empty_Stack();
    }
    delete tab[this->length];

    this->length--;
    if (isEmpty())
    {
        this->topElement = -1;
    }
    else
    {
        this->topElement = *tab[this->length];
    }

}

int ArrayStack::top() const
{
    if (isEmpty())
    {
        throw Empty_Stack();
    }
    return this->topElement;

}

bool ArrayStack::isEmpty() const
{
    if (this->length == 0)
    {
        return true;
    }
    return false;
}

int ArrayStack::size() const
{
    return this->length;
}

ArrayStack.h
#pragma once
#include "Stack.h"
#include "NotImplementedException.h"
class ArrayStack : public Stack
{
public:
    static const int DEFAULT_CAPACITY = 10;

    // ATTENTION, pour chacune des méthodes, lorsque
    // vous créez sa définition dans le .cpp, vous devez
    // remplacer {} (et éventuellement son contenu) par un ;
    ArrayStack();
    ~ArrayStack();
    void push(int element) override;
    void pop() override;
    int top() const override;
    bool isEmpty() const override;
    int size() const override;

private:
    int length;
    int** tab;
    int topElement;
    int maxCapacity;

};

A: I see a number of things wrong with how this class is managing its array:

*

*The constructor is allocating an array of int* pointers, but is not setting any of them to nullptr initially.  Which causes problems for the destructor, because it is calling delete on every single pointer, whether they have been initialized or not.  To avoid having to delete unused pointers, the destructor should be looping up to length, not maxCapacity.

*Likewise, pop() is not setting any freed pointers to nullptr, which also causes problems for the destructor when it loops up to maxCapacity rather than length.  It is also delete'ing the wrong array element, and going out of bounds if the array is at its max capacity.

*When push() allocates a new array (FYI, the outer while loop is unnecessary), it copies too many elements from the old array, which is smaller than the new array. Also, it is using delete instead of delete[] to free the old array.

*The class is not following the Rule of 3/5/0, as it should implement (or at least disable) the copy/move constructors and copy/move assignment operators.
Try something more like this instead:
ArrayStack.h
#pragma once
#include "Stack.h"
#include "NotImplementedException.h"

class ArrayStack : public Stack
{
public:
    static const int DEFAULT_CAPACITY = 10;

    // ATTENTION, pour chacune des méthodes, lorsque
    // vous créez sa définition dans le .cpp, vous devez
    // remplacer {} (et éventuellement son contenu) par un ;

    ArrayStack();
    ArrayStack(const ArrayStack &src);
    ArrayStack(ArrayStack &&src);
    ~ArrayStack();

    ArrayStack& operator=(ArrayStack rhs);

    void push(int element) override;
    void pop() override;
    int top() const override;
    bool isEmpty() const override;
    int size() const override;

private:
    int length;
    int** tab;
    int topElement;
    int maxCapacity;
};

ArrayStack.cpp
#include "ArrayStack.h"
#include <utility>

ArrayStack::ArrayStack()
{
   maxCapacity = DEFAULT_CAPACITY;
   tab = new int* [DEFAULT_CAPACITY];
   for (int i = 0; i < DEFAULT_CAPACITY; ++i) {
      tab[i] = nullptr;
   }
   length = 0;
   topElement = -1;
}

ArrayStack::ArrayStack(const ArrayStack &src)
{
   maxCapacity = src.maxCapacity;
   tab = new int* [maxCapacity];
   for (int i = 0; i < src.length; ++i) {
      tab[i] = new int (*(src.tab[i]));
   }
   for (int i = src.length; i < maxCapacity; ++i) {
      tab[i] = nullptr;
   }
   length = src.length;
   topElement = src.topElement;
}

ArrayStack::ArrayStack(ArrayStack &&src)
{
   maxCapacity = src.maxCapacity; src.maxCapacity = 0;
   tab = src.tab; src.tab = nullptr;
   length = src.length; src.length = 0;
   topElement = src.topElement; src.topElement = -1;
}

ArrayStack& ArrayStack::operator=(ArrayStack rhs)
{
    std::swap(maxCapacity, rhs.maxCapacity);
    std::swap(tab, rhs.tab);
    std::swap(length, rhs.length);
    std::swap(topElement, rhs.topElement);
    return *this;
}

ArrayStack::~ArrayStack()
{
    for (int i = 0; i < length; ++i) {
        delete tab[i];
    }
    delete[] tab;
}

void ArrayStack::push(int element)
{
    if (maxCapacity <= length) {
        int newCapacity = maxCapacity + DEFAULT_CAPACITY;

        int** temp = new int* [newCapacity];
        for (int i = 0; i < length; ++i) {
            temp[i] = tab[i];
        }
        for (int i = length; i < newCapacity; ++i) {
            temp[i] = nullptr;
        }

        delete[] tab;
        tab = temp;
        maxCapacity = newCapacity;
    }

    tab[length] = new int (element);
    ++length;

    topElement = element;
}

void ArrayStack::pop()
{
    if (isEmpty()) {
        throw Empty_Stack();
    }

    --length;
    delete tab[length];
    tab[length] = nullptr;

    if (isEmpty()) {
        topElement = -1;
    }
    else {
        topElement = *tab[length-1];
    }
}

int ArrayStack::top() const
{
    if (isEmpty()) {
        throw Empty_Stack();
    }
    return topElement;
}

bool ArrayStack::isEmpty() const
{
    return (length == 0);
}

int ArrayStack::size() const
{
    return length;
}

Online Demo

That being said, there is really no good reason to use an array of int* pointers at all. You should use an array of int values instead.  Then you will have a little less to manage manually:
ArrayStack.h
#pragma once
#include "Stack.h"
#include "NotImplementedException.h"

class ArrayStack : public Stack
{
public:
    static const int DEFAULT_CAPACITY = 10;

    // ATTENTION, pour chacune des méthodes, lorsque
    // vous créez sa définition dans le .cpp, vous devez
    // remplacer {} (et éventuellement son contenu) par un ;

    ArrayStack();
    ArrayStack(const ArrayStack &src);
    ArrayStack(ArrayStack &&src);
    ~ArrayStack();

    ArrayStack& operator=(ArrayStack rhs);

    void push(int element) override;
    void pop() override;
    int top() const override;
    bool isEmpty() const override;
    int size() const override;

private:
    int length;
    int* tab;
    int topElement;
    int maxCapacity;
};

ArrayStack.cpp
#include "ArrayStack.h"
#include <utility>

ArrayStack::ArrayStack()
{
   maxCapacity = DEFAULT_CAPACITY;
   tab = new int [DEFAULT_CAPACITY];
   length = 0;
   topElement = -1;
}

ArrayStack::ArrayStack(const ArrayStack &src)
{
   maxCapacity = src.maxCapacity;
   tab = new int [maxCapacity];
   for (int i = 0; i < src.length; ++i) {
      tab[i] = src.tab[i];
   }
   length = src.length;
   topElement = src.topElement;
}

ArrayStack::ArrayStack(ArrayStack &&src)
{
   maxCapacity = src.maxCapacity; src.maxCapacity = 0;
   tab = src.tab; src.tab = nullptr;
   length = src.length; src.length = 0;
   topElement = src.topElement; src.topElement = -1;
}

ArrayStack& ArrayStack::operator=(ArrayStack rhs)
{
    std::swap(maxCapacity, rhs.maxCapacity);
    std::swap(tab, rhs.tab);
    std::swap(length, rhs.length);
    std::swap(topElement, rhs.topElement);
    return *this;
}

ArrayStack::~ArrayStack()
{
    delete[] tab;
}

void ArrayStack::push(int element)
{
    if (maxCapacity <= length) {
        int newCapacity = maxCapacity + DEFAULT_CAPACITY;

        int* temp = new int [newCapacity];
        for (int i = 0; i < length; ++i) {
            temp[i] = tab[i];
        }

        delete[] tab;
        tab = temp;
        maxCapacity = newCapacity;
    }

    tab[length] = element;
    ++length;

    topElement = element;
}

void ArrayStack::pop()
{
    if (isEmpty()) {
        throw Empty_Stack();
    }

    --length;

    if (isEmpty()) {
        topElement = -1;
    }
    else {
        topElement = tab[length-1];
    }
}

int ArrayStack::top() const
{
    if (isEmpty()) {
        throw Empty_Stack();
    }
    return topElement;
}

bool ArrayStack::isEmpty() const
{
    return (length == 0);
}

int ArrayStack::size() const
{
    return length;
}

Online Demo
In which case, a better option would be to then replace the manual array with std::vector instead and let it do all of the heavy work for you:
ArrayStack.h
#pragma once
#include "Stack.h"
#include "NotImplementedException.h"
#include <vector>

class ArrayStack : public Stack
{
public:
    static const int DEFAULT_CAPACITY = 10;

    // ATTENTION, pour chacune des méthodes, lorsque
    // vous créez sa définition dans le .cpp, vous devez
    // remplacer {} (et éventuellement son contenu) par un ;

    ArrayStack();

    void push(int element) override;
    void pop() override;
    int top() const override;
    bool isEmpty() const override;
    int size() const override;

private:
    std::vector<int> tab;
    int topElement;
};

ArrayStack.cpp
#include "ArrayStack.h"

ArrayStack::ArrayStack()
{
   tab.reserve(DEFAULT_CAPACITY);
   topElement = -1;
}

void ArrayStack::push(int element)
{
    tab.push_back(element);
    topElement = element;
}

void ArrayStack::pop()
{
    if (isEmpty()) {
        throw Empty_Stack();
    }

    tab.pop_back();

    if (tab.empty()) {
        topElement = -1;
    }
    else {
        topElement = tab.back();
    }
}

int ArrayStack::top() const
{
    if (isEmpty()) {
        throw Empty_Stack();
    }
    return topElement;
}

bool ArrayStack::isEmpty() const
{
    return tab.empty();
}

int ArrayStack::size() const
{
    return tab.size();
}

Online Demo
And then, finally, use std::stack instead:
ArrayStack.h
#pragma once
#include "Stack.h"
#include "NotImplementedException.h"
#include <stack>

class ArrayStack : public Stack
{
public:
    // ATTENTION, pour chacune des méthodes, lorsque
    // vous créez sa définition dans le .cpp, vous devez
    // remplacer {} (et éventuellement son contenu) par un ;

    void push(int element) override;
    void pop() override;
    int top() const override;
    bool isEmpty() const override;
    int size() const override;

private:
    std::stack<int> tab;
};

ArrayStack.cpp
#include "ArrayStack.h"

void ArrayStack::push(int element)
{
    tab.push(element);
}

void ArrayStack::pop()
{
    if (isEmpty()) {
        throw Empty_Stack();
    }

    tab.pop();
}

int ArrayStack::top() const
{
    if (isEmpty()) {
        throw Empty_Stack();
    }
    return tab.top();
}

bool ArrayStack::isEmpty() const
{
    return tab.empty();
}

int ArrayStack::size() const
{
    return tab.size();
}

Online Demo
See how much cleaner that is? :-)


text:
Q: How to make "Flutter Form Builder" recognize submitted form data from questions in an RFlutter Alert? I am building a form using the "Flutter Form Builder" package 4.0.2.
Most form questions are on a screen, but the last two are on successive* popups created with the RFlutter Alert package 1.1.0
* By "successive" I mean there is a "Post" button on the bottom of the main form screen (see first image immediately below). When pressed, an RFlutter alert popup appears (see 2nd screenshot image below), with the second-to-last FormBuilderRadioGroup question ("q11"). When the "Next" button is pressed, yet another RFlutter alert popup appears, on which the last FormBuilderRadioGroup question appears ("q12"). The entire Flutter Form Builder form submits when the "Finish Posting" button here is pressed.

The user interface works well, but the problem is nothing from the questions in the alert popups (Q11 and Q12) gets submitted with the form (see console snapshot below - q1, q2 and q3 also have problems, but that's not what I'm asking about here).

Here is the code (skipped irrelevant parts, for length):
// This is the stateful widget that the main application instantiates, per https://api.flutter.dev/flutter/widgets/Form-class.html
class SandboxWriteReviewScreen extends StatefulWidget {
  // BEGIN code from material_tag_editor
  final String title = 'Material Tag Editor Demo';
// END code from material_tag_editor

  @override
  _SandboxWriteReviewScreenState createState() =>
      _SandboxWriteReviewScreenState();
}

// This is the private State class that goes with WriteReviewScreen
class _SandboxWriteReviewScreenState extends State<SandboxWriteReviewScreen> {
  var data;
  AutovalidateMode autovalidateMode = AutovalidateMode.always;
  bool readOnly = false;
  bool showSegmentedControl = true;
  //final _newFormbuilderKey = GlobalKey<FormState>();
  final _newnewFormbuilderKey = GlobalKey<FormBuilderState>();

  // above "GlobalKey" lets us generate a unique, app-wide ID that we can associate with our form, per https://fluttercrashcourse.com/blog/realistic-forms-part1
  final ValueChanged _onChanged = (val) => print(val);

  // BEGIN  related to FormBuilderTextField in form below
  final _ageController = TextEditingController(text: '45');
  bool _ageHasError = false;
  // END related to FormBuilderTextField in form below

  String qEleven;
  String qTwelve;

  // BEGIN code from material_tag_editor
  List<String> qOne = [];
  final FocusNode _focusNode = FocusNode();

  onDelete(index) {
    setState(() {
      qOne.removeAt(index);
    });
  }

  // below = reiteration for cons

  List<String> qThree = [];
  //final FocusNode _focusNode = FocusNode();

  uponDelete(index) {
    // NOTE: "uponDelete" for cons vs. "onDelete" for pros
    setState(() {
      qThree.removeAt(index);
    });
  }

// END code from material_tag_editor

  //final _user = User();

  List<bool> isSelected;

  int starIconColor =
      0xffFFB900; // was 0xffFFB900;  0xffD49428 is from this image: https://images.liveauctioneers.com/houses/logos/lg/bartonsauction550_large.jpg?auto=webp&format=pjpg&width=140

  @override
  void initState() {
    //isSelected = [true, false];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

Cont'd (skipped AppBar):
body: SingleChildScrollView(
        child: Container(
          child: Builder(
            builder: (context) => FormBuilder(
              // was "builder: (context) => Form("
              key: _newnewFormbuilderKey,
              initialValue: {
                'date': DateTime.now(),
              },
              child: Padding(
                padding: const EdgeInsets.all(14.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.0,
                    ),
                    RichText(
                      text: TextSpan(
                        style: TextStyle(
                          color: Colors.blue,
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            text:
                                'Q1 via TagEditor', // was 'What are 3 good or positive things about the house, property or neighborhood?', //  [ 1 ]
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16.0,
                            ),
                          ),
                          TextSpan(
                            text: '  (optional)',
                            style: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontStyle: FontStyle.italic,
                              fontSize: 14.0,
                              color: Colors.black54,
                            ), // was 'misleading or inaccurate?',
                          ),
                        ],
                      ),
                    ),
                    // BEGIN code from material_tag_editor
                    Padding(
                      padding: const EdgeInsets.only(top: 16.0),
                      child: TagEditor(
                        length: qOne.length,
                        delimiters: [
                          ','
                        ], // was delimiters: [',', ' '],  Also tried "return" ('\u2386',) and '\u{2386}'
                        hasAddButton: true,
                        textInputAction: TextInputAction
                            .next, // moves user from one field to the next!!!!
                        autofocus: false,
                        maxLines: 1,

                        // focusedBorder: OutlineInputBorder(
                        //   borderSide: BorderSide(color: Colors.lightBlue),
                        //   borderRadius: BorderRadius.circular(20.0),
                        // ),
                        inputDecoration: const InputDecoration(
                          // below was "border: InputBorder.none,"
                          isDense: true,
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(20.0),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.lightBlue),
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(20.0),
                            ),
                            // above is per https://github.com/flutter/flutter/issues/5191
                          ),
                          labelText: 'separate,  with,  commas',
                          labelStyle: TextStyle(
                            fontStyle: FontStyle.italic,
                            backgroundColor:
                                Color(0x65dffd02), // was Color(0xffDDFDFC),
                            color: Colors.black87, // was Color(0xffD82E6D),
                            fontSize: 14,
                          ),
                        ),
                        onTagChanged: (value) {
                          setState(() {
                            qOne.add(value);
                          });
                        },
                        tagBuilder: (context, index) => _Chip(
                          index: index,
                          label: qOne[index],
                          onDeleted: onDelete,
                        ),
                      ),
                    ),
                    // END code from material_tag_editor

                    SuperDivider(),

Cont'd (skipped Q2 - Q9):
SuperDivider(),
                    RichText(
                      text: TextSpan(
                        style: TextStyle(
                          color: Colors.blue,
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            text:
                                'Q10 - via FormBuilder\'s FormBuilderTextField', // [ 9 ]
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16.0,
                            ),
                          ),
                          TextSpan(
                            text: '  (optional)',
                            style: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontStyle: FontStyle.italic,
                              fontSize: 14.0,
                              color: Colors.black54,
                            ), // was 'misleading or inaccurate?',
                          ),
                        ],
                      ),
                    ),
                    GavTextField(
                      maxCharLength: 1200,
                      fieldAttribute: 'qTen',
                      fieldLabelText:
                          'Be honest & kind.', // was 'Be honest, but kind.',
                    ),
                    SuperDivider(),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                                primary: Colors.purple,
                                padding: EdgeInsets.symmetric(
                                    horizontal: 50, vertical: 20),
                                textStyle: TextStyle(
                                    fontSize: 20, fontWeight: FontWeight.bold)),
                            onPressed: () {
                              Alert(
                                context: context,
                                style: alertStyle,
                                title: 'Two quick things...',
                                desc: ' ',
                                content: Column(
                                  children: <Widget>[
                                    RichText(
                                      text: TextSpan(
                                        style: TextStyle(
                                          color: Colors.blue,
                                        ),
                                        children: <TextSpan>[
                                          TextSpan(
                                            text:
                                                'Q11 - via FormBuilder\'s FormBuilderRadioGroup', // [ 10 ]
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 16.0,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    FormBuilderRadioGroup(
                                      name: 'qEleven',
                                      decoration: const InputDecoration(
                                        border: InputBorder.none,
                                      ),
                                      orientation: OptionsOrientation.vertical,
                                      onChanged: _onChanged,
                                      options: [
                                        FormBuilderFieldOption(
                                          value: 'N',
                                          child: RichText(
                                            text: TextSpan(
                                              style: TextStyle(
                                                color: Colors.black,
                                              ),
                                              children: <TextSpan>[
                                                TextSpan(
                                                  text: 'No', // [ 10 ]
                                                  style: TextStyle(
                                                    fontWeight: FontWeight.w500,
                                                    fontSize: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        FormBuilderFieldOption(
                                          value: 'YesSometimes',
                                          child: RichText(
                                            text: TextSpan(
                                              style: TextStyle(
                                                color: Colors.black,
                                              ),
                                              children: <TextSpan>[
                                                TextSpan(
                                                  text:
                                                      'Yes, sometimes', // [ 10 ]
                                                  style: TextStyle(
                                                    fontWeight: FontWeight.w500,
                                                    fontSize: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        FormBuilderFieldOption(
                                          value: 'YesDaily',
                                          child: RichText(
                                            text: TextSpan(
                                              style: TextStyle(
                                                color: Colors.black,
                                              ),
                                              children: <TextSpan>[
                                                TextSpan(
                                                  text: 'Yes, daily', // [ 10 ]
                                                  style: TextStyle(
                                                    fontWeight: FontWeight.w500,
                                                    fontSize: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                buttons: [
                                  DialogButton(
                                    onPressed: () {
                                      Alert(
                                          context: context,
                                          style: alertStyle,
                                          title: 'And lastly:',
                                          desc: '',
                                          content: Column(
                                            children: <Widget>[
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: [
                                                  RichText(
                                                    text: TextSpan(
                                                      style: TextStyle(
                                                        color: Colors.blue,
                                                      ),
                                                      children: <TextSpan>[
                                                        TextSpan(
                                                          text:
                                                              ' Q12 - via FormBuilder\'s', // [ 10 ]

And finally (skipped Q12):
buttons: [
                                            DialogButton(
                                              // BEGIN submit form when button pressed per 4.0.2 Readme and video https://www.youtube.com/watch?v=7FBELQq808M
                                              onPressed: () {
                                                _newnewFormbuilderKey
                                                    .currentState
                                                    .save();
                                                if (_newnewFormbuilderKey
                                                    .currentState
                                                    .validate()) {
                                                  print(_newnewFormbuilderKey
                                                      .currentState.value);
                                                  print(
                                                    '  >>> Q1\'s value via separate print: {$qOne}',
                                                  );
                                                  print(
                                                    '  >>> Q3\'s value via separate print: {$qThree}',
                                                  );
                                                  print(
                                                    '   >>> Q11\'s value via separate print: {$qEleven}',
                                                  );
                                                  print(
                                                    '   >>> Q12\'s value via separate print: {$qTwelve}',
                                                  );
                                                  //print(_newFormbuilderKey.currentState.privacyChoice.value);
                                                } else {
                                                  print("validation failed");
                                                }
                                              },

                                              // END submit form when button pressed per 4.0.2 Readme and video https://www.youtube.com/watch?v=7FBELQq808M

                                              child: Text(
                                                "Finish Posting",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 20,
                                                ),
                                              ),
                                            )
                                          ]).show();
                                    },
                                    child: Text(
                                      "Next >",
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 20,
                                      ),
                                    ),
                                  )
                                ],
                              ).show();
                            },
                            child: Text(
                              'Post',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

Thank you!

A: The flutter form builder package automatically fetches the ancestor Form to add field values in theirs. But since your form fields are now in dialog, they are not guaranteed to be inside the parent layout from which the dialog was invoked.
Ref from flutter documentation (Link)
This function takes a builder which typically builds a Dialog widget.
Content below the dialog is dimmed with a ModalBarrier. The widget returned by the
builder does not share a context with the location that showDialog is originally
called from. Use a StatefulBuilder or a custom StatefulWidget if the dialog needs
to update dynamically.

You can instead save the value of these fields in the state of your stateful widget and them combine all values later for future operations. Since you are already saving them in a variable qEleven and qTwelve you can use it later.
Here is the snippet of code doing this for qEleven (compare with this section of code in the question above):
FormBuilderRadioGroup(
                                      name: 'qEleven',
                                      decoration: const InputDecoration(
                                        border: InputBorder.none,
                                      ),
                                      orientation: OptionsOrientation.vertical,
                                      onChanged: (val) {
                                        print(val);
                                        qEleven = val;
                                      },
                                      options: [
                                        FormBuilderFieldOption(
                                          value: 'N',
                                          child: RichText(
                                            text: TextSpan(
                                              style: TextStyle(
                                                color: Colors.black,
                                              ),
                                              children: <TextSpan>[
                                                TextSpan(
                                                  text: 'No', // [ 10 ]
                                                  style: TextStyle(
                                                    fontWeight: FontWeight.w500,
                                                    fontSize: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),

And here is a screenshot that highlights the differences between to code in the question (left) and the code based on the answer (right):

Another thing that can be done, is to modify form builder package to also accept state, but it might break in case you are accessing an unmounted state.


text:
Q: Python wordsearch generator overlaps words So I have been trying to make a word search grid generator but I've got one problem with this code and I don't know how to solve it. This code generates the word search grid and puts the words from the list in it but sometimes some characters of that word get overwritten by another word (as the position assignment is random and doesn't consider the previously generated indices). I want to fix this but I don't know how...
import string
import random

height = 15
width = 15
def wordsearch(word,grid):
    word = random.choice([word])
    wordlength = len(word)

    direction = random.choice([[1,0],[0,1],[1,1]])
    xsize = width   if direction[0] == 0 else width  - wordlength
    ysize = height if direction[1] == 0 else height - wordlength

    x = random.randrange(0,xsize)
    y = random.randrange(0,ysize)

    print([x,y])

    for i in range(0,wordlength):
        grid[y + direction[1]*i][x + direction[0]*i] = word[i]
    return grid

grid = [[random.choice(string.ascii_lowercase) for i in range(0,width)] for j in range(0,height)]

for word in ['hello','red','yellow','green','blue','father','mother','sister','brother','food','drinks', 'cheese']:
    grid = wordsearch(word, grid)

print("\n".join(map(lambda row: " ".join(row), grid)))

For example at [1,0] it generates 'green' downwards but the first 'e' got replaced by the word 'blue' generated at [1,2].
[6, 1]
[12, 7]
[2, 4]
[1, 0]
[1, 2]
[7, 2]
[7, 4]
[11, 6]
[3, 9]
[7, 10]
[5, 0]
[6, 0]
t g n v x d c f y r s m d z o
t r f v j h r h l l o r e v e
y b y v w t w i e y v f r r m
z e l b w c e a n e y z c w j
a n y u l l o m z k s h u z d
u s i c e i z h o a s e c j r
l c g n v y k e c t b s g q g
e f b c p s f r x e h i r t f
y q p r t h h a z e o s e z h
o l x b r o t h e r e t r z x
m f m m n u o f j d s e i e e
v z u d k x t k o v i r d o k
l s q o q w a l o o u n y y v
m q c u r v w i f d d d a p g
b a h c f o y g g n x e v z s

A: You should check whether the word positions you are randomly choosing are "colliding" (overlapping) with any of the positions already chosen. If yes, discard that position and generate a new one.
For an example implementation I am representing a word placement with a tuple: (start_row, start_col, direction, length), then the collision could be checked like this:
(this is perhaps a grossly inefficient implementation but should be intuitive; also, for small matrices (<1000 rows) it should work just fine):
def get_points(word_placement):
    start_row, start_col, direction, length = word_placement
    if direction == 'vertical': # column remains same
        return [(start_row+i, start_col) for i in range(length)]

    elif direction == 'horizontal': # row stays  same
        return [(start_row, start_col+i) for i in range(length)]

    elif direction == 'diagonal':
        return [(start_row+i, start_col+i) for i in range(length)]

def do_they_collide (wa, wb):
    points_a = get_points(wa)
    points_b = get_points(wb)
    if len(set(points_a).intersection(set(points_b))) > 0:
        return True
    else:
        return False

## Let's take an example
wa = (0, 1, 'vertical', 5)   # green
wb = (3, 0, 'horizontal', 4) # blue

do_they_collide(wa, wb)


text:
Q: Append a row of data to jtable I am doing small project in java swing using JTable. When user select value from JComboBox I would like to add it to JTable. I have tried some code but it doesn't work. Please give some suggestions.

A: The key is in your use of a model, and the easiest solution is to have your JTable use a DefaultTableModel for its model and call its addRow(...) method to add a "row" of data to the JTable. There are many examples of just this sort of thing on this and other sites if you look.
If you need more specific help, then yes, post your code including the code that doesn't work, and ask specific questions. Best to post an sscce.

A: Declare a model to your table and just add rows to the table using the model
DefaultTableModel dtm = new DefaultTableModel();
JTable table = new JTable(dtm);

// Add Columns
dtm.addColumn("Col1");
dtm.addColumn("Col2");

// Add row data
dtm.addRow(...);
dtm.addRow(...);

Read about DefaultTableModel for knowing different methods it has.


text:
Q: What does "ii" in the first colums of the output of dpkg-query mean? I executed dpkg-query -l libgtk2.0-0 libgtk-3-0 to find out the version of those packages, and I got the following output.
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                       Version            Architecture       Description
+++-==========================-==================-==================-==========================================================
ii  libgtk-3-0:amd64           3.22.30-1ubuntu1   amd64              GTK+ graphical user interface library
ii  libgtk2.0-0:amd64          2.24.32-1ubuntu1   amd64              GTK+ graphical user interface library

From man dpkg-query I get the following description for the first columns.
The first three columns of the output show the desired action, the package status, and errors, in that order.
          Desired action:
            u = Unknown
            i = Install
            h = Hold
            r = Remove
            p = Purge

          Package status:
            n = Not-installed
            c = Config-files
            H = Half-installed
            U = Unpacked
            F = Half-configured
            W = Triggers-awaiting
            t = Triggers-pending
            i = Installed

          Error flags:
            <empty> = (none)
            R = Reinst-required

From that description, ii would mean the desired action is install and that package is installed. It confuses me, as I would expect I don't need to take any action, if the package is already installed.
What exactly is that output telling me? Do I need to update the package, or is it already updated?

A: As you say,

From that description, ii would mean the desired action is install but that the package is installed.

This means that the desired state for the package is "installed", and that the current state of the package is "installed". Since both match, no change is needed. The action column doesn't specify actions you need to take, it specifies actions that the packaging system is supposed to take — in effect, this states that you've asked the packaging system to install these packages, directly or indirectly (via dependencies).
It doesn't say anything about whether the package is up-to-date; you need to look at the output of
apt policy libgtk2.0-0 libgtk-3-0

to determine that.
dpkg-query only looks at the local package database in /var/lib/dpkg/status, so it doesn't know about other package versions. APT is the tool which deals with package repositories and knows which versions of a package are available (and candidates for installation).

A: It says in the manual extract that you include in the question, it says in the header of the output.
Header
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/

Manual (edited to remove distractions)
Desired action:
    i = Install

Package status:
    i = Installed

It may be that you are miss-understanding the meaning of column, in the manual. They here mean a single character. Also I think the manual has a small error. It says desired action, but I think it means desired state.


text:
Q: $watch not firing for transcluded directive I'm using angularjs and I wrote a combobox and a tabs directive for my application which I want to use like this:
<tabs>
   <tab>Some content</tab>
   <tab>Some other content
     <my-combobox options="options" selection="selection">
   </tab>
</tab>

My problem is that at the moment, I can't watch properties changed by the combobox when it's inside a tab, meaning if I do this:
$scope.$watch("selection", function(){
     console.log("this code doesn't run when selection changes")
});

My watch doesn't fire when the user selects item from the combobox.
What puzzles me is that it does work when I take the combobox out of the tab

<my-combobox options="options" selection="selection">
<tabs>
   <tab>Some content</tab>
   <tab>Some other content</tab>
</tab>

So my question is how are the tabs affecting the watch of elements transcluded in them and how to fix it?
this is the code for the tabs directive:
angular.module("ip").directive("tabs", [function () {
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        templateUrl: "/Content/Directives/tabs.html",
        bindToController: true,
        controllerAs: "tabsController",
        scope: {
            onTabSelected: "=?"
        },
        controller: function () {
            var self = this;
            self.tabs = [];

            self.addTab = function (tab) {
                self.tabs.push(tab);

                if (self.tabs.length === 1) {
                    tab.active = true;
                    self.onTabSelected(tab);
                }
            }

            self.select = function (selectedTab) {
                angular.forEach(self.tabs, function (tab) {
                    if (tab.active && tab !== selectedTab) {
                        tab.active = false;
                    }
                });

                selectedTab.active = true;
                if (self.onTabSelected) { self.onTabSelected(selectedTab); }
            }
        }
    };
}]);

(Edit)
This is my code for the tabs.html file:

            {{tab.tabTitle}}

    <ng-transclude>
    </ng-transclude>

And the tab.js directive
angular.module("ip").directive("tab", [function () {
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        templateUrl: "/Content/Directives/tab.html",
        require: "^tabs",
        scope: {
            tabTitle: "@"
        },
        link: function (scope, element, attr, tabsCtrl) {
            scope.active = false;
            tabsCtrl.addTab(scope);
        }
    };
}]);

A: This is a data hiding problem. The corrected and working DEMO on PLNKR.

    <select ng-model="x.selection">
       <option value="a">A</option>
       <option value="b">B</option>
       <option value="c">C</option>
    </select>
    selection={{x.selection}}
    <tabs>
      <tab>Some content</tab>
      <tab>Some other content selection={{x.selection}}

         <my-combobox options="options" selection="x.selection">
         </my-combobox>
      </tab>
   </tabs>

Scope inheritance is normally straightfoward... until you need 2-way data binding. If you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. To fix, define objects in the parent for your model, then reference a property of that object in the child.
For more information, see

*

*What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
When a directive defines a new isolate scope, the $compile service creates a separate new inherited scope for linking transcluded contents, the so-called "correct transclusion scope" in the documentation.
See

*

*AngularJS Comprehensive Directive API Reference - DDO controller property

*AngularJS $compile Service API Reference - Transclusion functions