问:
Enable autocomplete querying in ElasticSearch
I am trying to build an ElasticSearch index which will have documents with product names, for instance of laptops -

```<code>{ "name" : "Laptop Blue I7"}
</code>```

Then I want to use it for autocomplete suggestion by querying the ES index. I have 2 main constraints:

There can be Synonyms of the name -

I want to define Synonyms for terms, like "Notebook" for "Laptop"
The ingested documents can be of the following kind -

```<code>"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Red I7"
"Laptop Red I7"
"Notebook Blue I7"
</code>```

Now, I am adding the following settings and mapping file while creating the index -

```<code>{
  "settings": {
    "index": {
      "analysis": {
        "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "synonyms" : ["Laptop,Notebook"]
                    }
                },
        "analyzer": {
        "synonym" : {
                        "tokenizer" : "keyword",
                        "filter" : ["synonym"]
                    }
}}}},
"mappings": {
    "catalog": {
      "properties": {
        "name": {
          "type": "text",
          "analyzer": "synonym"
        }
      }
    }
  }
}

</code>```

Querying -

When I query the data, with "Notebook",
the preferred response should be ordered in terms of frequency and synonym. However, when I query, the response is normally independent of the synonym and frequency. I use the following query -

```<code>/_search
{"query": {
        "query_string" : {"default_field" : "name", "query" : "Notebook"}
            } }
</code>```

The response I get is -

```<code>"Notebook Blue I7"
</code>```

While I would hope the response to be either of the following -

```<code>"Laptop Blue I7"
"Laptop Red I7"
</code>```

or

```<code>"Notebook Blue I7"
"Laptop Blue I7"
"Laptop Red I7"
</code>```

Any insights in resolving this would be helpful. Thanks

========
Edit 1:

When I use \_analyze on "Notebook" the response is

```<code>{'tokens': [{'end_offset': 3,
             'position': 0,
             'start_offset': 0,
             'token': 'Notebook',
             'type': '<ALPHANUM>'},
            {'end_offset': 3,
             'position': 0,
             'start_offset': 0,
             'token': 'Laptop',
             'type': 'SYNONYM'}]}
</code>```

答:
As Amit mentioned, to implement autocomplete edge n gram is what you should consider. I would like to explain why the setting you used didn't work for the complete word Notebook which when queried didn't yield the expected result. For this lets understand how analyzer above will work.

The synonym analyzer defined in the settings has two components, tokenizer and token filter. For an input string first the tokenizer will be applied. The ouput of the tokenizer will be token(s). These will then act as input of token filter and will result in final set of token(s).

You can read more on how analyzer works here.

Now lets consider the first e.g. Laptop Blue I7

For this input string first the keyword tokenizer will be applied and as you might be knowing that the keyword tokenizer takes input string and generate a single token which is the same input string without any modification. So the output of tokenizer will be Laptop Blue I7 as a single token. Now this token  will act as input for synonym token filter. According to the definition, Laptop and Notebook are synonyms but none of them matches the token Laptop Blue I7 so ultimately this filter will be doing nothing and will pass on the token as it is. So the final token generated will be Laptop Blue I7.

So when you search for Notebook it will not match the document with name value as above.

Note that if the input string is just Laptop or Notebook you will get the expected tokens because the keyword tokenizer will be generating single word token for the input. This is why _analyze on "Notebook" gives you the expected result.

So the conclusion is that keyword is the culprit here. To solve this we need a tokenizer which will generate seperate tokens as laptop, blue, i7, Easiest way to solve this will be to use standard instead of keyword.

Dealing with multi-word synonym

This answer might help you.

Body:
I am trying to build an ElasticSearch index which will have documents with product names, for instance of laptops -

{ "name" : "Laptop Blue I7"}

Then I want to use it for autocomplete suggestion by querying the ES index. I have 2 main constraints:

There can be Synonyms of the name -

I want to define Synonyms for terms, like "Notebook" for "Laptop"
The ingested documents can be of the following kind -

"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Blue I7"
"Laptop Red I7"
"Laptop Red I7"
"Notebook Blue I7"

Now, I am adding the following settings and mapping file while creating the index -

{
  "settings": {
    "index": {
      "analysis": {
        "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "synonyms" : ["Laptop,Notebook"]
                    }
                },
        "analyzer": {
        "synonym" : {
                        "tokenizer" : "keyword",
                        "filter" : ["synonym"]
                    }
}}}},
"mappings": {
    "catalog": {
      "properties": {
        "name": {
          "type": "text",
          "analyzer": "synonym"
        }
      }
    }
  }
}

Querying -

When I query the data, with "Notebook",
the preferred response should be ordered in terms of frequency and synonym. However, when I query, the response is normally independent of the synonym and frequency. I use the following query -

/_search
{"query": {
        "query_string" : {"default_field" : "name", "query" : "Notebook"}
            } }

The response I get is -

"Notebook Blue I7"

While I would hope the response to be either of the following -

"Laptop Blue I7"
"Laptop Red I7"

or

"Notebook Blue I7"
"Laptop Blue I7"
"Laptop Red I7"

Any insights in resolving this would be helpful. Thanks

========
Edit 1:

When I use \_analyze on "Notebook" the response is

{'tokens': [{'end_offset': 3,
             'position': 0,
             'start_offset': 0,
             'token': 'Notebook',
             'type': '<ALPHANUM>'},
            {'end_offset': 3,
             'position': 0,
             'start_offset': 0,
             'token': 'Laptop',
             'type': 'SYNONYM'}]}


来源: stackexchange

问:
What should I add in my code so I will get the output I want
I am trying to make a 'Tic-Tac-Toe' game, currently my output chooses a player and ask him to choose a sign for him, it displays the name of the player which is chosen, after this next player has to choose a sign for him, I want help with the code that will ask the other player which was not chosen to choose a sign</p>

```<code>import random

whose_turn = random.choice(['Player 1', 'Player 2'])
print(f"First Turn: {whose_turn}")
sign_player_1 = input(f"{whose_turn}, Choose a sign for you: ")
sign_player_2 = input(f"Opponent, Choose a sign for you: ")

Actual Output:

First Turn: Player 1
Player 1, Choose a sign for you: X
Opponent, Choose a sign for you: O

Expected Output:
First Turn: {Player chosen}
{Player chosen}, Choose a sign for you:
{Player not chosen}, Choose a sign for you:
</code>```

答:
You could use random.shuffle

```<code>from random import shuffle

players = ['Player 1', 'Player 2']
shuffle(players)
player1, player2 = players

print(f"First Turn: {player1}")
sign_player_1 = input(f"{player1}, Choose a sign for you: ")
sign_player_2 = input(f"{player2}, Choose a sign for you: ")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a 'Tic-Tac-Toe' game, currently my output chooses a player and ask him to choose a sign for him, it displays the name of the player which is chosen, after this next player has to choose a sign for him, I want help with the code that will ask the other player which was not chosen to choose a sign

import random

whose_turn = random.choice(['Player 1', 'Player 2'])
print(f"First Turn: {whose_turn}")
sign_player_1 = input(f"{whose_turn}, Choose a sign for you: ")
sign_player_2 = input(f"Opponent, Choose a sign for you: ")

Actual Output:

First Turn: Player 1
Player 1, Choose a sign for you: X
Opponent, Choose a sign for you: O

Expected Output:
First Turn: {Player chosen}
{Player chosen}, Choose a sign for you:
{Player not chosen}, Choose a sign for you:

Body:
You could use random.shuffle

from random import shuffle

players = ['Player 1', 'Player 2']
shuffle(players)
player1, player2 = players

print(f"First Turn: {player1}")
sign_player_1 = input(f"{player1}, Choose a sign for you: ")
sign_player_2 = input(f"{player2}, Choose a sign for you: ")


问:
ARCore custom object not touching the tracked plane with bottom
I am experimenting with the ARCore SDK inside Unity to make an Augmented Reality app. As a start I ran the HelloAR Demo app where the ground is detected and onto which you can place multiple Andy's when tapping on the screen. I notice the Andy's are placed on top of the plane, as it should.

Now, I create a 3D Cube object and replaced the Andy prefab with the Cube. This places Cubes instead of Andy's in the app. However, I notice that the bottom of the cube is not touching the plane! The plane runs through the center of the cube, which is not an ideal scenario!

I looked on the internet for a solution, but haven't found it yet. On another website there was someone with the same issue, but no solution was provided. Only a reponse stating that it works only with the ARCore demo objects, not with custom objects.

Can someone help me out on this one?

Thanks!

答: One thing I do is any objects that don't have centers where they should be, is to load the .obj into blender, and move it to the center of world axes. I might also tell it "center to geometry" before centering on world axis, then I export as .obj (selection only).</p>

ContentLicense: CC BY-SA 3.0


问:
How to sort angular material table rows by property not declared in displayed Columns
Here is the code that creates my tableModel:

```<code>const rowData = [{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d750f',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 3524583453452
},{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d7534',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 35245824528
},{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d7545',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 13219245949
}];

tableModel(data: Array<dataObj>) {
    return [{
        headers: ['DATE LOGGED', 'ASSET ID', 'DIVISION NAME', 'TYPE'],
        displayedColumns: ['eventStart', 'assetId', 'divisionName', 'type'],
        rows: rowData
    }];
}
</code>```

I want the default sort of the table rows to be based on the 'millisecond' properties of the row objects, but I do not want to display the property in the table. Is there a way to do this? I don't see anything about it in the docs and setting matSortStart="desc" just sorts the table based on the first column (eventStart in this case).

答:
you have to do 2 things to achieve that:

Add matSortActive="milliseconds" so that sorting is done by this column, you already knew matSortDirection="desc" which will work when added to the
 element

Add css which hides the milliseconds column (which we placed at the very last), since you didn't want to display it

relevant CSS:

```<code>td.mat-cell:last-of-type,
th.mat-header-cell:last-of-type
{display:none;}
</code>```

relevant HTML:

```<code><table mat-table [dataSource]="dataSource" matSort matSortActive="milliseconds" matSortDirection="desc" class="mat-elevation-z8">

    <!-- id Column -->
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> id. </th>
        <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>

    <!-- type Column -->
    <ng-container matColumnDef="type">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> type </th>
        <td mat-cell *matCellDef="let element"> {{element.type}} </td>
    </ng-container>

    <!-- assetName Column -->
    <ng-container matColumnDef="assetName">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> assetName </th>
        <td mat-cell *matCellDef="let element"> {{element.assetName}} </td>
    </ng-container>

    <!-- milliseconds Column
  -->
    <ng-container matColumnDef="milliseconds" class='hideMe'>
        <th mat-header-cell *matHeaderCellDef mat-sort-header> milliseconds </th>
        <td mat-cell *matCellDef="let element"> {{element.milliseconds}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code>```

complete working stackblitz is available here

Body:
Here is the code that creates my tableModel:

const rowData = [{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d750f',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 3524583453452
},{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d7534',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 35245824528
},{
        id: '74b0d34f-1e2f-47d1-b1ea-55658d5d7545',
        assetId: '9ff317cd-3b75-433d-a32b-949c67b84eee',
        type: 'DATA_RECORDING',
        eventStart: '2019-05-01T00:00:00Z',
        eventEnd: '2019-05-01T00:00:00Z',
        assetName: 584,
        milliseconds: 13219245949
}];

tableModel(data: Array<dataObj>) {
    return [{
        headers: ['DATE LOGGED', 'ASSET ID', 'DIVISION NAME', 'TYPE'],
        displayedColumns: ['eventStart', 'assetId', 'divisionName', 'type'],
        rows: rowData
    }];
}

I want the default sort of the table rows to be based on the 'millisecond' properties of the row objects, but I do not want to display the property in the table. Is there a way to do this? I don't see anything about it in the docs and setting matSortStart="desc" just sorts the table based on the first column (eventStart in this case).

Body:
you have to do 2 things to achieve that:

Add matSortActive="milliseconds" so that sorting is done by this column, you already knew matSortDirection="desc" which will work when added to the <table mat-table> element

Add css which hides the milliseconds column (which we placed at the very last), since you didn't want to display it

relevant CSS:

td.mat-cell:last-of-type,
th.mat-header-cell:last-of-type
{display:none;}

relevant HTML:

<table mat-table [dataSource]="dataSource" matSort matSortActive="milliseconds" matSortDirection="desc" class="mat-elevation-z8">

    <!-- id Column -->
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> id. </th>
        <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>

    <!-- type Column -->
    <ng-container matColumnDef="type">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> type </th>
        <td mat-cell *matCellDef="let element"> {{element.type}} </td>
    </ng-container>

    <!-- assetName Column -->
    <ng-container matColumnDef="assetName">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> assetName </th>
        <td mat-cell *matCellDef="let element"> {{element.assetName}} </td>
    </ng-container>

    <!-- milliseconds Column
  -->
    <ng-container matColumnDef="milliseconds" class='hideMe'>
        <th mat-header-cell *matHeaderCellDef mat-sort-header> milliseconds </th>
        <td mat-cell *matCellDef="let element"> {{element.milliseconds}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

complete working stackblitz is available here


问:
IFormFile property in .NET Core ViewModel causing stalled AJAX Request
I am giving users the ability to add images for a retail product inside of an Add/Edit Product modal.

Modal ViewModel:

```<code>public class ProductModalViewModel
{
    public ProductModalViewModel()
    {
        Product = new ProductDTO();
        Images = new List<ProductImageViewModel>();
    }

    public ProductDTO Product { get; set; }

    public List<ProductImageViewModel> Images { get; set; }
}
</code>```

Each product image is contained in its own ViewModel, as below:

Image ViewModel:

```<code>public class ProductImageViewModel
{
    public ProductImageViewModel()
    {
        ProductImage = new ProductImageDTO();
    }

    public ProductImageDTO ProductImage { get; set; }

    [DataType(DataType.Upload)]
    public IFormFile ImageFile { get; set; }
}
</code>```

Upon submitting the form to save the product (and any added images) my request gets hung up and displays "pending" in Chrome Development Tools. My controller action is never reached.

This only happens when I include the ProductImage Fields/ViewModel/Logic in my project. This was not occurring before adding that functionality to the modal, and works fine if I remove all of the ProductImage Fields/ViewModel/Logic then submit again.

Is there something inherently wrong with including my IFormFile inside of a nested ViewModel? Or could this be something else. The rest of my relevent code is below.

Controller:

```<code>[HttpPost]
public IActionResult SaveProduct([FromForm]ProductModalViewModel model)
{
    //save code
}
</code>```

View (Modal):

```<code><form id="formSaveProduct" onsubmit="SaveProduct(event)" enctype="multipart/form-data">
//Other product fields removed for brevity
    <div class="row">
        <div class="col-md-12">
            <ul class="list-group" id="image-list-group">
                @for (int i = 0; i < Model.Images.Count(); i++)
                {
                    <partial name="_ImageListItem" for="Images[i]" />
                }
            </ul>
        </div>
    </div>
</form>
</code>```

PartialView (ProductImage):

```<code><li class="list-group-item my-1">
    <input type="hidden" asp-for="ProductImage.Id" class="image-id" />
    <input type="hidden" asp-for="ProductImage.ProductId" class="image-productid" />

    <div class="row">
        <div class="col-3">
            <input type="text" readonly asp-for="ProductImage.Order" class="image-order" />
        </div>
        <div class="col-6">
            <img src="..\@Model.ProductImage.Path" class="image-display" />
        </div>
    </div>
</li>
</code>```

Script:

```<code>function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        success: function (result) {
            //removed for brevity
        }
    });
}
</code>```

答:
First you dont need this

```<code>[DataType(DataType.Upload)]
public IFormFile ImageFile { get; set; }
</code>```

so you can change your code to

```<code> public IFormFile ImageFile { get; set; }
</code>```

And in your script you should add contentType

```<code>function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        contentType: "multipart/form-data", //here
        success: function (result) {
            if (result.success) {
                $("#exampleModal").modal('toggle');
                location.reload();
            }
            else {
                $(".modal-body").html(result);
            }
        }
    });
}
</code>```

Body:
I am giving users the ability to add images for a retail product inside of an Add/Edit Product modal.

Modal ViewModel:

public class ProductModalViewModel
{
    public ProductModalViewModel()
    {
        Product = new ProductDTO();
        Images = new List<ProductImageViewModel>();
    }

    public ProductDTO Product { get; set; }

    public List<ProductImageViewModel> Images { get; set; }
}

Each product image is contained in its own ViewModel, as below:

Image ViewModel:

public class ProductImageViewModel
{
    public ProductImageViewModel()
    {
        ProductImage = new ProductImageDTO();
    }

    public ProductImageDTO ProductImage { get; set; }

    [DataType(DataType.Upload)]
    public IFormFile ImageFile { get; set; }
}

Upon submitting the form to save the product (and any added images) my request gets hung up and displays "pending" in Chrome Development Tools. My controller action is never reached.

This only happens when I include the ProductImage Fields/ViewModel/Logic in my project. This was not occurring before adding that functionality to the modal, and works fine if I remove all of the ProductImage Fields/ViewModel/Logic then submit again.

Is there something inherently wrong with including my IFormFile inside of a nested ViewModel? Or could this be something else. The rest of my relevent code is below.

Controller:

[HttpPost]
public IActionResult SaveProduct([FromForm]ProductModalViewModel model)
{
    //save code
}

View (Modal):

<form id="formSaveProduct" onsubmit="SaveProduct(event)" enctype="multipart/form-data">
//Other product fields removed for brevity

                @for (int i = 0; i < Model.Images.Count(); i++)
                {
                    <partial name="_ImageListItem" for="Images[i]" />
                }

</form>

PartialView (ProductImage):

    <input type="hidden" asp-for="ProductImage.Id" class="image-id" />
    <input type="hidden" asp-for="ProductImage.ProductId" class="image-productid" />

            <input type="text" readonly asp-for="ProductImage.Order" class="image-order" />

Script:

function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        success: function (result) {
            //removed for brevity
        }
    });
}

Body:
First you dont need this

[DataType(DataType.Upload)]
public IFormFile ImageFile { get; set; }

so you can change your code to

 public IFormFile ImageFile { get; set; }

And in your script you should add contentType

function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        contentType: "multipart/form-data", //here
        success: function (result) {
            if (result.success) {
                $("#exampleModal").modal('toggle');
                location.reload();
            }
            else {
                $(".modal-body").html(result);
            }
        }
    });
}


问:
how to creat a javascript function that combine input values from user input and out put them in a phrase?
i'm trying to creat a resume builder project to learn javascript. how can i creat a function that combine input value of a user, and output them in one phrase, some thing like this

<form>
    <input type:"text" id:"position">
    <input type:"text" id:"startdate">
    <input type:"date" id:"enddate">
</form>
```

and get this result:

started working as a position from startdate to enddate

with the ability to add new fieldset dynamicly if the user want to, that will be desplayed in a new phrase the same way just with new input

答:
First of all, your question is unclear. What have you tried? What are you trying to achieve?
Here are a simple example is to get you started. Just get the value of each field, and combine the value into a string.

```<code>function combineText() {
  var position = document.getElementById('position').value;
  var startDate = document.getElementById('startDate').value;
  var endDate = document.getElementById('endDate').value;

  var text = "started working as a "+position+" from "+startDate+" to "+endDate+".";

  document.getElementById('output').innerHTML = text;
}
</code>```

Working jsfiddle example with event listener and form.

Body:
i'm trying to creat a resume builder project to learn javascript. how can i creat a function that combine input value of a user, and output them in one phrase, some thing like this

<form>
    <input type:"text" id:"position">
    <input type:"text" id:"startdate">
    <input type:"date" id:"enddate">
</form>

and get this result:

started working as a position from startdate to enddate

with the ability to add new fieldset dynamicly if the user want to, that will be desplayed in a new phrase the same way just with new input

Body:
First of all, your question is unclear. What have you tried? What are you trying to achieve?
Here are a simple example is to get you started. Just get the value of each field, and combine the value into a string.

function combineText() {
  var position = document.getElementById('position').value;
  var startDate = document.getElementById('startDate').value;
  var endDate = document.getElementById('endDate').value;

  var text = "started working as a "+position+" from "+startDate+" to "+endDate+".";

  document.getElementById('output').innerHTML = text;
}

Working jsfiddle example with event listener and form.


问:
Owl Carousel 1px Height
I have a slider setup that can hold a Vimeo/Youtube video or images.

The video is the first slide.

On load of the page, the first slide has a background image pulled in from the video service (vimeo/youtube) and appears to play a role in collapsing the .owl-stage-outer .owl-height classes to a 1px height. Once I scroll to the next slide and then back, the video/video background image appears and sets the height for these classes properly.

I've searched through SO MANY proposed solutions but haven't found anything that works to fix the issue. It seems many have struggled with a similar issue.

This is literally the last bug I have to fix on this website. Would be so amazing if anyone had some additional insight.

I've tried using a plugin called imagesLoaded, as was suggested on the Owl Git repository, but its kicking an error of 'imagesLoaded is not a function'. The javascript is installed properly. I'm not sure why its not recognizing the function.

I've tried both ways of initializing:
$(window).load(function(){
and
$(document).ready(function(){

Would love to have a fix that is native to Owl. Has this issue been successfully addressed? Would be so grateful for some assistance.

Thanks!

Here's an example page: http://desrosiers.robertrhu.com/

This is the code I'm working with:

```<code><?php

/* Home Page image Slider */

?>

<script>
    $('.item-video').imagesLoaded({
        background: true
    }, function( imgLoad ) {
        $status.text( imgLoad.images.length + ' images loaded checking backgrounds' );
    }
                          );
</script>

<script>
    $(window).load(function(){
    //Initialize Owl Carousel Javascript
    $("#home-slider").owlCarousel({
        items: 1,
        loop: true,
        nav: true,
        navText: [
            "<img src='<?php echo get_template_directory_uri(); ?>/assets/images/desrosiers-architects-image-slider-arrow.png' />",
            "<img src='<?php echo get_template_directory_uri(); ?>/assets/images/desrosiers-architects-image-slider-arrow.png' />"
        ],
        margin: 0,
        dots: false,
        autoplay: false,
        animateOut: 'fadeOut',
        video: true,
        responsive: true,
        autoHeight:true,

    });
    // var mainCarousel = $("#home-slider");
    // mainCarousel.find('.owl-stage .slide').css('height', mainCarousel.find('.owl-stage-outer').height());

});
</script>
<!--Begin Home Page Property Hero Slider-->

<ul id="home-slider"
class="owl-carousel">

<?php if( have_rows('home_page_slider', 'option') ): ?>
    <?php while( have_rows('home_page_slider', 'option') ): the_row();

    //Variables
    $image = get_sub_field('home_page_photo', 'option');
    $vedio = get_sub_field('homepage_vedio', 'option');
    $alt = get_sub_field('home_page_photo_alt', 'option'); ?>

    <li class="slide item-video">
 <?php  if(!empty( $vedio) ){ ?> <a class="owl-video" href="<?php echo $vedio; ?>"></a> <?php } else { ?>
      <img class="slide-image"
             src="<?php echo $image; ?>"
             alt="<?php echo $alt; ?>" />
<?php  } ?>
    </li>

    <?php endwhile; ?>
<?php endif; ?>

</ul>
</code>```

答:
if you have multiple classes, you may use this:

```<code>var owlCar = $('.owl-carousel').owlCarousel({
        items       : 1,
        margin      : 10,
        loop        : true,
        autoHeight  : true
    });

    var length = $(".owl-stage-outer").length;

    var carTimer = setInterval(function(){
        var gotheight = true;
        for(var i=0; i<length; i++){
            if($(".owl-stage-outer").eq(i).height() < 2){
                gotheight = false;
                break;
            }
        }

        if(gotheight)
            clearInterval(carTimer);
        else
            owlCar.trigger('refresh.owl.carousel', [100]);
    }, 300);
</code>```

this work for me.

Title: Owl Carousel 1px Height

Body:
I have a slider setup that can hold a Vimeo/Youtube video or images.

The video is the first slide.

On load of the page, the first slide has a background image pulled in from the video service (vimeo/youtube) and appears to play a role in collapsing the .owl-stage-outer .owl-height classes to a 1px height. Once I scroll to the next slide and then back, the video/video background image appears and sets the height for these classes properly.

I've searched through SO MANY proposed solutions but haven't found anything that works to fix the issue. It seems many have struggled with a similar issue.

This is literally the last bug I have to fix on this website. Would be so amazing if anyone had some additional insight.

I've tried using a plugin called imagesLoaded, as was suggested on the Owl Git repository, but its kicking an error of 'imagesLoaded is not a function'. The javascript is installed properly. I'm not sure why its not recognizing the function.

I've tried both ways of initializing:
$(window).load(function(){
and
$(document).ready(function(){

Would love to have a fix that is native to Owl. Has this issue been successfully addressed? Would be so grateful for some assistance.

Thanks!

Here's an example page: http://desrosiers.robertrhu.com/

This is the code I'm working with:

<?php

/* Home Page image Slider */

?>

<?php if( have_rows('home_page_slider', 'option') ): ?>
    <?php while( have_rows('home_page_slider', 'option') ): the_row();

    //Variables
    $image = get_sub_field('home_page_photo', 'option');
    $vedio = get_sub_field('homepage_vedio', 'option');
    $alt = get_sub_field('home_page_photo_alt', 'option'); ?>

 <?php  if(!empty( $vedio) ){ ?> <a class="owl-video" href="<?php echo $vedio; ?>"> <?php } else { ?>
      <img class="slide-image"
             src="<?php echo $image; ?>"
             alt="<?php echo $alt; ?>" />
<?php  } ?>

    <?php endwhile; ?>
<?php endif; ?>

Body:
if you have multiple classes, you may use this:

var owlCar = $('.owl-carousel').owlCarousel({
        items       : 1,
        margin      : 10,
        loop        : true,
        autoHeight  : true
    });

    var length = $(".owl-stage-outer").length;

    var carTimer = setInterval(function(){
        var gotheight = true;
        for(var i=0; i<length; i++){
            if($(".owl-stage-outer").eq(i).height() < 2){
                gotheight = false;
                break;
            }
        }

        if(gotheight)
            clearInterval(carTimer);
        else
            owlCar.trigger('refresh.owl.carousel', [100]);
    }, 300);

this work for me.


问:
How to automatically scroll to an anchor while audio plays
I'm working on an online learning portal. I have an audio player on a page designed by https://www.cleanhtmlplayer.com. I want to automatically scroll to an anchor of a page at specific timestamps of the audio.

For example, I have Anchor 1 and Anchor 2 in a webpage. As the audio is playing, I want the page to automatically scroll to Anchor 2 at the 5-minute mark. Is this possible?

答:
You could add a listener to the timeupdate event and take an action depending on the value of the currentTime property.

If you rather prefer to use the Clean Html Player API, then when initializing in javascript on the plyrOptions argument, use the listeners property to bind to the timeupdate event.


问:
Select timestamp for one date and for a period time on the same field in one query
My query on the table require the condition as below:

Table:

```<code>user_id || amount || date
1       || 10     || 2019-04-01
1       || 25     || 2019-04-02
3       || 25     || 2019-04-04
1       || 25     || 2019-04-03
</code>```

Expect result: get user_id, date, amount of date, amount of month (sum all amount of date of user_id in month)

input parameter: user_id, date, start date of month, end date of month.

ex: user_id = 1, date = 2019-04-02, start_date_of_month = 2019-04-01, end_date_of_month = 2019-04-30

```<code>user_id || amount_of_date || date       || amount_of_month
1       || 25             || 2019-04-02 || 60
</code>```

答:
You can try below -</p>

```<code>select user_id,
       max(case when date=@inputdate then amount end) as amount_of_Date,
       min(case when date=@inputdate then date end) as date,
       sum(amount) as amount_of_month
from tablename
where user_id=1 and date between '2019-04-01' and '2019-04-30'
group  by user_id
</code>```

Body:
My query on the table require the condition as below:

Table:

user_id || amount || date
1       || 10     || 2019-04-01
1       || 25     || 2019-04-02
3       || 25     || 2019-04-04
1       || 25     || 2019-04-03

Expect result: get user_id, date, amount of date, amount of month (sum all amount of date of user_id in month)

input parameter: user_id, date, start date of month, end date of month.

ex: user_id = 1, date = 2019-04-02, start_date_of_month = 2019-04-01, end_date_of_month = 2019-04-30

user_id || amount_of_date || date       || amount_of_month
1       || 25             || 2019-04-02 || 60

Body:
You can try below -

select user_id,
       max(case when date=@inputdate then amount end) as amount_of_Date,
       min(case when date=@inputdate then date end) as date,
       sum(amount) as amount_of_month
from tablename
where user_id=1 and date between '2019-04-01' and '2019-04-30'
group  by user_id


问:
extjs form post rails
i am newbie to Ext JS...I want to post Ext JS form data to server...
How am i supposed to proceed? i am using Ext JS with rails...
I have followed link : Ext JS With rails but no luck..</p>

答: You may consider using Netzke, e.g.: http://blog.writelesscode.com/blog/2010/06/14/extjs-rails-crud-application-in-7-minutes/</p>

Title: extjs form post rails


问:
How to avoid nested loop in a real Javascript coding test
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

```<code>
const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

</code>```

[[1, 2]] should be returned.

答:
You can mimic a set of arrays with nested maps, where [1, 2] becomes an entry in the root map where the key is 1 and the value is another map with a key 2, like this:

```<code>const present = Symbol('present');

class ArraySet {
    constructor() {
        this._root = new Map();
    }

    add(array) {
        let node = this._root;

        for (const item of array) {
            if (node.has(item)) {
                node = node.get(item);
            } else {
                node.set(item, node = new Map());
            }
        }

        node[present] = true;
    }

    has(array) {
        let node = this._root;

        for (const item of array) {
            node = node.get(item);

            if (node === undefined) {
                return false;
            }
        }

        return !!node[present];
    }
}
</code>```

then:

```<code>const compareArrs = (arr1, arr2) => {
    const set = new ArraySet();
    arr1.forEach(set.add, set);
    return arr2.filter(set.has, set);
};
</code>```

const present = Symbol('present');

class ArraySet {
    constructor() {
        this._root = new Map();
    }

    add(array) {
        let node = this._root;

        for (const item of array) {
            if (node.has(item)) {
                node = node.get(item);
            } else {
                node.set(item, node = new Map());
            }
        }

        node[present] = true;
    }

    has(array) {
        let node = this._root;

        for (const item of array) {
            node = node.get(item);

            if (node === undefined) {
                return false;
            }
        }

        return !!node[present];
    }
}

const compareArrs = (arr1, arr2) => {
    const set = new ArraySet();
    arr1.forEach(set.add, set);
    return arr2.filter(set.has, set);
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));```
</div>
</div>
</p>

<p>That takes time proportional to <code>arr1.concat(arr2).flat().length</code>. Another approach that works as long as you can create an appropriate comparison function for the arrays, like this lexicographic one for when the usual JavaScript operators give a total ordering:</p>

```const lexCompare = (a, b) => {
    const len = Math.min(a.length, b.length);

    for (let i = 0; i < len; i++) {
        if (a[i]  b[i]) return 1;
    }

    return a.length - b.length;
};
```

<p><strong>and the input arrays contain no duplicates</strong> is to sort the combination of both arrays first:</p>

```const sorted = arr1.concat(arr2).sort(lexCompare);
```

<p>then look for duplicates created by the merge right beside each other:</p>

```return sorted.filter((item, i) => {
    if (i === 0) return false;

    const prev = sorted[i - 1];
    return prev.length === item.length && prev.every((x, i) => x === item[i]);
});
```

in time O((|arr1| + |arr2|) log (|arr1| + |arr2|) l) where l is the maximum array length. You can reduce that (|arr1| + |arr2|) log (|arr1| + |arr2|) to |arr1| log |arr1| + |arr2| log |arr2| but it might end up being slower.

Body:
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

[[1, 2]] should be returned.

Body:
You can mimic a set of arrays with nested maps, where [1, 2] becomes an entry in the root map where the key is 1 and the value is another map with a key 2, like this:

const present = Symbol('present');

class ArraySet {
    constructor() {
        this._root = new Map();
    }

    add(array) {
        let node = this._root;

        for (const item of array) {
            if (node.has(item)) {
                node = node.get(item);
            } else {
                node.set(item, node = new Map());
            }
        }

        node[present] = true;
    }

    has(array) {
        let node = this._root;

        for (const item of array) {
            node = node.get(item);

            if (node === undefined) {
                return false;
            }
        }

        return !!node[present];
    }
}

then:

const compareArrs = (arr1, arr2) => {
    const set = new ArraySet();
    arr1.forEach(set.add, set);
    return arr2.filter(set.has, set);
};

const present = Symbol('present');

class ArraySet {
    constructor() {
        this._root = new Map();
    }

    add(array) {
        let node = this._root;

        for (const item of array) {
            if (node.has(item)) {
                node = node.get(item);
            } else {
                node.set(item, node = new Map());
            }
        }

        node[present] = true;
    }

    has(array) {
        let node = this._root;

        for (const item of array) {
            node = node.get(item);

            if (node === undefined) {
                return false;
            }
        }

        return !!node[present];
    }
}

const compareArrs = (arr1, arr2) => {
    const set = new ArraySet();
    arr1.forEach(set.add, set);
    return arr2.filter(set.has, set);
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));

That takes time proportional to arr1.concat(arr2).flat().length. Another approach that works as long as you can create an appropriate comparison function for the arrays, like this lexicographic one for when the usual JavaScript operators give a total ordering:

const lexCompare = (a, b) => {
    const len = Math.min(a.length, b.length);

    for (let i = 0; i < len; i++) {
        if (a[i] < b[i]) return -1;
        if (a[i] > b[i]) return 1;
    }

    return a.length - b.length;
};

and the input arrays contain no duplicates is to sort the combination of both arrays first:

const sorted = arr1.concat(arr2).sort(lexCompare);

then look for duplicates created by the merge right beside each other:

return sorted.filter((item, i) => {
    if (i === 0) return false;

    const prev = sorted[i - 1];
    return prev.length === item.length && prev.every((x, i) => x === item[i]);
});

in time O((|arr1| + |arr2|) log (|arr1| + |arr2|) l) where l is the maximum array length. You can reduce that (|arr1| + |arr2|) log (|arr1| + |arr2|) to |arr1| log |arr1| + |arr2| log |arr2| but it might end up being slower.


问:
iOS MTKView (Metal Kit view) draws image without proper scale
I don't understand why MTKView doesn't use device's scale.

I have a retina device: 2x scale, MTKView.bounds of 400x200, and CIImage size of 800x400, but it draws only left bottom quarter of the image.

Strangely drawableSize returns bounds size (400x200).

Here's the code I use:

```<code>id<MTLTexture> targetTexture = self.currentDrawable.texture;
id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];

[ctx render:coreImage toMTLTexture:targetTexture commandBuffer:commandBuffer bounds:self.bounds colorSpace:colorSpace];

[commandBuffer presentDrawable:self.currentDrawable];
[commandBuffer commit];
</code>```

答:
Found it. I just need to use MTKView's method setDrawableSize to the scaled size I want:</p>

```<code>[self setDrawableSize:coreImage.extent.size];
</code>```

Body:
I don't understand why MTKView doesn't use device's scale.

I have a retina device: 2x scale, MTKView.bounds of 400x200, and CIImage size of 800x400, but it draws only left bottom quarter of the image.

Strangely drawableSize returns bounds size (400x200).

Here's the code I use:

id<MTLTexture> targetTexture = self.currentDrawable.texture;
id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];

[ctx render:coreImage toMTLTexture:targetTexture commandBuffer:commandBuffer bounds:self.bounds colorSpace:colorSpace];

[commandBuffer presentDrawable:self.currentDrawable];
[commandBuffer commit];

Body:
Found it. I just need to use MTKView's method setDrawableSize to the scaled size I want:

[self setDrawableSize:coreImage.extent.size];


问:
Room: replace SQLite cursor in Dao?
I have a JobIntentService that re-sets pending Alarm Notifications from an SQLite database.  It uses a query and a Cursor to get the Notification dates from 4 different columns in the database.  I am converting to a Room database and not sure how to convert the cursor to a Dao method.  Do I need to use @Transaction since I am getting Notifications from multiple columns in the database?  Would appreciate any insights or thoughts on how to build in Room.</p>

```<code>Service

public class Service extends JobIntentService {

static final int JOB_ID = 9;

public static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, RebootService.class, JOB_ID, work);
}

@Override
protected void onHandleWork(@NonNull Intent intent) {

    AlarmManager alarmManager1;
    Intent brIntent1;
    PendingIntent pendingIntent1;

    SQLiteDB sqLiteDB = SQLiteDB.getInstance(this);
    Calendar cal1 = Calendar.getInstance();

    Cursor cursor = sqLiteDB.resetNotifications();

     try {
          if (cursor.getCount() > 0) {
              cursor.moveToFirst();

              int dueDatentimeColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_DUEDATENTIME);
              int notifColumnIndex1 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_NOTIFTIME);
              int notif2ColumnIndex2 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_NOTIFTIME2);
              int randColumnIndex1 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_RANDINT);

              while (!cursor.isAfterLast()) {

                  do {

                      long notifTime1 = cursor.getLong(notifColumnIndex1);
                      int randInt1 = cursor.getInt(randColumnIndex1);
                      cal1.setTime(new Date(notifTime1));

                      // Set up a system AlarmManager to fire a future alarm that sends a Notification
                      // even if the app is in the background or closed.
                      alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

                      if (cal1.getTimeInMillis() > System.currentTimeMillis()) {
                          brIntent1 = new Intent(this, AlarmReceiver.class);
                       brIntent1.setAction("24Hour");

                       pendingIntent1 = PendingIntent.getBroadcast(this, randInt1, brIntent1,
                                    PendingIntent.FLAG_ONE_SHOT);

                      if (alarmManager1 != null && notifTime1 != -1) {
                          alarmManager1.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                      }
...
}

SQLiteDB.java

...
public Cursor resetNotifications() {

   SQLiteDatabase db = getReadableDatabase();

   String[] columns = new String[]{
                ItemContract.ItemEntry.COLUMN_NOTIFTIME,
                ItemContract.ItemEntry.COLUMN_NOTIFTIME2,
                ItemContract.ItemEntry.COLUMN_DUEDATENTIME,
                ItemContract.ItemEntry.COLUMN_RANDINT};

        return db.query(
                TABLE_NAME,
                columns, // The columns to return
                null,
                null,
                null,
                null,
                null
        );
}

This is the code I came up as a replacement:

public class RebootService extends JobIntentService {

// Unique job ID for this service
static final int JOB_ID = 10000;

// Convenience method for enqueueing work to this service.
public static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, RebootService.class, JOB_ID, work);
}

private QuickcardRepository reposit1;

@Override
protected void onHandleWork(@NonNull Intent intent) {

    reposit1 = new QuickcardRepository(getApplication());

    Bundle extras = intent.getExtras(); // Returns the Intent *that started this Service.*
    if (extras != null) {

        String classname = extras.getString("TAG");

        if (classname != null && classname.equals("bootCompleted")) {

            AlarmManager alarmManager1;
            Intent brIntent1, brIntent2, brIntent3;
            PendingIntent pendingIntent1, pendingIntent2, pendingIntent3;

            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
            Calendar cal3 = Calendar.getInstance();

            List<Quickcard> resetNotificationsList = reposit1.getNotifications();
            // Cycle through the Room database rows to get the Notifications data
            for (Quickcard quickcard: resetNotificationsList) {
                 // Quickcards without a Due date get a Due date in the database of -1.
                 // Therefore, only cycle through and get data for those quickcards that have
                //  a Due data and therefore have Notifications (reminders) where the actual
                //  "Due date" is != -1.
                 if(quickcard.getDuedatentime() != -1) {

                     // Set up the 24-Hour calendar object.
                     long notifTime1 = quickcard.getNotiftime();
                     int randInt1 = quickcard.getRandint();
                     cal1.setTime(new Date(notifTime1));

                     // Set up a system AlarmManager to fire a future alarm that sends a Notification
                     // even if the app is in the background or closed.  Have to add "context" here.
                     alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

                     // If the stated alarm trigger time is in the past, the alarm will be triggered immediately.
                     // So only set Alarms to fire Notifications for Duedates in the future
                     // (meaning > than the current System time).  Ignore those in the past.
                     if (cal1.getTimeInMillis() > System.currentTimeMillis()) {
                         // For the 24Hour Notifications.
                         // Set up a PendingIntent that will perform broadcast to the BroadcastReceiver.
                         brIntent1 = new Intent(this, AlarmReceiver.class);
                         brIntent1.setAction("24Hour");
                         // Need to use FLAG_ONE_SHOT on the PendingIntent, not FLAG_UPDATE_CURRENT.
                         // A random int is used to be able to set multiple alarms and then to be able to
                         // delete them later (if the user for ex., deletes the quickCards Duedate) using
                         // the same random int.
                         pendingIntent1 = PendingIntent.getBroadcast(this, randInt1, brIntent1,
                                 PendingIntent.FLAG_ONE_SHOT);

                         // Alarms have 3 properties below after "set(...)":
                         // 1) Alarm type:  RTC_WAKEUP type is chosen here to wake the device from sleep.
                         // 2) Trigger time: in this case, 24 hours before the Duedate/Duetime is reached.
                         // 3) Pending Intent:  A future Intent that is sent when the trigger time is reached.
                         int SDK_INT1 = Build.VERSION.SDK_INT;
                         if (SDK_INT1 >= Build.VERSION_CODES.M) {
                             // Wakes up the device in Doze Mode for API Level 23 and higher.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),
                                         pendingIntent1);
                             }
                         } else if (SDK_INT1 >= Build.VERSION_CODES.KITKAT) {
                             // Wakes up the device in Idle Mode for API Level 19 to 22.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.setExact(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                             }
                         } else {
                             // Old APIs Level 18 and below.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                             }
                         }
                     }
</code>```

答:
I believe that @Transaction wraps the code in a transaction. This is already done for all but @Query's (if the @Query isn't an update/delete query (if it is an update or delete query, it is wrapped within a transaction)).

I believe the issue as to whether or not a SELECT query should be wrapped within a transaction (@Transaction @Query......) is if @Relation is used. If it is then the List(s) of the related/associated items/objects are run as separate queries and thus running them all in a transaction will ensure consistent data. Without there is the potential that underlying data could be changed by other transactions and thus the resultant data could be inconsistent.

Saying that it would hardly have an impact to use @Transaction where it is not needed and may even have a positive impact if it were coded where it might inadvertently not bee coded.

Of course you can always return a Cursor anyway using Room. You may wish to have a look at Associating tables using Room database in Android Studio, which has some examples.

Based upon your code, primarily that you have an ItemContract with a subclass of ItemEntry then the Entity for an ItemEntry could be in ItemEntry.java, as per :-

```<code>@Entity
public class ItemEntry {

    @PrimaryKey(autoGenerate = true)
    private long id;
    @ColumnInfo(name = COLUMN_NOTIFTIME)
    private long notiftime;
    @ColumnInfo(name = COLUMN_NOTIFTIME2)
    private long notiftime2;
    @ColumnInfo(name = COLUMN_DUEDATENTIME)
    private long duedatentime;
    @ColumnInfo(name = COLUMN_RANDINT)
    public int randint;

    public ItemEntry(){

    }

    @Ignore
    public ItemEntry(long notiftime, long notiftime2, long duedatentime, int randint) {
        this.notiftime = notiftime;
        this.notiftime2 = notiftime2;
        this.duedatentime = duedatentime;
        this.randint = randint;
    }

    public long getId() {
        return id;
    }

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

    public long getNotiftime() {
        return notiftime;
    }

    public void setNotiftime(long notiftime) {
        this.notiftime = notiftime;
    }

    public long getNotiftime2() {
        return notiftime2;
    }

    public void setNotiftime2(long notiftime2) {
        this.notiftime2 = notiftime2;
    }

    public long getDuedatentime() {
        return duedatentime;
    }

    public void setDuedatentime(long duedatentime) {
        this.duedatentime = duedatentime;
    }

    public int getRandint() {
        return randint;
    }

    public void setRandint(int randint) {
        this.randint = randint;
    }
}
</code>```

Along with an interface ItemEntryDao.java as :-

```<code>@Dao
interface ItemEntryDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertItemEntries(ItemEntry... itemEntries);
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertItemEntry(ItemEntry itemEntry);
    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateItemEnrties(ItemEntry... itemEntries);
    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateItemEntry(ItemEntry itemEntry);
    @Delete
    int deleteItemEntries(ItemEntry... itemEntries);
    @Delete
    int deleteItemEntry(ItemEntry itemEntry);
    @Query("SELECT * FROM ItemEntry")
    List<ItemEntry> resetNotifications();
}
</code>```

The @Query is the equivalent to the Cursor BUT returns a List of ItemEntry objects.

The above could be used for example (that very basically replicates your code, but outputs the extracted data to the log) like :-

```<code>public void onHandleWork() {

    ItemEntry ie = new ItemEntry();
    ie.setNotiftime(100);
    ie.setNotiftime2(200);
    ie.setDuedatentime(500000);
    ie.setRandint(567);
    mDB.getItemEntryDao().insertItemEntry(ie);
    List<ItemEntry> mylist = mDB.getItemEntryDao().resetNotifications();
    for (ItemEntry itementry: mylist) {
        Log.d("ITEMENTRY",
                "\n\tnotiftime= " + String.valueOf(itementry.getNotiftime()) +
                        "\n\tnotiftime2= " + String.valueOf(itementry.getNotiftime2()) +
                        "\n\tduedatetime= " + String.valueOf(itementry.getDuedatentime()) +
                        "\n\trandint= " + String.valueOf(itementry.getRandint())

        );
    }
}
</code>```

mDB is the built object (i.e. an instance of the @Database class)

This would result in (for the first run) :-

```<code>05-28 14:31:14.587 7211-7211/aso.so56326640 D/ITEMENTRY:  notiftime= 100
      notiftime2= 200
      duedatetime= 500000
      randint= 567
</code>```

Title: Room: replace SQLite cursor in Dao?

Body:
I have a JobIntentService that re-sets pending Alarm Notifications from an SQLite database.  It uses a query and a Cursor to get the Notification dates from 4 different columns in the database.  I am converting to a Room database and not sure how to convert the cursor to a Dao method.  Do I need to use @Transaction since I am getting Notifications from multiple columns in the database?  Would appreciate any insights or thoughts on how to build in Room.

Service

public class Service extends JobIntentService {

static final int JOB_ID = 9;

public static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, RebootService.class, JOB_ID, work);
}

@Override
protected void onHandleWork(@NonNull Intent intent) {

    AlarmManager alarmManager1;
    Intent brIntent1;
    PendingIntent pendingIntent1;

    SQLiteDB sqLiteDB = SQLiteDB.getInstance(this);
    Calendar cal1 = Calendar.getInstance();

    Cursor cursor = sqLiteDB.resetNotifications();

     try {
          if (cursor.getCount() > 0) {
              cursor.moveToFirst();

              int dueDatentimeColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_DUEDATENTIME);
              int notifColumnIndex1 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_NOTIFTIME);
              int notif2ColumnIndex2 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_NOTIFTIME2);
              int randColumnIndex1 = cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_RANDINT);

              while (!cursor.isAfterLast()) {

                  do {

                      long notifTime1 = cursor.getLong(notifColumnIndex1);
                      int randInt1 = cursor.getInt(randColumnIndex1);
                      cal1.setTime(new Date(notifTime1));

                      // Set up a system AlarmManager to fire a future alarm that sends a Notification
                      // even if the app is in the background or closed.
                      alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

                      if (cal1.getTimeInMillis() > System.currentTimeMillis()) {
                          brIntent1 = new Intent(this, AlarmReceiver.class);
                       brIntent1.setAction("24Hour");

                       pendingIntent1 = PendingIntent.getBroadcast(this, randInt1, brIntent1,
                                    PendingIntent.FLAG_ONE_SHOT);

                      if (alarmManager1 != null && notifTime1 != -1) {
                          alarmManager1.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                      }
...
}

SQLiteDB.java

...
public Cursor resetNotifications() {

   SQLiteDatabase db = getReadableDatabase();

   String[] columns = new String[]{
                ItemContract.ItemEntry.COLUMN_NOTIFTIME,
                ItemContract.ItemEntry.COLUMN_NOTIFTIME2,
                ItemContract.ItemEntry.COLUMN_DUEDATENTIME,
                ItemContract.ItemEntry.COLUMN_RANDINT};

        return db.query(
                TABLE_NAME,
                columns, // The columns to return
                null,
                null,
                null,
                null,
                null
        );
}

This is the code I came up as a replacement:

public class RebootService extends JobIntentService {

// Unique job ID for this service
static final int JOB_ID = 10000;

// Convenience method for enqueueing work to this service.
public static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, RebootService.class, JOB_ID, work);
}

private QuickcardRepository reposit1;

@Override
protected void onHandleWork(@NonNull Intent intent) {

    reposit1 = new QuickcardRepository(getApplication());

    Bundle extras = intent.getExtras(); // Returns the Intent *that started this Service.*
    if (extras != null) {

        String classname = extras.getString("TAG");

        if (classname != null && classname.equals("bootCompleted")) {

            AlarmManager alarmManager1;
            Intent brIntent1, brIntent2, brIntent3;
            PendingIntent pendingIntent1, pendingIntent2, pendingIntent3;

            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
            Calendar cal3 = Calendar.getInstance();

            List<Quickcard> resetNotificationsList = reposit1.getNotifications();
            // Cycle through the Room database rows to get the Notifications data
            for (Quickcard quickcard: resetNotificationsList) {
                 // Quickcards without a Due date get a Due date in the database of -1.
                 // Therefore, only cycle through and get data for those quickcards that have
                //  a Due data and therefore have Notifications (reminders) where the actual
                //  "Due date" is != -1.
                 if(quickcard.getDuedatentime() != -1) {

                     // Set up the 24-Hour calendar object.
                     long notifTime1 = quickcard.getNotiftime();
                     int randInt1 = quickcard.getRandint();
                     cal1.setTime(new Date(notifTime1));

                     // Set up a system AlarmManager to fire a future alarm that sends a Notification
                     // even if the app is in the background or closed.  Have to add "context" here.
                     alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

                     // If the stated alarm trigger time is in the past, the alarm will be triggered immediately.
                     // So only set Alarms to fire Notifications for Duedates in the future
                     // (meaning > than the current System time).  Ignore those in the past.
                     if (cal1.getTimeInMillis() > System.currentTimeMillis()) {
                         // For the 24Hour Notifications.
                         // Set up a PendingIntent that will perform broadcast to the BroadcastReceiver.
                         brIntent1 = new Intent(this, AlarmReceiver.class);
                         brIntent1.setAction("24Hour");
                         // Need to use FLAG_ONE_SHOT on the PendingIntent, not FLAG_UPDATE_CURRENT.
                         // A random int is used to be able to set multiple alarms and then to be able to
                         // delete them later (if the user for ex., deletes the quickCards Duedate) using
                         // the same random int.
                         pendingIntent1 = PendingIntent.getBroadcast(this, randInt1, brIntent1,
                                 PendingIntent.FLAG_ONE_SHOT);

                         // Alarms have 3 properties below after "set(...)":
                         // 1) Alarm type:  RTC_WAKEUP type is chosen here to wake the device from sleep.
                         // 2) Trigger time: in this case, 24 hours before the Duedate/Duetime is reached.
                         // 3) Pending Intent:  A future Intent that is sent when the trigger time is reached.
                         int SDK_INT1 = Build.VERSION.SDK_INT;
                         if (SDK_INT1 >= Build.VERSION_CODES.M) {
                             // Wakes up the device in Doze Mode for API Level 23 and higher.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),
                                         pendingIntent1);
                             }
                         } else if (SDK_INT1 >= Build.VERSION_CODES.KITKAT) {
                             // Wakes up the device in Idle Mode for API Level 19 to 22.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.setExact(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                             }
                         } else {
                             // Old APIs Level 18 and below.
                             // The "... != -1" test only sets up pendingIntents for quickCards that have
                             // a Notification.  quickCards with no Duedate & Duetime are bypassed.
                             if (alarmManager1 != null && notifTime1 != -1) {
                                 alarmManager1.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pendingIntent1);
                             }
                         }
                     }

Body:
I believe that @Transaction wraps the code in a transaction. This is already done for all but @Query's (if the @Query isn't an update/delete query (if it is an update or delete query, it is wrapped within a transaction)).

I believe the issue as to whether or not a SELECT query should be wrapped within a transaction (@Transaction @Query......) is if @Relation is used. If it is then the List(s) of the related/associated items/objects are run as separate queries and thus running them all in a transaction will ensure consistent data. Without there is the potential that underlying data could be changed by other transactions and thus the resultant data could be inconsistent.

Saying that it would hardly have an impact to use @Transaction where it is not needed and may even have a positive impact if it were coded where it might inadvertently not bee coded.

Of course you can always return a Cursor anyway using Room. You may wish to have a look at Associating tables using Room database in Android Studio, which has some examples.

Based upon your code, primarily that you have an ItemContract with a subclass of ItemEntry then the Entity for an ItemEntry could be in ItemEntry.java, as per :-

@Entity
public class ItemEntry {

    @PrimaryKey(autoGenerate = true)
    private long id;
    @ColumnInfo(name = COLUMN_NOTIFTIME)
    private long notiftime;
    @ColumnInfo(name = COLUMN_NOTIFTIME2)
    private long notiftime2;
    @ColumnInfo(name = COLUMN_DUEDATENTIME)
    private long duedatentime;
    @ColumnInfo(name = COLUMN_RANDINT)
    public int randint;

    public ItemEntry(){

    }

    @Ignore
    public ItemEntry(long notiftime, long notiftime2, long duedatentime, int randint) {
        this.notiftime = notiftime;
        this.notiftime2 = notiftime2;
        this.duedatentime = duedatentime;
        this.randint = randint;
    }

    public long getId() {
        return id;
    }

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

    public long getNotiftime() {
        return notiftime;
    }

    public void setNotiftime(long notiftime) {
        this.notiftime = notiftime;
    }

    public long getNotiftime2() {
        return notiftime2;
    }

    public void setNotiftime2(long notiftime2) {
        this.notiftime2 = notiftime2;
    }

    public long getDuedatentime() {
        return duedatentime;
    }

    public void setDuedatentime(long duedatentime) {
        this.duedatentime = duedatentime;
    }

    public int getRandint() {
        return randint;
    }

    public void setRandint(int randint) {
        this.randint = randint;
    }
}

Along with an interface ItemEntryDao.java as :-

@Dao
interface ItemEntryDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertItemEntries(ItemEntry... itemEntries);
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertItemEntry(ItemEntry itemEntry);
    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateItemEnrties(ItemEntry... itemEntries);
    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateItemEntry(ItemEntry itemEntry);
    @Delete
    int deleteItemEntries(ItemEntry... itemEntries);
    @Delete
    int deleteItemEntry(ItemEntry itemEntry);
    @Query("SELECT * FROM ItemEntry")
    List<ItemEntry> resetNotifications();
}

The @Query is the equivalent to the Cursor BUT returns a List of ItemEntry objects.

The above could be used for example (that very basically replicates your code, but outputs the extracted data to the log) like :-

public void onHandleWork() {

    ItemEntry ie = new ItemEntry();
    ie.setNotiftime(100);
    ie.setNotiftime2(200);
    ie.setDuedatentime(500000);
    ie.setRandint(567);
    mDB.getItemEntryDao().insertItemEntry(ie);
    List<ItemEntry> mylist = mDB.getItemEntryDao().resetNotifications();
    for (ItemEntry itementry: mylist) {
        Log.d("ITEMENTRY",
                "\n\tnotiftime= " + String.valueOf(itementry.getNotiftime()) +
                        "\n\tnotiftime2= " + String.valueOf(itementry.getNotiftime2()) +
                        "\n\tduedatetime= " + String.valueOf(itementry.getDuedatentime()) +
                        "\n\trandint= " + String.valueOf(itementry.getRandint())

        );
    }
}

mDB is the built object (i.e. an instance of the @Database class)

This would result in (for the first run) :-

05-28 14:31:14.587 7211-7211/aso.so56326640 D/ITEMENTRY:  notiftime= 100
      notiftime2= 200
      duedatetime= 500000
      randint= 567


问:
XAML For Reflection Effect
I'm a XAML/WPF newbie, and I thought I'd write an alarm clock application to get into it.  I want to get past the basic textboxes, dropdowns etc, which are fairly simple once you get the hang of the layout model, but I'd like to get into the graphics side of things.

I'd like to display alarm clock digits on a black backdrop, but importantly the alarm clock numbers to have that reflection effect like they're stood up on a piece of glass (like how Apple marketing often is implemented).

How do I get started with this?  I'm looking at Charles Petzold's stuff for inspiration but struggling a little.

答:
Take a look at the XAML Reflections sample on the WindowsClient.net.

If you need more samples, the WindowsClient site also has a Control Gallery with list of useful snippets, tool sna dsytle and there's also the full list of WPF Samples you can download and study.

OwnerDisplayName: Neil Barnwell

ContentLicense: CC BY-SA 2.5

Title: XAML For Reflection Effect

LastEditorDisplayName: Neil Barnwell

OwnerDisplayName: Franci Penov


问:
what is the difference between Using Xml Parser and Xpath in XML
I Would like to know what are the difference between Using Xml Parser and Xpath in XML.Because, both are used to get the any pieces of information in the xml document.That why i asked this question...</p>

答:
An XML Parser turns an XML document into a data structure that you can access programatically (or a stream of SAX events).

XPath is a query language for taking an XML based data structure (or a stream of SAX events) and finding the bits of it you want.

The difference is rather like that of an HTML parser and a CSS selector engine or a Car and a Road Map. They are two completely different things that can be used together.


问:
the asynctask function is not recognizing the result value
I am accessing via AsyncTask the JSON, but in the onPostExecute, the String result is not getting the result value.

I would like it to read json and return the value "perfil", after that, send new to the main activity

credits Google Translate....

Acess MainActivity to MecanismoString

```<code>String login = textousuario.getText().toString();
            String senha = textosenha.getText().toString();
            String urllogin = "http...."
            String tipo = "";
            MecanismoString mecanismoString = new MecanismoString(this, this);
            mecanismoString.execute(tipo, urllogin, login, senha);
</code>```

Asynctask MecanismoString

```<code>public class MecanismoString extends AsyncTask <String, String, String> {

    private Interfacestring Interfacestring;
    private RequestQueue requestQueue;
    private StringRequest request;
    private Interfacestring execinterface;

    String usuario, senha, result;

    Context context;
    Toast toast;

    public MecanismoString (Context context, Interfacestring execinterface){
        this.context = context;
        this.Interfacestring = execinterface;
    }

    @Override
    public String doInBackground(String... params) {

        Log.i("Script", "1 ->" + params[0]);
        Log.i("Script", "2 ->" + params[1]);
        Log.i("Script", "3 ->" + params[2]);
        Log.i("Script", "4 ->" + params[3]);

        usuario = params[2];
        senha = params[3];

        requestQueue = Volley.newRequestQueue(context);

        request = new StringRequest(Request.Method.POST, params[1], new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    result = jsonObject.getString("perfil");

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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("login", usuario);
                hashMap.put("senha", senha);

                return hashMap;
            }
        };

        requestQueue.add(request);

        return (result);
    }

    @Override
    protected void onPostExecute(String result) {

        execinterface.carregarString(result);

    }

}
</code>```

code that returns the value of MecanismoString

```<code>public void carregarString(String result) {

        Toast.makeText(context.getApplicationContext(),
                result,
                Toast.LENGTH_SHORT) .show();

    }
</code>```

Error Log

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ic.eng.br.eunaobra, PID: 13735
    java.lang.NullPointerException: Attempt to invoke interface method 'void ic.eng.br.eunaobra.Interfacestring.carregarString(java.lang.String)' on a null object reference
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:94)
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:22)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.-wrap1(Unknown Source:0)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
I/qtaguid: Untagging socket 76 failed errno=-22
W/NetworkManagementSocketTagger: untagSocket(76) failed with errno -22
Application terminated.
</code>```

答:
please pass a correct context and execinterface object :

```<code>MecanismoString mecanismoString = new MecanismoString(MainActivity.this, correct execinterface object);
</code>```

please remove getApplicationContext() from carregarString()since you already have a context:

```<code> public void carregarString(String result) {
        Toast.makeText(context,result,Toast.LENGTH_SHORT) .show();
    }
</code>```

Body:
I am accessing via AsyncTask the JSON, but in the onPostExecute, the String result is not getting the result value.

I would like it to read json and return the value "perfil", after that, send new to the main activity

credits Google Translate....

Acess MainActivity to MecanismoString

String login = textousuario.getText().toString();
            String senha = textosenha.getText().toString();
            String urllogin = "http...."
            String tipo = "";
            MecanismoString mecanismoString = new MecanismoString(this, this);
            mecanismoString.execute(tipo, urllogin, login, senha);

Asynctask MecanismoString

public class MecanismoString extends AsyncTask <String, String, String> {

    private Interfacestring Interfacestring;
    private RequestQueue requestQueue;
    private StringRequest request;
    private Interfacestring execinterface;

    String usuario, senha, result;

    Context context;
    Toast toast;

    public MecanismoString (Context context, Interfacestring execinterface){
        this.context = context;
        this.Interfacestring = execinterface;
    }

    @Override
    public String doInBackground(String... params) {

        Log.i("Script", "1 ->" + params[0]);
        Log.i("Script", "2 ->" + params[1]);
        Log.i("Script", "3 ->" + params[2]);
        Log.i("Script", "4 ->" + params[3]);

        usuario = params[2];
        senha = params[3];

        requestQueue = Volley.newRequestQueue(context);

        request = new StringRequest(Request.Method.POST, params[1], new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    result = jsonObject.getString("perfil");

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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("login", usuario);
                hashMap.put("senha", senha);

                return hashMap;
            }
        };

        requestQueue.add(request);

        return (result);
    }

    @Override
    protected void onPostExecute(String result) {

        execinterface.carregarString(result);

    }

}

code that returns the value of MecanismoString

public void carregarString(String result) {

        Toast.makeText(context.getApplicationContext(),
                result,
                Toast.LENGTH_SHORT) .show();

    }

Error Log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ic.eng.br.eunaobra, PID: 13735
    java.lang.NullPointerException: Attempt to invoke interface method 'void ic.eng.br.eunaobra.Interfacestring.carregarString(java.lang.String)' on a null object reference
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:94)
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:22)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.-wrap1(Unknown Source:0)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
I/qtaguid: Untagging socket 76 failed errno=-22
W/NetworkManagementSocketTagger: untagSocket(76) failed with errno -22
Application terminated.

Body:
please pass a correct context and execinterface object :

MecanismoString mecanismoString = new MecanismoString(MainActivity.this, correct execinterface object);

please remove getApplicationContext() from carregarString()since you already have a context:

 public void carregarString(String result) {
        Toast.makeText(context,result,Toast.LENGTH_SHORT) .show();
    }


问:
sequelize.js addIndex not using indexName
I am trying to create an index using sequelize.js addIndex function, the index is created but not with the name specified in the indexName option.

I am using the code below

```<code>  queryInterface.addIndex('Item',
  ['name', 'description'], {
    indicesType: 'FULLTEXT',
    indexName: 'idx_item_fulltext'
  })
</code>```

After running migration, the index is created with the name 'item_name_description' and not 'idx_item_fulltext' which is the name I specified.

答:
For sequelize-cli and sequelize version 5+ there are no indicesType and indexName properties in addIndex options:

Please try:

queryInterface.addIndex('Item', ['name', 'description'], {
    type: 'FULLTEXT',
    name: 'idx_item_fulltext'
})
```

Body:
I am trying to create an index using sequelize.js addIndex function, the index is created but not with the name specified in the indexName option.

I am using the code below

  queryInterface.addIndex('Item',
  ['name', 'description'], {
    indicesType: 'FULLTEXT',
    indexName: 'idx_item_fulltext'
  })

After running migration, the index is created with the name 'item_name_description' and not 'idx_item_fulltext' which is the name I specified.


问:
Fixed div on the bottom of the scrollable div
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

```<code>.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}
</code>```

答:
You'll get a much nicer result (no occluded scrollbars) using flex:

.content {
  display: flex;
  justify-content: space-evenly;
  height: 400px;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 0 1 250px;
  margin: 0 5px;
}

.fixed-div {
  background-color: red;
  overflow-y: auto;
  flex: 1 1 auto;
}

.button {
  background-color: grey;
  flex: 0 0 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>I need grey area fixed on the bottom, not dependent on text amount</h1>
<div class="content">
  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio! Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est </p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio! Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>
</div></code>```

Body:
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}

Body:
You'll get a much nicer result (no occluded scrollbars) using flex:

.content {
  display: flex;
  justify-content: space-evenly;
  height: 400px;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 0 1 250px;
  margin: 0 5px;
}

.fixed-div {
  background-color: red;
  overflow-y: auto;
  flex: 1 1 auto;
}

.button {
  background-color: grey;
  flex: 0 0 30px;
}

<h1>I need grey area fixed on the bottom, not dependent on text amount</h1>
<div class="content">
  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio! Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est </p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio! Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>
</div>


问:
javafx @font-face css error "loadStyleSheetUnprivileged"
I'm trying to load a custom font in JavaFx css using this method

```<code>@font-face {
    font-family: 'Roboto';
    src: url('fonts/Roboto-Medium.ttf');
}
</code>```

I've done every thing proper with the correct path but I'm getting this error

```<code>Nov 28, 2015 4:49:18 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load @font-face font [file:/C:/Users/RootUser/Desktop/Java8%20projects/RemoteViewer/out/production/JavaFxApplication/application/fonts/Roboto-Medium.ttf]
</code>```

This is my project structure "screenshot"

Note I'm using intellij Idea as my IDE.Thanks in advance.

答:
For others who have come to this answer when searching:

The same error also occurs if you accidently leave out the quotes for the font name in a style, e.g.:

```<code>-fx-font-family: Monserrat;
</code>```

is wrong, it needs to be

```<code>-fx-font-family: 'Montserrat';
</code>```

Body:
I'm trying to load a custom font in JavaFx css using this method

@font-face {
    font-family: 'Roboto';
    src: url('fonts/Roboto-Medium.ttf');
}

I've done every thing proper with the correct path but I'm getting this error

Nov 28, 2015 4:49:18 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load @font-face font [file:/C:/Users/RootUser/Desktop/Java8%20projects/RemoteViewer/out/production/JavaFxApplication/application/fonts/Roboto-Medium.ttf]

This is my project structure "screenshot"

Note I'm using intellij Idea as my IDE.Thanks in advance.

Body:
For others who have come to this answer when searching:

The same error also occurs if you accidently leave out the quotes for the font name in a style, e.g.:

-fx-font-family: Monserrat;

is wrong, it needs to be

-fx-font-family: 'Montserrat';


问:
how to print local outputs in tensorflow federated?
I want to print local outputs of clients in the tensorflow federated tutorial https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification. What should I do?</p>

答:
If you only want a list of the values that go into the aggregations (e.g. into tff.federated_mean), one option would be to add additional outputs to aggregate_mnist_metrics_across_clients() to include metrics computed using tff.federated_collect().

This might look something like:

```<code>@tff.federated_computation
def aggregate_mnist_metrics_across_clients(metrics):
  return {
      'num_examples': tff.federated_sum(metrics.num_examples),
      'loss': tff.federated_mean(metrics.loss, metrics.num_examples),
      'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples),
      'per_client/num_examples': tff.federated_collect(metrics.num_examples),
      'per_client/loss': tff.federated_collect(metrics.loss),
      'per_client/accuracy': tff.federated_collect(metrics.accuracy),
  }
</code>```

Which will get printed a few cells later when the computation runs:

```<code>state, metrics = iterative_process.next(state, federated_train_data)
print('round  1, metrics={}'.format(metrics))

round  1, metrics=<...,per_client/accuracy=[0.14516129, 0.10642202, 0.13972603],per_client/loss=[3.2409852, 3.417463, 2.9516447],per_client/num_examples=[930.0, 1090.0, 730.0]>
</code>```

Note however: if you want to know the value of a specific client, there is intentionally no way to do that. By design, TFF's language intentionally avoids a notion of client identity; there is desire to avoid making clients addressable.

Body:
If you only want a list of the values that go into the aggregations (e.g. into tff.federated_mean), one option would be to add additional outputs to aggregate_mnist_metrics_across_clients() to include metrics computed using tff.federated_collect().

This might look something like:

@tff.federated_computation
def aggregate_mnist_metrics_across_clients(metrics):
  return {
      'num_examples': tff.federated_sum(metrics.num_examples),
      'loss': tff.federated_mean(metrics.loss, metrics.num_examples),
      'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples),
      'per_client/num_examples': tff.federated_collect(metrics.num_examples),
      'per_client/loss': tff.federated_collect(metrics.loss),
      'per_client/accuracy': tff.federated_collect(metrics.accuracy),
  }

Which will get printed a few cells later when the computation runs:

state, metrics = iterative_process.next(state, federated_train_data)
print('round  1, metrics={}'.format(metrics))

round  1, metrics=<...,per_client/accuracy=[0.14516129, 0.10642202, 0.13972603],per_client/loss=[3.2409852, 3.417463, 2.9516447],per_client/num_examples=[930.0, 1090.0, 730.0]>

Note however: if you want to know the value of a specific client, there is intentionally no way to do that. By design, TFF's language intentionally avoids a notion of client identity; there is desire to avoid making clients addressable.


问:
how to declare a variable in html for primary key and use it in an 'if' statement
I need to run a segment of a code when the primary key of the object is 1,4,7...etc.
Basically, I need to run a if statement for a certain block of code.</p>

```<code>            {% with i = ev.pk %}
                {% if i%3 == 1 %}
                <div class="container">
                    <div class="intro"></div>
                    <div class="row articles">
                {% endif %}
            {% endwith %}
                        <div class="col-sm-6 col-md-4 item" data-aos="fade-left"><a href="#"><img class="img-fluid" src="{{ ev.image.url }}"></a>
                            <h3 class="name">{{ ev.event_title }}</h3>
                            <p class="description">{{ event.event_details }}</p><em class="float-left">{{ ev.date }}</em><em class="float-right">{{ ev.venue }}</em></div>

                    </div>
                </div>
        {% endfor %}```

The above code doesn't work, I need:
1. Declare a variable (i)
2. assign it ev.pk
3. run an if statement {% if i%3 == 1%}

I am open for suggestions if there is a better way to code this.

</code>```

答:
Probably this will work (using divisibleby):

```<code>{% with ev.pk as i %}
       {% if i|divisibleby:3 %}
       <div class="container">
           <div class="intro"></div>
           <div class="row articles">
       {% endif %}
{% endwith %}
</code>```

Body:
I need to run a segment of a code when the primary key of the object is 1,4,7...etc.
Basically, I need to run a if statement for a certain block of code.

            {% with i = ev.pk %}
                {% if i%3 == 1 %}

                {% endif %}
            {% endwith %}

{{ ev.event_title }}

{{ event.event_details }}
{{ ev.date }}{{ ev.venue }}

        {% endfor %}```

The above code doesn't work, I need:
1. Declare a variable (i)
2. assign it ev.pk
3. run an if statement {% if i%3 == 1%}

I am open for suggestions if there is a better way to code this.

Body:
Probably this will work (using divisibleby):

{% with ev.pk as i %}
       {% if i|divisibleby:3 %}
       <div class="container">
           <div class="intro"></div>
           <div class="row articles">
       {% endif %}
{% endwith %}