问:
SQL error 1064 in simple cakePHP setup
I am using the simplest controller and model as shown here:

http://book.cakephp.org/view/1341/Basic-Usage

But when i go to www.mysite.com/categories
the code that causes it is:

```<code><?php
class CategoriesController extends AppController {

    var $name = 'Categories';

    function index() {
        $this->data = $this->Category->generatetreelist(null, null, null, '   ');
        debug ($this->data); die;
    }
}
?>
</code>```

i get the following error:

```<code>Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Code | Context

            $out = null;
            if ($error) {
                trigger_error('<span style="color:Red;text-align:left"><b>' . __('SQL Error:', true) . "</b> {$this->error}</span>", E_USER_WARNING);

$sql    =   "recover"
$error  =   "1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1"
$out    =   null

DboSource::showQuery() - CORE/cake/libs/model/datasources/dbo_source.php, line 684
DboSource::execute() - CORE/cake/libs/model/datasources/dbo_source.php, line 266
DboSource::fetchAll() - CORE/cake/libs/model/datasources/dbo_source.php, line 410
DboSource::query() - CORE/cake/libs/model/datasources/dbo_source.php, line 364
Model::call__() - CORE/cake/libs/model/model.php, line 502
Overloadable::__call() - CORE/cake/libs/overloadable_php5.php, line 50
AppModel::recover() - [internal], line ??
CategoriesController::index() - APP/controllers/categories_controller.php, line 7
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83

Query: recover

app/controllers/categories_controller.php (line 8)
</code>```

I am totally confused, since I just copy-pasted from the original cakephp cookbook tutorial.

I have:
controllers/categories_controller.php
models/category_model.php
and the code is copy paste from the tutorial.

Any help?

答:
Problem solved. Misnaming the model file.
It Was: category_model.php
Should have been: category.php =(</p>

Title: SQL error 1064 in simple cakePHP setup

Body:
I am using the simplest controller and model as shown here:

http://book.cakephp.org/view/1341/Basic-Usage

But when i go to www.mysite.com/categories
the code that causes it is:

<?php
class CategoriesController extends AppController {

    var $name = 'Categories';

    function index() {
        $this->data = $this->Category->generatetreelist(null, null, null, '   ');
        debug ($this->data); die;
    }
}
?>

i get the following error:

Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Code | Context

            $out = null;
            if ($error) {
                trigger_error('' . __('SQL Error:', true) . " {$this->error}", E_USER_WARNING);

$sql    =   "recover"
$error  =   "1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1"
$out    =   null

DboSource::showQuery() - CORE/cake/libs/model/datasources/dbo_source.php, line 684
DboSource::execute() - CORE/cake/libs/model/datasources/dbo_source.php, line 266
DboSource::fetchAll() - CORE/cake/libs/model/datasources/dbo_source.php, line 410
DboSource::query() - CORE/cake/libs/model/datasources/dbo_source.php, line 364
Model::call__() - CORE/cake/libs/model/model.php, line 502
Overloadable::__call() - CORE/cake/libs/overloadable_php5.php, line 50
AppModel::recover() - [internal], line ??
CategoriesController::index() - APP/controllers/categories_controller.php, line 7
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83

Query: recover

app/controllers/categories_controller.php (line 8)

I am totally confused, since I just copy-pasted from the original cakephp cookbook tutorial.

I have:
controllers/categories_controller.php
models/category_model.php
and the code is copy paste from the tutorial.

Any help?


来源: stackexchange

问:
Vue Router - build from JSON
I'm quite new to Vue.js. I'm used to vanilla JavaScript.

I need to be able to generate route paths from a JSON file.

How can I achieve it?

EDIT

For example, say this is my JSON:

```<code>[
  {
    "name": "Product 1",
    "url": "product-1",
  },
  {
    "name": "Product 2",
    "url": "product-2",
  }
]
</code>```

I basically need Vue Router to redirect URL/product-1 to Product 1's component (which will be <Product-1></Product-1>), and URL/product-2 to Product 2's component (<Product-2></Product-2>)

答:
Assuming your component's name is name in the object, we need to match your structure to Vue Router API.
Thus, we can do as follows:

const myRoutes = [
  {
    "name": "Product 1",
    "url": "product-1",
  },
  {
    "name": "Product 2",
    "url": "product-2",
  }
]

const router = new VueRouter({
  routes: myRouters
          .map(({name, url})=>({component: name, path: `/${url}`)),
})
```

ContentLicense: CC BY-SA 4.0

Title: Vue Router - build from JSON

Body:
I'm quite new to Vue.js. I'm used to vanilla JavaScript.

I need to be able to generate route paths from a JSON file.

How can I achieve it?

EDIT

For example, say this is my JSON:

[
  {
    "name": "Product 1",
    "url": "product-1",
  },
  {
    "name": "Product 2",
    "url": "product-2",
  }
]

I basically need Vue Router to redirect URL/product-1 to Product 1's component (which will be <Product-1></Product-1>), and URL/product-2 to Product 2's component (<Product-2></Product-2>)


问:
How to construct a list of tuples of all possible combinations
I just can't come up with a way to solve my problem: x is an integer. I want a list of all possibles combinations of  x-tuples where those tuples' elements are in range from 0 to x (excluding x).

So if x = 3 I have 3^3 combinations: [(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)].

If x = 4 I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}.

Body:
Here's the proper way to use itertools to get what you want:

list(itertools.product(range(3), repeat=3))

The output is:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1),
 (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0),
 (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2),
 (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1),
 (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0),
 (2, 2, 1), (2, 2, 2)]

Of course, this can scale up by using values other than 3.  In general:

list(itertools.product(range(x), repeat=x))

will work for any x.


问:
Model validation on a page model wrapping a DTO
I have been playing around with ASP.NET Core MVC for quite a while and now I'm facing an set-back. I have implemented my project using CQRS using mediatR and automapper but I cannot seem to find  proper way to validate my page models.

My design is based on have the entities separated from the pages. The commands/queries return a page model which usually wraps a DTO which implements has a profile for inline maps to map from an entity to the DTO.

How could one use validation and display error messages to the page by validating a DTO wrapped inside a page model?

Now, for some demo code:

A demo query:

```<code>namespace HM.Application.Queries
{
    public class GetAllMedicsQuery : IRequest<MedicIndexModel> { }

    public class GetAllMedicsQueryHandler : IRequestHandler<GetAllMedicsQuery, MedicIndexModel>
    {
        private readonly IMedicRepository _medicRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetAllMedicsQueryHandler> _logger;

        public GetAllMedicsQueryHandler(IMedicRepository medicRepository, IMapper mapper, ILogger<GetAllMedicsQueryHandler> logger)
        {
            _medicRepository = medicRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<MedicIndexModel> Handle(GetAllMedicsQuery request, CancellationToken cancellationToken)
        {
            var medics = await _medicRepository.GetAllMedics();
            MedicIndexModel medicIndexModel = new MedicIndexModel()
            {
                Medics = _mapper.Map<IEnumerable<MedicIndexDTO>>(medics)
            };

            return medicIndexModel;
        }
    }
}
</code>```

The page model:

```<code>namespace HM.Application.ViewModels
{
    public class MedicIndexModel : PageModel
    {
        public IEnumerable<MedicIndexDTO> Medics { get; set; }
    }
}
</code>```

And the DTO:

```<code>namespace HM.DTO
{
    public class MedicIndexDTO : IHaveCustomMapping
    {
        public string id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string email { get; set; }
        public string rank { get; set; }

        public void CreateMappings(Profile configuration)
        {
            configuration.CreateMap<Medic, MedicIndexDTO>()
                .ForMember(medicDto => medicDto.id, options => options.MapFrom(medic => medic.Id))
                .ForMember(medicDto => medicDto.firstName, options => options.MapFrom(medic => medic.firstName))
                .ForMember(medicDto => medicDto.lastName, options => options.MapFrom(medic => medic.lastName))
                .ForMember(medicDto => medicDto.email, options => options.MapFrom(medic => medic.Email))
                .ForMember(medicDto => medicDto.rank, options => options.MapFrom(medic => medic.rank));
        }
    }
}
</code>```

Thanks!

答:
Suppose you have a custom page model, let it be MyCustomPageModel which inherits PageModel and it contains a DTO of some kind. This DTO contains some properties which have attribute validation or other form of validation. When used as the page model, the validation will still work for the fields inside the DTO, although it does not inherit himself the PageModel. To put it together, one can write

```<code>public class MyCustomPageModel : PageModel {
    public SomeDTO dto  {get; set;}
}
</code>```

and have working validation!

Body:
I have been playing around with ASP.NET Core MVC for quite a while and now I'm facing an set-back. I have implemented my project using CQRS using mediatR and automapper but I cannot seem to find  proper way to validate my page models.

My design is based on have the entities separated from the pages. The commands/queries return a page model which usually wraps a DTO which implements has a profile for inline maps to map from an entity to the DTO.

How could one use validation and display error messages to the page by validating a DTO wrapped inside a page model?

Now, for some demo code:

A demo query:

namespace HM.Application.Queries
{
    public class GetAllMedicsQuery : IRequest<MedicIndexModel> { }

    public class GetAllMedicsQueryHandler : IRequestHandler<GetAllMedicsQuery, MedicIndexModel>
    {
        private readonly IMedicRepository _medicRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetAllMedicsQueryHandler> _logger;

        public GetAllMedicsQueryHandler(IMedicRepository medicRepository, IMapper mapper, ILogger<GetAllMedicsQueryHandler> logger)
        {
            _medicRepository = medicRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<MedicIndexModel> Handle(GetAllMedicsQuery request, CancellationToken cancellationToken)
        {
            var medics = await _medicRepository.GetAllMedics();
            MedicIndexModel medicIndexModel = new MedicIndexModel()
            {
                Medics = _mapper.Map<IEnumerable<MedicIndexDTO>>(medics)
            };

            return medicIndexModel;
        }
    }
}

The page model:

namespace HM.Application.ViewModels
{
    public class MedicIndexModel : PageModel
    {
        public IEnumerable<MedicIndexDTO> Medics { get; set; }
    }
}

And the DTO:

namespace HM.DTO
{
    public class MedicIndexDTO : IHaveCustomMapping
    {
        public string id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string email { get; set; }
        public string rank { get; set; }

        public void CreateMappings(Profile configuration)
        {
            configuration.CreateMap<Medic, MedicIndexDTO>()
                .ForMember(medicDto => medicDto.id, options => options.MapFrom(medic => medic.Id))
                .ForMember(medicDto => medicDto.firstName, options => options.MapFrom(medic => medic.firstName))
                .ForMember(medicDto => medicDto.lastName, options => options.MapFrom(medic => medic.lastName))
                .ForMember(medicDto => medicDto.email, options => options.MapFrom(medic => medic.Email))
                .ForMember(medicDto => medicDto.rank, options => options.MapFrom(medic => medic.rank));
        }
    }
}

Thanks!

Body:
Suppose you have a custom page model, let it be MyCustomPageModel which inherits PageModel and it contains a DTO of some kind. This DTO contains some properties which have attribute validation or other form of validation. When used as the page model, the validation will still work for the fields inside the DTO, although it does not inherit himself the PageModel. To put it together, one can write

public class MyCustomPageModel : PageModel {
    public SomeDTO dto  {get; set;}
}

and have working validation!


问:
queue implementation does not return first element
I want to emulate a queue by using linked lists in Java. My general schema is to have a list of nodes, with two nodes that points to the first and last element of my queue. When I perform the dequeue() I want to get ride of the first element. So far what I have done is the following:

```<code>public class Node {
    public Object e;
    Node next;

    public Node(Object e) {
        this.e = e;
    }
}

public class Queue {
    Node queueList;
    Node first, last;
    int count;

    public void enQueue(Object n) {
        Node temp = new Node(n);
        temp.next = last;
        last = temp;
        if (queueList == null) {
            first = temp;
        }
        count++;
        queueList=temp;
    }

    public Object deQueue() {
        Node previous = last;
        Node current = last.next;
        Object num = null;
        if (count == 0)
            System.out.println("empty queue");
        else {
            while (current.next != null) {
                previous = previous.next;
                current = current.next;
            }
            num = first.e;
            first = previous;
            count--;
        }
        return num;
    }

    public void print() {
        Node current = last;
        while (current != null) {
            System.out.println(current.e);
            current = current.next;
        }
    }
}
</code>```

I do not want to use double linked lists, so for the dequeue() operation what I do is to traverse my list with two pointers like this:

So when the current.next points to a null, I want that previous to be the first node. The problem that I got is when I print the elements of my queue it stills prints me: 10,15,5,18, but the 18 value is not deleted. Any help?

Thanks

答:
There are basically two things I would correct in your code.
First of all, the Queue field was not assigned any value, and I also doubt its utility, basically its logic can be applied using first

```<code>public void enQueue(Object n) {
    Node temp = new Node(n);
    temp.next = last;
    last = temp;
    if (first == null) { <--- HERE
        first = temp;
    }
    count++;
}
</code>```

The second one is that you never put the value of the new head of the queue next to null which is needed in that case

```<code>public Object deQueue() {
    Node previous = last;
    Node current = last.next;
    Object num = null;
    if (count == 0) System.out.println("empty queue");
    else {
        while (current.next != null) {
            previous = previous.next;
            current = current.next;
        }
        num = first.e;
        first = previous;
        first.next = null; <--- HERE
        count--;
    }
    return num;
}
</code>```

Body:
I want to emulate a queue by using linked lists in Java. My general schema is to have a list of nodes, with two nodes that points to the first and last element of my queue. When I perform the dequeue() I want to get ride of the first element. So far what I have done is the following:

public class Node {
    public Object e;
    Node next;

    public Node(Object e) {
        this.e = e;
    }
}

public class Queue {
    Node queueList;
    Node first, last;
    int count;

    public void enQueue(Object n) {
        Node temp = new Node(n);
        temp.next = last;
        last = temp;
        if (queueList == null) {
            first = temp;
        }
        count++;
        queueList=temp;
    }

    public Object deQueue() {
        Node previous = last;
        Node current = last.next;
        Object num = null;
        if (count == 0)
            System.out.println("empty queue");
        else {
            while (current.next != null) {
                previous = previous.next;
                current = current.next;
            }
            num = first.e;
            first = previous;
            count--;
        }
        return num;
    }

    public void print() {
        Node current = last;
        while (current != null) {
            System.out.println(current.e);
            current = current.next;
        }
    }
}

I do not want to use double linked lists, so for the dequeue() operation what I do is to traverse my list with two pointers like this:

So when the current.next points to a null, I want that previous to be the first node. The problem that I got is when I print the elements of my queue it stills prints me: 10,15,5,18, but the 18 value is not deleted. Any help?

Thanks

Body:
There are basically two things I would correct in your code.
First of all, the Queue field was not assigned any value, and I also doubt its utility, basically its logic can be applied using first

public void enQueue(Object n) {
    Node temp = new Node(n);
    temp.next = last;
    last = temp;
    if (first == null) { <--- HERE
        first = temp;
    }
    count++;
}

The second one is that you never put the value of the new head of the queue next to null which is needed in that case

public Object deQueue() {
    Node previous = last;
    Node current = last.next;
    Object num = null;
    if (count == 0) System.out.println("empty queue");
    else {
        while (current.next != null) {
            previous = previous.next;
            current = current.next;
        }
        num = first.e;
        first = previous;
        first.next = null; <--- HERE
        count--;
    }
    return num;
}


问:
finding whether the body contains gzipped data
i have a program wherein it searches the reply from a curl request for specific strings. i sometimes get gzipped data. is there a way to find whether the reply is text or gzipped format?
header sometimes contain gziipped,deflate header, but its not consistent. is there a way to search the string and find if its gzipped?</p>

答:
You could try taking a look at the first two bytes of data. For gzipped data, they should be 0x1f, 0x8b.</p>

```<code>Member header and trailer

ID1 (IDentification 1)
ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213),
to identify the file as being in gzip format.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could try taking a look at the first two bytes of data. For gzipped data, they should be 0x1f, 0x8b.

Member header and trailer

ID1 (IDentification 1)
ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213),
to identify the file as being in gzip format.


问:
How can i use forEach for Json Array in javascript
Hi Everyove i have a json array GelenDeger is like

```<code>>GelenDeger
{Localizations: null, Languages: null, AgencyModels: null, GetCitiesModel: {…}, GetCountyModel: null, …}
AgencyAddress: null
GetCitiesModel: {IL_KOD: "35", IL_AD: null, ULKE_KOD: null}
GetCountyModel: null
HtmlResult: ""
M_ACENTE: (4) [{…}, {…}, {…}, {…}]
countryCode: 1234
</code>```

and I can get when I click the button

GelenDeger.M_ACENTE[0].ADRES_TEXT

and

GelenDeger.M_ACENTE[0].ACENTE_AD

but I need a loop and without having to use indexes like [0] or [1] or [2] but I don't know how can to do this. Can you help me on this. Thanks.

My js code :

```<code>function jsFiltreleme(GelenDeger) {
                    $("#myDiv").append(
                        "<div style='border-style:ridge;'>adress : <strong>" + GelenDeger.M_ACENTE[0].ADRES_TEXT + "</strong><br>" +
                        "name : <strong>" + GelenDeger.M_ACENTE[0].ACENTE_AD+ "</strong></div>"
                    );
                }
</code>```

My html code :

```<code><li class="none buttonBox">
    <input id="register" type="submit" value="Search">
</li>
<div id="myDiv"></div>
</code>```

BTW my JSON array can be changeable like M_ACENTE: (10) [{…}, {…}, {…}, {…}]

答:
You can use forEach() for that purpose.

```<code>function jsFiltreleme(GelenDeger) {
      GelenDeger.M_ACENTE.forEach(acente => {
        $("#myDiv").append(
          "<div style='border-style:ridge;'>adress : <strong>" + acente.ADRES_TEXT + "</strong><br>" +
          "name : <strong>" + acente.ACENTE_AD + "</strong></div>"
        );
      });
 }
</code>```

You can check if the div is not empty and then clearing it.

```<code>if ($("#myDiv").html() !== "") {
  $("#myDiv").html() = ""
}
</code>```

Body:
Hi Everyove i have a json array GelenDeger is like

>GelenDeger
{Localizations: null, Languages: null, AgencyModels: null, GetCitiesModel: {…}, GetCountyModel: null, …}
AgencyAddress: null
GetCitiesModel: {IL_KOD: "35", IL_AD: null, ULKE_KOD: null}
GetCountyModel: null
HtmlResult: ""
M_ACENTE: (4) [{…}, {…}, {…}, {…}]
countryCode: 1234

and I can get when I click the button

GelenDeger.M_ACENTE[0].ADRES_TEXT

and

GelenDeger.M_ACENTE[0].ACENTE_AD

but I need a loop and without having to use indexes like [0] or [1] or [2] but I don't know how can to do this. Can you help me on this. Thanks.

My js code :

function jsFiltreleme(GelenDeger) {
                    $("#myDiv").append(
                        "
adress : " + GelenDeger.M_ACENTE[0].ADRES_TEXT + "
" +
                        "name : " + GelenDeger.M_ACENTE[0].ACENTE_AD+ "
"
                    );
                }

My html code :

    <input id="register" type="submit" value="Search">

BTW my JSON array can be changeable like M_ACENTE: (10) [{…}, {…}, {…}, {…}]

Body:
You can use forEach() for that purpose.

function jsFiltreleme(GelenDeger) {
      GelenDeger.M_ACENTE.forEach(acente => {
        $("#myDiv").append(
          "<div style='border-style:ridge;'>adress : <strong>" + acente.ADRES_TEXT + "</strong><br>" +
          "name : <strong>" + acente.ACENTE_AD + "</strong></div>"
        );
      });
 }

You can check if the div is not empty and then clearing it.

if ($("#myDiv").html() !== "") {
  $("#myDiv").html() = ""
}


问:
git diff ignore semicolon at end of line
A colleague has created a commit where his editor has appended semicolons to each line (amongst other changes).

I know that I can use the -w switch to ignore whitespace errors. Would there be some kind of git magic to make git ignore ; altogether, or even better only when at EOL ?

Something like:

```<code>git diff --ignore=; -w
</code>```

答:
Maybe you can solve that with the --word-diff-regex option. This is what I did: I created a simple file and committed it with the following content.

```<code>first line
second line
third line
</code>```

Then I modified it like this:

```<code>first line;
second; line;
third changed line;
</code>```

If I have correctly understood, you need to show only the following differences:
second -> second;
third line -> third changed line

You can partially do this executing:

```<code>git diff  --word-diff-regex='[^ \\n;]+' HEAD..HEAD~1
</code>```

And this is the output:

```<code>first line
second line
third[-changed-] line
</code>```

I said partially because even if I found a regex to detect also the first change ('[^ \\n]+(?!\\n|$)'), git does not seem to accept it, for some reason I am not aware of (I am still working on it).

Anyway, the logic behind it is that this option "overrides" how git considers a word. I know this is not the right regex since it is not covering several cases, change it based on your needs (for example if you consider test1;test2 a word).

Body:
A colleague has created a commit where his editor has appended semicolons to each line (amongst other changes).

I know that I can use the -w switch to ignore whitespace errors. Would there be some kind of git magic to make git ignore ; altogether, or even better only when at EOL ?

Something like:

git diff --ignore=; -w

Body:
Maybe you can solve that with the --word-diff-regex option. This is what I did: I created a simple file and committed it with the following content.

first line
second line
third line

Then I modified it like this:

first line;
second; line;
third changed line;

If I have correctly understood, you need to show only the following differences:
second -> second;
third line -> third changed line

You can partially do this executing:

git diff  --word-diff-regex='[^ \\n;]+' HEAD..HEAD~1

And this is the output:

first line
second line
third[-changed-] line

I said partially because even if I found a regex to detect also the first change ('[^ \\n]+(?!\\n|$)'), git does not seem to accept it, for some reason I am not aware of (I am still working on it).

Anyway, the logic behind it is that this option "overrides" how git considers a word. I know this is not the right regex since it is not covering several cases, change it based on your needs (for example if you consider test1;test2 a word).


问:
which way is best and worst to find and display customer lived in newyork? stateful or stateless or singleton?
I am trying to get the number of customer who lived in newyork and display on my page. But some doubt in my mind, which way is best to worst, Like stateless, stateful and singleton ejb? Any idea, which way i have to implement my application.

答:
In this case it would be Stateless.
As long as there is no state accross several invocations there is no need for a Stateful Bean.
A singleton could be a bottleneck, as i would not use a method like getCustomersinNewYork() but getCustomers(City city), and a Singleton is only one instance which should be used to synchronize. But it is possible to have the method concurrent and store a Map with results for each City - but consider you need to handle the concurrency.

From my point of view I would keep the application stateless and let the StatelessBean calcuate the number of customers per city for each request.
If there is a need to enhance the performance because the requests are repeated I would use a cache like Infinispan to store that - i.e. with expiration to recalculate the number from time to time or let it drop it not used for longer.

Make sense?


问:
React-Native authentication with Azure AD
I am building an app in react-native and need to authenticate to a server via Azure AD. I have tried to google this but surprisingly there is not much content related to this.
I have found this library 'react-native-azure-ad' but not so much documentation about it. I dont understand how to use it.
My main questions is: Where do I need to place my server's url when using this library, in order to authenticate to it?

Thanks for any suggestions!

EDIT:

Here is my code:

```<code>    import { ReactNativeAD, ADLoginView } from 'react-native-azure-ad'

const CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

    class LandingView2 extends React.Component {

        constructor(props) {
            super(props)
            this.AzureADContext = {
                client_id: CLIENT_ID,
                // Optional
                redirect_url: 'http://localhost:8080',
                // Optional
                authority_host: 'xxxx',
                // Optional
                tenant: 'common',
                // Optional
                prompt: 'none',
                // Optional
                login_hint: 'user@domain.com',
                // This is required if client_id is a web application id
                // but not recommended doing this way.
                client_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                resources: [
                    'https://graph.microsoft.com',
                    'https://outlook.office365.com',
                    // ... more resources
                ]
            }
        }

        render() {

            new ReactNativeAD({
                client_id: CLIENT_ID,
                resources: [
                    'https://outlook.office365.com'
                ]
            })

            return <ADLoginView
                context={ReactNativeAD.getContext(CLIENT_ID)}
                onSuccess={this.onLoginSuccess.bind(this)} />
        }

        onLoginSuccess(credentials) {
            console.log(credentials['https://outlook.office365.com'].access_token)
            // use the access token ..
        }

    }
</code>```

答:
You need to create two applications in AAD.

a native application for your app

another application for your server/API

You can then use the clientId or AppID URI of the API as the "resource" for the code shown in the question. All the other parameters are taken from your client app.

If everything is successful, you will get an access token which you can then use as a bearer token when calling your API.

```<code>credentials['https://yourtenant.onmicrosoft.com/yourapiname'].access_token
</code>```

Body:
I am building an app in react-native and need to authenticate to a server via Azure AD. I have tried to google this but surprisingly there is not much content related to this.
I have found this library 'react-native-azure-ad' but not so much documentation about it. I dont understand how to use it.
My main questions is: Where do I need to place my server's url when using this library, in order to authenticate to it?

Thanks for any suggestions!

EDIT:

Here is my code:

    import { ReactNativeAD, ADLoginView } from 'react-native-azure-ad'

const CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

    class LandingView2 extends React.Component {

        constructor(props) {
            super(props)
            this.AzureADContext = {
                client_id: CLIENT_ID,
                // Optional
                redirect_url: 'http://localhost:8080',
                // Optional
                authority_host: 'xxxx',
                // Optional
                tenant: 'common',
                // Optional
                prompt: 'none',
                // Optional
                login_hint: 'user@domain.com',
                // This is required if client_id is a web application id
                // but not recommended doing this way.
                client_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                resources: [
                    'https://graph.microsoft.com',
                    'https://outlook.office365.com',
                    // ... more resources
                ]
            }
        }

        render() {

            new ReactNativeAD({
                client_id: CLIENT_ID,
                resources: [
                    'https://outlook.office365.com'
                ]
            })

            return <ADLoginView
                context={ReactNativeAD.getContext(CLIENT_ID)}
                onSuccess={this.onLoginSuccess.bind(this)} />
        }

        onLoginSuccess(credentials) {
            console.log(credentials['https://outlook.office365.com'].access_token)
            // use the access token ..
        }

    }

Body:
You need to create two applications in AAD.

a native application for your app

another application for your server/API

You can then use the clientId or AppID URI of the API as the "resource" for the code shown in the question. All the other parameters are taken from your client app.

If everything is successful, you will get an access token which you can then use as a bearer token when calling your API.

credentials['https://yourtenant.onmicrosoft.com/yourapiname'].access_token


问:
Create object of class from string user input Python
Say I want to implement a simple database in Python. I do this by creating a class

```<code>class myStruct():
    def __init__(self,name,salary,doB,title):
        self.name=name
        self.salary=salary
        self.doB=doB
        self.title=title
</code>```

Now, I want to create objects of that class. But I want users to input all the variables themselves for each object, and the name of the object would be the user inputted name. I saw some other StackOverflow pages describing something like this, such as this link how to dynamically create an instance of a class in python?
but that had to do with a classes imported from another module, and I didn't understand klass=global()["class_name"]. I don't understand how to link from user inputted string to use global().

Again, the idea is even the name of every object of class myStruct is typed in by the user, along with all the other fields for that object. How would I do this?

EDIT: I don't think some people understood what I was trying to do. The point is not to write out

```<code>instance=MyStruct(name,salary,doB,title)
</code>```

in my code but instead, to have a function that creates an instance that's named after whatever user inputted for name. so it would be something like

```<code>name=input('Enter your name')
'%s' %name=MyStruct(name)
</code>```

Do you get it? The name is substituted in.

答:
I was running into a similar problem ... But in my case, my input "names" are from a file and the number of attributes can vary. The following is my current solution. I'm sure there are better ways to do this, and I hope someone else can provide those.

```<code>import numpy as np

class Target():
    sample = {}
    @classmethod
    def create(cls, name):
        target = Target(name)
        cls.sample[name] = target
        return target
    def __init__(self, name):
        self.name = name

names = ('Moon', 'Earth', 'Mars')
# gravity in units of m / s^{-2}
grav = np.array([1.620, 9.807, 3.711])
sample = {}
for idx in np.arange(0, len(names), 1):
    name = names[idx]
    sample[name] = Target(name)
    setattr(sample[name], 'grav', grav[idx])
    if (name == names[1]):
        # number of moons
        setattr(sample[name], 'num_moons', 1)
    elif (name == names[2]):
        # number of moons
        setattr(sample[name], 'num_moons', 2)

for idx in np.arange(0, len(names), 1):
    name = names[idx]
    print(sample[names[idx]].name + ':')
    print('    Gravity = %.3f (m s^{-2})'%sample[names[idx]].grav)
    if (idx == 1):
        print('    Number of moons = %i'%(sample[names[idx]].num_moons))
</code>```

P.S. You can imagine that my input file has three lines, and each line has different length (but not difficult to convert into lists, numpy arrays).
Moon 1.620
Earth 9.807 1
Mars 3.711 2

Body:
Say I want to implement a simple database in Python. I do this by creating a class

class myStruct():
    def __init__(self,name,salary,doB,title):
        self.name=name
        self.salary=salary
        self.doB=doB
        self.title=title

Now, I want to create objects of that class. But I want users to input all the variables themselves for each object, and the name of the object would be the user inputted name. I saw some other StackOverflow pages describing something like this, such as this link how to dynamically create an instance of a class in python?
but that had to do with a classes imported from another module, and I didn't understand klass=global()["class_name"]. I don't understand how to link from user inputted string to use global().

Again, the idea is even the name of every object of class myStruct is typed in by the user, along with all the other fields for that object. How would I do this?

EDIT: I don't think some people understood what I was trying to do. The point is not to write out

instance=MyStruct(name,salary,doB,title)

in my code but instead, to have a function that creates an instance that's named after whatever user inputted for name. so it would be something like

name=input('Enter your name')
'%s' %name=MyStruct(name)

Do you get it? The name is substituted in.

Body:
I was running into a similar problem ... But in my case, my input "names" are from a file and the number of attributes can vary. The following is my current solution. I'm sure there are better ways to do this, and I hope someone else can provide those.

import numpy as np

class Target():
    sample = {}
    @classmethod
    def create(cls, name):
        target = Target(name)
        cls.sample[name] = target
        return target
    def __init__(self, name):
        self.name = name

names = ('Moon', 'Earth', 'Mars')
# gravity in units of m / s^{-2}
grav = np.array([1.620, 9.807, 3.711])
sample = {}
for idx in np.arange(0, len(names), 1):
    name = names[idx]
    sample[name] = Target(name)
    setattr(sample[name], 'grav', grav[idx])
    if (name == names[1]):
        # number of moons
        setattr(sample[name], 'num_moons', 1)
    elif (name == names[2]):
        # number of moons
        setattr(sample[name], 'num_moons', 2)

for idx in np.arange(0, len(names), 1):
    name = names[idx]
    print(sample[names[idx]].name + ':')
    print('    Gravity = %.3f (m s^{-2})'%sample[names[idx]].grav)
    if (idx == 1):
        print('    Number of moons = %i'%(sample[names[idx]].num_moons))

P.S. You can imagine that my input file has three lines, and each line has different length (but not difficult to convert into lists, numpy arrays).
Moon 1.620
Earth 9.807 1
Mars 3.711 2


问:
Laravel Dusk - Failed to connect to localhost port 9515: Connection refused
I want to create a test which I will use from Controller so I write:

```<code><?php

namespace App\Http\Controllers\Modules;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Dusk\ElementResolver;
use Exception;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;

class TestController extends Controller {

  public function test() {

    $process = (new ChromeProcess)->toProcess();
    if ($process->isStarted()) {
      $process->stop();
    }
    $process->start();

    $options      = (new ChromeOptions)->addArguments(['--disable-gpu', '--headless', '--no-sandbox']);
    $capabilities = DesiredCapabilities::chrome()
      ->setCapability(ChromeOptions::CAPABILITY, $options);

          $driver = retry(1, function () use ($capabilities) {
      return RemoteWebDriver::create('http://localhost:9515', $capabilities, 60000, 60000);
    }, 50);

    $browser = new Browser($driver, new ElementResolver($driver, ''));
    $browser->resize(1920, 1080);
    $browser->visit('https://example.com/login')->click('#.btn > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block');
    $browser->driver->takeScreenshot(base_path('tests/Browser/screenshots/logged.png'));

  }

}
</code>```

When I run this script using localhost:8000/test I got this message:

Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error
  thrown for http POST to /session with params:
  {"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"binary":"","args":["--disable-gpu","--headless","--no-sandbox"]}}}
  Failed to connect to localhost port 9515: Connection refused

How I can solve this problem?

Current I use WAMP server on Win10 for local testing but then I will move the code on Linux Ubuntu 18.

答:
I can't fully explain it, but this works for me on Windows:

```<code>$process = (new ChromeProcess)->toProcess();
if ($process->isStarted()) {
  $process->stop();
}

$process->start(null, [
    'SystemRoot' => 'C:\\WINDOWS',
    'TEMP' => 'C:\Users\<User>\AppData\Local\Temp',
]);

[...]
</code>```

Replace <User> with the name of your user directory.

Body:
I want to create a test which I will use from Controller so I write:

<?php

namespace App\Http\Controllers\Modules;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Dusk\ElementResolver;
use Exception;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;

class TestController extends Controller {

  public function test() {

    $process = (new ChromeProcess)->toProcess();
    if ($process->isStarted()) {
      $process->stop();
    }
    $process->start();

    $options      = (new ChromeOptions)->addArguments(['--disable-gpu', '--headless', '--no-sandbox']);
    $capabilities = DesiredCapabilities::chrome()
      ->setCapability(ChromeOptions::CAPABILITY, $options);

          $driver = retry(1, function () use ($capabilities) {
      return RemoteWebDriver::create('http://localhost:9515', $capabilities, 60000, 60000);
    }, 50);

    $browser = new Browser($driver, new ElementResolver($driver, ''));
    $browser->resize(1920, 1080);
    $browser->visit('https://example.com/login')->click('#.btn > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block');
    $browser->driver->takeScreenshot(base_path('tests/Browser/screenshots/logged.png'));

  }

}

When I run this script using localhost:8000/test I got this message:

Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error
  thrown for http POST to /session with params:
  {"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"binary":"","args":["--disable-gpu","--headless","--no-sandbox"]}}}
  Failed to connect to localhost port 9515: Connection refused

How I can solve this problem?

Current I use WAMP server on Win10 for local testing but then I will move the code on Linux Ubuntu 18.

Body:
I can't fully explain it, but this works for me on Windows:

$process = (new ChromeProcess)->toProcess();
if ($process->isStarted()) {
  $process->stop();
}

$process->start(null, [
    'SystemRoot' => 'C:\\WINDOWS',
    'TEMP' => 'C:\Users\<User>\AppData\Local\Temp',
]);

[...]

Replace <User> with the name of your user directory.


问:
How to Properly Set Up custom Event
OK - I've fought and fought with this and read a million posts, tutorials, etc. None of them seem to address directly what I'm trying to do here. I've got this little code example to illustrate.

Basically, I want to be able to raise/fire a custom event from the button and have the label respond to that event.

(Please note that I AM NOT INTERESTED in finding other ways to do it than what I'm trying to do here with the actual Event objects. I know perfectly well how to do it with change listeners and such, but I want to learn how to do it this way.)

Here is the code, which you can see doesn't get me the result I'm looking for. Much of it comes from some examples (that didn't really work for me) and I admit there's parts here that are going "whoosh" over my head.

If someone can help me get it working, I can dissect it later to make sure I understand what is going on exactly. Here's the code:

```<code>import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//-------------------------------------------------------------------
public class MyDemo extends Application {

    public static void main(String[] args) {
    launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

    // label that should receive the event and react to it
    MyLabel lblReceiver = new MyLabel("And I Should Receive & React");

    // button to firs the event
    Button btnSender = new Button("Initate Event");
    btnSender.setPrefWidth(200);
    btnSender.setOnAction(e -> {
        MyEvent.fireEvent(lblReceiver, e); // really confused what the first parameter here is supposed to be.
    });

    // set up stage and show it
    Stage stage = new Stage();
    VBox root = new VBox(btnSender, lblReceiver);
    root.setSpacing(10);
    root.setPadding(new Insets(10, 10, 10, 10));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    }

}
//-------------------------------------------------------------------

// Interface for objects that want to listen to my event
//-------------------------------------------------------------------
interface MyEventListener {
    void onMyEvent();
}
//-------------------------------------------------------------------

// My event definition itself
//-------------------------------------------------------------------
class MyEvent extends Event {

    public static final EventType<MyEvent> MY_EVENT = new EventType<>(ANY, "MY_EVENT");

    public MyEvent(EventType<? extends MyEvent> eventType) {
    super(eventType);
    }
}
//-------------------------------------------------------------------

//base/parent class for my label - this is what should receive/respond to event and
// where I'm sure i have problems - just don't know what.
//-------------------------------------------------------------------
class MyLabel extends Label implements MyEventListener {

    public MyLabel(String name) {
    this.setAlignment(Pos.CENTER);
    this.setText(name);
    this.setPrefWidth(200);
    }

    @Override // this is what I'm expecting to happen when i click the button
    public void onMyEvent() {
    this.setText("YAY! i got the event!");
    }

    private final ObjectProperty<EventHandler<? super MyEvent>> onMyEventProp
        = new SimpleObjectProperty<EventHandler<? super MyEvent>>(this, "onMyEvent") {
    @Override
    protected void invalidated() {
        setEventHandler(MyEvent.MY_EVENT, get());
    }
    };

    public final void setOnMyEvent(EventHandler<? super MyEvent> handler) {
    onMyEventProp.set(handler);
    }

    public final EventHandler<? super MyEvent> getOnMyEvent() {
    return onMyEventProp.get();
    }

    public final ObjectProperty<EventHandler<? super MyEvent>> onMyEventProperty() {
    return onMyEventProp;
    }

}
//-------------------------------------------------------------------
</code>```

答:
Answer

You seem have everything set up correctly except for two problems.

You never add an EventHandler that listens for your event.

Implementing an arbitrary interface will not make your object react to your custom event. The event processing system has no knowledge of your interface and doesn't even know you've implemented it. If you want your onMyEvent() method to be invoked when your event reaches the label, you would need to do something like:

```<code>public MyLabel() {
    //...
    addEventHandler(MyEvent.MY_EVENT, event -> onMyEvent());
}
</code>```

Note I used addEventHandler so that the class itself doesn't rely on the onMyEvent property. If you relied on the property then outside code could accidentally break your code by replacing the EventHandler.

This makes me wonder if the MyEventListener interface is really necessary. Couldn't you just do what you needed inside the EventHandler?

You never actually fire an instance of your MyEvent.

You currently have:

```<code>btnSender.setOnAction(e -> MyEvent.fireEvent(lblReceiver, e));
</code>```

This simply refires e (an ActionEvent) towards lblReceiver. The fireEvent method is a static method declared by javafx.event.Event. Prefixing the method call with MyEvent doesn't change what method is actually called here. Change that to the following:

```<code>btnSender.setOnAction(e -> Event.fireEvent(lblReceiver, new MyEvent()));
// or...
btnSender.setOnAction(e -> lblReceiver.fireEvent(new MyEvent()));

// The second option is a convenience method and simply forwards to Event.fireEvent
</code>```

In order to actually fire an instance of your own event class at your label.

Fundamentals of Event Dispatching

There are two phases to event processing in JavaFX:

Capturing phase

The first phase. Here the event travels from the start of its path down to the target. At each step along the way the appropriate event filters are invoked. Filters are added via methods such as Node.addEventFilter(EventType,EventHandler).

Bubbling phase

The second phase. Here the event travels from the target back up to the start of the path. At each step along the way the appropriate event handlers are invoked. Handlers are added via methods such as Node.addEventHandler(EventType,EventHandler) and via properties such as Node.onKeyPressed and ButtonBase.onAction.

And event processing consists of the following components:

javafx.event.Event (and subclasses)

The actual object passed around. Carries information related to the event (e.g. the cursor's location for MouseEvents).

An Event also carries the source. However, the source is dynamic; it will always be the object the EventHandler currently handling the event was added to. So an EventHandler added to a Button will have the Button as the event's source, but the same event will have the parent as it's source for an EventHandler added to the parent. This behavior doesn't change even if you used the same EventHandler instance both times.

javafx.event.EventType

Refines the meaning of a class of Event. For example, a MouseEvent with the MOUSE_PRESSED type means, unsurprisingly, the mouse was pressed. An EventType has a supertype; this forms a hierarchy across all types for every kind of event. A handler registered for a supertype will also be notified of subtypes.

You cannot have two or more EventTypes with the same supertype and name. This is why instances are typically public static final fields of the corresponding event class.

javafx.event.EventHandler

Handles any events its registered for. This is a functional interface (can be the target of a lambda expression or method reference). It's implementations of this interface that do the application-level work (i.e. do something when a button is fired).

javafx.event.EventDispatcher

Responsible for dispatching the event to the appropriate handlers. Each object capable of being the target of an event typically has its own dispatcher. For example, each Window, Scene, and Node instance has its own EventDispatcher instance (held in a property).

Note: Outside highly specialized situations, you will never have to deal with this interface directly.

javafx.event.EventDispatchChain

Represents the path the event will take when it's fired at a target. Instances of this interface function as a stack of EventDispatchers. When an event is fired, a new chain is created and configured based on the event's target. In the case of the scene graph and the target is a Node, the stack consists of the EventDispatchers belonging to the Window, the Scene, and then each Node down to (parent to child) and including the target. The event travels down this chain (the capturing phase) and then back up this chain (the bubbling phase).

Note: You will likely never need to use this interface directly.

javafx.event.EventTarget

The actual target of the event. The EventTarget interface has one method that is used to build the EventDispatchChain. In other words, the target determines the path of the event. This is the first argument in Event.fireEvent(EventTarget,Event).

Note: You only need to use this interface if you're creating an object that can (obviously) be the target of events (and your object doesn't extend from an implementation of EventTarget).

Title: How to Properly Set Up custom Event

Body:
OK - I've fought and fought with this and read a million posts, tutorials, etc. None of them seem to address directly what I'm trying to do here. I've got this little code example to illustrate.

Basically, I want to be able to raise/fire a custom event from the button and have the label respond to that event.

(Please note that I AM NOT INTERESTED in finding other ways to do it than what I'm trying to do here with the actual Event objects. I know perfectly well how to do it with change listeners and such, but I want to learn how to do it this way.)

Here is the code, which you can see doesn't get me the result I'm looking for. Much of it comes from some examples (that didn't really work for me) and I admit there's parts here that are going "whoosh" over my head.

If someone can help me get it working, I can dissect it later to make sure I understand what is going on exactly. Here's the code:

import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//-------------------------------------------------------------------
public class MyDemo extends Application {

    public static void main(String[] args) {
    launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

    // label that should receive the event and react to it
    MyLabel lblReceiver = new MyLabel("And I Should Receive & React");

    // button to firs the event
    Button btnSender = new Button("Initate Event");
    btnSender.setPrefWidth(200);
    btnSender.setOnAction(e -> {
        MyEvent.fireEvent(lblReceiver, e); // really confused what the first parameter here is supposed to be.
    });

    // set up stage and show it
    Stage stage = new Stage();
    VBox root = new VBox(btnSender, lblReceiver);
    root.setSpacing(10);
    root.setPadding(new Insets(10, 10, 10, 10));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    }

}
//-------------------------------------------------------------------

// Interface for objects that want to listen to my event
//-------------------------------------------------------------------
interface MyEventListener {
    void onMyEvent();
}
//-------------------------------------------------------------------

// My event definition itself
//-------------------------------------------------------------------
class MyEvent extends Event {

    public static final EventType<MyEvent> MY_EVENT = new EventType<>(ANY, "MY_EVENT");

    public MyEvent(EventType<? extends MyEvent> eventType) {
    super(eventType);
    }
}
//-------------------------------------------------------------------

//base/parent class for my label - this is what should receive/respond to event and
// where I'm sure i have problems - just don't know what.
//-------------------------------------------------------------------
class MyLabel extends Label implements MyEventListener {

    public MyLabel(String name) {
    this.setAlignment(Pos.CENTER);
    this.setText(name);
    this.setPrefWidth(200);
    }

    @Override // this is what I'm expecting to happen when i click the button
    public void onMyEvent() {
    this.setText("YAY! i got the event!");
    }

    private final ObjectProperty<EventHandler<? super MyEvent>> onMyEventProp
        = new SimpleObjectProperty<EventHandler<? super MyEvent>>(this, "onMyEvent") {
    @Override
    protected void invalidated() {
        setEventHandler(MyEvent.MY_EVENT, get());
    }
    };

    public final void setOnMyEvent(EventHandler<? super MyEvent> handler) {
    onMyEventProp.set(handler);
    }

    public final EventHandler<? super MyEvent> getOnMyEvent() {
    return onMyEventProp.get();
    }

    public final ObjectProperty<EventHandler<? super MyEvent>> onMyEventProperty() {
    return onMyEventProp;
    }

}
//-------------------------------------------------------------------

Body:
Answer

You seem have everything set up correctly except for two problems.

You never add an EventHandler that listens for your event.

Implementing an arbitrary interface will not make your object react to your custom event. The event processing system has no knowledge of your interface and doesn't even know you've implemented it. If you want your onMyEvent() method to be invoked when your event reaches the label, you would need to do something like:

public MyLabel() {
    //...
    addEventHandler(MyEvent.MY_EVENT, event -> onMyEvent());
}

Note I used addEventHandler so that the class itself doesn't rely on the onMyEvent property. If you relied on the property then outside code could accidentally break your code by replacing the EventHandler.

This makes me wonder if the MyEventListener interface is really necessary. Couldn't you just do what you needed inside the EventHandler?

You never actually fire an instance of your MyEvent.

You currently have:

btnSender.setOnAction(e -> MyEvent.fireEvent(lblReceiver, e));

This simply refires e (an ActionEvent) towards lblReceiver. The fireEvent method is a static method declared by javafx.event.Event. Prefixing the method call with MyEvent doesn't change what method is actually called here. Change that to the following:

btnSender.setOnAction(e -> Event.fireEvent(lblReceiver, new MyEvent()));
// or...
btnSender.setOnAction(e -> lblReceiver.fireEvent(new MyEvent()));

// The second option is a convenience method and simply forwards to Event.fireEvent

In order to actually fire an instance of your own event class at your label.

Fundamentals of Event Dispatching

There are two phases to event processing in JavaFX:

Capturing phase

The first phase. Here the event travels from the start of its path down to the target. At each step along the way the appropriate event filters are invoked. Filters are added via methods such as Node.addEventFilter(EventType,EventHandler).

Bubbling phase

The second phase. Here the event travels from the target back up to the start of the path. At each step along the way the appropriate event handlers are invoked. Handlers are added via methods such as Node.addEventHandler(EventType,EventHandler) and via properties such as Node.onKeyPressed and ButtonBase.onAction.

And event processing consists of the following components:

javafx.event.Event (and subclasses)

The actual object passed around. Carries information related to the event (e.g. the cursor's location for MouseEvents).

An Event also carries the source. However, the source is dynamic; it will always be the object the EventHandler currently handling the event was added to. So an EventHandler added to a Button will have the Button as the event's source, but the same event will have the parent as it's source for an EventHandler added to the parent. This behavior doesn't change even if you used the same EventHandler instance both times.

javafx.event.EventType

Refines the meaning of a class of Event. For example, a MouseEvent with the MOUSE_PRESSED type means, unsurprisingly, the mouse was pressed. An EventType has a supertype; this forms a hierarchy across all types for every kind of event. A handler registered for a supertype will also be notified of subtypes.

You cannot have two or more EventTypes with the same supertype and name. This is why instances are typically public static final fields of the corresponding event class.

javafx.event.EventHandler

Handles any events its registered for. This is a functional interface (can be the target of a lambda expression or method reference). It's implementations of this interface that do the application-level work (i.e. do something when a button is fired).

javafx.event.EventDispatcher

Responsible for dispatching the event to the appropriate handlers. Each object capable of being the target of an event typically has its own dispatcher. For example, each Window, Scene, and Node instance has its own EventDispatcher instance (held in a property).

Note: Outside highly specialized situations, you will never have to deal with this interface directly.

javafx.event.EventDispatchChain

Represents the path the event will take when it's fired at a target. Instances of this interface function as a stack of EventDispatchers. When an event is fired, a new chain is created and configured based on the event's target. In the case of the scene graph and the target is a Node, the stack consists of the EventDispatchers belonging to the Window, the Scene, and then each Node down to (parent to child) and including the target. The event travels down this chain (the capturing phase) and then back up this chain (the bubbling phase).

Note: You will likely never need to use this interface directly.

javafx.event.EventTarget

The actual target of the event. The EventTarget interface has one method that is used to build the EventDispatchChain. In other words, the target determines the path of the event. This is the first argument in Event.fireEvent(EventTarget,Event).

Note: You only need to use this interface if you're creating an object that can (obviously) be the target of events (and your object doesn't extend from an implementation of EventTarget).


问:
Index when using OR in query
What is the best way to create index when I have a query like this?

```<code>... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...
</code>```

I know that only one index can be used in a query so I can't create two indexes, one for user_1 and one for user_2.

Also could solution for this type of query be used for this query?

```<code>WHERE ((user_1 = '$user_id' AND user_2 = '$friend_id') OR (user_1 = '$friend_id' AND user_2 = '$user_id'))
</code>```

答:
I know that only one index can be used in a query…

This is incorrect. Under the right circumstances, MySQL will routinely use multiple indexes in a query. (For example, a query JOINing multiple tables will almost always use at least one index on each table involved.)

In the case of your first query, MySQL will use an index merge union optimization. If both columns are indexed, the EXPLAIN output will give an explanation along the lines of:

```<code>Using union(index_on_user_1,index_on_user_2); Using where
</code>```

The query shown in your second example is covered by an index on (user_1, user_2). Create that index if you plan on running those queries routinely.

Title: Index when using OR in query

Body:
What is the best way to create index when I have a query like this?

... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...

I know that only one index can be used in a query so I can't create two indexes, one for user_1 and one for user_2.

Also could solution for this type of query be used for this query?

WHERE ((user_1 = '$user_id' AND user_2 = '$friend_id') OR (user_1 = '$friend_id' AND user_2 = '$user_id'))

Body:
I know that only one index can be used in a query…

This is incorrect. Under the right circumstances, MySQL will routinely use multiple indexes in a query. (For example, a query JOINing multiple tables will almost always use at least one index on each table involved.)

In the case of your first query, MySQL will use an index merge union optimization. If both columns are indexed, the EXPLAIN output will give an explanation along the lines of:

Using union(index_on_user_1,index_on_user_2); Using where

The query shown in your second example is covered by an index on (user_1, user_2). Create that index if you plan on running those queries routinely.


问:
Reverse a graph - trying to get mote efficient
I'm trying to get more efficient in this reverse graph problem. The idea is straightforward, you get a directed connected cyclic graph and you reverse the direction of the edges.

I got it right, but I'd like to make it faster, some entries are taking almost 2s. That's terrible...

If someone knows anything that can help to speed up this code below, please tell me.

```<code>static class Node
        {
            Integer val;
            Vector<Node> neighbours = new Vector<Node>(0);
            Node(Integer _val)
            {
                val = _val;
                neighbours.clear();
            }
        };

static Node build_other_graph(Node node)
    {
        if(node.neighbours.size() == 0)
            return new Node(node.val);

        dfs(node);
        return col.get(node.val);
    }

    static Node n = null;
    static HashMap<Integer, Node> col = new HashMap<>();
    static HashSet<Integer> visited = new HashSet<>();
    static void dfs(Node node)
    {
        if(node == null || visited.contains(node.val))
            return;

        //visit
        Vector<Node> adj = node.neighbours;
        visited.add(node.val);
        for(Node i: adj)
        {
            if(col.keySet().contains(i.val))
            {
               if(col.keySet().contains(node.val))
                    col.get(i.val).neighbours.add(col.get(node.val));
               else
                   col.get(i.val).neighbours.add(new Node(node.val));
            }
            else
            {
               Node v = new Node(i.val);
               if(col.keySet().contains(node.val))
                    v.neighbours.add(col.get(node.val));
               else
                    v.neighbours.add(new Node(node.val));
               col.put(i.val, v);
            }
            dfs(i);
        }
    }
</code>```

答:
So here is simple example of what i mean. See how long it runs - mutch more time for initialisation, but reverse goes instantly and only ones</p>

```<code>   package graph.nodes.simple;

import java.util.ArrayList;

public class GArrayListGraph extends ArrayList<GArrayListNode> {

    /**
     *
     */
    private static final long serialVersionUID = 2493196722065921126L;
    boolean calculated = false;

    public GArrayListNode addNode(Object e) {

        GArrayListNode ret = new GArrayListNode(e);
        super.add(ret);
        return ret ;
    }

    public void addEdge(GArrayListNode a, GArrayListNode b) {

        a.neighbours.add(b);
    }

    public void printall() {

        System.out.println("GArrayListGraph");

        for (GArrayListNode node : this) {

            System.out.println(node.toString());
        }

    }

    public void reverce() {

        if (!calculated) {
            for (GArrayListNode node : this) {

                for (GArrayListNode neighbour : node.neighbours) {

                    neighbour.neighboursReverse.add(node);

                }
            }
            this.calculated = true;
        }
        // swap neighbours and neighboursReverse
        for (GArrayListNode node : this) {

            ArrayList<GArrayListNode> temp = node.neighbours;
            node.neighbours = node.neighboursReverse;
            node.neighboursReverse = temp;

        }

    }
}

package graph.nodes.simple;

import java.util.ArrayList;

import java.util.Random;

import java.util.Timer;
import java.util.TimerTask;

public class GArrayListNode {

    Object val;
    ArrayList<GArrayListNode> neighbours;
    ArrayList<GArrayListNode> neighboursReverse;

    public GArrayListNode(Object val) {
        this.val = val;
        this.neighbours = new ArrayList<GArrayListNode>();
        this.neighboursReverse = new ArrayList<GArrayListNode>();
    }

    @Override
    public String toString() {

        return val.toString() + " : " + this.toStringChildren();
    }

    public String toStringChildren() {

        StringBuilder sb = new StringBuilder();

        for (GArrayListNode node : neighbours) {

            sb.append(node.val).append(',');

        }
        return sb.toString();
    }

    public static void main(String[] args) {

        GArrayListGraph g = new GArrayListGraph();

        GArrayListNode n10 = g.addNode(10);

        GArrayListNode n11 = g.addNode(11);

        GArrayListNode n12 = g.addNode(12);

        GArrayListNode n13 = g.addNode(13);

        GArrayListNode n14 = g.addNode(14);

        g.addEdge(n10, n11);

        g.addEdge(n11, n12);

        g.addEdge(n10, n12);

        g.addEdge(n12, n13);

        g.addEdge(n12, n14);

        g.addEdge(n14, n10);

        g.printall();

        g.reverce();

        g.printall();

        g.reverce();

        g.printall();

        System.out.println("see its the same, now time performance test");

        int nodes = 1000 * 1000 * 10;

        for (int i = 0; i < nodes; i++) {

            g.addNode(i);

        }

        int edges = 1000 * 10;

        Random r = new Random();
        for (int i = 0; i < nodes; i++) {

            int from = r.nextInt(nodes);
            int to = r.nextInt(nodes);

            g.addEdge(g.get(from), g.get(to));

        }

        long startTime = System.currentTimeMillis();
        System.out.println("start" );
        g.reverce();

        long elapsed = System.currentTimeMillis() - startTime;

        System.out.println("elapsed " + elapsed);

    }

}
</code>```

Body:
I'm trying to get more efficient in this reverse graph problem. The idea is straightforward, you get a directed connected cyclic graph and you reverse the direction of the edges.

I got it right, but I'd like to make it faster, some entries are taking almost 2s. That's terrible...

If someone knows anything that can help to speed up this code below, please tell me.

static class Node
        {
            Integer val;
            Vector<Node> neighbours = new Vector<Node>(0);
            Node(Integer _val)
            {
                val = _val;
                neighbours.clear();
            }
        };

static Node build_other_graph(Node node)
    {
        if(node.neighbours.size() == 0)
            return new Node(node.val);

        dfs(node);
        return col.get(node.val);
    }

    static Node n = null;
    static HashMap<Integer, Node> col = new HashMap<>();
    static HashSet<Integer> visited = new HashSet<>();
    static void dfs(Node node)
    {
        if(node == null || visited.contains(node.val))
            return;

        //visit
        Vector<Node> adj = node.neighbours;
        visited.add(node.val);
        for(Node i: adj)
        {
            if(col.keySet().contains(i.val))
            {
               if(col.keySet().contains(node.val))
                    col.get(i.val).neighbours.add(col.get(node.val));
               else
                   col.get(i.val).neighbours.add(new Node(node.val));
            }
            else
            {
               Node v = new Node(i.val);
               if(col.keySet().contains(node.val))
                    v.neighbours.add(col.get(node.val));
               else
                    v.neighbours.add(new Node(node.val));
               col.put(i.val, v);
            }
            dfs(i);
        }
    }

Body:
So here is simple example of what i mean. See how long it runs - mutch more time for initialisation, but reverse goes instantly and only ones

   package graph.nodes.simple;

import java.util.ArrayList;

public class GArrayListGraph extends ArrayList<GArrayListNode> {

    /**
     *
     */
    private static final long serialVersionUID = 2493196722065921126L;
    boolean calculated = false;

    public GArrayListNode addNode(Object e) {

        GArrayListNode ret = new GArrayListNode(e);
        super.add(ret);
        return ret ;
    }

    public void addEdge(GArrayListNode a, GArrayListNode b) {

        a.neighbours.add(b);
    }

    public void printall() {

        System.out.println("GArrayListGraph");

        for (GArrayListNode node : this) {

            System.out.println(node.toString());
        }

    }

    public void reverce() {

        if (!calculated) {
            for (GArrayListNode node : this) {

                for (GArrayListNode neighbour : node.neighbours) {

                    neighbour.neighboursReverse.add(node);

                }
            }
            this.calculated = true;
        }
        // swap neighbours and neighboursReverse
        for (GArrayListNode node : this) {

            ArrayList<GArrayListNode> temp = node.neighbours;
            node.neighbours = node.neighboursReverse;
            node.neighboursReverse = temp;

        }

    }
}

package graph.nodes.simple;

import java.util.ArrayList;

import java.util.Random;

import java.util.Timer;
import java.util.TimerTask;

public class GArrayListNode {

    Object val;
    ArrayList<GArrayListNode> neighbours;
    ArrayList<GArrayListNode> neighboursReverse;

    public GArrayListNode(Object val) {
        this.val = val;
        this.neighbours = new ArrayList<GArrayListNode>();
        this.neighboursReverse = new ArrayList<GArrayListNode>();
    }

    @Override
    public String toString() {

        return val.toString() + " : " + this.toStringChildren();
    }

    public String toStringChildren() {

        StringBuilder sb = new StringBuilder();

        for (GArrayListNode node : neighbours) {

            sb.append(node.val).append(',');

        }
        return sb.toString();
    }

    public static void main(String[] args) {

        GArrayListGraph g = new GArrayListGraph();

        GArrayListNode n10 = g.addNode(10);

        GArrayListNode n11 = g.addNode(11);

        GArrayListNode n12 = g.addNode(12);

        GArrayListNode n13 = g.addNode(13);

        GArrayListNode n14 = g.addNode(14);

        g.addEdge(n10, n11);

        g.addEdge(n11, n12);

        g.addEdge(n10, n12);

        g.addEdge(n12, n13);

        g.addEdge(n12, n14);

        g.addEdge(n14, n10);

        g.printall();

        g.reverce();

        g.printall();

        g.reverce();

        g.printall();

        System.out.println("see its the same, now time performance test");

        int nodes = 1000 * 1000 * 10;

        for (int i = 0; i < nodes; i++) {

            g.addNode(i);

        }

        int edges = 1000 * 10;

        Random r = new Random();
        for (int i = 0; i < nodes; i++) {

            int from = r.nextInt(nodes);
            int to = r.nextInt(nodes);

            g.addEdge(g.get(from), g.get(to));

        }

        long startTime = System.currentTimeMillis();
        System.out.println("start" );
        g.reverce();

        long elapsed = System.currentTimeMillis() - startTime;

        System.out.println("elapsed " + elapsed);

    }

}


答: The gzip file format starts with some "magic bytes". You can check whether the body starts with these, and if it does, push back the bytes into the stream and start unzipping it.</p>

Title: finding whether the body contains gzipped data

Body:
i have a program wherein it searches the reply from a curl request for specific strings. i sometimes get gzipped data. is there a way to find whether the reply is text or gzipped format?
header sometimes contain gziipped,deflate header, but its not consistent. is there a way to search the string and find if its gzipped?


问:
How to implement asynchronous code that looks synchronous mimicking async / await?
Otherwise said, I want to rely on epoll (or similar) to write asynchronous network code that looks like regular code that is without relying on callbacks.

The code must look like synchronous code but unlike synchronous code instead of blocking to wait for network io, it must suspend the current coroutine and restart it when the file descriptor is ready.

答:
My initial thought to achieve that was relying on generators and yield. But this was a mistake that was partly mis-guided by the fact that python used to abuse yield from.

Anyway, guile fibers was a great insipiration and I adapted it to chez scheme.

Here is an example server code:

```<code>(define (handler request port)
  (values 200 #f (http-get "https://httpbin.davecheney.com/ip")))

(untangle (lambda ()
            (run-server "127.0.0.1" 8888)))
</code>```

The handler returns its IP according the httpbin service. The code look synchronous with the help of call/cc actually call/1cc.

untangle will initiate the event loop with a lambda passed as argument!

Here is the definition of run-server:

```<code>(define (run-server ip port handler)
  (log 'info "HTTP server running at ~a:~a" ip port)
  (let* ((sock (socket 'inet 'stream 'ipv4)))
    (socket:setsockopt sock 1 2 1) ;; re-use address
    (socket:bind sock (make-address ip port))
    (socket:listen sock 1024)
    (let loop ()
      (let ((client (accept sock)))
        (let ((port (fd->port client)))
          (spawn (lambda () (run-once handler port)))
          (loop))))))
</code>```

As you can see there is no callback. The only thing that is somewhat different from simple synchronous webserver is the spawn procedure that will handle the request in its own coroutine. In particular accept is asynchronous.

run-once will just pass the scheme request to handler and take its 3 values to build the response. Not very interesting. The part that looks synchronous, but is actually asynchronous is http-get above.

I will only explain, how accept works, given http-get requires to introduce custom binary ports, but suffice to say it is the same behavior...

```<code>(define (accept fd)
  (let ((out (socket:%accept fd 0 0)))
    (if (= out -1)
        (let ((code (socket:errno)))
          (if (= code EWOULDBLOCK)
              (begin
                (abort-to-prompt fd 'read)
                (accept fd))
              (error 'accept (socket:strerror code))))
        out)))
</code>```

As you can see it calls a procedure abort-to-prompt that we could call simply pause that will "stop" the coroutine and call the prompt handler.

abort-to-prompt works in cooperation with call-with-prompt.

Since chez scheme doesn't have prompts I emulate it using two one shot continuations call/1cc

```<code>(define %prompt #f)
(define %abort (list 'abort))

(define (call-with-prompt thunk handler)
  (call-with-values (lambda ()
                      (call/1cc
                       (lambda (k)
                         (set! %prompt k)
                         (thunk))))
    (lambda out
      (cond
       ((and (pair? out) (eq? (car out) %abort))
        (apply handler (cdr out)))
       (else (apply values out))))))

(define (abort-to-prompt . args)
  (call/1cc
   (lambda (k)
     (let ((prompt %prompt))
       (set! %prompt #f)
       (apply prompt (cons %abort (cons k args)))))))
</code>```

call-with-prompt will initiate a continuation a set! global called %prompt which means there is single prompt for THUNK. If the continuation arguments OUT, the second lambda of call-with-values, starts with the unique object %abort it means the continuation was reached via abort-to-prompt. It will call the HANDLER with the abort-to-prompt continuation and any argument passed to call-with-prompt continuation parameter that is the (apply handler (cons k (cdr out))).

abort-to-promp will initiate a new continuation to be able to come back, after the code executes the prompt's continuation stored in %prompt.

The call-with-prompt is at the heart of the event-loop. Here is it, in two pieces:

```<code>(define (exec epoll thunk waiting)
  (call-with-prompt
   thunk
   (lambda (k fd mode) ;; k is abort-to-prompt continuation that
                       ;; will allow to restart the coroutine

     ;; add fd to the correct epoll set
     (case mode
       ((write) (epoll-wait-write epoll fd))
       ((read) (epoll-wait-read epoll fd))
       (else (error 'untangle "mode not supported" mode)))
     (scheme:hash-table-set! waiting fd (make-event k mode)))))

(define (event-loop-run-once epoll waiting)
  ;; execute every callback waiting in queue,
  ;; call the above exec procedure
  (let loop ()
    (unless (null? %queue)
      ;; XXX: This is done like that because, exec might spawn
      ;; new coroutine, so we need to cut %queue right now.
      (let ((head (car %queue))
            (tail (cdr %queue)))
        (set! %queue tail)
        (exec epoll head waiting)
        (loop))))

    ;; wait for ONE event
    (let ((fd (epoll-wait-one epoll (inf))
      (let ((event (scheme:hash-table-ref waiting fd)))
        ;; the event is / will be processed, no need to keep around
        (scheme:hash-table-delete! waiting fd)
        (case (event-mode event)
          ((write) (epoll-ctl epoll 2 fd (make-epoll-event-out fd)))
          ((read) (epoll-ctl epoll 2 fd (make-epoll-event-in fd))))
        ;; here it will schedule the event continuation that is the
        ;; abort-to-prompt continuation that will be executed by the
        ;; next call the above event loop event-loop-run-once
        (spawn (event-continuation event))))))
</code>```

I think that is all.

Body:
My initial thought to achieve that was relying on generators and yield. But this was a mistake that was partly mis-guided by the fact that python used to abuse yield from.

Anyway, guile fibers was a great insipiration and I adapted it to chez scheme.

Here is an example server code:

(define (handler request port)
  (values 200 #f (http-get "https://httpbin.davecheney.com/ip")))

(untangle (lambda ()
            (run-server "127.0.0.1" 8888)))

The handler returns its IP according the httpbin service. The code look synchronous with the help of call/cc actually call/1cc.

untangle will initiate the event loop with a lambda passed as argument!

Here is the definition of run-server:

(define (run-server ip port handler)
  (log 'info "HTTP server running at ~a:~a" ip port)
  (let* ((sock (socket 'inet 'stream 'ipv4)))
    (socket:setsockopt sock 1 2 1) ;; re-use address
    (socket:bind sock (make-address ip port))
    (socket:listen sock 1024)
    (let loop ()
      (let ((client (accept sock)))
        (let ((port (fd->port client)))
          (spawn (lambda () (run-once handler port)))
          (loop))))))

As you can see there is no callback. The only thing that is somewhat different from simple synchronous webserver is the spawn procedure that will handle the request in its own coroutine. In particular accept is asynchronous.

run-once will just pass the scheme request to handler and take its 3 values to build the response. Not very interesting. The part that looks synchronous, but is actually asynchronous is http-get above.

I will only explain, how accept works, given http-get requires to introduce custom binary ports, but suffice to say it is the same behavior...

(define (accept fd)
  (let ((out (socket:%accept fd 0 0)))
    (if (= out -1)
        (let ((code (socket:errno)))
          (if (= code EWOULDBLOCK)
              (begin
                (abort-to-prompt fd 'read)
                (accept fd))
              (error 'accept (socket:strerror code))))
        out)))

As you can see it calls a procedure abort-to-prompt that we could call simply pause that will "stop" the coroutine and call the prompt handler.

abort-to-prompt works in cooperation with call-with-prompt.

Since chez scheme doesn't have prompts I emulate it using two one shot continuations call/1cc

(define %prompt #f)
(define %abort (list 'abort))

(define (call-with-prompt thunk handler)
  (call-with-values (lambda ()
                      (call/1cc
                       (lambda (k)
                         (set! %prompt k)
                         (thunk))))
    (lambda out
      (cond
       ((and (pair? out) (eq? (car out) %abort))
        (apply handler (cdr out)))
       (else (apply values out))))))

(define (abort-to-prompt . args)
  (call/1cc
   (lambda (k)
     (let ((prompt %prompt))
       (set! %prompt #f)
       (apply prompt (cons %abort (cons k args)))))))

call-with-prompt will initiate a continuation a set! global called %prompt which means there is single prompt for THUNK. If the continuation arguments OUT, the second lambda of call-with-values, starts with the unique object %abort it means the continuation was reached via abort-to-prompt. It will call the HANDLER with the abort-to-prompt continuation and any argument passed to call-with-prompt continuation parameter that is the (apply handler (cons k (cdr out))).

abort-to-promp will initiate a new continuation to be able to come back, after the code executes the prompt's continuation stored in %prompt.

The call-with-prompt is at the heart of the event-loop. Here is it, in two pieces:

(define (exec epoll thunk waiting)
  (call-with-prompt
   thunk
   (lambda (k fd mode) ;; k is abort-to-prompt continuation that
                       ;; will allow to restart the coroutine

     ;; add fd to the correct epoll set
     (case mode
       ((write) (epoll-wait-write epoll fd))
       ((read) (epoll-wait-read epoll fd))
       (else (error 'untangle "mode not supported" mode)))
     (scheme:hash-table-set! waiting fd (make-event k mode)))))

(define (event-loop-run-once epoll waiting)
  ;; execute every callback waiting in queue,
  ;; call the above exec procedure
  (let loop ()
    (unless (null? %queue)
      ;; XXX: This is done like that because, exec might spawn
      ;; new coroutine, so we need to cut %queue right now.
      (let ((head (car %queue))
            (tail (cdr %queue)))
        (set! %queue tail)
        (exec epoll head waiting)
        (loop))))

    ;; wait for ONE event
    (let ((fd (epoll-wait-one epoll (inf))
      (let ((event (scheme:hash-table-ref waiting fd)))
        ;; the event is / will be processed, no need to keep around
        (scheme:hash-table-delete! waiting fd)
        (case (event-mode event)
          ((write) (epoll-ctl epoll 2 fd (make-epoll-event-out fd)))
          ((read) (epoll-ctl epoll 2 fd (make-epoll-event-in fd))))
        ;; here it will schedule the event continuation that is the
        ;; abort-to-prompt continuation that will be executed by the
        ;; next call the above event loop event-loop-run-once
        (spawn (event-continuation event))))))

I think that is all.


问:
Flutter failed to compile apk: Finished with error: Gradle task assembleDebug failed with exit code 1
Flutter failed to compile an apk. I am not sure if this has something to do with AndroidX or something.

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Finished with error: Gradle task assembleDebug failed with exit code 1
</code>```

I ran flutter clean. I also ran flutter run -v. This is what happened: https://1drv.ms/t/s!An3OLJ7n0CjEku1SBrSABWab901z3Q

(I have used an external file locker because the stack trace is too large for the Stack Overflow editor).

This issue is similar to https://github.com/flutter/flutter/issues/30634

答:
In the debug mode applications worked well, but when I tried to build a release version, it had this error.

"Flutter doctor -v" was ok.

Made flutter clean.

Checked all AndroidX recommendations, used all latest versions of packages.

Checked android/app/fourpillarsappru1.keystore settings.

Finally the decision was use build in in Android Studio commands instead of command line "flutter build apk".

So, the decision in my case was:

Open build.gradle for editing in Android Studio

Choose Build / Generate Signed Bundle/APK

Body:
Flutter failed to compile an apk. I am not sure if this has something to do with AndroidX or something.

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Finished with error: Gradle task assembleDebug failed with exit code 1

I ran flutter clean. I also ran flutter run -v. This is what happened: https://1drv.ms/t/s!An3OLJ7n0CjEku1SBrSABWab901z3Q

(I have used an external file locker because the stack trace is too large for the Stack Overflow editor).

This issue is similar to https://github.com/flutter/flutter/issues/30634


答: You could look at the first bytes of the file. Perhaps they containt a magic number.</p>


Title: How to construct a list of tuples of all possible combinations

Body:
I just can't come up with a way to solve my problem: x is an integer. I want a list of all possibles combinations of  x-tuples where those tuples' elements are in range from 0 to x (excluding x).

So if x = 3 I have 3^3 combinations: [(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)].

If x = 4 I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}.

Body:
Ok, not permatations, but permutations with repeats perhaps.

Anyway, itertools.product() is doing that:

list(itertools.product([0,1,2],repeats=3))

result:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]

oh it's a dupe. But I found it too :-)

(Side remark: combinations are about subsets, and thus order of elements does not matter to them)


问:
Calling DialogFragment in Fragment Kotlin
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

```<code>val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")
</code>```

Here is my CustomDialogFragment code:

```<code>import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}
</code>```

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)

答: I see no DialogFragment imports in your customDialog() class. Actually, there is a Fragment import on line no: 9. are you sure you are extending from the correct DialogFragment?

Body:
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")

Here is my CustomDialogFragment code:

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)