问:
In pandas how to convert notation to a whole number?
In python3 and pandas I open a CSV like this:

```<code>import pandas as pd
kwargs = {'sep': ';', 'dtype': str, 'encoding': 'utf-8'}
df = pd.read_csv("COVID_sp_29_mai_2020.csv", **kwargs)

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7119 entries, 0 to 7118
Data columns (total 27 columns):
 #   Column                          Non-Null Count  Dtype
---  ------                          --------------  -----
 0   Secretaria                      7119 non-null   object
 1   Assunto                         7119 non-null   object
 2   13979                           7119 non-null   object
 3   Valor de Empenho no Processo    7119 non-null   object
 4   Órgão                           7119 non-null   object
 5   Código UG Documento             7119 non-null   object
 6   Descrição Processo              7119 non-null   object
 7   Finalidade                      7119 non-null   object
 8   R$ Empenho                      7119 non-null   object
 9   Tipo Documento                  7119 non-null   object
 10  Data Atualização                7119 non-null   object
 11  R$ Pago                         7119 non-null   object
 12  Número Empenho                  7119 non-null   object
 13  Número Documento NE Ref / Anul  335 non-null    object
 14  Número Processo                 7119 non-null   object
 15  CGC CPF                         7026 non-null   object
 16  Nome Credor                     7119 non-null   object
 17  Data Emissão                    7119 non-null   object
 18  Ação Orçamentária               7119 non-null   object
 19  Fonte                           7119 non-null   object
 20  Código Fonte                    7119 non-null   object
 21  Descrição                       7119 non-null   object
 22  Unnamed: 22                     0 non-null      object
 23  Unnamed: 23                     0 non-null      object
 24  Unnamed: 24                     0 non-null      object
 25  Unnamed: 25                     16 non-null     object
 26  Unnamed: 26                     17 non-null     object
dtypes: object(27)
memory usage: 1.5+ MB
</code>```

The column has 'CGC CPF' has identification codes, which can sometimes only have numbers or numbers and letters

The lines that the identification code 'CGC CPF' has only numbers the file is notated. Example:

```<code>Educação;Merenda em Casa;regular;81.508.955,00 ;SECRETARIA DA EDUCACAO;80358;MERENDA EM CASA;MERENDA EM CASA;-40280955;NE;29/05/2020;0;2020NE00119;2020NE00120;20407/20;2,29E+13;PICPAY SERVICOS S/A;01/04/2020;FORNEC. ALIMENTACAO P/ALUNOS EDUCACAO BASICA;Federal;5003002;DISPENSA DE LICITACAO;;;;Data Atualização;Data Atualização
</code>```

In this case, the code for this line is "2,29E+13" in the CSV. It's a company code, which I know is "22896431000110"

Please, how can I convert the column notation to an integer?

I want to convert the exponential notation value to int. And also with that I will check if the CSV value is correct

答:
Try this - </p>

```<code>df['CGC CPF'].fillna('UNK', inplace=True)
df.loc[:, 'CGC CPF'] = df.loc[:, 'CGC CPF'].str.replace(',','') #replacing ',' in target column with blank, for us to interpret exponential values
match = ['E+','e+'] #Since there are both e+ and E+ notation
df['CGC CPF'] = df['CGC CPF'].apply(lambda x: float(x) if any(m in x for m in match) else x)  #using float to convert exponential to a number
</code>```

Body:
In python3 and pandas I open a CSV like this:

import pandas as pd
kwargs = {'sep': ';', 'dtype': str, 'encoding': 'utf-8'}
df = pd.read_csv("COVID_sp_29_mai_2020.csv", **kwargs)

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7119 entries, 0 to 7118
Data columns (total 27 columns):
 #   Column                          Non-Null Count  Dtype
---  ------                          --------------  -----
 0   Secretaria                      7119 non-null   object
 1   Assunto                         7119 non-null   object
 2   13979                           7119 non-null   object
 3   Valor de Empenho no Processo    7119 non-null   object
 4   Órgão                           7119 non-null   object
 5   Código UG Documento             7119 non-null   object
 6   Descrição Processo              7119 non-null   object
 7   Finalidade                      7119 non-null   object
 8   R$ Empenho                      7119 non-null   object
 9   Tipo Documento                  7119 non-null   object
 10  Data Atualização                7119 non-null   object
 11  R$ Pago                         7119 non-null   object
 12  Número Empenho                  7119 non-null   object
 13  Número Documento NE Ref / Anul  335 non-null    object
 14  Número Processo                 7119 non-null   object
 15  CGC CPF                         7026 non-null   object
 16  Nome Credor                     7119 non-null   object
 17  Data Emissão                    7119 non-null   object
 18  Ação Orçamentária               7119 non-null   object
 19  Fonte                           7119 non-null   object
 20  Código Fonte                    7119 non-null   object
 21  Descrição                       7119 non-null   object
 22  Unnamed: 22                     0 non-null      object
 23  Unnamed: 23                     0 non-null      object
 24  Unnamed: 24                     0 non-null      object
 25  Unnamed: 25                     16 non-null     object
 26  Unnamed: 26                     17 non-null     object
dtypes: object(27)
memory usage: 1.5+ MB

The column has 'CGC CPF' has identification codes, which can sometimes only have numbers or numbers and letters

The lines that the identification code 'CGC CPF' has only numbers the file is notated. Example:

Educação;Merenda em Casa;regular;81.508.955,00 ;SECRETARIA DA EDUCACAO;80358;MERENDA EM CASA;MERENDA EM CASA;-40280955;NE;29/05/2020;0;2020NE00119;2020NE00120;20407/20;2,29E+13;PICPAY SERVICOS S/A;01/04/2020;FORNEC. ALIMENTACAO P/ALUNOS EDUCACAO BASICA;Federal;5003002;DISPENSA DE LICITACAO;;;;Data Atualização;Data Atualização

In this case, the code for this line is "2,29E+13" in the CSV. It's a company code, which I know is "22896431000110"

Please, how can I convert the column notation to an integer?

I want to convert the exponential notation value to int. And also with that I will check if the CSV value is correct

Body:
Try this -

df['CGC CPF'].fillna('UNK', inplace=True)
df.loc[:, 'CGC CPF'] = df.loc[:, 'CGC CPF'].str.replace(',','') #replacing ',' in target column with blank, for us to interpret exponential values
match = ['E+','e+'] #Since there are both e+ and E+ notation
df['CGC CPF'] = df['CGC CPF'].apply(lambda x: float(x) if any(m in x for m in match) else x)  #using float to convert exponential to a number


来源: stackexchange

问:
Angular Routing Issue 'Cannot match any routes'
I just set up a new Angular project and added two Component Routes in my AppRouting Module.

I get the following error when I try to access a route:

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'cr-calculator'
Error: Cannot match any routes. URL Segment: 'cr-calculator'
    at ApplyRedirects.noMatchError (router.js:4396)
    at CatchSubscriber.selector (router.js:4360)
    at CatchSubscriber.error (catchError.js:29)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at ThrowIfEmptySubscriber._error (Subscriber.js:75)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41632)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)
</code>```

And also the router-outlet doesn't work for me for some reason, it just shows blank even if I have some content in my Route Components.

This is my app-routing.module.ts:

```<code>import { CrCalculatorPageComponent } from './../pages/cr-calculator-page/cr-calculator-page.component';
import { HomePageComponent } from './../pages/home-page/home-page.component';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

export const routes: Routes = [
  {
    path: '',
    data: {
      linkName: 'Home',
      showInMenu: true,
      animation: 'HomePage'
    },
    component: HomePageComponent
  },
  {
    path: 'cr-calculator',
    data: {
      linkName: 'CR Calculator',
      showInMenu: true,
      animation: 'CrCalculator'
    },
    component: CrCalculatorPageComponent
  }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

... and this is my app.module.ts:

```<code>import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { CrCalculatorPageComponent } from './pages/cr-calculator-page/cr-calculator-page.component';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavMenuComponent,
    HomePageComponent,
    CrCalculatorPageComponent
  ],
  imports: [
    BrowserModule,
    RouterModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

I have multi-checked my code and not found anything. I have also checked out some answered Questions here already but nothing helped me solving my issue.

Thanks in advance and please tell me if you need some more code to review the issue.

// EDIT

HTML-Code with routerLink Statements:

```<code><ul class="navbar-nav mr-auto">
  <ng-container *ngFor="let link of links">
    <li class="nav-item" *ngIf="link.data.showInMenu" [routerLinkActive]="['active']">
      <a class="nav-link" [routerLink]="link.path">{{link.data.linkName}}</a>
    </li>
  </ng-container>
</ul>
</code>```

'links' is basically the routes Object-Array from the app-routing.module.ts

答: I solved the issue. You all could not know that because when I created the project I added the App Routing tag in the command line which automatically generated a AppRouting Module and imported that in my app.module.ts. So the error was that I had two AppRouting Modules and I've added my routes in the custom AppRouting but in the app.module.ts the Blank App Routing module was linked.

ContentLicense: CC BY-SA 4.0

Body:
I just set up a new Angular project and added two Component Routes in my AppRouting Module.

I get the following error when I try to access a route:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'cr-calculator'
Error: Cannot match any routes. URL Segment: 'cr-calculator'
    at ApplyRedirects.noMatchError (router.js:4396)
    at CatchSubscriber.selector (router.js:4360)
    at CatchSubscriber.error (catchError.js:29)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at ThrowIfEmptySubscriber._error (Subscriber.js:75)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41632)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)

And also the router-outlet doesn't work for me for some reason, it just shows blank even if I have some content in my Route Components.

This is my app-routing.module.ts:

import { CrCalculatorPageComponent } from './../pages/cr-calculator-page/cr-calculator-page.component';
import { HomePageComponent } from './../pages/home-page/home-page.component';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

export const routes: Routes = [
  {
    path: '',
    data: {
      linkName: 'Home',
      showInMenu: true,
      animation: 'HomePage'
    },
    component: HomePageComponent
  },
  {
    path: 'cr-calculator',
    data: {
      linkName: 'CR Calculator',
      showInMenu: true,
      animation: 'CrCalculator'
    },
    component: CrCalculatorPageComponent
  }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

... and this is my app.module.ts:

import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { CrCalculatorPageComponent } from './pages/cr-calculator-page/cr-calculator-page.component';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavMenuComponent,
    HomePageComponent,
    CrCalculatorPageComponent
  ],
  imports: [
    BrowserModule,
    RouterModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I have multi-checked my code and not found anything. I have also checked out some answered Questions here already but nothing helped me solving my issue.

Thanks in advance and please tell me if you need some more code to review the issue.

// EDIT

HTML-Code with routerLink Statements:

  <ng-container *ngFor="let link of links">

      {{link.data.linkName}}

  </ng-container>

'links' is basically the routes Object-Array from the app-routing.module.ts


问:
Find longest squential streak in arraylist java
I am trying to write a code in java where suppose i have an arraylist of (1,3,4,5,8,9,11,12,13,14,15)

i need the code to analyze the longest streak of consecutive numbers in the arraylist. From the above arraylist 11,12,13,14,15 is the longest streak so the code should give this in the output in form of another arraylist.

the code should be executed on any ArrayList consisting of different numbers

actually, i have made the code where i have come up to the point of extracting index of postive values from a bigger arraylist and stored it in another arraylist. Now, im stuck at finding the longest streak of consecutive numbers in the newly made arraylist.

Here is my code:

List<Integer> mega = new ArrayList<Integer>();
for (int i = 0; i <= data.size() - 1; i++) {
    double a = (data.get(i).adjClose) - (data.get(i).open); //calculating a value
    if (a > 0) { // if value is bigger than zero, then store the index of that element in a new arraylist
        mega.add(i);
    }
}
```

答:
```<code>ArrayList<Integer> bigger = new ArrayList<>();
for (int x = 0; x < numbers.size(); x++) {
  int current = numbers.get(x);
  ArrayList<Integer> temp = new ArrayList<>();
  temp.add(current);
  for (int y = x + 1; y < numbers.size(); y++) {
    int nextValue = numbers.get(y);
    if (nextValue == current + 1) {
      temp.add(nextValue);
      current = nextValue;
    }
    else {
      break;
    }
  }

  if (temp.size() > bigger.size()) {
    bigger.clear();
    bigger.addAll(temp);
  }
}
</code>```

numbers is the ArraList of your numbers and
Inside bigger is your sequence.

Body:
ArrayList<Integer> bigger = new ArrayList<>();
for (int x = 0; x < numbers.size(); x++) {
  int current = numbers.get(x);
  ArrayList<Integer> temp = new ArrayList<>();
  temp.add(current);
  for (int y = x + 1; y < numbers.size(); y++) {
    int nextValue = numbers.get(y);
    if (nextValue == current + 1) {
      temp.add(nextValue);
      current = nextValue;
    }
    else {
      break;
    }
  }

  if (temp.size() > bigger.size()) {
    bigger.clear();
    bigger.addAll(temp);
  }
}

numbers is the ArraList of your numbers and
Inside bigger is your sequence.


问:
How to align the widgets to the right in single column?
I want the widgets to align right but a single column used. Is there another way to align these items?

Code:

```<code>Column(LayoutPadding(20.dp)) {
    Align(alignment = Alignment.TopRight) {
        Text(text = "0")
        Text(text = "testOperation")
    }
}
</code>```

Result:

```<code>(RIGHT ALIGNED) 0

</code>```

Expected:

```<code>(RIGHT ALIGNED) 0
(RIGHT ALIGNED) testOperation
</code>```

答:
With 1.0.0-beta03 just use something like:

```<code>Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.End
) {
    Column (){
        Text(
                text = "First item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Second item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Third item",
                modifier = Modifier.padding(16.dp)
        )
    }
}
</code>```

Body:
I want the widgets to align right but a single column used. Is there another way to align these items?

Code:

Column(LayoutPadding(20.dp)) {
    Align(alignment = Alignment.TopRight) {
        Text(text = "0")
        Text(text = "testOperation")
    }
}

Result:

(RIGHT ALIGNED) 0

Expected:

(RIGHT ALIGNED) 0
(RIGHT ALIGNED) testOperation

Body:
With 1.0.0-beta03 just use something like:

Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.End
) {
    Column (){
        Text(
                text = "First item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Second item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Third item",
                modifier = Modifier.padding(16.dp)
        )
    }
}


问:
Can you use 2 or more OR conditions in an if statement?
I tried to test this myself before asking on the forum but my simple code to test this didn't seem to work.

```<code>#include <iostream>
using namespace std;

int main() {
cout << "Enter int: ";
int number;
cin >> number;
if (number==1||2||3) {
    cout << "Your number was 1, 2, or 3." << endl;
}
else if (number==4||5||6) {
    cout << "Your number was 4, 5, or 6." << endl;
}
else {
    cout << "Your number was above 6." << endl;
}
return 0;
}
</code>```

It always returns the first condition. My question is, is it even possible to have more than 2 OR conditions? Or is my syntax incorrect?

答:
You have to compare like this

if (number == 1 || number ==2 || number == 3){...}
You have to put number == every time you compare it.

A Pro Tip
Always initialise variables, int number{0};
Don't declare var without initialising them.

Body:
I tried to test this myself before asking on the forum but my simple code to test this didn't seem to work.

#include <iostream>
using namespace std;

int main() {
cout << "Enter int: ";
int number;
cin >> number;
if (number==1||2||3) {
    cout << "Your number was 1, 2, or 3." << endl;
}
else if (number==4||5||6) {
    cout << "Your number was 4, 5, or 6." << endl;
}
else {
    cout << "Your number was above 6." << endl;
}
return 0;
}

It always returns the first condition. My question is, is it even possible to have more than 2 OR conditions? Or is my syntax incorrect?


问:
Explode multiple columns in Spark SQL table
There was a question regarding this issue here:

Explode (transpose?) multiple columns in Spark SQL table

Suppose that we have extra columns as below:

```<code>**userId    someString      varA     varB      varC    varD**
   1        "example1"    [0,2,5]   [1,2,9]    [a,b,c] [red,green,yellow]
   2        "example2"    [1,20,5]  [9,null,6] [d,e,f] [white,black,cyan]
</code>```

To conclude an output like below:

```<code>userId    someString      varA     varB   varC     varD
   1      "example1"       0         1     a       red
   1      "example1"       2         2     b       green
   1      "example1"       5         9     c       yellow
   2      "example2"       1         9     d       white
   2      "example2"       20       null   e       black
   2      "example2"       5         6     f       Cyan
</code>```

The answer was by defining a udf as:

```<code>val zip = udf((xs: Seq[Long], ys: Seq[Long]) => xs.zip(ys))
</code>```

and defining "withColumn".

```<code>df.withColumn("vars", explode(zip($"varA", $"varB"))).select(
   $"userId", $"someString",
   $"vars._1".alias("varA"), $"vars._2".alias("varB")).show
</code>```

If we need to extend the above answer, with more columns, what is the easiest way to amend the above code. Any help please.

答:
If you want to extend the UDF for more columns, do as below:

```<code>val zip = udf((xs: Seq[String], ys: Seq[String], zs: Seq[String]) =>
  for (((xs,ys),zs) <- xs zip ys zip zs) yield (xs,ys,zs))

df.withColumn("vars", explode(zip($"varA", $"varB", $"varC"))).select(
  $"userId", $"someString", $"vars._1".alias("varA"),
  $"vars._2".alias("varB"),$"vars._3".alias("varC")).show
</code>```

This logic can be applied for n columns as required.

ContentLicense: CC BY-SA 3.0

Body:
There was a question regarding this issue here:

Explode (transpose?) multiple columns in Spark SQL table

Suppose that we have extra columns as below:

**userId    someString      varA     varB      varC    varD**
   1        "example1"    [0,2,5]   [1,2,9]    [a,b,c] [red,green,yellow]
   2        "example2"    [1,20,5]  [9,null,6] [d,e,f] [white,black,cyan]

To conclude an output like below:

userId    someString      varA     varB   varC     varD
   1      "example1"       0         1     a       red
   1      "example1"       2         2     b       green
   1      "example1"       5         9     c       yellow
   2      "example2"       1         9     d       white
   2      "example2"       20       null   e       black
   2      "example2"       5         6     f       Cyan

The answer was by defining a udf as:

val zip = udf((xs: Seq[Long], ys: Seq[Long]) => xs.zip(ys))

and defining "withColumn".

df.withColumn("vars", explode(zip($"varA", $"varB"))).select(
   $"userId", $"someString",
   $"vars._1".alias("varA"), $"vars._2".alias("varB")).show

If we need to extend the above answer, with more columns, what is the easiest way to amend the above code. Any help please.

Body:
If you want to extend the UDF for more columns, do as below:

val zip = udf((xs: Seq[String], ys: Seq[String], zs: Seq[String]) =>
  for (((xs,ys),zs) <- xs zip ys zip zs) yield (xs,ys,zs))

df.withColumn("vars", explode(zip($"varA", $"varB", $"varC"))).select(
  $"userId", $"someString", $"vars._1".alias("varA"),
  $"vars._2".alias("varB"),$"vars._3".alias("varC")).show

This logic can be applied for n columns as required.


问:
Dynamic query in LINQ
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

```<code>string name
string address
int phoneno
</code>```

I have to query based on information given similar to

```<code>query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;
</code>```

Edit #1:

the items are changeable at run time like

```<code>private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}
</code>```

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

```<code>var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}
</code>```

This yeilds Empty, where as i used this

```<code>var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);
</code>```

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

```<code>for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}
</code>```

What is the mistake here?

答:
You can use the fluent interface and add a new Where clause fpr each condition. Something like:

```<code> var result = from cus in customers select cus;
 if(!string.IsNullOrEmpty(name))
         result= result.Where(p => p.Name == name);
</code>```

EDIT upon hte comment:

if you are querying over a collection in memory, you could retrieve the properties using reflection.

```<code>private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
      var result = from cus in customers select cus;

      foreach(string key in attributes.Keys)
             result= result.Where(p => GetProperty(p, key )== attributes[key]);

         return result.ToList();
}
</code>```

Supposing GetProperty retrieve the property by reflection.

Using Linq2Sql this method will result in retrieving all record an then iterating over them using reflection.

OwnerDisplayName: Mohanavel

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Title: Dynamic query in LINQ

Body:
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to query based on information given similar to

query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;

Edit #1:

the items are changeable at run time like

private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}

This yeilds Empty, where as i used this

var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}

What is the mistake here?

Body:
You can use the fluent interface and add a new Where clause fpr each condition. Something like:

 var result = from cus in customers select cus;
 if(!string.IsNullOrEmpty(name))
         result= result.Where(p => p.Name == name);

EDIT upon hte comment:

if you are querying over a collection in memory, you could retrieve the properties using reflection.

private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
      var result = from cus in customers select cus;

      foreach(string key in attributes.Keys)
             result= result.Where(p => GetProperty(p, key )== attributes[key]);

         return result.ToList();
}

Supposing GetProperty retrieve the property by reflection.

Using Linq2Sql this method will result in retrieving all record an then iterating over them using reflection.

OwnerDisplayName: Mouk

LastEditorDisplayName: Mouk


问:
.innerHTML not working or am I using it wrong?
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

```<code><table width="90%" border="0" align="center" cellpadding="5" cellspacing="0">

  <tr>
    <td colspan="2" align="left">Via Email:</td>
    <td width="1070" align="right"></td>
  </tr>

  <script>
  $('#addEmail').click(function()       {
document.getElementById('emailList').innerHTML = "12345";
  });
  </script>

      <span  id="emailList">
   <tr>
    <td width="27" align="left"><img src="icon_mail.png" width="24" height="24"></td>
    <td width="228" align="left">123obama@whitehouse.com</td>
    <td align="right"><a href="#" id="dialog_link" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-close"></span>remove</a></td>
  </tr>
     </span>

  <tr>
    <td colspan="3" align="left"><br>
      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      <a href="#" id="addEmail" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-mail-closed"></span>Add Email</a></td>
    </tr>
</table>
</code>```

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

答:
The HTML is invalid — you can't wrap a
 in a . The browser is performing error recovery on your code and producing a DOM that isn't what you expect it to be. When you try to edit the content of the span, the span probably isn't where you think it is.

… you can't put a script between table rows either.

… and you are trying to bind an event handler to a link before the link exists in the document. You either need to move the script so it appears after the link, or move the code that does the work into an event handler that runs after the link exists (such as the ready event).

Body:
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

    Via Email:

    123obama@whitehouse.com
    remove

      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      Add Email

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

Body:
The HTML is invalid — you can't wrap a <tr> in a <span>. The browser is performing error recovery on your code and producing a DOM that isn't what you expect it to be. When you try to edit the content of the span, the span probably isn't where you think it is.

… you can't put a script between table rows either.

… and you are trying to bind an event handler to a link before the link exists in the document. You either need to move the script so it appears after the link, or move the code that does the work into an event handler that runs after the link exists (such as the ready event).


问:
Put/print mean of a variable to log in SAS
How do i print the mean of a variable to the log in SAS?

```<code>data fruit;
input zip fruit & $22. pounds;
datalines;
10034 apples, grapes kiwi  123456
92626  oranges  97654
25414 pears apple      987654
;
</code>```

This is what I've tried:

```<code>data _null_;
   set fruit;
   put mean(zip);
run;
</code>```

答:
In data step, you can use putlog statement to print the value on log. Based on @cherry_bueno 's answer, the putlog version is:

```<code>proc means data=fruit;
  var pounds;
  output out=testmean mean=fruit_mean;
run;

data _null_;
  set testmean;
  putlog 'mean of x is ' fruit_mean;
run;
</code>```

Body:
How do i print the mean of a variable to the log in SAS?

data fruit;
input zip fruit & $22. pounds;
datalines;
10034 apples, grapes kiwi  123456
92626  oranges  97654
25414 pears apple      987654
;

This is what I've tried:

data _null_;
   set fruit;
   put mean(zip);
run;

Body:
In data step, you can use putlog statement to print the value on log. Based on @cherry_bueno 's answer, the putlog version is:

proc means data=fruit;
  var pounds;
  output out=testmean mean=fruit_mean;
run;

data _null_;
  set testmean;
  putlog 'mean of x is ' fruit_mean;
run;


问:
Invariant Violation: A VirtualizedList contains a cell which itself contains more than one VirtualizedList
The complete error is:

Invariant Violation: A VirtualizedList contains a cell which itself
  contains more than one VirtualizedList of the same orientation as the
  parent list. You must pass a unique listKey prop to each sibling list.

Every single one of my FlatList components has a keyExtractor prop. Every item within the List from react-native-elements component has a key prop.

Could anyone shed any light on the meaning of this problem?

答:
I got this error. But fixed using unique string </p>

```<code>listKey={moment().valueOf().toString()}
</code>```

Body:
I got this error. But fixed using unique string

listKey={moment().valueOf().toString()}


问:
Pandonic way of adding two Series with respect to bin-membership of index

Setup

```<code>>>> import pandas as pd
>>> import numpy as np
>>> s1 = pd.Series([100, 1000, 10000], index=[0, 2, 5])
s1
0      100
2     1000
5    10000
dtype: int64
>>> s2 = pd.Series(np.arange(7)*10)
>>> s2
0     0
1    10
2    20
3    30
4    40
5    50
6    60
dtype: int32
</code>```

Assumptions:

The index of s1 is guaranteed to be monotonically increasing.

There is no index in s2 smaller than the minimum index of s1.

Clarification: The index of s2 cannot be assumed to have any particular order!

Desired result

I want to add the values of s1 to the values of s2 as follows (see comments for explanation):

```<code>>>> result
0      100 # 100 + 0, because index 0 is in [0, 2)
1      110 # 100 + 10, because index 1 is in [0, 2)
2     1020 # 1000 + 20, because index 2 is in [2, 5)
3     1030 # 1000 + 20, because index 3 is in [2, 5)
4     1040 # 1000 + 40, because index 4 is in [2, 5)
5    10050 # 10000 + 50, because index 5 is in [5, inf)
6    10060 # 10000 + 50, because index 6 is in [5, inf)
dtype: int64
</code>```

Attempt

I created versions of s1 and s2 where the bins are the index.

```<code>>>> edges = [*s1.index, np.inf]
>>> s1_binned = pd.Series(s1.values, index=pd.cut(s1.index, bins=edges, right=False))
>>> s2_binned = pd.Series(s2.values, index=pd.cut(s2.index, bins=edges, right=False))
s1_binned
[0.0, 2.0)      100
[2.0, 5.0)     1000
[5.0, inf)    10000
dtype: int64
>>> s2_binned
[0.0, 2.0)     0
[0.0, 2.0)    10
[2.0, 5.0)    20
[2.0, 5.0)    30
[2.0, 5.0)    40
[5.0, inf)    50
[5.0, inf)    60
dtype: int32
</code>```

Then I indexed into s1 with the index of s2 to get the values to add.

```<code>>>> to_add = s1_binned[s2_binned.index]
>>> to_add
[0.0, 2.0)      100
[0.0, 2.0)      100
[2.0, 5.0)     1000
[2.0, 5.0)     1000
[2.0, 5.0)     1000
[5.0, inf)    10000
[5.0, inf)    10000
dtype: int64
</code>```

Finally I can add the values of to_add to s2.

```<code>>>> s2 + to_add.values
0      100
1      110
2     1020
3     1030
4     1040
5    10050
6    10060
dtype: int64
</code>```

I have the feeling that there is a better solution, but I don't have much experience with "mapping" values to bins.

答:
Use Series.add with new Series created by Series.reindex with method='ffill':

```<code>s1 = s1.sort_index()
s2 = s2.sort_index()

s = s2.add(s1.reindex(s2.index, method='ffill'))
#similar solution
#s = s2.add(s1.reindex_like(s2, method='ffill'))
print (s)
0      100
1      110
2     1020
3     1030
4     1040
5    10050
6    10060
dtype: int64
</code>```

Body:
Setup

>>> import pandas as pd
>>> import numpy as np
>>> s1 = pd.Series([100, 1000, 10000], index=[0, 2, 5])
s1
0      100
2     1000
5    10000
dtype: int64
>>> s2 = pd.Series(np.arange(7)*10)
>>> s2
0     0
1    10
2    20
3    30
4    40
5    50
6    60
dtype: int32

Assumptions:

The index of s1 is guaranteed to be monotonically increasing.

There is no index in s2 smaller than the minimum index of s1.

Clarification: The index of s2 cannot be assumed to have any particular order!

Desired result

I want to add the values of s1 to the values of s2 as follows (see comments for explanation):

>>> result
0      100 # 100 + 0, because index 0 is in [0, 2)
1      110 # 100 + 10, because index 1 is in [0, 2)
2     1020 # 1000 + 20, because index 2 is in [2, 5)
3     1030 # 1000 + 20, because index 3 is in [2, 5)
4     1040 # 1000 + 40, because index 4 is in [2, 5)
5    10050 # 10000 + 50, because index 5 is in [5, inf)
6    10060 # 10000 + 50, because index 6 is in [5, inf)
dtype: int64

Attempt

I created versions of s1 and s2 where the bins are the index.

>>> edges = [*s1.index, np.inf]
>>> s1_binned = pd.Series(s1.values, index=pd.cut(s1.index, bins=edges, right=False))
>>> s2_binned = pd.Series(s2.values, index=pd.cut(s2.index, bins=edges, right=False))
s1_binned
[0.0, 2.0)      100
[2.0, 5.0)     1000
[5.0, inf)    10000
dtype: int64
>>> s2_binned
[0.0, 2.0)     0
[0.0, 2.0)    10
[2.0, 5.0)    20
[2.0, 5.0)    30
[2.0, 5.0)    40
[5.0, inf)    50
[5.0, inf)    60
dtype: int32

Then I indexed into s1 with the index of s2 to get the values to add.

>>> to_add = s1_binned[s2_binned.index]
>>> to_add
[0.0, 2.0)      100
[0.0, 2.0)      100
[2.0, 5.0)     1000
[2.0, 5.0)     1000
[2.0, 5.0)     1000
[5.0, inf)    10000
[5.0, inf)    10000
dtype: int64

Finally I can add the values of to_add to s2.

>>> s2 + to_add.values
0      100
1      110
2     1020
3     1030
4     1040
5    10050
6    10060
dtype: int64

I have the feeling that there is a better solution, but I don't have much experience with "mapping" values to bins.

Body:
Use Series.add with new Series created by Series.reindex with method='ffill':

s1 = s1.sort_index()
s2 = s2.sort_index()

s = s2.add(s1.reindex(s2.index, method='ffill'))
#similar solution
#s = s2.add(s1.reindex_like(s2, method='ffill'))
print (s)
0      100
1      110
2     1020
3     1030
4     1040
5    10050
6    10060
dtype: int64


问:
FFmpeg on Android
I have got FFmpeg compiled (libffmpeg.so) on Android. Now I have to build either an application like RockPlayer or use existing Android multimedia framework to invoke FFmpeg.

Do you have steps / procedures / code / example on integrating FFmpeg on Android / StageFright?

Can you please guide me on how can I use this library for multimedia playback?

I have a requirement where I have already audio and video transport streams, which I need to feed to FFmpeg and get it decoded / rendered. How can I do this on Android, since IOMX APIs are OMX based and cannot plug-in FFmpeg here?

Also I could not find documentation on the FFmpeg APIs which need to be used for playback.

答:
First, add the dependency of FFmpeg library

```<code>implementation 'com.writingminds:FFmpegAndroid:0.3.2'
</code>```

Then load in activity

```<code>FFmpeg ffmpeg;
    private void trimVideo(ProgressDialog progressDialog) {

    outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
            + "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
            + "filter_apply.mp4";

    if (startTrim.equals("")) {
        startTrim = "00:00:00";
    }

    if (endTrim.equals("")) {
        endTrim = timeTrim(player.getDuration());
    }

    String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};

    execFFmpegBinary1(cmd, progressDialog);
    }

    private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {

    ProgressDialog progressDialog = prpg;

    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                progressDialog.dismiss();
                Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS wgith output : " + s);

//                    pathVideo = outputAudioMux;
                String finalPath = outputAudioMux;
                videoPath = outputAudioMux;
                Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
                intent.putExtra("pathGPU", finalPath);
                startActivity(intent);
                finish();
                MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);

            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started gcommand : ffmpeg " + command);
                progressDialog.setMessage("Please Wait video triming...");
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Startedf command : ffmpeg " + command);

            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished f command : ffmpeg " + command);
                progressDialog.dismiss();
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now
    }
}

  private void loadFFMpegBinary() {
    try {
        if (ffmpeg == null) {
            ffmpeg = FFmpeg.getInstance(this);
        }
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
            @Override
            public void onFailure() {
                showUnsupportedExceptionDialog();
            }

            @Override
            public void onSuccess() {
                Log.d("dd", "ffmpeg : correct Loaded");
            }
        });
    } catch (FFmpegNotSupportedException e) {
        showUnsupportedExceptionDialog();
    } catch (Exception e) {
        Log.d("dd", "EXception no controlada : " + e);
    }
}

private void showUnsupportedExceptionDialog() {
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Not Supported")
            .setMessage("Device Not Supported")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .create()
            .show();

}
    public String timeTrim(long milliseconds) {
        String finalTimerString = "";
        String minutString = "";
        String secondsString = "";

        // Convert total duration into time
        int hours = (int) (milliseconds / (1000 * 60 * 60));
        int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
        int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
        // Add hours if there

        if (hours < 10) {
            finalTimerString = "0" + hours + ":";
        } else {
            finalTimerString = hours + ":";
        }

        if (minutes < 10) {
            minutString = "0" + minutes;
        } else {
            minutString = "" + minutes;
        }

        // Prepending 0 to seconds if it is one digit
        if (seconds < 10) {
            secondsString = "0" + seconds;
        } else {
            secondsString = "" + seconds;
        }

        finalTimerString = finalTimerString + minutString + ":" + secondsString;

        // return timer string
        return finalTimerString;
    }
</code>```

Also use another feature by FFmpeg

```<code>===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};

===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};

===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};

===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};

===> Add two mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()

===> Add three mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
</code>```

Title: FFmpeg on Android

Body:
First, add the dependency of FFmpeg library

implementation 'com.writingminds:FFmpegAndroid:0.3.2'

Then load in activity

FFmpeg ffmpeg;
    private void trimVideo(ProgressDialog progressDialog) {

    outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
            + "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
            + "filter_apply.mp4";

    if (startTrim.equals("")) {
        startTrim = "00:00:00";
    }

    if (endTrim.equals("")) {
        endTrim = timeTrim(player.getDuration());
    }

    String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};

    execFFmpegBinary1(cmd, progressDialog);
    }

    private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {

    ProgressDialog progressDialog = prpg;

    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                progressDialog.dismiss();
                Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS wgith output : " + s);

//                    pathVideo = outputAudioMux;
                String finalPath = outputAudioMux;
                videoPath = outputAudioMux;
                Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
                intent.putExtra("pathGPU", finalPath);
                startActivity(intent);
                finish();
                MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);

            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started gcommand : ffmpeg " + command);
                progressDialog.setMessage("Please Wait video triming...");
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Startedf command : ffmpeg " + command);

            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished f command : ffmpeg " + command);
                progressDialog.dismiss();
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now
    }
}

  private void loadFFMpegBinary() {
    try {
        if (ffmpeg == null) {
            ffmpeg = FFmpeg.getInstance(this);
        }
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
            @Override
            public void onFailure() {
                showUnsupportedExceptionDialog();
            }

            @Override
            public void onSuccess() {
                Log.d("dd", "ffmpeg : correct Loaded");
            }
        });
    } catch (FFmpegNotSupportedException e) {
        showUnsupportedExceptionDialog();
    } catch (Exception e) {
        Log.d("dd", "EXception no controlada : " + e);
    }
}

private void showUnsupportedExceptionDialog() {
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Not Supported")
            .setMessage("Device Not Supported")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .create()
            .show();

}
    public String timeTrim(long milliseconds) {
        String finalTimerString = "";
        String minutString = "";
        String secondsString = "";

        // Convert total duration into time
        int hours = (int) (milliseconds / (1000 * 60 * 60));
        int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
        int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
        // Add hours if there

        if (hours < 10) {
            finalTimerString = "0" + hours + ":";
        } else {
            finalTimerString = hours + ":";
        }

        if (minutes < 10) {
            minutString = "0" + minutes;
        } else {
            minutString = "" + minutes;
        }

        // Prepending 0 to seconds if it is one digit
        if (seconds < 10) {
            secondsString = "0" + seconds;
        } else {
            secondsString = "" + seconds;
        }

        finalTimerString = finalTimerString + minutString + ":" + secondsString;

        // return timer string
        return finalTimerString;
    }

Also use another feature by FFmpeg

===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};

===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};

===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};

===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};

===> Add two mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()

===> Add three mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()


问:
Preventing ExoPlayer used via video_player in Flutter from spamming the logs
Whenever I play a new file in my video_player I get a long list of logs which makes it a lot harder to see my own logging. A lot of it with Logging value info and hi Is there a way to make the video_player a lot less chatty?</p>

```<code>I/ExoPlayerImpl(21717): Init d44ef38 [ExoPlayerLib/2.9.6] [crosshatch, Pixel 3 XL, Google, 29]
W/MetadataUtil(21717): Failed to parse index/count attribute: trkn
D/CCodec  (21717): allocate(c2.qti.avc.decoder)
I/Codec2Client(21717): Creating a Codec2 client to service "default"
I/Codec2Client(21717): Client to Codec2 service "default" created
I/CCodec  (21717): setting up 'default' as default (vendor) store
I/CCodec  (21717): Created component [c2.qti.avc.decoder]
D/CCodecConfig(21717): read media type: video/avc
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.pool-ids.values
D/CCodecConfig(21717): ignoring local param raw.size (0xd2001800) as it is already supported
D/CCodecConfig(21717): ignoring local param raw.color (0xd2001809) as it is already supported
D/CCodecConfig(21717): ignoring local param raw.hdr-static-info (0xd200180a) as it is already supported
I/CCodecConfig(21717): query failed after returning 17 values (BAD_INDEX)
D/CCodecConfig(21717): c2 config diff is Dict {
D/CCodecConfig(21717):   c2::i32 algo.priority.value = -1
D/CCodecConfig(21717):   c2::float algo.rate.value = 4.2039e-44
D/CCodecConfig(21717):   c2::u32 algo.secure-mode.value = 0
D/CCodecConfig(21717):   c2::float coded.frame-rate.value = 30
D/CCodecConfig(21717):   c2::u32 coded.pl.level = 20480
D/CCodecConfig(21717):   c2::u32 coded.pl.profile = 20480
D/CCodecConfig(21717):   c2::u32 coded.vui.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.primaries = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.range = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.transfer = 0
D/CCodecConfig(21717):   c2::u32 default.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 default.color.primaries = 3
D/CCodecConfig(21717):   c2::u32 default.color.range = 2
D/CCodecConfig(21717):   c2::u32 default.color.transfer = 0
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 13271040
D/CCodecConfig(21717):   c2::u32 input.delay.value = 4
D/CCodecConfig(21717):   string input.media-type.value = "video/avc"
D/CCodecConfig(21717):   c2::u32 output.delay.value = 18
D/CCodecConfig(21717):   string output.media-type.value = "video/raw"
D/CCodecConfig(21717):   c2::u32 raw.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 raw.color.primaries = 0
D/CCodecConfig(21717):   c2::u32 raw.color.range = 0
D/CCodecConfig(21717):   c2::u32 raw.color.transfer = 0
D/CCodecConfig(21717):   c2::float raw.hdr-static-info.mastering.blue.x = 1.4013e-45
D/CCodecConfig(21717):   c2::float raw.hdr-static-info.mastering.blue.y = 1.4013e-45
D/CCodecConfig(21717):   c2::float raw.hdr-
W/ColorUtils(21717): expected specified color aspects (0:0:0:0)
D/SurfaceUtils(21717): connecting to surface 0x7669bd6010, reason connectToSurface
I/MediaCodec(21717): [c2.qti.avc.decoder] setting surface generation to 22238212
D/SurfaceUtils(21717): disconnecting from surface 0x7669bd6010, reason connectToSurface(reconnect)
D/SurfaceUtils(21717): connecting to surface 0x7669bd6010, reason connectToSurface(reconnect)
D/CCodecConfig(21717): no c2 equivalents for csd-1
D/CCodecConfig(21717): no c2 equivalents for native-window
D/CCodecConfig(21717): c2 config diff is   c2::i32 algo.priority.value = 0
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 393216
D/CCodecConfig(21717):   c2::u32 raw.max-size.height = 450
D/CCodecConfig(21717):   c2::u32 raw.max-size.width = 500
D/CCodecConfig(21717):   c2::u32 raw.pixel-format.value = 34
D/CCodecConfig(21717):   c2::u32 raw.size.height = 450
D/CCodecConfig(21717):   c2::u32 raw.size.width = 500
W/Codec2Client(21717): query -- param skipped: index = 1107298332.
D/CCodec  (21717): client requested max input size 6306, which is smaller than what component recommended (393216); overriding with component recommendation.
W/CCodec  (21717): This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
D/CCodec  (21717): setup formats input: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t feature-secure-playback = 0
D/CCodec  (21717):   int32_t frame-rate = 30
D/CCodec  (21717):   int32_t height = 450
D/CCodec  (21717):   int32_t level = 1
D/CCodec  (21717):   int32_t max-input-size = 393216
D/CCodec  (21717):   string mime = "video/avc"
D/CCodec  (21717):   int32_t priority = 0
D/CCodec  (21717):   int32_t profile = 1
D/CCodec  (21717):   int32_t width = 500
D/CCodec  (21717):   Rect crop(0, 0, 499, 449)
D/CCodec  (21717): } and output: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t android._video-scaling = 1
D/CCodec  (21717):   Rect crop(0, 0, 499, 449)
D/CCodec  (21717):   int32_t color-standard = 2
D/CCodec  (21717):   int32_t color-range = 2
D/CCodec  (21717):   int32_t color-transfer = 3
D/CCodec  (21717):   int32_t android._dataspace = 258
D/CCodec  (21717):   int32_t width = 500
D/CCodec  (21717):   int32_t feature-secure-playback = 0
D/CCodec  (21717):   int32_t frame-rate = 30
D/CCodec  (21717):   int32_t height = 450
D/CCodec  (21717):   int32_t max-height = 450
D/CCodec  (21717):   int32_t max-width = 500
D/CCodec  (21717):   string mime = "video/raw"
D/CCodec  (21717):   int32_t priority = 0
D/CCodec  (21717):   int32_t rotation-degrees = 0
D/CCodec  (21717):   Buffer hdr-static-info = {
D/CCodec  (21717):     00000000:  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................
D/CCodec  (21717):     00000010:  00 00 00 00 00 00 00 00  00                       .........
D/CCodec  (21717):   }
D/CCodec  (21717):   int32_t android._color-format = 21307083
W/Codec2Client(21717): query -- param skipped: index = 1342179345.
W/Codec2Client(21717): query -- param skipped: index = 2415921170.
W/Codec2Client(21717): query -- param skipped: index = 1610614798.
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query input allocators returned 0 params => BAD_INDEX (6)
D/BufferPoolAccessor(21717): bufferpool2 0x76406c5620 : 8(3145728 size) total buffers - 8(3145728 size) used buffers - 0/8 (recycle/alloc) - 8/77 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x7668ace020 : 5(40960 size) total buffers - 5(40960 size) used buffers - 1/7 (recycle/alloc) - 6/129 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x76408a3020 : 10(3932160 size) total buffers - 10(3932160 size) used buffers - 0/12 (recycle/alloc) - 12/77 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x76c4dcd820 : 6(49152 size) total buffers - 5(40960 size) used buffers - 1/7 (recycle/alloc) - 6/129 (fetch/transfer)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Created input block pool with allocatorID 16 => poolID 23 - OK (0)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query output allocators returned 0 params => BAD_INDEX (6)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query output surface allocator returned 0 params => BAD_INDEX (6)
I/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Created output block pool with allocatorID 18 => poolID 68 - OK
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Configured output block pool ids 68 => OK
D/Codec2-block_helper(21717): remote graphic buffer migration 0/0
D/Codec2Client(21717): generation remote change 22238212
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76c468f220 cached: 0/0M, 0/0% in use; allocs: 8, 0% recycled; transfers: 77, 90% unfetced
D/CCodec  (21717): allocate(c2.android.aac.decoder)
I/Codec2Client(21717): Creating a Codec2 client to service "default"
I/Codec2Client(21717): Client to Codec2 service "default" created
I/CCodec  (21717): setting up 'default' as default (vendor) store
I/CCodec  (21717): Created component [c2.android.aac.decoder]
D/CCodecConfig(21717): read media type: audio/mp4a-latm
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.max-count.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.subscribed-indices.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: input.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.pool-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.pool-ids.values
D/CCodecConfig(21717): c2 config diff is   c2::u32 raw.color.primaries = 3
D/CCodecConfig(21717):   c2::u32 raw.color.range = 2
D/CCodecConfig(21717):   c2::u32 raw.crop.height = 450
D/CCodecConfig(21717):   c2::u32 raw.crop.left = 0
D/CCodecConfig(21717):   c2::u32 raw.crop.top = 0
D/CCodecConfig(21717):   c2::u32 raw.crop.width = 500
I/CCodecConfig(21717): query failed after returning 16 values (BAD_INDEX)
D/CCodecConfig(21717): c2 config diff is Dict {
D/CCodecConfig(21717):   c2::u32 coded.aac-packaging.value = 0
D/CCodecConfig(21717):   c2::u32 coded.bitrate.value = 64000
D/CCodecConfig(21717):   c2::u32 coded.pl.level = 0
D/CCodecConfig(21717):   c2::u32 coded.pl.profile = 8192
D/CCodecConfig(21717):   c2::float coding.drc.attenuation-factor.value = 1
D/CCodecConfig(21717):   c2::float coding.drc.boost-factor.value = 1
D/CCodecConfig(21717):   c2::i32 coding.drc.compression-mode.value = 3
D/CCodecConfig(21717):   c2::i32 coding.drc.effect-type.value = 3
D/CCodecConfig(21717):   c2::float coding.drc.encoded-level.value = 0.25
D/CCodecConfig(21717):   c2::float coding.drc.reference-level.value = -16
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 8192
D/CCodecConfig(21717):   c2::u32 input.delay.value = 0
D/CCodecConfig(21717):   string input.media-type.value = "audio/mp4a-latm"
D/CCodecConfig(21717):   c2::u32 output.delay.value = 2
D/CCodecConfig(21717):   string output.media-type.value = "audio/raw"
D/CCodecConfig(21717):   c2::u32 raw.channel-count.value = 1
D/CCodecConfig(21717):   c2::u32 raw.sample-rate.value = 44100
D/CCodecConfig(21717): }
D/CCodecConfig(21717): config failed => CORRUPTED
D/CCodecConfig(21717): c2 config diff is   c2::u32 raw.channel-count.value = 2
W/Codec2Client(21717): query -- param skipped: index = 1107298332.
D/CCodec  (21717): client requested max input size 399, which is smaller than what component recommended (8192); overriding with component recommendation.
W/CCodec  (21717): This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
D/CCodec  (21717): setup formats input: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t channel-count = 2
D/CCodec  (21717):   int32_t level = 0
D/CCodec  (21717):   int32_t max-input-size = 8192
D/CCodec  (21717):   string mime = "audio/mp4a-latm"
D/CCodec  (21717):   int32_t profile = 2
D/CCodec  (21717):   int32_t sample-rate = 44100
D/CCodec  (21717): } and output: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t channel-count = 2
D/CCodec  (21717):   string mime = "audio/raw"
D/CCodec  (21717):   int32_t sample-rate = 44100
D/CCodec  (21717): }
W/Codec2Client(21717): query -- param skipped: index = 1342179345.
W/Codec2Client(21717): query -- param skipped: index = 2415921170.
W/Codec2Client(21717): query -- param skipped: index = 1610614798.
D/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Created input block pool with allocatorID 16 => poolID 24 - OK (0)
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76c4d5c420 cached: 0/0M, 0/0% in use; allocs: 7, 14% recycled; transfers: 129, 95% unfetced
I/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Created output block pool with allocatorID 16 => poolID 78 - OK
D/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Configured output block pool ids 78 => OK
D/AudioTrack(21717): getTimestamp_l(414): device stall time corrected using current time 13946010578548
W/AudioTrack(21717): getTimestamp_l(414): retrograde timestamp time corrected, 13946013355111 < 13946020549903
I/ExoPlayerImpl(21717): Release c26b052 [ExoPlayerLib/2.9.6] [crosshatch, Pixel 3 XL, Google, 29] [goog.exo.core]
D/SurfaceUtils(21717): disconnecting from surface 0x76bfc5e010, reason disconnectFromSurface
E/BufferQueueProducer(21717): [SurfaceTexture-0-21717-1] detachBuffer: BufferQueue has been abandoned
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76406c5620 cached: 0/0M, 0/0% in use; allocs: 8, 0% recycled; transfers: 77, 90% unfetced
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x7668ace020 cached: 0/0M, 0/0% in use; allocs: 7, 14% recycled; transfers: 129, 95% unfetced
D/AudioTrack(21717): stop(414): called with 129024 frames delivered
</code>```

答:
Exoplayer provider a class to config Log.
https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/util/Log.html

You can try:

1, Add implement to your gradle of module android.

```<code>implementation 'com.google.android.exoplayer:exoplayer-core:2.9.6'
</code>```

2, Config Log on MainActivity

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.setLogLevel(LOG_LEVEL_OFF)
}
</code>```

Hope it helps!

Body:
Whenever I play a new file in my video_player I get a long list of logs which makes it a lot harder to see my own logging. A lot of it with Logging value info and hi Is there a way to make the video_player a lot less chatty?

I/ExoPlayerImpl(21717): Init d44ef38 [ExoPlayerLib/2.9.6] [crosshatch, Pixel 3 XL, Google, 29]
W/MetadataUtil(21717): Failed to parse index/count attribute: trkn
D/CCodec  (21717): allocate(c2.qti.avc.decoder)
I/Codec2Client(21717): Creating a Codec2 client to service "default"
I/Codec2Client(21717): Client to Codec2 service "default" created
I/CCodec  (21717): setting up 'default' as default (vendor) store
I/CCodec  (21717): Created component [c2.qti.avc.decoder]
D/CCodecConfig(21717): read media type: video/avc
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.pool-ids.values
D/CCodecConfig(21717): ignoring local param raw.size (0xd2001800) as it is already supported
D/CCodecConfig(21717): ignoring local param raw.color (0xd2001809) as it is already supported
D/CCodecConfig(21717): ignoring local param raw.hdr-static-info (0xd200180a) as it is already supported
I/CCodecConfig(21717): query failed after returning 17 values (BAD_INDEX)
D/CCodecConfig(21717): c2 config diff is Dict {
D/CCodecConfig(21717):   c2::i32 algo.priority.value = -1
D/CCodecConfig(21717):   c2::float algo.rate.value = 4.2039e-44
D/CCodecConfig(21717):   c2::u32 algo.secure-mode.value = 0
D/CCodecConfig(21717):   c2::float coded.frame-rate.value = 30
D/CCodecConfig(21717):   c2::u32 coded.pl.level = 20480
D/CCodecConfig(21717):   c2::u32 coded.pl.profile = 20480
D/CCodecConfig(21717):   c2::u32 coded.vui.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.primaries = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.range = 0
D/CCodecConfig(21717):   c2::u32 coded.vui.color.transfer = 0
D/CCodecConfig(21717):   c2::u32 default.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 default.color.primaries = 3
D/CCodecConfig(21717):   c2::u32 default.color.range = 2
D/CCodecConfig(21717):   c2::u32 default.color.transfer = 0
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 13271040
D/CCodecConfig(21717):   c2::u32 input.delay.value = 4
D/CCodecConfig(21717):   string input.media-type.value = "video/avc"
D/CCodecConfig(21717):   c2::u32 output.delay.value = 18
D/CCodecConfig(21717):   string output.media-type.value = "video/raw"
D/CCodecConfig(21717):   c2::u32 raw.color.matrix = 0
D/CCodecConfig(21717):   c2::u32 raw.color.primaries = 0
D/CCodecConfig(21717):   c2::u32 raw.color.range = 0
D/CCodecConfig(21717):   c2::u32 raw.color.transfer = 0
D/CCodecConfig(21717):   c2::float raw.hdr-static-info.mastering.blue.x = 1.4013e-45
D/CCodecConfig(21717):   c2::float raw.hdr-static-info.mastering.blue.y = 1.4013e-45
D/CCodecConfig(21717):   c2::float raw.hdr-
W/ColorUtils(21717): expected specified color aspects (0:0:0:0)
D/SurfaceUtils(21717): connecting to surface 0x7669bd6010, reason connectToSurface
I/MediaCodec(21717): [c2.qti.avc.decoder] setting surface generation to 22238212
D/SurfaceUtils(21717): disconnecting from surface 0x7669bd6010, reason connectToSurface(reconnect)
D/SurfaceUtils(21717): connecting to surface 0x7669bd6010, reason connectToSurface(reconnect)
D/CCodecConfig(21717): no c2 equivalents for csd-1
D/CCodecConfig(21717): no c2 equivalents for native-window
D/CCodecConfig(21717): c2 config diff is   c2::i32 algo.priority.value = 0
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 393216
D/CCodecConfig(21717):   c2::u32 raw.max-size.height = 450
D/CCodecConfig(21717):   c2::u32 raw.max-size.width = 500
D/CCodecConfig(21717):   c2::u32 raw.pixel-format.value = 34
D/CCodecConfig(21717):   c2::u32 raw.size.height = 450
D/CCodecConfig(21717):   c2::u32 raw.size.width = 500
W/Codec2Client(21717): query -- param skipped: index = 1107298332.
D/CCodec  (21717): client requested max input size 6306, which is smaller than what component recommended (393216); overriding with component recommendation.
W/CCodec  (21717): This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
D/CCodec  (21717): setup formats input: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t feature-secure-playback = 0
D/CCodec  (21717):   int32_t frame-rate = 30
D/CCodec  (21717):   int32_t height = 450
D/CCodec  (21717):   int32_t level = 1
D/CCodec  (21717):   int32_t max-input-size = 393216
D/CCodec  (21717):   string mime = "video/avc"
D/CCodec  (21717):   int32_t priority = 0
D/CCodec  (21717):   int32_t profile = 1
D/CCodec  (21717):   int32_t width = 500
D/CCodec  (21717):   Rect crop(0, 0, 499, 449)
D/CCodec  (21717): } and output: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t android._video-scaling = 1
D/CCodec  (21717):   Rect crop(0, 0, 499, 449)
D/CCodec  (21717):   int32_t color-standard = 2
D/CCodec  (21717):   int32_t color-range = 2
D/CCodec  (21717):   int32_t color-transfer = 3
D/CCodec  (21717):   int32_t android._dataspace = 258
D/CCodec  (21717):   int32_t width = 500
D/CCodec  (21717):   int32_t feature-secure-playback = 0
D/CCodec  (21717):   int32_t frame-rate = 30
D/CCodec  (21717):   int32_t height = 450
D/CCodec  (21717):   int32_t max-height = 450
D/CCodec  (21717):   int32_t max-width = 500
D/CCodec  (21717):   string mime = "video/raw"
D/CCodec  (21717):   int32_t priority = 0
D/CCodec  (21717):   int32_t rotation-degrees = 0
D/CCodec  (21717):   Buffer hdr-static-info = {
D/CCodec  (21717):     00000000:  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................
D/CCodec  (21717):     00000010:  00 00 00 00 00 00 00 00  00                       .........
D/CCodec  (21717):   }
D/CCodec  (21717):   int32_t android._color-format = 21307083
W/Codec2Client(21717): query -- param skipped: index = 1342179345.
W/Codec2Client(21717): query -- param skipped: index = 2415921170.
W/Codec2Client(21717): query -- param skipped: index = 1610614798.
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query input allocators returned 0 params => BAD_INDEX (6)
D/BufferPoolAccessor(21717): bufferpool2 0x76406c5620 : 8(3145728 size) total buffers - 8(3145728 size) used buffers - 0/8 (recycle/alloc) - 8/77 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x7668ace020 : 5(40960 size) total buffers - 5(40960 size) used buffers - 1/7 (recycle/alloc) - 6/129 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x76408a3020 : 10(3932160 size) total buffers - 10(3932160 size) used buffers - 0/12 (recycle/alloc) - 12/77 (fetch/transfer)
D/BufferPoolAccessor(21717): bufferpool2 0x76c4dcd820 : 6(49152 size) total buffers - 5(40960 size) used buffers - 1/7 (recycle/alloc) - 6/129 (fetch/transfer)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Created input block pool with allocatorID 16 => poolID 23 - OK (0)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query output allocators returned 0 params => BAD_INDEX (6)
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Query output surface allocator returned 0 params => BAD_INDEX (6)
I/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Created output block pool with allocatorID 18 => poolID 68 - OK
D/CCodecBufferChannel(21717): [c2.qti.avc.decoder#139] Configured output block pool ids 68 => OK
D/Codec2-block_helper(21717): remote graphic buffer migration 0/0
D/Codec2Client(21717): generation remote change 22238212
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76c468f220 cached: 0/0M, 0/0% in use; allocs: 8, 0% recycled; transfers: 77, 90% unfetced
D/CCodec  (21717): allocate(c2.android.aac.decoder)
I/Codec2Client(21717): Creating a Codec2 client to service "default"
I/Codec2Client(21717): Client to Codec2 service "default" created
I/CCodec  (21717): setting up 'default' as default (vendor) store
I/CCodec  (21717): Created component [c2.android.aac.decoder]
D/CCodecConfig(21717): read media type: audio/mp4a-latm
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.max-count.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.subscribed-indices.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: input.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.allocator-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: output.buffers.pool-ids.values
D/ReflectedParamUpdater(21717): extent() != 1 for single value type: algo.buffers.pool-ids.values
D/CCodecConfig(21717): c2 config diff is   c2::u32 raw.color.primaries = 3
D/CCodecConfig(21717):   c2::u32 raw.color.range = 2
D/CCodecConfig(21717):   c2::u32 raw.crop.height = 450
D/CCodecConfig(21717):   c2::u32 raw.crop.left = 0
D/CCodecConfig(21717):   c2::u32 raw.crop.top = 0
D/CCodecConfig(21717):   c2::u32 raw.crop.width = 500
I/CCodecConfig(21717): query failed after returning 16 values (BAD_INDEX)
D/CCodecConfig(21717): c2 config diff is Dict {
D/CCodecConfig(21717):   c2::u32 coded.aac-packaging.value = 0
D/CCodecConfig(21717):   c2::u32 coded.bitrate.value = 64000
D/CCodecConfig(21717):   c2::u32 coded.pl.level = 0
D/CCodecConfig(21717):   c2::u32 coded.pl.profile = 8192
D/CCodecConfig(21717):   c2::float coding.drc.attenuation-factor.value = 1
D/CCodecConfig(21717):   c2::float coding.drc.boost-factor.value = 1
D/CCodecConfig(21717):   c2::i32 coding.drc.compression-mode.value = 3
D/CCodecConfig(21717):   c2::i32 coding.drc.effect-type.value = 3
D/CCodecConfig(21717):   c2::float coding.drc.encoded-level.value = 0.25
D/CCodecConfig(21717):   c2::float coding.drc.reference-level.value = -16
D/CCodecConfig(21717):   c2::u32 input.buffers.max-size.value = 8192
D/CCodecConfig(21717):   c2::u32 input.delay.value = 0
D/CCodecConfig(21717):   string input.media-type.value = "audio/mp4a-latm"
D/CCodecConfig(21717):   c2::u32 output.delay.value = 2
D/CCodecConfig(21717):   string output.media-type.value = "audio/raw"
D/CCodecConfig(21717):   c2::u32 raw.channel-count.value = 1
D/CCodecConfig(21717):   c2::u32 raw.sample-rate.value = 44100
D/CCodecConfig(21717): }
D/CCodecConfig(21717): config failed => CORRUPTED
D/CCodecConfig(21717): c2 config diff is   c2::u32 raw.channel-count.value = 2
W/Codec2Client(21717): query -- param skipped: index = 1107298332.
D/CCodec  (21717): client requested max input size 399, which is smaller than what component recommended (8192); overriding with component recommendation.
W/CCodec  (21717): This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
D/CCodec  (21717): setup formats input: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t channel-count = 2
D/CCodec  (21717):   int32_t level = 0
D/CCodec  (21717):   int32_t max-input-size = 8192
D/CCodec  (21717):   string mime = "audio/mp4a-latm"
D/CCodec  (21717):   int32_t profile = 2
D/CCodec  (21717):   int32_t sample-rate = 44100
D/CCodec  (21717): } and output: AMessage(what = 0x00000000) = {
D/CCodec  (21717):   int32_t channel-count = 2
D/CCodec  (21717):   string mime = "audio/raw"
D/CCodec  (21717):   int32_t sample-rate = 44100
D/CCodec  (21717): }
W/Codec2Client(21717): query -- param skipped: index = 1342179345.
W/Codec2Client(21717): query -- param skipped: index = 2415921170.
W/Codec2Client(21717): query -- param skipped: index = 1610614798.
D/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Created input block pool with allocatorID 16 => poolID 24 - OK (0)
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76c4d5c420 cached: 0/0M, 0/0% in use; allocs: 7, 14% recycled; transfers: 129, 95% unfetced
I/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Created output block pool with allocatorID 16 => poolID 78 - OK
D/CCodecBufferChannel(21717): [c2.android.aac.decoder#582] Configured output block pool ids 78 => OK
D/AudioTrack(21717): getTimestamp_l(414): device stall time corrected using current time 13946010578548
W/AudioTrack(21717): getTimestamp_l(414): retrograde timestamp time corrected, 13946013355111 < 13946020549903
I/ExoPlayerImpl(21717): Release c26b052 [ExoPlayerLib/2.9.6] [crosshatch, Pixel 3 XL, Google, 29] [goog.exo.core]
D/SurfaceUtils(21717): disconnecting from surface 0x76bfc5e010, reason disconnectFromSurface
E/BufferQueueProducer(21717): [SurfaceTexture-0-21717-1] detachBuffer: BufferQueue has been abandoned
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x76406c5620 cached: 0/0M, 0/0% in use; allocs: 8, 0% recycled; transfers: 77, 90% unfetced
D/BufferPoolAccessor(21717): Destruction - bufferpool2 0x7668ace020 cached: 0/0M, 0/0% in use; allocs: 7, 14% recycled; transfers: 129, 95% unfetced
D/AudioTrack(21717): stop(414): called with 129024 frames delivered

Body:
Exoplayer provider a class to config Log.
https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/util/Log.html

You can try:

1, Add implement to your gradle of module android.

implementation 'com.google.android.exoplayer:exoplayer-core:2.9.6'

2, Config Log on MainActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.setLogLevel(LOG_LEVEL_OFF)
}

Hope it helps!


问:
Ionic 5 toastController doesn't show "close" button
I migrated from Ionic 4 to Ionic 5 and noticed my toastControllers are not showing the "close" button even if I set up the ToastOptions properties with showCloseButton: true

答:
I fixed it adding explicitly the buttons array like this:</p>

```<code>let toast = this.toastCtrl.create({
    message: 'User was added successfully',
    showCloseButton: true,
    position: 'top',
    buttons: [
          {
            text: "close",
            handler: () => {
              console.log('Close clicked');
            }
          }
        ]
  });
</code>```

Body:
I fixed it adding explicitly the buttons array like this:

let toast = this.toastCtrl.create({
    message: 'User was added successfully',
    showCloseButton: true,
    position: 'top',
    buttons: [
          {
            text: "close",
            handler: () => {
              console.log('Close clicked');
            }
          }
        ]
  });


问:
Can I filter options automatically on the Django Admin "add" page?
Consider a Word-A-Day Django webapp that presents the user with a vocabulary word each day, with the difficulty of the word increasing from "common" on Monday to "obscure" on Friday.

The models in models.py look like this:

```<code>class WordADay(models.Model):
    """A vocabulary word and its assigned day"""

    date = models.DateField(
        help_text="The date to post the selected word"
    )
    word = models.ForeignKey(
        Words,
        help_text="The selected vocabulary word"
    )

class Word(models.Model):
    """Vocabulary words"""

    OBSCURITY_CHOICES = [(1,'Monday'),
                         (2,'Tuesday'),
                         (3,'Wednesday'),
                         (4,'Thursday'),
                         (5,'Friday')]

    word = models.CharField(
        max_length=32,
        help_text="A vocabulary word"
    )
    difficulty = models.PositiveSmallIntegerField(
        choices=OBSCURITY_CHOICES,
        help_text="How obscure the word is"
    )
</code>```

On the Admin "add" page for the WordADay model, I want to be able to first select a day from the standard calendar selector for the 'date' field.  Once selected, I'd like the options in the drop-down selector for the 'word' field to be automatically filtered to only those instances of the Word model that have the correct difficulty, with "1" corresponding to a Monday date and "5" corresponding to a Friday date.  That is, I'd like to filter Foreign Key options according to the value selected for a different field.

For the sake of discussion, I can provide a skeleton admin.py

```<code>from django.contrib import admin
from .models import WordADay, Word
from django.db import models

@admin.register(WordADay)
class WordADayAdmin(admin.ModelAdmin):
    pass

@admin.register(Word)
class WordAdmin(admin.ModelAdmin):
    pass
</code>```

though of course it's not complete because I don't know what to put in it.

After a couple of hours of digging through the documentation I found the list_filter property, described as

Set list_filter to activate filters in the right sidebar of the change list page of the admin

This isn't what I want; I want a filter on the "add" page, not the "change" page, and I don't want a sidebar, I want the filter to be automatic once the date is selected.

Is this possible without creating a new AdminSite from scratch?

答:
It's not something that there is any built in functionality within the django-admin to do. However, you wouldn't have to quite go to the extents of creating a completely new admin site from scratch.

The best way to do this would be to use javascript to update the values of the relevant form values. You'll need to add an event listner on the change event of one of your inputs, and set it to update another one.

Because django-admin uses jquery in one or two places you have access to jquery for free, or it is relatively easy to do this with just plain javascript.

In terms of how you attach the javascript to this page you have two options:

load the javascript via your modelAdmin)

```<code>class MyAdmin(admin.ModelAdmin):
    class Media:
        js = ('js/my_script.js', ) # this should be a file from your static directory
</code>```

Extend the template.

```<code>class MyAdmin(admin.ModelAdmin):
    change_form_template = "my_template.html"
</code>```

then in my_template.html

```<code>{% extends "admin/change_form.html" %}
{% block %}
{% block extrahead %}
{{ block.super }}
  ... add your script here
{% endblock %}
</code>```

The advantage of the second option is that you can alter your script based on values loaded in through context, but this might not be necessary.

Body:
Consider a Word-A-Day Django webapp that presents the user with a vocabulary word each day, with the difficulty of the word increasing from "common" on Monday to "obscure" on Friday.

The models in models.py look like this:

class WordADay(models.Model):
    """A vocabulary word and its assigned day"""

    date = models.DateField(
        help_text="The date to post the selected word"
    )
    word = models.ForeignKey(
        Words,
        help_text="The selected vocabulary word"
    )

class Word(models.Model):
    """Vocabulary words"""

    OBSCURITY_CHOICES = [(1,'Monday'),
                         (2,'Tuesday'),
                         (3,'Wednesday'),
                         (4,'Thursday'),
                         (5,'Friday')]

    word = models.CharField(
        max_length=32,
        help_text="A vocabulary word"
    )
    difficulty = models.PositiveSmallIntegerField(
        choices=OBSCURITY_CHOICES,
        help_text="How obscure the word is"
    )

On the Admin "add" page for the WordADay model, I want to be able to first select a day from the standard calendar selector for the 'date' field.  Once selected, I'd like the options in the drop-down selector for the 'word' field to be automatically filtered to only those instances of the Word model that have the correct difficulty, with "1" corresponding to a Monday date and "5" corresponding to a Friday date.  That is, I'd like to filter Foreign Key options according to the value selected for a different field.

For the sake of discussion, I can provide a skeleton admin.py

from django.contrib import admin
from .models import WordADay, Word
from django.db import models

@admin.register(WordADay)
class WordADayAdmin(admin.ModelAdmin):
    pass

@admin.register(Word)
class WordAdmin(admin.ModelAdmin):
    pass

though of course it's not complete because I don't know what to put in it.

After a couple of hours of digging through the documentation I found the list_filter property, described as

Set list_filter to activate filters in the right sidebar of the change list page of the admin

This isn't what I want; I want a filter on the "add" page, not the "change" page, and I don't want a sidebar, I want the filter to be automatic once the date is selected.

Is this possible without creating a new AdminSite from scratch?

Body:
It's not something that there is any built in functionality within the django-admin to do. However, you wouldn't have to quite go to the extents of creating a completely new admin site from scratch.

The best way to do this would be to use javascript to update the values of the relevant form values. You'll need to add an event listner on the change event of one of your inputs, and set it to update another one.

Because django-admin uses jquery in one or two places you have access to jquery for free, or it is relatively easy to do this with just plain javascript.

In terms of how you attach the javascript to this page you have two options:

load the javascript via your modelAdmin)

class MyAdmin(admin.ModelAdmin):
    class Media:
        js = ('js/my_script.js', ) # this should be a file from your static directory

Extend the template.

class MyAdmin(admin.ModelAdmin):
    change_form_template = "my_template.html"

then in my_template.html

{% extends "admin/change_form.html" %}
{% block %}
{% block extrahead %}
{{ block.super }}
  ... add your script here
{% endblock %}

The advantage of the second option is that you can alter your script based on values loaded in through context, but this might not be necessary.


问:
Is there any way to redraw tmux window when switching smaller monitor to bigger one?
I started a tmux session on a smaller terminal. When I "attach" to the same session on a larger resolution monitor, it draws dots around the console. It doesn't fit the new window size. Is there any way to redraw and clean the window? CTRL+L or CTRL-B + R doesn't help.

答: I use Ctrl-b + q which makes it flash number for each pane, redrawing them on the way.