问:
SwiftUI Binding to Computed Property?
I have two classes, one is the ContentView who is displaying the information from my data source. The data source is my CharacterRepository.

What I'm struggling with right now is making sure I always have a sorted list inside of my CharacterRepository.

Here's the code I have so far:

```<code>class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}
</code>```

and

```<code>struct InitiativeTrackerScreen: View {
    @EnvironmentObject var characterRepository: CharacterRepository

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(characterRepository.characters) { entry in
                        CharacterListElement(character: entry)
                    }
    ...
</code>```

Now my intended approach would be something like turning the characters variable into a computed property that runs the "sorted by" function every time the get gets executed. Unfortunately, Binding to a computed property is not yet possible in SwiftUI (not sure, will it ever be?).

Can someone please help me with this? I don't want to go back to the old approach of sorting and redrawing every time something changes. That's not why I am using SwiftUI with ist sweet bindings.

答:
I think it may be unnecessary overhead to be sorting the data in the property getter.

The simple (and performance-conscious) solution is to sort the data when it changes, and then to update a @Published non-computed property and bind to that:

```<code>class CharacterRepository: ObservableObject {
    func updateCharacters(_ characters: [Character]) {
       self.characters = characters.sorted() // or whatever sorting strategy you need...
    }

    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}
</code>```

If you prefer to be über-purist about this at the cost of performance, then you can manually create a Binding - something like this:

```<code>class CharacterRepository: ObservableObject {
   let sortedCharacters: Binding<[Character]>
   ...

   init() {
      self.sortedCharacters = .init(get: { return characters.sorted() }, set: { self.characters = $0 })
   }

   ...
}
</code>```

Title: SwiftUI Binding to Computed Property?

Body:
I have two classes, one is the ContentView who is displaying the information from my data source. The data source is my CharacterRepository.

What I'm struggling with right now is making sure I always have a sorted list inside of my CharacterRepository.

Here's the code I have so far:

class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}

and

struct InitiativeTrackerScreen: View {
    @EnvironmentObject var characterRepository: CharacterRepository

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(characterRepository.characters) { entry in
                        CharacterListElement(character: entry)
                    }
    ...

Now my intended approach would be something like turning the characters variable into a computed property that runs the "sorted by" function every time the get gets executed. Unfortunately, Binding to a computed property is not yet possible in SwiftUI (not sure, will it ever be?).

Can someone please help me with this? I don't want to go back to the old approach of sorting and redrawing every time something changes. That's not why I am using SwiftUI with ist sweet bindings.

Body:
I think it may be unnecessary overhead to be sorting the data in the property getter.

The simple (and performance-conscious) solution is to sort the data when it changes, and then to update a @Published non-computed property and bind to that:

class CharacterRepository: ObservableObject {
    func updateCharacters(_ characters: [Character]) {
       self.characters = characters.sorted() // or whatever sorting strategy you need...
    }

    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}

If you prefer to be über-purist about this at the cost of performance, then you can manually create a Binding - something like this:

class CharacterRepository: ObservableObject {
   let sortedCharacters: Binding<[Character]>
   ...

   init() {
      self.sortedCharacters = .init(get: { return characters.sorted() }, set: { self.characters = $0 })
   }

   ...
}


来源: stackexchange

问:
Django: dynamically defining model fields
I have a Model with 100 identical fields named field_1, field_2, and so on.
Is there a method to define these fields in a cycle (just to avoid writing and maintaining 100 rows)?

That is, now I have to name each field separately:

```<code>class MyModel(models.Model):
    field_1 = models.CharField(...)
    field_2 = models.CharField(...)
    field_3 = models.CharField(...)
    field_4 = models.CharField(...)
    field_5 = models.CharField(...)
    ...
</code>```

I would like something like:

```<code>class MyModel(models.Model):
    for i in range(1, 101):
        eval("field_%d = models.CharField(...)"%i)
</code>```

but, of course, I do not like eval.

Any hint?

NOTE
I need such a model because I'm doing a two-step importation from CSV/Excel: first, I put Excel rows into this table, then process the table and import data in the actual application (where I'm using ForeignKeys, as suggested)

答:
Honestly, I have not looked at this or used it, but check out this snippet. It is all about CSV import.

what does your data look like? If it's like most excel sheets, the fields are in columns and the data is in rows. In that case maybe you dont need 100 fields in your model, make a field for each columns

```<code>+-----+---------+----------+-------+
| id  |  name   |  address | phone |
+-----+---------+----------+-------+
| 1   | person1 |   blah   |  foo  |
| ... |   ...   |   ...    |  ...  |
| 100 |person100|   bar    |  baz  |
</code>```

 for example this data only need 3 fields (or 4 if the ID is explicitly defined), you wouldn't need to (and shouldn't) define 100 fields for each row. Now, if you have 100 columns of data, ok there may be a reason to want to automate, but have generic named fields seems... less than useful. So if the data is always the same format (in terms of columns), it may be worth putting the leg work into descriptive model fields.

ContentLicense: CC BY-SA 3.0

Body:
I have a Model with 100 identical fields named field_1, field_2, and so on.
Is there a method to define these fields in a cycle (just to avoid writing and maintaining 100 rows)?

That is, now I have to name each field separately:

class MyModel(models.Model):
    field_1 = models.CharField(...)
    field_2 = models.CharField(...)
    field_3 = models.CharField(...)
    field_4 = models.CharField(...)
    field_5 = models.CharField(...)
    ...

I would like something like:

class MyModel(models.Model):
    for i in range(1, 101):
        eval("field_%d = models.CharField(...)"%i)

but, of course, I do not like eval.

Any hint?

NOTE
I need such a model because I'm doing a two-step importation from CSV/Excel: first, I put Excel rows into this table, then process the table and import data in the actual application (where I'm using ForeignKeys, as suggested)

Body:
Honestly, I have not looked at this or used it, but check out this snippet. It is all about CSV import.

what does your data look like? If it's like most excel sheets, the fields are in columns and the data is in rows. In that case maybe you dont need 100 fields in your model, make a field for each columns

+-----+---------+----------+-------+
| id  |  name   |  address | phone |
+-----+---------+----------+-------+
| 1   | person1 |   blah   |  foo  |
| ... |   ...   |   ...    |  ...  |
| 100 |person100|   bar    |  baz  |

 for example this data only need 3 fields (or 4 if the ID is explicitly defined), you wouldn't need to (and shouldn't) define 100 fields for each row. Now, if you have 100 columns of data, ok there may be a reason to want to automate, but have generic named fields seems... less than useful. So if the data is always the same format (in terms of columns), it may be worth putting the leg work into descriptive model fields.


问:
STM32 GPIO Interrupt using IDR register
```<code>    /* Configure EXTI interupt PB4 */
    SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR2_EXTI4_PB;
    EXTI->IMR |= EXTI_IMR_IM4;                                                                          //Interrupt Mask on line 2  */
    EXTI->RTSR |= EXTI_RTSR_RT4;
    EXTI->FTSR |= EXTI_FTSR_FT4;
    NVIC_EnableIRQ(EXTI4_15_IRQn);                                                                          //Załączenie przerwania na pinie zasilania
    NVIC_SetPriority(EXTI4_15_IRQn,1);
</code>```

This is how I configure the EXTI

```<code>    GPIOB->MODER =      (0U << GPIO_MODER_MODE4_Pos);
    GPIOB->PUPDR =      (1U << GPIO_PUPDR_PUPD4_Pos);
</code>```

This is how I manage the pins

```<code>    while(1)
    {
        if(state == 0){
            ServoToggle(0, 100, 255);
            delay(1000);
        } else {
            ServoToggle(0, 115, 255);
            delay(1000);
            ServoToggle(0, 60, 255);
            delay(1000);
        }
        delay(1);
    }
</code>```

This is what my program does after stand-up

```<code>void EXTI4_15_IRQHandler(void)
{
    if(!(GPIOB->IDR & GPIO_IDR_ID4)){
        state = 0;
    } else {
        state = 1;
    }
    EXTI->PR = EXTI_PR_PR4;
}
</code>```

This is how I'm trying to handle the interrupt.

And this thing does not work. Idk why but for PA0 it works like a charm but changing to PB4 stops poping up interrupt event.

I've got a button connected to the pin that changed the IDR register on press.

What am I missing?

I'm using STM32L052 family

答:
An EXTI IRQ from 4-15 is quite uncommon. Maybe you could add the exakt controller you are using?

On an STM32F415 for example it would be EXTI4_IRQHandler for the IRQ handler.

ContentLicense: CC BY-SA 4.0

Title: STM32 GPIO Interrupt using IDR register

Body:
    /* Configure EXTI interupt PB4 */
    SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR2_EXTI4_PB;
    EXTI->IMR |= EXTI_IMR_IM4;                                                                          //Interrupt Mask on line 2  */
    EXTI->RTSR |= EXTI_RTSR_RT4;
    EXTI->FTSR |= EXTI_FTSR_FT4;
    NVIC_EnableIRQ(EXTI4_15_IRQn);                                                                          //Załączenie przerwania na pinie zasilania
    NVIC_SetPriority(EXTI4_15_IRQn,1);

This is how I configure the EXTI

    GPIOB->MODER =      (0U << GPIO_MODER_MODE4_Pos);
    GPIOB->PUPDR =      (1U << GPIO_PUPDR_PUPD4_Pos);

This is how I manage the pins

    while(1)
    {
        if(state == 0){
            ServoToggle(0, 100, 255);
            delay(1000);
        } else {
            ServoToggle(0, 115, 255);
            delay(1000);
            ServoToggle(0, 60, 255);
            delay(1000);
        }
        delay(1);
    }

This is what my program does after stand-up

void EXTI4_15_IRQHandler(void)
{
    if(!(GPIOB->IDR & GPIO_IDR_ID4)){
        state = 0;
    } else {
        state = 1;
    }
    EXTI->PR = EXTI_PR_PR4;
}

This is how I'm trying to handle the interrupt.

And this thing does not work. Idk why but for PA0 it works like a charm but changing to PB4 stops poping up interrupt event.

I've got a button connected to the pin that changed the IDR register on press.

What am I missing?

I'm using STM32L052 family


问:
Time difference in days based on specific condition in pandas
I have a data frame as shown below

```<code>ID   CONSTRUCTION_DATE   START_DATE   END_DATE      CANCELLED_DATE
1    2016-02-06          2016-02-26   2017-02-26    NaT
1    2016-02-06          2017-03-27   2018-02-26    2017-05-22
1    2016-02-06          2017-08-27   2019-02-26    2017-10-21
1    2016-02-06          2018-07-27   2021-02-26    NaT
2    2016-05-06          2017-03-27   2018-02-26    NaT
2    2016-05-06          2018-08-27   2019-02-26    NaT
</code>```

Above data has to be order based on ID and START_DATE.

From the above data frame I would like to prepare below dataframe

```<code>ID   D_from_C_to_first_S_D    T_D_V_aft_c  T_D_V_w_cancel   N_of_cancel    Lst_END_DATE_to_today
1    20                       376          29               2              After_today
1    325                      NaN          182              0              358
</code>```

Where

CANCELLED_DATE = NaT means contract not cancelled

D_from_C_to_first_S_D = Days from CONSTRUCTION_DATE to first START_DATE.

T_D_V_aft_c = Total days vacant after cancellation ( for ID = 1, two cancelled date, 97+279 = 376)

T_D_V_w_cancel = Total days vacant without cancellation (just find the sum of difference of previous END_DATE with next START_DATE.

Lst_END_DATE_to_today = Days from last end date to today.

Body:
I have a data frame as shown below

ID   CONSTRUCTION_DATE   START_DATE   END_DATE      CANCELLED_DATE
1    2016-02-06          2016-02-26   2017-02-26    NaT
1    2016-02-06          2017-03-27   2018-02-26    2017-05-22
1    2016-02-06          2017-08-27   2019-02-26    2017-10-21
1    2016-02-06          2018-07-27   2021-02-26    NaT
2    2016-05-06          2017-03-27   2018-02-26    NaT
2    2016-05-06          2018-08-27   2019-02-26    NaT

Above data has to be order based on ID and START_DATE.

From the above data frame I would like to prepare below dataframe

ID   D_from_C_to_first_S_D    T_D_V_aft_c  T_D_V_w_cancel   N_of_cancel    Lst_END_DATE_to_today
1    20                       376          29               2              After_today
1    325                      NaN          182              0              358

Where

CANCELLED_DATE = NaT means contract not cancelled

D_from_C_to_first_S_D = Days from CONSTRUCTION_DATE to first START_DATE.

T_D_V_aft_c = Total days vacant after cancellation ( for ID = 1, two cancelled date, 97+279 = 376)

T_D_V_w_cancel = Total days vacant without cancellation (just find the sum of difference of previous END_DATE with next START_DATE.

Lst_END_DATE_to_today = Days from last end date to today.

Body:
First was created new columns for possible easy verify solution:

today = pd.to_datetime('now').floor('d')
m = df['CANCELLED_DATE'].isna()
df['D_from_C_to_first_S_D'] = df['START_DATE'].sub(df['CONSTRUCTION_DATE']).dt.days
df['T_D_V_aft_c'] = df.groupby('ID')['START_DATE'].shift(-1).sub(df['CANCELLED_DATE']).dt.days
df['T_D_V_w_cancel'] = df.groupby('ID')['START_DATE'].shift(-1).sub(df.loc[m, 'END_DATE']).dt.days
df['N_of_cancel'] = np.where(m, 0, 1)
s = df['END_DATE'].rsub(today).dt.days
df['Lst_END_DATE_to_today'] = s.mask(s.lt(0), 'After_today')

print (df)
   ID CONSTRUCTION_DATE  START_DATE    END_DATE CANCELLED_DATE
0   1        2016-02-06  2016-02-26  2017-02-26            NaT
1   1        2016-02-06  2017-03-27  2018-02-26     2017-05-22
2   1        2016-02-06  2017-08-27  2019-02-26     2017-10-21
3   1        2016-02-06  2018-07-27  2021-02-26            NaT
4   2        2016-05-06  2017-03-27  2018-02-26            NaT
5   2        2016-05-06  2018-08-27  2019-02-26            NaT
   ID CONSTRUCTION_DATE START_DATE   END_DATE CANCELLED_DATE  \
0   1        2016-02-06 2016-02-26 2017-02-26            NaT
1   1        2016-02-06 2017-03-27 2018-02-26     2017-05-22
2   1        2016-02-06 2017-08-27 2019-02-26     2017-10-21
3   1        2016-02-06 2018-07-27 2021-02-26            NaT
4   2        2016-05-06 2017-03-27 2018-02-26            NaT
5   2        2016-05-06 2018-08-27 2019-02-26            NaT

   D_from_C_to_first_S_D  T_D_V_aft_c  T_D_V_w_cancel  N_of_cancel  \
0                     20          NaN            29.0            0
1                    415         97.0             NaN            1
2                    568        279.0             NaN            1
3                    902          NaN             NaN            0
4                    325          NaN           182.0            0
5                    843          NaN             NaN            0

  Lst_END_DATE_to_today
0                  1089
1                   724
2                   359
3           After_today
4                   724
5                   359

And then aggregate by GroupBy.agg by first, last and sum in custom function for NaNs instead 0:

f = lambda x: x.sum(min_count=1)
df1 = df.groupby('ID').agg(D_from_C_to_first_S_D=('D_from_C_to_first_S_D','first'),
                           T_D_V_aft_c=('T_D_V_aft_c',f),
                           T_D_V_w_cancel=('T_D_V_w_cancel',f),
                           N_of_cancel=('N_of_cancel',f),
                           Lst_END_DATE_to_today=('Lst_END_DATE_to_today','last'),
                           ).reset_index()

print (df1)
   ID  D_from_C_to_first_S_D  T_D_V_aft_c  T_D_V_w_cancel  N_of_cancel  \
0   1                     20        376.0            29.0            2
1   2                    325          NaN           182.0            0

  Lst_END_DATE_to_today
0           After_today
1                   359


问:
RegEx Lookbehind / Lookahead in Google Data Studio
I need to use RegEx in Google Data Studio.

As part of a project I need to make a dashboard in Google Data Studio, but I'm having trouble extracting different elements from the column:

```<code>P. (number) - Title/\\/Author/\\/Topic
</code>```

Examples:

P. 9 - Harry Pottér sold: 2.2m in 2019/\/John Johnson/\/Movies

P. 120 - The Readers Say, that/\/NA/\/Debat

I need to extract Title, Author and Topic into separate columns.

答:
Here's one way it could be achieved using 3 REGEXP_EXTRACT fields:

Title

```<code>REGEXP_EXTRACT(Field, "^P\\. \\d+ - (.*)/./.*/./.*$")
</code>```

Author

```<code>REGEXP_EXTRACT(Field, "/./(.*)/./\\w+$")
</code>```

Topic

```<code>REGEXP_EXTRACT(Field, "(\\w+)$")
</code>```

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate.

Body:
I need to use RegEx in Google Data Studio.

As part of a project I need to make a dashboard in Google Data Studio, but I'm having trouble extracting different elements from the column:

P. (number) - Title/\\/Author/\\/Topic

Examples:

P. 9 - Harry Pottér sold: 2.2m in 2019/\/John Johnson/\/Movies

P. 120 - The Readers Say, that/\/NA/\/Debat

I need to extract Title, Author and Topic into separate columns.

Body:
Here's one way it could be achieved using 3 REGEXP_EXTRACT fields:

Title

REGEXP_EXTRACT(Field, "^P\\. \\d+ - (.*)/./.*/./.*$")

Author

REGEXP_EXTRACT(Field, "/./(.*)/./\\w+$")

Topic

REGEXP_EXTRACT(Field, "(\\w+)$")

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate.


问:
Kendo scrollview(angular) next/prev methods use
I am using kendo scrollview (angular) in my angular project, but I am not able to call next prev method provided by kendo.

Is there anyone who used it, and provide information for the same.

ANy example appreciated.

答:
Please follow these steps...

Install Kendo scrollview using ng add @progress/kendo-angular-scrollview.

Import BrowserAnimationsModule, ScrollViewModule in the module which you are using.

Install kendo UI theme using npm install --save @progress/kendo-theme-default.

Add "node_modules/@progress/kendo-theme-default/dist/all.css" in angular.json styles
array

{
  "styles": [
    "node_modules/@progress/kendo-theme-default/dist/all.css"
  ]
}

Then kendo UI will work as expected


问:
Place the three columns with the same height
Using the bootstrap I created three columns. Within each column I have several rows.

My problem is that the columns are not the same height, the left column is bigger than the rest, they were supposed to all be the same height.

In the cards I did not define any height, that is, if any of the columns increased the height, the rest would follow this growth automatically in order to have all the same height.

Is there a way to place all the columns at the same height without using measurements in pixels (px)?

Thanks

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

```

答:
If you are using Bootstrap4 then you can easily achieve by BS4 predefined classes like h-100 and also your html structure is not correct way so follow as per bootstrap instructions.

Predefined classes for width & height follow: https://getbootstrap.com/docs/4.3/utilities/sizing/#relative-to-the-parent

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

          Lorem ipsum dolor sit amet, consectetur adipisicing elit

          Ut enim ad minim veniam, quis nostrud exercitation ullamco.

          Laboris nisi ut aliquip ex ea

          Voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat

```

Body:
If you are using Bootstrap4 then you can easily achieve by BS4 predefined classes like h-100 and also your html structure is not correct way so follow as per bootstrap instructions.

Predefined classes for width & height follow: https://getbootstrap.com/docs/4.3/utilities/sizing/#relative-to-the-parent

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container my-2">
  <div class="row">
    <div class="col-3">
      <div class="card cardm h-100">
        <div class="card-body">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit
        </div>
      </div>
    </div>
    <div class="col-3">
      <div class="card cardm h-100">
        <div class="card-body">
          Ut enim ad minim veniam, quis nostrud exercitation ullamco.
        </div>
      </div>
    </div>
   <div class="col-3">
      <div class="card cardm h-100">
        <div class="card-body">
          Laboris nisi ut aliquip ex ea
        </div>
      </div>
    </div>
   <div class="col-3">
      <div class="card cardm h-100">
        <div class="card-body">
          Voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
        </div>
      </div>
    </div>
  </div>
</div>


问:
How to merge interfaces from NPM modules correctly in TypeScript?
The @types/yandex-maps package contains namespace ymaps.

It has interface IEventManager.

I want to add a new method to this interface IEventManager.

I'm trying to do this in my file .d.ts:

```<code>import {IEvent} from '@types/yandex-maps';

declare module '@types/yandex-maps' {
    declare namespace ymaps {
        interface IEventManager {
            once(types: string[][] | string[] | string, callback: (event: object | IEvent) => void, context?: object, priority?: number): this;
        }
    }
}
</code>```

But it doesn't work! How do I add the method I need correctly?

答:
Put this d.ts file in types folder & add it to include.

```<code>// tsconfig.json
{
  ...
  "include": ["types/*.d.ts"]
}
</code>```

Body:
The @types/yandex-maps package contains namespace ymaps.

It has interface IEventManager.

I want to add a new method to this interface IEventManager.

I'm trying to do this in my file .d.ts:

import {IEvent} from '@types/yandex-maps';

declare module '@types/yandex-maps' {
    declare namespace ymaps {
        interface IEventManager {
            once(types: string[][] | string[] | string, callback: (event: object | IEvent) => void, context?: object, priority?: number): this;
        }
    }
}

But it doesn't work! How do I add the method I need correctly?

Body:
Put this d.ts file in types folder & add it to include.

// tsconfig.json
{
  ...
  "include": ["types/*.d.ts"]
}


问:
Error: redirect_uri_mismatch Google API, how to fix?
I have created this HTTP trigger azure function, which contains the code(below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

I also created the Client_Id and Client_secret using Google Console API and stored that data in the client_secrets.json file. (E.g https://github.com/youtube/api-samples/blob/master/dotnet/client_secrets.json)

I try to run the function locally, pasting this: http://localhost:7071/api/Function1 in a browser, I am getting the following error:

400, That's an error. Error: redirect_rui_mismatch The redirect URI in
  the request, http://localhost58085/authorize/, does not match the ones
  authorized for the OAuth client. To update the authorized redirect
  URIs, visit. http://consolse.Developers.google.com/apis/credentials.

I am not sure what I am doing wrong, and I don't know what the URL I should put in for "Authorized redirect URIs"

Code:

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\Test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}
</code>```

答:
The way Oauth2 works is that a user is presented with a consent screen

Do you want to grant Peters awesome application access to your YouTube account.

If the user accepts this then an Authorization code is returned to your application at the point of the redirect uri

http://localhost:7071/api/Function1

This is the file in your application that is able to handle the authorization handshake. This redirect uri must be registered in the Google developer console it helps to ensure that no one trys to hijack your authorization call and send it over to their site and then they will have access to the users data.

how to add redirect uri

Under credentials find the one you are looking for

Click the pencil icon

Note

Please remember that GoogleWebAuthorizationBroker.AuthorizeAsync is used for installed applications its going to open the browser consent window on the server if you try to put this up as a function.  you need to do something more like this for a web application Asp.net mvc I cant claim to know a lot about azure functions but if there anything like cloud functions i dont think they have the ability to display a web browser page to your user.  I dont think you can authenticate a user with Oauth2 from an azure function.

Body:
I have created this HTTP trigger azure function, which contains the code(below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

I also created the Client_Id and Client_secret using Google Console API and stored that data in the client_secrets.json file. (E.g https://github.com/youtube/api-samples/blob/master/dotnet/client_secrets.json)

I try to run the function locally, pasting this: http://localhost:7071/api/Function1 in a browser, I am getting the following error:

400, That's an error. Error: redirect_rui_mismatch The redirect URI in
  the request, http://localhost58085/authorize/, does not match the ones
  authorized for the OAuth client. To update the authorized redirect
  URIs, visit. http://consolse.Developers.google.com/apis/credentials.

I am not sure what I am doing wrong, and I don't know what the URL I should put in for "Authorized redirect URIs"

Code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\Test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}


问:
Best way to check if server is reachable in .NET?
I have created a timeclock application in C# that connects to a web service on our server in order to clock employees in/out. The application resides in the system tray and clocks users out if they shut down/suspend their machines or if they are idle for more than three hours to which it clocks them out at the time of last activity.

My issue arises that when a user brings his machine back up from a sleep state (which fires the SystemEvents.PowerModeChanged event), the application attempts to clock the employee back in but the network connection isn't fully initialized at that time and the web-service call times out.

An obvious solution, albeit it a hack, would be to put a delay on the clock in but this wouldn't necessarily fix the problem across the board. What I am looking to do is a sort of "relentless" clock in where it will wait until it can see the server until it actually attempts to clock in.

What is the best method to determine if a connection to a web service can be made?

答: Ping can be disabled although the web service port is open. I wouldn't use this method...</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: me me


问:
Inheritance base class reference C#
```<code>class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();
</code>```

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"

答:
```<code>Base ObjectOrReference = new Drifted();
</code>```

with that, you have created a Drifted instance but is referenced by Base reference variable ObjectOrReference. Right now it's capabilities are limited to that of what's available in Base. If you want to, say access int b in Drifted, you'll have to cast it to Drifted

Title: Inheritance base class reference C#

Body:
class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"

Body:
Base ObjectOrReference = new Drifted();

with that, you have created a Drifted instance but is referenced by Base reference variable ObjectOrReference. Right now it's capabilities are limited to that of what's available in Base. If you want to, say access int b in Drifted, you'll have to cast it to Drifted


问:
Check tab from activity to fragment in android
enter image description here

look like this  i am here using adapter class for non answerd tab , actully i'm need when we select radio button and click to next then tab will be selected as answerd
here is non selected code
1.From adapter class

```<code> public View getSelectedTabView(int position) {
    View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
    ImageView imageView = view.findViewById(R.id.custom_tab_circle);
    TextView textView = view.findViewById(R.id.custom_tab_textView);
    //textView.setText(mfragmentTitlelist.get(position+1));
    //textView.setText(position);
    //textView.setText((CharSequence) fragmentList.get(position));
    StringBuilder builder = new StringBuilder();

    builder.append(position+1).toString();
    textView.setText(builder.toString());
    imageView.setImageResource(R.drawable.selected_circle);
    // here is image will be transparent
    imageView.setAlpha(0.5f);

    //.setTextColor(ContextCompat.getColor(context, R.color.yellow));
    //ImageView tabImageView = view.findViewById(R.id.tabImageView);
    //imageView.setImageResource(mFragmentIconList.get(position));
    //imageView.setColorFilter(ContextCompat.getColor(context, R.color.background_color), PorterDuff.Mode.SRC_ATOP);
    return view;
}
</code>```

**2. now we call this code in Activity.java **

```<code>  highLightCurrentTab(position);

  private void highLightCurrentTab(int position) {
    TabLayout.Tab tab = tabLayout.getTabAt(position);
    assert tab != null;
    tab.setCustomView(null);
    tab.setCustomView(adapter.getSelectedTabView(position));
    /*tab.setCustomView(adapter.getPageTitle(position).charAt(position));*/

}
</code>```

so help me out what to do for  when select a answer my tab image will be selected as answered ...
thanks ..

答:
You can use this for listener to your tablayout;

```<code>  tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});
</code>```

Also you can check is selected any radio button with this code;

```<code>if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}

else
{
  // one of the radio buttons is checked
}
</code>```

Body:
enter image description here

look like this  i am here using adapter class for non answerd tab , actully i'm need when we select radio button and click to next then tab will be selected as answerd
here is non selected code
1.From adapter class

 public View getSelectedTabView(int position) {
    View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
    ImageView imageView = view.findViewById(R.id.custom_tab_circle);
    TextView textView = view.findViewById(R.id.custom_tab_textView);
    //textView.setText(mfragmentTitlelist.get(position+1));
    //textView.setText(position);
    //textView.setText((CharSequence) fragmentList.get(position));
    StringBuilder builder = new StringBuilder();

    builder.append(position+1).toString();
    textView.setText(builder.toString());
    imageView.setImageResource(R.drawable.selected_circle);
    // here is image will be transparent
    imageView.setAlpha(0.5f);

    //.setTextColor(ContextCompat.getColor(context, R.color.yellow));
    //ImageView tabImageView = view.findViewById(R.id.tabImageView);
    //imageView.setImageResource(mFragmentIconList.get(position));
    //imageView.setColorFilter(ContextCompat.getColor(context, R.color.background_color), PorterDuff.Mode.SRC_ATOP);
    return view;
}

**2. now we call this code in Activity.java **

  highLightCurrentTab(position);

  private void highLightCurrentTab(int position) {
    TabLayout.Tab tab = tabLayout.getTabAt(position);
    assert tab != null;
    tab.setCustomView(null);
    tab.setCustomView(adapter.getSelectedTabView(position));
    /*tab.setCustomView(adapter.getPageTitle(position).charAt(position));*/

}

so help me out what to do for  when select a answer my tab image will be selected as answered ...
thanks ..

Body:
You can use this for listener to your tablayout;

  tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});

Also you can check is selected any radio button with this code;

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}

else
{
  // one of the radio buttons is checked
}


问:
React-Native Accumulate results from a loop to a single string
I want to extract the data in between the  tag and, based on the content, return <View><Text>This is a Text</Text></View> or <View><Text>This is a Picture</Text></View>

The problem is that I don't know how to accumulate the result from the matches to Article, and then return {Article} as the final result.

In the case below, I should end up with that render:

```<code><View><Text>This is a Text</Text></View>
<View><Text>This is a Picture</Text></View>
<View><Text>This is a Text</Text></View>
</code>```

instead, I get the final result. I tried Article = Article + <View><Text>This is a Text</Text></View> and Article += <View><Text>This is a Text</Text></View> but they both failed.

```<code>export default class App extends React.Component {
  render() {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str =   '<RNVW><p>Markets are mixed in Asia, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China\'s shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney\'s S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs," Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China\'s report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>';

    let match;
    let Article;
    while ((match = pattern.exec(str)) !== null) {
      if (match[1].startsWith("<p>") !== false) {
       Article = (
        <View><Text>This is a Text</Text></View>
        );
      } else {
      Article = (
           <View><Text>This is a Picture</Text></View>
        );
      }
    }

    return (
      <View style={styles.container}>
     {Article}
      </View>
    );
  }
}
</code>```

答:
Hey Vincent

you were doing one mistake with Article, you are trying to allocate a new item to Article every time instead, you should go with array and push new items every time in the array.

Made some changes in your code:

```<code>class App extends Component {

articleView = () => {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str ="<RNVW><p>Markets are mixed in Asia, with Japan's benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan's benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China's shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney's S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src=\"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png\"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>\"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs,\" Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China's report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>";

let match;
let Article = [];
while ((match = pattern.exec(str)) !== null) {
  if (match[1].startsWith("<p>") !== false) {
    Article.push(
      <View>
        <Text>This is a Text</Text>
      </View>
    );
  } else {
    Article.push(
      <View>
        <Text>This is a Picture</Text>
      </View>
    );
  }
}
return Article;

};
render() {
  return (
   <View>
    {this.articleView()}
  </View>
  );
 }
}
</code>```

it will give you desired output :)

I hope that's what you were looking for!

Thanks!

Body:
I want to extract the data in between the  tag and, based on the content, return <View><Text>This is a Text</Text></View> or <View><Text>This is a Picture</Text></View>

The problem is that I don't know how to accumulate the result from the matches to Article, and then return {Article} as the final result.

In the case below, I should end up with that render:

<View><Text>This is a Text</Text></View>
<View><Text>This is a Picture</Text></View>
<View><Text>This is a Text</Text></View>

instead, I get the final result. I tried Article = Article + <View><Text>This is a Text</Text></View> and Article += <View><Text>This is a Text</Text></View> but they both failed.

export default class App extends React.Component {
  render() {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str =   '<RNVW>
Markets are mixed in Asia, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted in the last quarter

BANGKOK -- Markets were mixed in Asia on Monday, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China\'s shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts.

The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney\'s S&P ASX/200 edged 1% lower to 7,125.10.
</RNVW><RNVW></RNVW><RNVW>
Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks.

The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel.

"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs," Evans-Pritchard said in a commentary.

Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China\'s report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.
</RNVW>';

    let match;
    let Article;
    while ((match = pattern.exec(str)) !== null) {
      if (match[1].startsWith("
") !== false) {
       Article = (
        <View><Text>This is a Text</Text></View>
        );
      } else {
      Article = (
           <View><Text>This is a Picture</Text></View>
        );
      }
    }

    return (
      <View style={styles.container}>
     {Article}
      </View>
    );
  }
}

Body:
Hey Vincent

you were doing one mistake with Article, you are trying to allocate a new item to Article every time instead, you should go with array and push new items every time in the array.

Made some changes in your code:

class App extends Component {

articleView = () => {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str ="<RNVW><p>Markets are mixed in Asia, with Japan's benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan's benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China's shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney's S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src=\"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png\"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>\"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs,\" Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China's report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>";

let match;
let Article = [];
while ((match = pattern.exec(str)) !== null) {
  if (match[1].startsWith("<p>") !== false) {
    Article.push(
      <View>
        <Text>This is a Text</Text>
      </View>
    );
  } else {
    Article.push(
      <View>
        <Text>This is a Picture</Text>
      </View>
    );
  }
}
return Article;

};
render() {
  return (
   <View>
    {this.articleView()}
  </View>
  );
 }
}

it will give you desired output :)

I hope that's what you were looking for!

Thanks!


问:
Continued: Segmentation fault for program that indexes words from a file
I am getting a segmentation fault for a program that is supposed to index words read from a file. I changed the first part of my code where I tried to create a dynamic array, realizing that arrays cannot be dynamic. Previously, I used to get a segmentation fault, but now the program compiles but doesn't even run properly. I would highly appreciate some feedback. The link to my previous post is
Segmentation Fault for a Program that Indexes Words from a File  </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    //Check if the usage is correct
    if (argc != 2)
    {
        printf("Usage: ./test15 text\n");
        return 1;
    }

    //Main program
    char *file = argv[1];
    FILE *ptr = fopen(file, "r");
    char ch;
    int i = 0;
    int k = 0;
    int j = 0;
    char *text = malloc(sizeof(char));

    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            k++;
        }
        i++;
    }

    char *word[k];
    i = 0;
    int l = 0;

    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            for (int m = j; m < i; m++)
            {
                int d = i - j;
                strncat(word[l], &text[m], d);
            }
            j = i + 1;
            l++;
        }
        i++;
        printf("%s\n", word[l]);
    }
    return 0;
}
</code>```

答:
With

```<code>char *text = malloc(sizeof(char));
</code>```

you allocate space for a single char. text is in essence a single-element array.

Then in the following loop, if there's more than a single byte in the file, you will go out of bounds of this single-element array. This leads to undefined behavior.

Furthermore

```<code>char *word[k];
</code>```

here you define an array of uninitialized pointers. Attempting to dereference these pointers also leads to undefined behavior.

And when you use a strcat-like function the destination pointer must be a pointer to a valid null-terminated string.

On another note, the fgetc function return an int. This is actually very important for the comparison against EOF.

Body:
I am getting a segmentation fault for a program that is supposed to index words read from a file. I changed the first part of my code where I tried to create a dynamic array, realizing that arrays cannot be dynamic. Previously, I used to get a segmentation fault, but now the program compiles but doesn't even run properly. I would highly appreciate some feedback. The link to my previous post is
Segmentation Fault for a Program that Indexes Words from a File

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    //Check if the usage is correct
    if (argc != 2)
    {
        printf("Usage: ./test15 text\n");
        return 1;
    }

    //Main program
    char *file = argv[1];
    FILE *ptr = fopen(file, "r");
    char ch;
    int i = 0;
    int k = 0;
    int j = 0;
    char *text = malloc(sizeof(char));

    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            k++;
        }
        i++;
    }

    char *word[k];
    i = 0;
    int l = 0;

    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            for (int m = j; m < i; m++)
            {
                int d = i - j;
                strncat(word[l], &text[m], d);
            }
            j = i + 1;
            l++;
        }
        i++;
        printf("%s\n", word[l]);
    }
    return 0;
}

Body:
With

char *text = malloc(sizeof(char));

you allocate space for a single char. text is in essence a single-element array.

Then in the following loop, if there's more than a single byte in the file, you will go out of bounds of this single-element array. This leads to undefined behavior.

Furthermore

char *word[k];

here you define an array of uninitialized pointers. Attempting to dereference these pointers also leads to undefined behavior.

And when you use a strcat-like function the destination pointer must be a pointer to a valid null-terminated string.

On another note, the fgetc function return an int. This is actually very important for the comparison against EOF.


问:
Django - how to select unique values in col
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

```<code>class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...
</code>```

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

答:
For this you can use the Django Max funciton</p>

```<code>from django.db.models import Max
_user = User.objects.get(...)
_game = Game.objects.get(...)
score = Score.objects.filter(user=_user,game=_game)
max_score = score.aggregate(Max('val'))
</code>```

Body:
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

Body:
For this you can use the Django Max funciton

from django.db.models import Max
_user = User.objects.get(...)
_game = Game.objects.get(...)
score = Score.objects.filter(user=_user,game=_game)
max_score = score.aggregate(Max('val'))


问:
Maven cannot downlad dependencies/plugins from https://repo.maven.apache.org/maven2
I've got following error when I'm trying to build my project:

Failed to collect dependencies at org.msgpack:jackson-dataformat-msgpack:jar:0.8.17 -> com.fasterxml.jackson.core:jackson-databind:jar:2.9.9: Failed to read artifact descriptor for com.fasterxml.jackson.core:jackson-databind:jar:2.9.9: Could not transfer artifact com.fasterxml.jackson.core:jackson-databind:pom:2.9.9 from/to maven (https://repo1.maven.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I read that the problem is with  http://repo1.maven.org/maven2 and I need to change it to https. Done that, still it doesn't work. Then I found another suggestion in google -> add the maven certificate with keytool & restart. Done that. Still doesn't work. Asked a colleague to send me theirs repo and it worked (ofc, there're all the dependencies). Then I wanted to introduce categories in our junit tests, so I added surefire plugin and this time the problem is similar:

```<code>Unable to generate classpath: org.apache.maven.artifact.resolver.ArtifactResolutionException:
Unable to get dependency information for org.apache.maven.surefire:surefire-grouper:jar:2.12.4: Failed to retrieve POM for org.apache.maven.surefire:surefire-grouper:jar:2.12.4:
Could not transfer artifact org.apache.maven.surefire:surefire-grouper:pom:2.12.4 from/to maven (https://repo1.maven.org/maven2): sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: u
nable to find valid certification path to requested target [ERROR]   org.apache.maven.surefire:surefire-grouper:jar:2.12.4
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR]   maven (https://repo1.maven.org/maven2, releases=true, snapshots=true),
[ERROR]   central (https://repo.maven.apache.org/maven2, releases=true, snapshots=false),
[ERROR]   apache.snapshots (http://repository.apache.org/snapshots, releases=false, snapshots=true)
[ERROR] Path to dependency:
[ERROR]         1) dummy:dummy:jar:1.0
[ERROR]         2) org.apache.maven.surefire:surefire-junit47:jar:2.12.4
[ERROR]         3) org.apache.maven.surefire:common-junit48:jar:2.12.4
</code>```

So then I decide to go and download one by one, but it's a hell and I prefer to fix this issue instead of manually download everything.

答: It turns out that the problem was with our firewall - somehow it blocks requests to all maven repos. When I asked the ITs to stop it and test it, maven was able to download everything from the standard maven repo (the one with https)</p>

Body:
I've got following error when I'm trying to build my project:

Failed to collect dependencies at org.msgpack:jackson-dataformat-msgpack:jar:0.8.17 -> com.fasterxml.jackson.core:jackson-databind:jar:2.9.9: Failed to read artifact descriptor for com.fasterxml.jackson.core:jackson-databind:jar:2.9.9: Could not transfer artifact com.fasterxml.jackson.core:jackson-databind:pom:2.9.9 from/to maven (https://repo1.maven.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I read that the problem is with  http://repo1.maven.org/maven2 and I need to change it to https. Done that, still it doesn't work. Then I found another suggestion in google -> add the maven certificate with keytool & restart. Done that. Still doesn't work. Asked a colleague to send me theirs repo and it worked (ofc, there're all the dependencies). Then I wanted to introduce categories in our junit tests, so I added surefire plugin and this time the problem is similar:

Unable to generate classpath: org.apache.maven.artifact.resolver.ArtifactResolutionException:
Unable to get dependency information for org.apache.maven.surefire:surefire-grouper:jar:2.12.4: Failed to retrieve POM for org.apache.maven.surefire:surefire-grouper:jar:2.12.4:
Could not transfer artifact org.apache.maven.surefire:surefire-grouper:pom:2.12.4 from/to maven (https://repo1.maven.org/maven2): sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: u
nable to find valid certification path to requested target [ERROR]   org.apache.maven.surefire:surefire-grouper:jar:2.12.4
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR]   maven (https://repo1.maven.org/maven2, releases=true, snapshots=true),
[ERROR]   central (https://repo.maven.apache.org/maven2, releases=true, snapshots=false),
[ERROR]   apache.snapshots (http://repository.apache.org/snapshots, releases=false, snapshots=true)
[ERROR] Path to dependency:
[ERROR]         1) dummy:dummy:jar:1.0
[ERROR]         2) org.apache.maven.surefire:surefire-junit47:jar:2.12.4
[ERROR]         3) org.apache.maven.surefire:common-junit48:jar:2.12.4

So then I decide to go and download one by one, but it's a hell and I prefer to fix this issue instead of manually download everything.


问:
DJI Android SDK Integration Demo Tutorial Issue
I am following this exact tutorial for adding the SDK into a new android project.
However, when i try running the project on my physical device i get the following error:

```<code>No implementation found for void dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(java.lang.String)
(tried Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory and Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory__Ljava_lang_String_2)
java.lang.UnsatisfiedLinkError: No implementation found for void dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(java.lang.String) (tried Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory and Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory__Ljava_lang_String_2)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(Native Method)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.e(Unknown Source:12)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.b(Unknown Source:2)
    at dji.upgrade.internal.csdk.CSDKManager.a(Unknown Source:15)
    at dji.upgrade.internal.UpgradeManagerImpl.a(Unknown Source:27)
    at dji.sdk.sdkmanager.DJISDKManager.initParams(Unknown Source:24)
    at dji.sdk.sdkmanager.DJISDKManager.initSDKManager(Unknown Source:253)
    at dji.sdk.sdkmanager.DJISDKManager.registerApp(Unknown Source:45)
    at dji.sdk.sdkmanager.DJISDKManager.access$600(Unknown Source:0)
    at dji.sdk.sdkmanager.DJISDKManager$5$1.onDownloadSuccess(Unknown Source:6)
    at dji.internal.flysafe.DJIFlySafeDBLoader.a(Unknown Source:19)
    at dji.sdk.sdkmanager.DJISDKManager$5.run(Unknown Source:33)
    at dji.sdksharedlib.util.DJISDKCacheThreadManager$1.run(Unknown Source:5)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
</code>```

This is my gradle sample:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.airsmat"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
     }
     buildTypes {
            release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        doNotStrip "*/*/libdjivideo.so"
        doNotStrip "*/*/libSDKRelativeJNI.so"
        doNotStrip "*/*/libFlyForbid.so"
        doNotStrip "*/*/libduml_vision_bokeh.so"
        doNotStrip "*/*/libyuv2.so"
        doNotStrip "*/*/libGroudStation.so"
        doNotStrip "*/*/libFRCorkscrew.so"
        doNotStrip "*/*/libUpgradeVerify.so"
        doNotStrip "*/*/libFR.so"
        doNotStrip "*/*/libDJIFlySafeCore.so"
        doNotStrip "*/*/libdjifs_jni.so"
        doNotStrip "*/*/libsfjni.so"
        exclude 'META-INF/rxjava.properties'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    /**
     * Dji SDK
     */
    implementation('com.dji:dji-sdk:4.11.1')
    compileOnly('com.dji:dji-sdk-provided:4.11.1')
 }
</code>```

How do i resolve please. I have encountered the issues on github here and here and tried the suggestions but still the same error.

答:
I was getting the same issue while using the code given in the tutorials. To fix this issue I tried downloading the same app from their github repository, please find it's link here.

I think they are updating their repository but code in the tutorials is not upto date. I hope this will help someone who is looking for the solution to this problem.

Body:
I am following this exact tutorial for adding the SDK into a new android project.
However, when i try running the project on my physical device i get the following error:

No implementation found for void dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(java.lang.String)
(tried Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory and Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory__Ljava_lang_String_2)
java.lang.UnsatisfiedLinkError: No implementation found for void dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(java.lang.String) (tried Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory and Java_dji_upgrade_internal_csdk_upgradeadapter_UpgradeAdapterManager_setFirmwareStoreDirectory__Ljava_lang_String_2)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.setFirmwareStoreDirectory(Native Method)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.e(Unknown Source:12)
    at dji.upgrade.internal.csdk.upgradeadapter.UpgradeAdapterManager.b(Unknown Source:2)
    at dji.upgrade.internal.csdk.CSDKManager.a(Unknown Source:15)
    at dji.upgrade.internal.UpgradeManagerImpl.a(Unknown Source:27)
    at dji.sdk.sdkmanager.DJISDKManager.initParams(Unknown Source:24)
    at dji.sdk.sdkmanager.DJISDKManager.initSDKManager(Unknown Source:253)
    at dji.sdk.sdkmanager.DJISDKManager.registerApp(Unknown Source:45)
    at dji.sdk.sdkmanager.DJISDKManager.access$600(Unknown Source:0)
    at dji.sdk.sdkmanager.DJISDKManager$5$1.onDownloadSuccess(Unknown Source:6)
    at dji.internal.flysafe.DJIFlySafeDBLoader.a(Unknown Source:19)
    at dji.sdk.sdkmanager.DJISDKManager$5.run(Unknown Source:33)
    at dji.sdksharedlib.util.DJISDKCacheThreadManager$1.run(Unknown Source:5)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)

This is my gradle sample:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.airsmat"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
     }
     buildTypes {
            release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        doNotStrip "*/*/libdjivideo.so"
        doNotStrip "*/*/libSDKRelativeJNI.so"
        doNotStrip "*/*/libFlyForbid.so"
        doNotStrip "*/*/libduml_vision_bokeh.so"
        doNotStrip "*/*/libyuv2.so"
        doNotStrip "*/*/libGroudStation.so"
        doNotStrip "*/*/libFRCorkscrew.so"
        doNotStrip "*/*/libUpgradeVerify.so"
        doNotStrip "*/*/libFR.so"
        doNotStrip "*/*/libDJIFlySafeCore.so"
        doNotStrip "*/*/libdjifs_jni.so"
        doNotStrip "*/*/libsfjni.so"
        exclude 'META-INF/rxjava.properties'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    /**
     * Dji SDK
     */
    implementation('com.dji:dji-sdk:4.11.1')
    compileOnly('com.dji:dji-sdk-provided:4.11.1')
 }

How do i resolve please. I have encountered the issues on github here and here and tried the suggestions but still the same error.


问:
How to use tumbling window to group XML elements by content?
How do I group based on whether there's a match to [0-9] for digits with a tumbling window?

desired output:

```<code>...
<record>
    <name>joe</name>
    <data>phone1</data>
    <data>phone2</data>
</record>
...
</code>```

current output, not grouped:

```<code><xml>
  <record>
    <person key="$s" data="name">phone1</person>
  </record>
  <record>
    <person key="$s" data="name">phone2</person>
  </record>
  <record>
    <person key="$s" data="name">phone3sue</person>
  </record>
  <record>
    <person key="$s" data="name">cell4</person>
  </record>
  <record>
    <person key="$s" data="name">home5alice</person>
  </record>
  <record>
    <person key="$s" data="name">atrib6</person>
  </record>
  <record>
    <person key="$s" data="name">x7</person>
  </record>
  <record>
    <person key="$s" data="name">y9</person>
  </record>
  <record>
    <person key="$s" data="name">z10</person>
  </record>
</xml>
</code>```

input:

```<code><text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
</code>```

The notion is that each "person" will have a name (no digits) and perhaps additional data.  So looking to read in each line and then group based on where the names are found.

code:

```<code>xquery version "3.0";

<xml>
{
for tumbling window $line in db:open("foo.txt")//text()
start $s when matches($s, '[0-9]')
return
<record>

       <person key='$s' data="name">{$line}</person>

 </record>
}
 </xml>
</code>```

Looking at the output, "phone3sue" is obviously doing some matching and grouping, although not exactly as desired because "phone3" should be in its own element, nested within "joe" rather than "sue".  But, still, there's some matching happening there.

from the saxon mailing list:

On Wed, Feb 19, 2020 at 10:31:37AM -0800, thufir scripsit:

I'll re-read the section on windowing; my impression was that it was more
    for display or report purposes.

Windowing is how you take chunks out of a stream of data.

What you've got is effectively a stream of line elements; you can
  identify the "name" lines, but you don't now how far part they are/how
  much data is between any particular pair of names.

Windows lets you say "I want the chunk of this stream that starts with
  a name line and continues up to (but not including) the next name
  line".

Would you elaborate on what you mean by two steps, a bit more concretely?

You're trying to take some input XML and turn it into different output
  XML.

If this is pure transformation -- change all of the elements named FOO
  to element named BAZ -- XQuery's not the best tool choice. Use XSLT if
  you can.  They're computationally the same but the languages have
  different biases and XSLT does transforms more naturally.

If the output XML is a representation of an abstraction of your input
  -- morally some sort of report -- it helps a lot to have the abstraction, and then present it.

So in your case, what you have is a stream containing an implicit
  association between names and data.  (It's a stream of lines; the only
  way you know these data lines go with that name line is position.  So
  implicit.)  If you turn that into an explicit mapping between names
  and data -- such as by creating a map variable where the keys are the
  contents of the name line (with spaces handled somehow) and the
  entries for each key are the data lines associated with that name --
  you have done the abstraction part.

You can then take that map and produce the XML output you want from
  it, which is much simpler than trying to combine the "create new XML"
  and "do the abstraction steps".  The last thing I posted has an
  example of turning a map into elements, but as a pattern it's just

map:keys($map) ! {.}{$map(.)}

(it gets more complicated if you've got nodes or a sequence in the
  entry, but not much more.)

That make something a little closer to sense?

-- Graydon

_______________________________________________ saxon-help mailing list archived at http://saxon.markmail.org/
  saxon-help@lists.sourceforge.net
  https://lists.sourceforge.net/lists/listinfo/saxon-help

答:
The following tries to use a tumbling window which starts with any line not containing any ASCII digit (the name of the person) followed by any line containing at least one ASCII digit (i.e. the data lines):

```<code>declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'xml';
declare option output:indent 'yes';

<xml>
{
    for tumbling window $person in text/line
    start $name next $data when matches($name, '^[^0-9]+$') and matches($data, '[0-9]')
    return
        <person>
        {
            <name>{ data($name) }</name>,
            tail($person) ! <data>{data()}</data>

        }
        </person>
}
</xml>
</code>```

https://xqueryfiddle.liberty-development.net/gWmuPs1

Output there is

```<code><?xml version="1.0" encoding="UTF-8"?>
<xml>
   <person>
      <name>joe</name>
      <data>phone1</data>
      <data>phone2</data>
      <data>phone3</data>
   </person>
   <person>
      <name>sue</name>
      <data>cell4</data>
      <data>home5</data>
   </person>
   <person>
      <name>alice</name>
      <data>atrib6</data>
      <data>x7</data>
      <data>y9</data>
      <data>z10</data>
   </person>
</xml>
</code>```

Body:
How do I group based on whether there's a match to [0-9] for digits with a tumbling window?

desired output:

...
<record>
    <name>joe</name>
    <data>phone1</data>
    <data>phone2</data>
</record>
...

current output, not grouped:

<xml>
  <record>
    <person key="$s" data="name">phone1</person>
  </record>
  <record>
    <person key="$s" data="name">phone2</person>
  </record>
  <record>
    <person key="$s" data="name">phone3sue</person>
  </record>
  <record>
    <person key="$s" data="name">cell4</person>
  </record>
  <record>
    <person key="$s" data="name">home5alice</person>
  </record>
  <record>
    <person key="$s" data="name">atrib6</person>
  </record>
  <record>
    <person key="$s" data="name">x7</person>
  </record>
  <record>
    <person key="$s" data="name">y9</person>
  </record>
  <record>
    <person key="$s" data="name">z10</person>
  </record>
</xml>

input:

<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>

The notion is that each "person" will have a name (no digits) and perhaps additional data.  So looking to read in each line and then group based on where the names are found.

code:

xquery version "3.0";

<xml>
{
for tumbling window $line in db:open("foo.txt")//text()
start $s when matches($s, '[0-9]')
return
<record>

       <person key='$s' data="name">{$line}</person>

 </record>
}
 </xml>

Looking at the output, "phone3sue" is obviously doing some matching and grouping, although not exactly as desired because "phone3" should be in its own element, nested within "joe" rather than "sue".  But, still, there's some matching happening there.

from the saxon mailing list:

On Wed, Feb 19, 2020 at 10:31:37AM -0800, thufir scripsit:

I'll re-read the section on windowing; my impression was that it was more
    for display or report purposes.

Windowing is how you take chunks out of a stream of data.

What you've got is effectively a stream of line elements; you can
  identify the "name" lines, but you don't now how far part they are/how
  much data is between any particular pair of names.

Windows lets you say "I want the chunk of this stream that starts with
  a name line and continues up to (but not including) the next name
  line".

Would you elaborate on what you mean by two steps, a bit more concretely?

You're trying to take some input XML and turn it into different output
  XML.

If this is pure transformation -- change all of the elements named FOO
  to element named BAZ -- XQuery's not the best tool choice. Use XSLT if
  you can.  They're computationally the same but the languages have
  different biases and XSLT does transforms more naturally.

If the output XML is a representation of an abstraction of your input
  -- morally some sort of report -- it helps a lot to have the abstraction, and then present it.

So in your case, what you have is a stream containing an implicit
  association between names and data.  (It's a stream of lines; the only
  way you know these data lines go with that name line is position.  So
  implicit.)  If you turn that into an explicit mapping between names
  and data -- such as by creating a map variable where the keys are the
  contents of the name line (with spaces handled somehow) and the
  entries for each key are the data lines associated with that name --
  you have done the abstraction part.

You can then take that map and produce the XML output you want from
  it, which is much simpler than trying to combine the "create new XML"
  and "do the abstraction steps".  The last thing I posted has an
  example of turning a map into elements, but as a pattern it's just

map:keys($map) ! {.}{$map(.)}

(it gets more complicated if you've got nodes or a sequence in the
  entry, but not much more.)

That make something a little closer to sense?

-- Graydon

_______________________________________________ saxon-help mailing list archived at http://saxon.markmail.org/
  saxon-help@lists.sourceforge.net
  https://lists.sourceforge.net/lists/listinfo/saxon-help

Body:
The following tries to use a tumbling window which starts with any line not containing any ASCII digit (the name of the person) followed by any line containing at least one ASCII digit (i.e. the data lines):

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'xml';
declare option output:indent 'yes';

<xml>
{
    for tumbling window $person in text/line
    start $name next $data when matches($name, '^[^0-9]+$') and matches($data, '[0-9]')
    return
        <person>
        {
            <name>{ data($name) }</name>,
            tail($person) ! <data>{data()}</data>

        }
        </person>
}
</xml>

https://xqueryfiddle.liberty-development.net/gWmuPs1

Output there is

<?xml version="1.0" encoding="UTF-8"?>
<xml>
   <person>
      <name>joe</name>
      <data>phone1</data>
      <data>phone2</data>
      <data>phone3</data>
   </person>
   <person>
      <name>sue</name>
      <data>cell4</data>
      <data>home5</data>
   </person>
   <person>
      <name>alice</name>
      <data>atrib6</data>
      <data>x7</data>
      <data>y9</data>
      <data>z10</data>
   </person>
</xml>


问:
Performantly render tens of thousands of spheres of variable size/color/position in Three.js?
This question is picking up from my last question where I found that using Points leads to problems: https://stackoverflow.com/a/60306638/4749956

To solve this you'll need to draw your points using quads instead of points. There are many ways to do that. Draw each quad as a separate mesh or sprite, or merge all the quads into another mesh, or use InstancedMesh where you'll need a matrix per point, or write custom shaders to do points (see the last example on this article)

I've been trying to figure this answer out. My questions are

What is 'instancing'? What is the difference between merging geometries and instancing? And, if I were to do either one of these, what geometry would I use and how would I vary color? I've been looking at this example:

https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_performance.html

And I see that for each sphere you would have a geometry which would apply the position and the size (scale?). Would the underlying geometry be a SphereBufferGeometry of unit radius, then? But, how do you apply color?

Also, I read about the custom shader method, and it makes some vague sense. But, it seems more complex. Would the performance be any better than the above?

答:
This is quite a broad topic. In short, both merging and instancing is about reducing the number of draw calls when rendering something.

If you bind your sphere geometry once, but keep re-rendering it, it costs you more to tell your computer to draw it many times, than it takes your computer to compute what it takes to draw it. You end up with the GPU, a powerful parallel processing device, sitting idle.

Obviously, if you create a unique sphere at each point in space, and merge them all, you pay the price of telling the gpu to render once, and it will be busy rendering thousands of your spheres.

However, merging this will increase your memory footprint, and has some overhead when you're actually creating the unique data. Instancing is a built-in clever way of achieving the same effect, at less the memory cost.

I have an article written on this topic.


问:
Delete a duplicate widget in appJar
how can I delete a duplicate widget in appJar?

i get this error

```<code>appJar.appjar.ItemLookupError: Duplicate widgetName: my_label_name
</code>```

I want to delete the widget(actually a label) to make another one, but with the same name

I can't figure it out how I tried with removeWidgetType but it doesn't seem to work? did I pass good arguments into the removeWidgetType

```<code>
for line in chatlog:
                print(line)

                saved_line = line
                chatlog.truncate(0)

                app.removeWidgetType('Label', 'chatline')
                app.addLabel('chatline', saved_line)
</code>```

答:
Your issue is with the line app.removeWidgetType(...)

That function relies on the first parameter being a number, in this case it would be 0 for a Label. This is a wrapper function used by all the specific widget removal functions.

You should be using:

app.removeLabel('chatLine')

That will then call the function you're using, passing the correct number identifier.

See here for some more details: http://appjar.info/pythonWidgetOptions/#widget-manipulation

Title: Delete a duplicate widget in appJar

Body:
how can I delete a duplicate widget in appJar?

i get this error

appJar.appjar.ItemLookupError: Duplicate widgetName: my_label_name

I want to delete the widget(actually a label) to make another one, but with the same name

I can't figure it out how I tried with removeWidgetType but it doesn't seem to work? did I pass good arguments into the removeWidgetType

for line in chatlog:
                print(line)

                saved_line = line
                chatlog.truncate(0)

                app.removeWidgetType('Label', 'chatline')
                app.addLabel('chatline', saved_line)


答: It is and always be a reference. Think of object variables as pointers/refernces. While the actual object creation/allocation happens on heap, references are created on local stack space.</p>

Title: Inheritance base class reference C#


问:
How to use constructor injection in Mapstruct's mapper?
In some mapper classes, I need to use an autowired ObjectMapper to transform String to JsonNode or verse-vera. I can acheive my goal by using the field injection with @autowired. But it's not suitable for unit test so I'd like to try using the constructor injection.

My current working code with the field injection:

```<code>@Mapper(componentModel = "spring")
public class CustomMapper {
  @autowired
  ObjectMapper mapper;
}
</code>```

I try to convert it to the constructor injection so I can provide constructor argument in my unit test:

```<code>@Mapper(componentModel = "spring")
public class CustomMapper {
  ObjectMapper mapper;

  public CustomMapper(ObjectMapper mapper) {
    this.mapper = mapper;
  }
}
</code>```

But I get a Constructor in CustomMapper cannot be applied to the given type error during compilation.
How do I fix it? Or is there other better way to map String to JsonNode in Mapstruct?

答:
Constructor injection cannot be used in the mapper definition. Only in the mapper implementation.

However, for unit testing I'd suggest that you use setter injection.

Your mapper will then look like:

```<code>@Mapper( componentModel = "spring")
public class CustomMapper {

    protected ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper) {
        this.mapper = mapper;
   }

}
</code>```

Body:
In some mapper classes, I need to use an autowired ObjectMapper to transform String to JsonNode or verse-vera. I can acheive my goal by using the field injection with @autowired. But it's not suitable for unit test so I'd like to try using the constructor injection.

My current working code with the field injection:

@Mapper(componentModel = "spring")
public class CustomMapper {
  @autowired
  ObjectMapper mapper;
}

I try to convert it to the constructor injection so I can provide constructor argument in my unit test:

@Mapper(componentModel = "spring")
public class CustomMapper {
  ObjectMapper mapper;

  public CustomMapper(ObjectMapper mapper) {
    this.mapper = mapper;
  }
}

But I get a Constructor in CustomMapper cannot be applied to the given type error during compilation.
How do I fix it? Or is there other better way to map String to JsonNode in Mapstruct?

Body:
Constructor injection cannot be used in the mapper definition. Only in the mapper implementation.

However, for unit testing I'd suggest that you use setter injection.

Your mapper will then look like:

@Mapper( componentModel = "spring")
public class CustomMapper {

    protected ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper) {
        this.mapper = mapper;
   }

}


问:
how to cut or break the loop of modulo and continue the loop in separate html table
badly need assistance how to break modulo in visible by 3 but i need it loop or continue the loop in separate html table, because in my mine.. it will continuing the loop like below

Sample_table

```<code>|     1    |
|     2    |
|     3    |
|     4    |
|     5    |
|     6    |
</code>```

Current output

```<code>|     1    |     2   |     3    |
|     4    |     5   |     6    |
</code>```

Desired Output

```<code>HTML table page 1
|     1    |     2   |     3    |

HTML table page 2
|     4    |     5   |     6    |
</code>```

My current code

//$resultz =  explode('xxx',$result['0']['tanning']);
//$i = 0;
$i=0;
foreach($result as $results) {
    if ($i%3 == 0) {
        echo  "
TITLE
	";
        echo  "".$results['data1']."	";
    } else {
        echo  "".$results['data1']."	";
    }
    $i++;
}
echo "
";
```

Thankss

答:
Can be many solutions.
May be so:</p>

```<code><?
// controller
/*$array = array(
  1,
  2,
  3,
  4,
  5,
  6,
  7
  // ...
);*/

$array =array(
    array('id'=>1,'name'=>'a'),
    array('id'=>2,'name'=>'a'),
    array('id'=>3,'name'=>'a'),
    array('id'=>4,'name'=>'a'),
    array('id'=>5,'name'=>'a'),
    array('id'=>6,'name'=>'a'),
    array('id'=>7,'name'=>'a')
);

echo '$array ```';
print_r($array);
echo '```';

$column = 0;
$row = 0;
$maxColumn = 3; // max number of columns
$arrayNew = array();
foreach($array as $key => $val){
  $column++;

  $arrayNew[$row][$key] = $val;

  if ($column == $maxColumn){
    $column = 0;
    $row++;
  }
}

if( $column >= 1) { // add empty values so that the table is beautiful (if necessary)
  for($i = 0; $i < ($maxColumn - $column); $i++){
    //$arrayNew[$row][] = '';
    $arrayNew[$row][] = array();
  }
}

// template
foreach ($arrayNew as $keyValueArray => $valueArray) { ?>
  <table>
    <tr>
      <?foreach ($valueArray as $key => $value) { ?>
        <td><?=$value['id']?></td>
      <?}?>
    </tr>
  </table>
<?}
</code>```

Body:
badly need assistance how to break modulo in visible by 3 but i need it loop or continue the loop in separate html table, because in my mine.. it will continuing the loop like below

Sample_table

|     1    |
|     2    |
|     3    |
|     4    |
|     5    |
|     6    |

Current output

|     1    |     2   |     3    |
|     4    |     5   |     6    |

Desired Output

HTML table page 1
|     1    |     2   |     3    |

HTML table page 2
|     4    |     5   |     6    |

My current code

//$resultz =  explode('xxx',$result['0']['tanning']);
//$i = 0;
$i=0;
foreach($result as $results) {
    if ($i%3 == 0) {
        echo  "
TITLE
	";
        echo  "".$results['data1']."	";
    } else {
        echo  "".$results['data1']."	";
    }
    $i++;
}
echo "
";

Thankss

Body:
Can be many solutions.
May be so:

<?
// controller
/*$array = array(
  1,
  2,
  3,
  4,
  5,
  6,
  7
  // ...
);*/

$array =array(
    array('id'=>1,'name'=>'a'),
    array('id'=>2,'name'=>'a'),
    array('id'=>3,'name'=>'a'),
    array('id'=>4,'name'=>'a'),
    array('id'=>5,'name'=>'a'),
    array('id'=>6,'name'=>'a'),
    array('id'=>7,'name'=>'a')
);

echo '$array <pre>';
print_r($array);
echo '</pre>';

$column = 0;
$row = 0;
$maxColumn = 3; // max number of columns
$arrayNew = array();
foreach($array as $key => $val){
  $column++;

  $arrayNew[$row][$key] = $val;

  if ($column == $maxColumn){
    $column = 0;
    $row++;
  }
}

if( $column >= 1) { // add empty values so that the table is beautiful (if necessary)
  for($i = 0; $i < ($maxColumn - $column); $i++){
    //$arrayNew[$row][] = '';
    $arrayNew[$row][] = array();
  }
}

// template
foreach ($arrayNew as $keyValueArray => $valueArray) { ?>
  <table>
    <tr>
      <?foreach ($valueArray as $key => $value) { ?>
        <td><?=$value['id']?></td>
      <?}?>
    </tr>
  </table>
<?}


问:
How to format an interpolated String
I need to format a string like "Send %d seconds ago", "Harry likes %s", "I think %1$s likes %2$s". These can be implemented in Android, but i don't know how to implement it in Dart for Flutter.

答:
you could also have something simple like this:

Usage

interpolate('Hello {#}{#}, cool {#}',['world','!','?']);
// Hello world!, cool ?
```

<ul>
<li>Function</li>
</ul>

<pre class="lang-dart prettyprint-override"><code>  static const needleRegex = r'{#}';
  static const needle = '{#}';
  static final RegExp exp = new RegExp(needleRegex);

  static String interpolate(String string, List l) {
    Iterable<RegExpMatch> matches = exp.allMatches(string);

    assert(l.length == matches.length);

    var i = -1;
    return string.replaceAllMapped(exp, (match) {
      print(match.group(0));
      i = i + 1;
      return '${l[i]}';
    });
  }
</code>```

Title: How to format an interpolated String

Body:
you could also have something simple like this:

Usage

interpolate('Hello {#}{#}, cool {#}',['world','!','?']);
// Hello world!, cool ?

Function

  static const needleRegex = r'{#}';
  static const needle = '{#}';
  static final RegExp exp = new RegExp(needleRegex);

  static String interpolate(String string, List l) {
    Iterable<RegExpMatch> matches = exp.allMatches(string);

    assert(l.length == matches.length);

    var i = -1;
    return string.replaceAllMapped(exp, (match) {
      print(match.group(0));
      i = i + 1;
      return '${l[i]}';
    });
  }


问:
How to print date in the format of mm/dd/yyyy in VB
I need to print the date in the format of mm/dd/yyyy.
if the date is 4/24/2009 it should print the date as 04/24/2009.
that is zero padding is also needed..
I used date function to get the current date...but the date is getting in the format of m/dd/yyyy...</p>

答:
Formatting DateTime as a string is straightforward. Often we use format patterns like "HH." But methods like ToShortDateString are also useful.

Example. First we get the current time through DateTime.Now. When you execute these code examples, the current DateTime will be different on your computer.
Here: A format string beginning with MMM (for the month) is used. Look at how the pattern matches up to the output of the program.

VB.NET program that uses format string with DateTime

Module Module1
    Sub Main()
        ' Use current time.
        ' ... Use a format.
        ' ... Write to console.
        Dim time As DateTime = DateTime.Now
        Dim format As String = "MMM ddd d HH:mm yyyy"
        Console.WriteLine(time.ToString(format))
    End Sub
End Module

Output

Feb Tue 21 13:26 2017