问:
Testing a function with a @cache.memoize gives PicklingError
I have some tests for functions that use cache, for example:

Function:

```<code>@retry(stop=stop_after_attempt(3))
@cache.cached(timeout=60, key_prefix='resouce_group_list')
def get_azure_resource_groups():

    data = []
    resource_client = get_azure_resource_client()
    for item in resource_client.resource_groups.list():
        data.append(item)
    return data
</code>```

Test:

```<code>@patch("dev_maintenance.machines.get_azure_resource_client")
def test_get_azure_list_rg(get_azure_resource_client):

    cache.clear()
    data = []
    with app.app_context():
        ret = get_azure_resource_groups()
        get_azure_resource_client.assert_called_once()
        expected = get_azure_resource_client.return_value.resource_groups.list.return_value
        assert len(get_azure_resource_client.return_value.method_calls) == 1
        for item in expected:
            data.append(item)
        assert ret == data
        cache.clear()
</code>```

The above test works fine, it passes, no errors and the test is using cache.

But i got other tests, and the decorator here does not matter, it will give the same error if i change the decorator to @cache.cache:

Function:

```<code>@retry(stop=stop_after_attempt(3))
@cache.memoize(60)
def get_azure_machine_info(rg_name, machine_name, expand="instanceView"):

    try:
        compute_client = get_azure_compute_client()
        return compute_client.virtual_machines.get(rg_name, machine_name, expand=expand)
    except CloudError:
        return None
</code>```

Test:

```<code>@patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):

    cache.delete_memoized(get_azure_machine_info)
    with app.app_context():
        ret = get_azure_machine_info("rg1", "m1")
        print(ret)
        get_azure_compute_client.assert_called_once()
        assert len(get_azure_compute_client.return_value.method_calls) == 1
        assert (
            ret == get_azure_compute_client.return_value.virtual_machines.get.return_value
            )

        get_azure_compute_client.return_value.virtual_machines.get.assert_called_once_with(
            "rg1", "m1", expand="instanceView"
            )
        cache.delete_memoized(get_azure_machine_info)
</code>```

Now here the test fails with the error on this line ret = get_azure_machine_info("rg1", "m1"):

```<code>value = None, from_value = PicklingError("Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock")

>   ???
E   tenacity.RetryError: RetryError[<Future at 0x105c7c3d0 state=finished raised PicklingError>]

<string>:3: RetryError
</code>```

I tried to mock the cache passing a patch decorator like:

```<code>@patch("dev_maintenance.machines.cache") or @patch("dev_maintenance.cache")
</code>```

I tried to set the CACHE_TYPE to null in the test case, instantiating the cache object and passing the config:

```<code>cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "redis"})
</code>```

but no success so far, any help?

答:
I'am writing the answer here for people that need to test functions that are cached with flask-caching and have the same error then me.

What i needed was to create an Object inside the test and make the mock_value = Object like this:

First i create a simple class:

```<code>class MachineInfo(object):
    pass
</code>```

Then in my test:

```<code>@patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):

    cache.clear()
    expected_res = MachineInfo()
    expected_res.id = "id"
    expected_res.name = "machine1"
    expected_res.location = "location"
    expected_res.hardware_profile = "hardware"
    expected_res.storage_profile = "storage"
    expected_res.network_profile = "network_profile"
    get_azure_compute_client.return_value.virtual_machines.get.return_value = expected_res
    res = get_azure_machine_info("rg1", "m1")
    assert res == expected_res
    cache.clear()
</code>```

Then i could assert function_call() == Object or function_call() == mock.return_value

This simulates what the actual azure returns, an object, so i just make the mock return the object that i created so i can simulate the function itself.

Body:
I have some tests for functions that use cache, for example:

Function:

@retry(stop=stop_after_attempt(3))
@cache.cached(timeout=60, key_prefix='resouce_group_list')
def get_azure_resource_groups():

    data = []
    resource_client = get_azure_resource_client()
    for item in resource_client.resource_groups.list():
        data.append(item)
    return data

Test:

@patch("dev_maintenance.machines.get_azure_resource_client")
def test_get_azure_list_rg(get_azure_resource_client):

    cache.clear()
    data = []
    with app.app_context():
        ret = get_azure_resource_groups()
        get_azure_resource_client.assert_called_once()
        expected = get_azure_resource_client.return_value.resource_groups.list.return_value
        assert len(get_azure_resource_client.return_value.method_calls) == 1
        for item in expected:
            data.append(item)
        assert ret == data
        cache.clear()

The above test works fine, it passes, no errors and the test is using cache.

But i got other tests, and the decorator here does not matter, it will give the same error if i change the decorator to @cache.cache:

Function:

@retry(stop=stop_after_attempt(3))
@cache.memoize(60)
def get_azure_machine_info(rg_name, machine_name, expand="instanceView"):

    try:
        compute_client = get_azure_compute_client()
        return compute_client.virtual_machines.get(rg_name, machine_name, expand=expand)
    except CloudError:
        return None

Test:

@patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):

    cache.delete_memoized(get_azure_machine_info)
    with app.app_context():
        ret = get_azure_machine_info("rg1", "m1")
        print(ret)
        get_azure_compute_client.assert_called_once()
        assert len(get_azure_compute_client.return_value.method_calls) == 1
        assert (
            ret == get_azure_compute_client.return_value.virtual_machines.get.return_value
            )

        get_azure_compute_client.return_value.virtual_machines.get.assert_called_once_with(
            "rg1", "m1", expand="instanceView"
            )
        cache.delete_memoized(get_azure_machine_info)

Now here the test fails with the error on this line ret = get_azure_machine_info("rg1", "m1"):

value = None, from_value = PicklingError("Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock")

>   ???
E   tenacity.RetryError: RetryError[<Future at 0x105c7c3d0 state=finished raised PicklingError>]

<string>:3: RetryError

I tried to mock the cache passing a patch decorator like:

@patch("dev_maintenance.machines.cache") or @patch("dev_maintenance.cache")

I tried to set the CACHE_TYPE to null in the test case, instantiating the cache object and passing the config:

cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "redis"})

but no success so far, any help?

Body:
I'am writing the answer here for people that need to test functions that are cached with flask-caching and have the same error then me.

What i needed was to create an Object inside the test and make the mock_value = Object like this:

First i create a simple class:

class MachineInfo(object):
    pass

Then in my test:

@patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):

    cache.clear()
    expected_res = MachineInfo()
    expected_res.id = "id"
    expected_res.name = "machine1"
    expected_res.location = "location"
    expected_res.hardware_profile = "hardware"
    expected_res.storage_profile = "storage"
    expected_res.network_profile = "network_profile"
    get_azure_compute_client.return_value.virtual_machines.get.return_value = expected_res
    res = get_azure_machine_info("rg1", "m1")
    assert res == expected_res
    cache.clear()

Then i could assert function_call() == Object or function_call() == mock.return_value

This simulates what the actual azure returns, an object, so i just make the mock return the object that i created so i can simulate the function itself.


来源: stackexchange

问:
How to prevent page refresh when using ng5-slider for Angular
I have an ng5-slider which has a range from 0 - 1000 and is adjustable by the user.

When I adjust the slider at the bottom of the page, the page refreshes and pulls me to the top of the page.

I would like to prevent that from occurring. How do I do this ?

Here is my code:

page.component.html

```<code>          <div>
            <ng5-slider
              [(value)]="minValue"
              [(highValue)]="maxValue"
              (userChangeStart)="onUserChangeStart($event)"
              (userChangeEnd)="onUserChangeEnd($event)"
              [options]="options"
              (userChange)="onUserChange($event)">
            </ng5-slider>
          </div>
</code>```

page.component.ts

```<code>@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
  logText = '';
  arr_price = [];
  minValue = 0;
  maxValue = 1000;
  options: Options = {
    floor: 0,
    ceil: 1000
  };

  getChangeContextString(changeContext: ChangeContext): string {
    return `${changeContext.value} ${changeContext.highValue}`;
  }

  onUserChangeStart(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
  }

  onUserChangeEnd(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
    this.apply();
  }

  onUserChange(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
    const value = this.logText;
    const value_arr = value.split(' ');
    this.arr_price = value_arr;
  }
}
</code>```

I've tried to remove (userChangeStart) and (userChangeEnd) and the page did not reload which is what I want.

However, when I manually click the refresh button, the slider values reverted back to its original 0 --------------- 1000.

I am thinking that I have to implement userChangeStart and userChangeEnd for data to be persisted but if only I can somehow prevent page reload from within these handler functions...

答:
I fixed the bug by setting scrollPositionRestoration to disabled in the app routing module.

Initially it was set to enabled and thus any click event at the bottom of the page will bring the page to the top.

```<code>imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'disabled' })]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an ng5-slider which has a range from 0 - 1000 and is adjustable by the user.

When I adjust the slider at the bottom of the page, the page refreshes and pulls me to the top of the page.

I would like to prevent that from occurring. How do I do this ?

Here is my code:

page.component.html

            <ng5-slider
              [(value)]="minValue"
              [(highValue)]="maxValue"
              (userChangeStart)="onUserChangeStart($event)"
              (userChangeEnd)="onUserChangeEnd($event)"
              [options]="options"
              (userChange)="onUserChange($event)">
            </ng5-slider>

page.component.ts

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
  logText = '';
  arr_price = [];
  minValue = 0;
  maxValue = 1000;
  options: Options = {
    floor: 0,
    ceil: 1000
  };

  getChangeContextString(changeContext: ChangeContext): string {
    return `${changeContext.value} ${changeContext.highValue}`;
  }

  onUserChangeStart(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
  }

  onUserChangeEnd(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
    this.apply();
  }

  onUserChange(changeContext: ChangeContext): void {
    this.logText = this.getChangeContextString(changeContext);
    const value = this.logText;
    const value_arr = value.split(' ');
    this.arr_price = value_arr;
  }
}

I've tried to remove (userChangeStart) and (userChangeEnd) and the page did not reload which is what I want.

However, when I manually click the refresh button, the slider values reverted back to its original 0 --------------- 1000.

I am thinking that I have to implement userChangeStart and userChangeEnd for data to be persisted but if only I can somehow prevent page reload from within these handler functions...

Body:
I fixed the bug by setting scrollPositionRestoration to disabled in the app routing module.

Initially it was set to enabled and thus any click event at the bottom of the page will bring the page to the top.

imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'disabled' })]


问:
Is it possible to restrict who can complete a Pull Request in Azure DevOps?
We are just moving from another Git-Repo-Hosting-system to Azure DevOps. In the previous system it was possible to restrict who is allowed to complete a pull request (assuming that all findings are resolved). That means the Pull request was "ready" to be merged but only specific people had the permissions to actually execute the merge.

Looking through the documentation of Azure DevOps I have not found such a feature out-of-the-box.
Did I simply miss it or it is not possible at all?

Thank you

答:
Daniel's right.  Branch policies already do exactly what you're saying. Policies enforce your team's code quality and change management standards.

You just need to use Require a minimum number of reviewers:

When the required number of reviewers approve the pull request, it can finish.

Also expand with more detail info and show you a example how will this works in your side. Image you have two teams:

Developers:

Patrick

Carl

......

[project]\PM and Developer Managers

PM and Developer Managers:

PM

Developer Managers

One could add the PM and Developer Managers: team as "required" on the branch policy, and keep the Developers team rights to pull requests, allowing other develops to still approve requests and comment etc.

But the request can't be completed until a user in PM and Developer Managers group approves it.


问:
What is UPCRTD attribute in IBMi AS400?
Could anyone tell me what is does UPCRTD attribute mean in IBMi AS400 system?
I guess this is a user profile creation date-time, but I didn't find any official documentation which simply says, that UPCRTD means user profile creation date time.
Can anyone please refer any document I can find useful?</p>

答:
You will not find this detailed information in a document. UPCRTD is one of the column of the result table of the command DSPUSRPRF TYPE(*BASIC) OUTPUT(*OUTFILE)

You can see there that this table has the same structure as QADSPUPB when TYPE(*BASIC)

The by SQL wou can find information about the column or your machine

```<code>select
    TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_TEXT
from
    QSYS2.SYSCOLUMNS
where
    (TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME) = ('QSYS', 'QADSPUPB', 'UPCRTD');
</code>```

gives

```<code>|TABLE_SCHEMA|TABLE_NAME|COLUMN_NAME|COLUMN_TEXT                                       |
|------------|----------|-----------|--------------------------------------------------|
|QSYS        |QADSPUPB  |UPCRTD     |Creation date: YYMMDD                             |
</code>```

Title: What is UPCRTD attribute in IBMi AS400?

Body:
You will not find this detailed information in a document. UPCRTD is one of the column of the result table of the command DSPUSRPRF TYPE(*BASIC) OUTPUT(*OUTFILE)

You can see there that this table has the same structure as QADSPUPB when TYPE(*BASIC)

The by SQL wou can find information about the column or your machine

select
    TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_TEXT
from
    QSYS2.SYSCOLUMNS
where
    (TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME) = ('QSYS', 'QADSPUPB', 'UPCRTD');

gives

|TABLE_SCHEMA|TABLE_NAME|COLUMN_NAME|COLUMN_TEXT                                       |
|------------|----------|-----------|--------------------------------------------------|
|QSYS        |QADSPUPB  |UPCRTD     |Creation date: YYMMDD                             |


问:
Post request with axios one after another Vuejs
I have 2 post request, if the first one is trigger the second one must await for the response and the do a post request. I read something about await and async, but no good.</p>

```<code>let changed =false;

if(//something then){
    changed = true;
    axios.post('/uploadfile/' + id,  // This must be first
        formData,
    {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
    })
    .then(function(response){
        // get response and do something
    })
    .catch(function(){
        //
    });
}

// if changed = true, then await for response from first post
axios.post('/uploadfile' + this.id_contract,  // If
    data,
    {
    headers: {
        Authorization: getToken()
    }
})
.then(function(){
    // do something else
})
.catch(function(){
    //
});
</code>```

答:
you can just chain the second call with .then of the first request</p>

```<code>axios.post('/whatever').then((response) => {
    return axios.post('/whatever2');
}).then((response) => {
    console.log('Response', response);
});
</code>```

Body:
I have 2 post request, if the first one is trigger the second one must await for the response and the do a post request. I read something about await and async, but no good.

let changed =false;

if(//something then){
    changed = true;
    axios.post('/uploadfile/' + id,  // This must be first
        formData,
    {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
    })
    .then(function(response){
        // get response and do something
    })
    .catch(function(){
        //
    });
}

// if changed = true, then await for response from first post
axios.post('/uploadfile' + this.id_contract,  // If
    data,
    {
    headers: {
        Authorization: getToken()
    }
})
.then(function(){
    // do something else
})
.catch(function(){
    //
});

Body:
you can just chain the second call with .then of the first request

axios.post('/whatever').then((response) => {
    return axios.post('/whatever2');
}).then((response) => {
    console.log('Response', response);
});


问:
Replacing values in particular row with another row in R language
I have matrix and i want to replace the fourth row enteries with the 1st row values. Which R command would help me?
I am using replace command but its giving me dimension error.</p>

```<code>> replace(g1,g[1,],g[2,])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    4    2    2    3    4    5    6
[2,]    5    6    0    1    2    3    4
[3,]    6    5    6    0    1    2    3
[4,]    0   NA   NA   NA   NA   NA   NA
[5,]    1   NA   NA   NA   NA   NA   NA
</code>```

答:
If you would like to use replace, you can try the code below

```<code>g1 <- replace(g1,row(g1)==4,g1[1,])
</code>```

Otherwise, g1[4,] <- g[1,] would be enough.

Body:
I have matrix and i want to replace the fourth row enteries with the 1st row values. Which R command would help me?
I am using replace command but its giving me dimension error.

> replace(g1,g[1,],g[2,])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    4    2    2    3    4    5    6
[2,]    5    6    0    1    2    3    4
[3,]    6    5    6    0    1    2    3
[4,]    0   NA   NA   NA   NA   NA   NA
[5,]    1   NA   NA   NA   NA   NA   NA

Body:
If you would like to use replace, you can try the code below

g1 <- replace(g1,row(g1)==4,g1[1,])

Otherwise, g1[4,] <- g[1,] would be enough.


问:
How to fix Google Script Error "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"?
I have this code that works fine. The code is supposed to copy and filter data from one spreadsheet to another using values in Column E. When I enter certain values like "Business 2", it runs fine. But if I enter other values like "Business 1", I get this error - "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"

I have cleaned and trimmed the cell contents with =CLEAN(TRIM())

Here is the code

```<code>function copySheetValuesV2(){
  var source = SpreadsheetApp.getActiveSheet();
  var sourceName = source.getSheetName();
  var sValues = source.getDataRange().getValues();

  //var rawData = range.getValues()     // get value from spreadsheet 1
var data = []                       // Filtered Data will be stored in this array
for (var i = 0; i< sValues.length ; i++){
if(sValues[i][4] == "Business 1")            // Check to see if column E says "Business 1" if not skip it
{
data.push(sValues[i])
}
}

  var destination = SpreadsheetApp.openById('idvalue');
  var shttoDelete = destination.getSheetByName('Copy of Dashboard');

  source.copyTo(destination);
  var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
  destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
  destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();

}
</code>```

I need help with finding why the script isn't reading certain values from the column.

答:
Cannot read property 'length' of undefined in your case means that the array data is empty

Your code pushes sValues into data if sValues[i][4] == "Business 1".

If not, data stays empty and data[0] does not exist and thus has no length.

You can avoid this error by verifying that data is not empty before running the rest of your code.

The easiest way to do it would be with an if statement, e.g.

```<code> if(data[0]){
    source.copyTo(destination);
    var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
    destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
    destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();
  }
</code>```

Body:
I have this code that works fine. The code is supposed to copy and filter data from one spreadsheet to another using values in Column E. When I enter certain values like "Business 2", it runs fine. But if I enter other values like "Business 1", I get this error - "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"

I have cleaned and trimmed the cell contents with =CLEAN(TRIM())

Here is the code

function copySheetValuesV2(){
  var source = SpreadsheetApp.getActiveSheet();
  var sourceName = source.getSheetName();
  var sValues = source.getDataRange().getValues();

  //var rawData = range.getValues()     // get value from spreadsheet 1
var data = []                       // Filtered Data will be stored in this array
for (var i = 0; i< sValues.length ; i++){
if(sValues[i][4] == "Business 1")            // Check to see if column E says "Business 1" if not skip it
{
data.push(sValues[i])
}
}

  var destination = SpreadsheetApp.openById('idvalue');
  var shttoDelete = destination.getSheetByName('Copy of Dashboard');

  source.copyTo(destination);
  var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
  destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
  destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();

}

I need help with finding why the script isn't reading certain values from the column.

Body:
Cannot read property 'length' of undefined in your case means that the array data is empty

Your code pushes sValues into data if sValues[i][4] == "Business 1".

If not, data stays empty and data[0] does not exist and thus has no length.

You can avoid this error by verifying that data is not empty before running the rest of your code.

The easiest way to do it would be with an if statement, e.g.

 if(data[0]){
    source.copyTo(destination);
    var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
    destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
    destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();
  }


问:
YUI Datatable - "Data Error."
I'm trying to make a datatable using YUI with JSON returned data.

Included is the json returned data, and the page data displayed.

JSON Data:

```<code>[{"supplier_id":"127","name":"Adams Farms","description":"","ofarm":"1","active":"1"},{"supplier_id":"141","name":"Barriger Farms","description":"","ofarm":"1","active":"1"}]
</code>```

Javascript for YUI:

```<code><script type="text/javascript">
YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.example.JSON = function() {
        var myColumnDefs = [
            {key:"supplier_id", label:"ID"},
            {key:"name", label:"Name"},
            {key:"description", label:"Notes"},
            {key:"ofarm", label:"Ofarm"},
            {key:"active", label:"Active"}
        ];

        var myDataSource = new YAHOO.util.DataSource("ajax/select/supplier");
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.responseSchema = {
            fields: ["supplier_id","name","description","ofarm","active"]
        };

        var myDataTable = new YAHOO.widget.DataTable("json", myColumnDefs,
                myDataSource);

        return {
            oDS: myDataSource,
            oDT: myDataTable
        };
    }();
});
</script>
</code>```

Page View:

YUI Test (header)

This example populates a DataTable with data. (intro text)

ID - Name - Notes - Ofarm - Active   (column titles)

Data error. (returned data)

答: As a side note, I found this page when looking for the cause of "Data error" in a YUI datatable, and I eventually found out that I was missing the /build/connection/connection-min.js script reference on my web page.</p>

ContentLicense: CC BY-SA 2.5

Title: YUI Datatable - "Data Error."

Body:
I'm trying to make a datatable using YUI with JSON returned data.

Included is the json returned data, and the page data displayed.

JSON Data:

[{"supplier_id":"127","name":"Adams Farms","description":"","ofarm":"1","active":"1"},{"supplier_id":"141","name":"Barriger Farms","description":"","ofarm":"1","active":"1"}]

Javascript for YUI:

Page View:

YUI Test (header)

This example populates a DataTable with data. (intro text)

ID - Name - Notes - Ofarm - Active   (column titles)

Data error. (returned data)

ContentLicense: CC BY-SA 3.0


问:
How to implement variables in the this.state.shown ? "constant " : " constant"
I need to show the text box value in this.state.shown but i accepts only constants if give variable name it prints the same. how to use variable here for eg:

```<code>{this.state.shown ? "Reject Reason" : "Accepted Reason"}
</code>```

is working fine.

```<code><textarea placeholder="Reason for Rejection" id="mdlplc" className="mdlcnt"/>

const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;

{this.state.shown ? "rejectReason " : ""}
</code>```

its not working?

My full component code is:

```<code>import React, { Component } from 'react';
import Modal from 'react-responsive-modal';
import '../dashboard/Dashboard.css';
import './BasicTable.css';
//import SearchField from 'react-search-field';

export class BasicTable extends Component {

  state = {
    open: false,
  };
  onSubmitdata = () => {
    this.setState({open: false});
    this.setState({ shown: !this.state.shown });
  }
  onOpenModal = () => {
    this.setState({ open: true });
  };
  on
  onCloseModal = () => {
    this.setState({ open: false });
  };
  render() {
    const { open } = this.state;
    const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;

    return (
      <div>
        <div className="row">

        <h4 className="card-title"> View Appointments</h4>

          <div className="col-lg-12 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
              <div className="table-responsive">
                  <table className="table reposive" >

                   <tr >
                       <td className="noBorder" id="details">Doctor Name</td>
                       <td className="noBorder"> Jessica Smith</td>
                   </tr>
                   <tr>
                       <td className="noBorder" id="details">Patient Name</td>
                       <td className="noBorder">Jack Robinson</td>
                   </tr>
                   <tr>
                       <td className="noBorder" id="details">Date</td>
                       <td className="noBorder">Jan 15 2020</td>
                   </tr>
                   <tr>
                       <td className="noBorder" id="details">Time</td>
                       <td className="noBorder"> 9.00 AM to 9.00 AM</td>
                   </tr>
                   <tr>
                       <td className="noBorder" id="details">Status</td>
                       <td className="noBorder" id="status">BOOKED</td>
                   </tr>
                   <tr>
                       <td className="noBorder" id="details"> {this.state.shown ? "Reject Reason" : ""}</td>
                       <td className="noBorder" >{this.state.shown ? rejectReason : ""}</td>
                   </tr>
                  </table>
                  <button onClick={this.onOpenModal} className="badge badge-dange">Reject Appointment</button>
                </div>
              </div>
            </div>
          </div>
          <div>

        <Modal open={open} onClose={this.onCloseModal} center>
          <p id="mdlhd">Reject Appointment</p>
          <textarea  placeholder="Reason for Rejection" id="mdlplc" className="mdlcnt" />
          <button id="mdlsbt" onClick={this.onSubmitdata}>Submit</button>
          <button id="mdlcnl" onClick={this.onCloseModal}>Cancel</button>
        </Modal>
      </div>
        </div>
      </div>
    )
  }
}

export default BasicTable
</code>```

答:
You can use a ref to the element to have a reference to the element itself and you can get the value of it:

```<code>constructor(props){ // add this block to your class component.
    super(props);
    this.mdlplcRef = React.createRef() // in a class component's constructor
}
// const mdlplcRef = useRef(); // the functional component way
</code>```

then use this ref to the element:

```<code><textarea ref={this.mdlplcRef}
          placeholder="Reason for Rejection"
          id="mdlplc" className="mdlcnt"/>
</code>```

Now in the render update this line to get the value:

```<code>// const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;
const rejectReason = this.mdlplcRef.current.value;

{this.state.shown ? rejectReason : ""}
</code>```

Body:
I need to show the text box value in this.state.shown but i accepts only constants if give variable name it prints the same. how to use variable here for eg:

{this.state.shown ? "Reject Reason" : "Accepted Reason"}

is working fine.

<textarea placeholder="Reason for Rejection" id="mdlplc" className="mdlcnt"/>

const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;

{this.state.shown ? "rejectReason " : ""}

its not working?

My full component code is:

import React, { Component } from 'react';
import Modal from 'react-responsive-modal';
import '../dashboard/Dashboard.css';
import './BasicTable.css';
//import SearchField from 'react-search-field';

export class BasicTable extends Component {

  state = {
    open: false,
  };
  onSubmitdata = () => {
    this.setState({open: false});
    this.setState({ shown: !this.state.shown });
  }
  onOpenModal = () => {
    this.setState({ open: true });
  };
  on
  onCloseModal = () => {
    this.setState({ open: false });
  };
  render() {
    const { open } = this.state;
    const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;

    return (

 View Appointments

                       Doctor Name
                        Jessica Smith

                       Patient Name
                       Jack Robinson

                       Date
                       Jan 15 2020

                       Time
                        9.00 AM to 9.00 AM

                       Status
                       BOOKED

                        {this.state.shown ? "Reject Reason" : ""}
                       {this.state.shown ? rejectReason : ""}

                  <button onClick={this.onOpenModal} className="badge badge-dange">Reject Appointment</button>

        <Modal open={open} onClose={this.onCloseModal} center>

Reject Appointment

          <textarea  placeholder="Reason for Rejection" id="mdlplc" className="mdlcnt" />
          <button id="mdlsbt" onClick={this.onSubmitdata}>Submit</button>
          <button id="mdlcnl" onClick={this.onCloseModal}>Cancel</button>
        </Modal>

    )
  }
}

export default BasicTable

Body:
You can use a ref to the element to have a reference to the element itself and you can get the value of it:

constructor(props){ // add this block to your class component.
    super(props);
    this.mdlplcRef = React.createRef() // in a class component's constructor
}
// const mdlplcRef = useRef(); // the functional component way

then use this ref to the element:

<textarea ref={this.mdlplcRef}
          placeholder="Reason for Rejection"
          id="mdlplc" className="mdlcnt"/>

Now in the render update this line to get the value:

// const rejectReason = document.getElementsByClassName("mdlcnt").innerHTML;
const rejectReason = this.mdlplcRef.current.value;

{this.state.shown ? rejectReason : ""}


问:
Change twitter banner from url
How would I go by changing the twitter banner using an image from url using tweepy library: https://github.com/tweepy/tweepy/blob/v2.3.0/tweepy/api.py#L392

So far I got this and it returns:

```<code>def banner(self):
    url = 'https://blog.snappa.com/wp-content/uploads/2019/01/Twitter-Header-Size.png'
    file = requests.get(url)
    self.api.update_profile_banner(filename=file.content)
</code>```

ValueError: stat: embedded null character in path

It seems like filename requires an image to be downloaded. Anyway to process this without downloading the image and then removing it?

答:
```<code>import tempfile

def banner():
    url = 'file_url'
    file = requests.get(url)
    temp = tempfile.NamedTemporaryFile(suffix=".png")
    try:
        temp.write(file.content)
        self.api.update_profile_banner(filename=temp.name)
    finally:
        temp.close()
</code>```

Title: Change twitter banner from url

Body:
How would I go by changing the twitter banner using an image from url using tweepy library: https://github.com/tweepy/tweepy/blob/v2.3.0/tweepy/api.py#L392

So far I got this and it returns:

def banner(self):
    url = 'https://blog.snappa.com/wp-content/uploads/2019/01/Twitter-Header-Size.png'
    file = requests.get(url)
    self.api.update_profile_banner(filename=file.content)

ValueError: stat: embedded null character in path

It seems like filename requires an image to be downloaded. Anyway to process this without downloading the image and then removing it?


问:
Laravel - whereHas last relation is = 'manual'
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

```<code>$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

Or

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.

答:
It looks like you already have a great Laravel answer, but in case you end up going down the native query option, which you can then hydrate, here's a raw sql option... At the least, I hope it might help you visualise what you're trying to achieve.

CREATE TABLE leads (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `info` varchar(100) NULL default NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE statuses (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `leads_id` int(11) null default null,
  `description` varchar(100) NULL default NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `leads` (`info`) VALUES ('foo'), ('bar'), ('test');

INSERT INTO `statuses` (`leads_id`, `description`) VALUES
(1, 'manual'),
(1, 'auto'),
(1, 'auto'),
(2, 'auto'),
(2, 'auto'),
(2, 'manual'),
(3, 'manual'),
(3, 'manual'),
(3, 'manual');

SELECT l.*
FROM statuses s
JOIN leads l ON l.id = s.leads_id
WHERE s.id IN (
    SELECT MAX(s.id)
    FROM leads l
    JOIN statuses s ON s.leads_id = l.id
    GROUP BY l.id
)
AND s.description LIKE '%manual%'
```

Body:
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

Or

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.


问:
object of data specific to current logged in user

The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

```<code>  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });
</code>```

答:
here is my answer

 121

Base Map

Save

Home

```

I changed a few structures which were not coherent. Saving and loading them was causing discrepancies. I also suggest storing all users in a single object and accessing the data from userMap because multiple users can use same browser.

Body:
The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });

Body:
here is my answer

<html>
<body>
 <span class="border username">121</span>
 <div class="border basemap">Base Map</div>
 <div class="border saveBtn">Save</div>
 <div id="home" class="border">Home</div>

 <style>
  .border{
   border: solid gray 1px;
   border-radius: 2px;
   text-align: center;
   background: #eee;
   margin: 5px;
   width: 100px;
  }
 </style>
 <script type="text/javascript">
  // Here I am trying to initialize the variables
  var key = 1;
  var currentUser;
  var basemapSaved;
  var userA = {
   BaseMap: {
    id: 1234
   }
  };

  var app = {
   widget: {
    Manager: {
     Gallery: {
      activeBasemap: {
       Item: {
        id: {
              portalItem: {
          id: 1234 // this is where I want to load saved value from local storage object
         }
        }
       }
      }
     }
    }
   }
  };

  // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

  function checkUser()  {
   var node = document.querySelectorAll("span.username")[0];
   currentUser = node.textContent;
   var key = currentUser;
   console.log("current user is:" + key);
  }

  // This is just a handler to wait to my basemap gallery loads before trying to save

  var basemapMod = document.getElementsByClassName("basemap")[0];
  basemapMod.addEventListener('click', ()=>{
   console.log("basemapMod click");
   setTimeout(
    function() {
     BaseMapSaver();
    }, 2000);
  });

  function BaseMapSaver() {
   var savebtnBM = document.getElementsByClassName("saveBtn")[0];
   savebtnBM.addEventListener('click', ()=>{
    console.log("savebtnBM click");
    checkUser();
    // This is where I get the data from my API to save, gathers fine
    basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id.portalItem.id;

        /** saving users, instead of userA */
    const userAParseValue = JSON.parse(localStorage.getItem('users'));
    userA.BaseMap.basemapSaved = basemapSaved;
    const finalUsers = {...userAParseValue, userA}
    // Below I am trying to set it, at first without the object key but would like to use the key
    var saveMap = localStorage.setItem('users', JSON.stringify(finalUsers));

    console.log(userA);
   });
  }
  // Home button
  var defaultViewHbtn = document.getElementById("home");

  defaultViewHbtn.addEventListener('click', ()=>{
   console.log("defaultViewHbtn click");
   checkUser();

   // Here I try to parse the value from local storage object
   const userAParseValue = JSON.parse(localStorage.getItem('users'));

   // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
   userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
   console.log(userBaseMap);

   app.widget.Manager.Gallery.activeBasemap.Item.id = {
    portalItem: {
      id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
     }
    };
  });
 </script>
</body>
</html>

I changed a few structures which were not coherent. Saving and loading them was causing discrepancies. I also suggest storing all users in a single object and accessing the data from userMap because multiple users can use same browser.


问:
Kubernetes talking to specific ports externally
Having a pod inside a namespace, I can do certain connections externally but some seem to be blocked.  I have tested and due to limitations I cannot run Wireshark and tcpdump inside my namespace.  So I setup some tests on the destinations.

```<code>Here is a sample of tests
nc -v -z -w 2 machinename 445
works like a champ.
nc -v -z -w 2 machinename 80
works like a champ
nc -v -z -w 2 machinename 8080 works
nc -v -z -w 2 machine 5985 - fails with a timeout
</code>```

Outside of Kubernetes from a bare metal machine
nc -v -z -w 2 machinename 5985  - works

So I look at my egress

```<code>apiVersion: extensions/v1beta1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress
</code>```

When I do a netmon on the target machine name.  I see the working calls fine.  This port is just an example because of a python service that calls 5985 I have a few others but I am picking on a known port (winerm).  I never see on target the netmon call.  The belief I have is that from the pod it is blocked outright and never escapes the namespace.

I can rule out routing as other ports work.  I can rule out egress it is wide open. Since I can reliably say TCP traffic that is ruled out as I UDP issue.

What I don't know is why only specific ports are blocked for TCP traffic.  I have 2 other ports with another application that are in the same state.

So it's not all ports, just some.  No reasoning that I can see.

If anyone has any ideas on what to look at, please let me know as I have searched and searched and so far all I can find in ingress solutions to expose ports not a service in a pod calling out having issues.

答: If you cluster uses calico cni, then verify are there any GlobalNetworkPolicies (https://docs.projectcalico.org/v3.11/reference/resources/globalnetworkpolicy) with higher priority (lower order) created which is restricting these specific ports.</p>

Body:
Having a pod inside a namespace, I can do certain connections externally but some seem to be blocked.  I have tested and due to limitations I cannot run Wireshark and tcpdump inside my namespace.  So I setup some tests on the destinations.

Here is a sample of tests
nc -v -z -w 2 machinename 445
works like a champ.
nc -v -z -w 2 machinename 80
works like a champ
nc -v -z -w 2 machinename 8080 works
nc -v -z -w 2 machine 5985 - fails with a timeout

Outside of Kubernetes from a bare metal machine
nc -v -z -w 2 machinename 5985  - works

So I look at my egress

apiVersion: extensions/v1beta1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress

When I do a netmon on the target machine name.  I see the working calls fine.  This port is just an example because of a python service that calls 5985 I have a few others but I am picking on a known port (winerm).  I never see on target the netmon call.  The belief I have is that from the pod it is blocked outright and never escapes the namespace.

I can rule out routing as other ports work.  I can rule out egress it is wide open. Since I can reliably say TCP traffic that is ruled out as I UDP issue.

What I don't know is why only specific ports are blocked for TCP traffic.  I have 2 other ports with another application that are in the same state.

So it's not all ports, just some.  No reasoning that I can see.

If anyone has any ideas on what to look at, please let me know as I have searched and searched and so far all I can find in ingress solutions to expose ports not a service in a pod calling out having issues.


问:
Raw H264 frames in mpegts container using libavcodec
I would really appreciate some help with the following issue:

I have a gadget with a camera, producing H264 compressed video frames, these frames are being sent to my application. These frames are not in a container, just raw data.

I want to use ffmpeg and libav functions to create a video file, which can be used later.

If I decode the frames, then encode them, everything works fine, I get a valid video file. (the decode/encode steps are the usual libav commands, nothing fancy here, I took them from the almighty internet, they are rock solid)... However, I waste a lot of time by decoding and encoding, so I would like to skip this step and directly put the frames in the output stream. Now, the problems come.

Here is the code I came up with for producing the encoding:

```<code>AVFrame* picture;

avpicture_fill((AVPicture*) picture, (uint8_t*)frameData,
                 codecContext->pix_fmt, codecContext->width,
                 codecContext->height);
int outSize = avcodec_encode_video(codecContext, videoOutBuf,
                 sizeof(videoOutBuf), picture);
if (outSize > 0)
{
    AVPacket packet;
    av_init_packet(&packet);
    packet.pts = av_rescale_q(codecContext->coded_frame->pts,
                  codecContext->time_base, videoStream->time_base);
    if (codecContext->coded_frame->key_frame)
    {
        packet.flags |= PKT_FLAG_KEY;
    }
    packet.stream_index = videoStream->index;
    packet.data =  videoOutBuf;
    packet.size =  outSize;

    av_interleaved_write_frame(context, &packet);
    put_flush_packet(context->pb);
}
</code>```

Where the variables are like:

frameData is the decoded frame data, that came from the camera, it was decoded in a previous step and videoOutBuf is a plain uint8_t buffer for holding the data

I have modified the application in order to not to decode the frames, but simply pass through the data like:

```<code>    AVPacket packet;
    av_init_packet(&packet);

    packet.stream_index = videoStream->index;
    packet.data = (uint8_t*)frameData;
    packet.size = currentFrameSize;

    av_interleaved_write_frame(context, &packet);
    put_flush_packet(context->pb);
</code>```

where

frameData is the raw H264 frame
and currentFrameSize is the size of the raw H264 frame, ie. the number of bytes I get from the gadget for every frame.

And suddenly the application is not working correctly anymore, the produced video is unplayable. This is obvious, since I was not setting a correct PTS for the packet. What I did was the following (I'm desperate, you can see it from this approach :) )

```<code>    packet.pts = timestamps[timestamp_counter ++];
</code>```

where timestamps is actually a list of PTS's produced by the working code above, and written to a file (yes, you read it properly, I logged all the PTS's for a 10 minute session, and wanted to use them).

The application still does not work.

Now, here I am without any clue what to do, so here is the question:

I would like to create an "mpegts" video stream using libav functions, insert in the stream already encoded video frames and create a video file with it. How do I do it?

Thanks,
f.

答:
I believe if you set the following, you will see video playback.

```<code>packet.flags |= AV_PKT_FLAG_KEY;
packet.pts = packet.dts = 0;
</code>```

You should really set packet.flags according to the h264 packet headers.  You might try this fellow stack overflowian's suggestion for extracting directly from the stream.

If you are also adding audio, then pts/dts is going to be more important.  I suggest you study this tutorial

EDIT

I found time to extract out what is working for me from my test app.  For some reason, dts/pts values of zero works for me, but values other than 0 or AV_NOPTS_VALUE do not.  I wonder if we have different versions of ffmpeg.  I have the latest from git://git.videolan.org/ffmpeg.git.

fftest.cpp

```<code>#include <string>

#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif

//#define _M
#define _M printf( "%s(%d) : MARKER\n", __FILE__, __LINE__ )

extern "C"
{
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
};

AVFormatContext *fc = 0;
int vi = -1, waitkey = 1;

// < 0 = error
// 0 = I-Frame
// 1 = P-Frame
// 2 = B-Frame
// 3 = S-Frame
int getVopType( const void *p, int len )
{
    if ( !p || 6 >= len )
        return -1;

    unsigned char *b = (unsigned char*)p;

    // Verify NAL marker
    if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
    {   b++;
        if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
            return -1;
    } // end if

    b += 3;

    // Verify VOP id
    if ( 0xb6 == *b )
    {   b++;
        return ( *b & 0xc0 ) >> 6;
    } // end if

    switch( *b )
    {   case 0x65 : return 0;
        case 0x61 : return 1;
        case 0x01 : return 2;
    } // end switch

    return -1;
}

void write_frame( const void* p, int len )
{
    if ( 0 > vi )
        return;

    AVStream *pst = fc->streams[ vi ];

    // Init packet
    AVPacket pkt;
    av_init_packet( &pkt );
    pkt.flags |= ( 0 >= getVopType( p, len ) ) ? AV_PKT_FLAG_KEY : 0;
    pkt.stream_index = pst->index;
    pkt.data = (uint8_t*)p;
    pkt.size = len;

    // Wait for key frame
    if ( waitkey )
        if ( 0 == ( pkt.flags & AV_PKT_FLAG_KEY ) )
            return;
        else
            waitkey = 0;

    pkt.dts = AV_NOPTS_VALUE;
    pkt.pts = AV_NOPTS_VALUE;

//  av_write_frame( fc, &pkt );
    av_interleaved_write_frame( fc, &pkt );
}

void destroy()
{
    waitkey = 1;
    vi = -1;

    if ( !fc )
        return;

_M; av_write_trailer( fc );

    if ( fc->oformat && !( fc->oformat->flags & AVFMT_NOFILE ) && fc->pb )
        avio_close( fc->pb );

    // Free the stream
_M; av_free( fc );

    fc = 0;
_M;
}

int get_nal_type( void *p, int len )
{
    if ( !p || 5 >= len )
        return -1;

    unsigned char *b = (unsigned char*)p;

    // Verify NAL marker
    if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
    {   b++;
        if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
            return -1;
    } // end if

    b += 3;

    return *b;
}

int create( void *p, int len )
{
    if ( 0x67 != get_nal_type( p, len ) )
        return -1;

    destroy();

    const char *file = "test.avi";
    CodecID codec_id = CODEC_ID_H264;
//  CodecID codec_id = CODEC_ID_MPEG4;
    int br = 1000000;
    int w = 480;
    int h = 354;
    int fps = 15;

    // Create container
_M; AVOutputFormat *of = av_guess_format( 0, file, 0 );
    fc = avformat_alloc_context();
    fc->oformat = of;
    strcpy( fc->filename, file );

    // Add video stream
_M; AVStream *pst = av_new_stream( fc, 0 );
    vi = pst->index;

    AVCodecContext *pcc = pst->codec;
_M; avcodec_get_context_defaults2( pcc, AVMEDIA_TYPE_VIDEO );
    pcc->codec_type = AVMEDIA_TYPE_VIDEO;

    pcc->codec_id = codec_id;
    pcc->bit_rate = br;
    pcc->width = w;
    pcc->height = h;
    pcc->time_base.num = 1;
    pcc->time_base.den = fps;

    // Init container
_M; av_set_parameters( fc, 0 );

    if ( !( fc->oformat->flags & AVFMT_NOFILE ) )
        avio_open( &fc->pb, fc->filename, URL_WRONLY );

_M; av_write_header( fc );

_M; return 1;
}

int main( int argc, char** argv )
{
    int f = 0, sz = 0;
    char fname[ 256 ] = { 0 };
    char buf[ 128 * 1024 ];

    av_log_set_level( AV_LOG_ERROR );
    av_register_all();

    do
    {
        // Raw frames in v0.raw, v1.raw, v2.raw, ...
//      sprintf( fname, "rawvideo/v%lu.raw", f++ );
        sprintf( fname, "frames/frame%lu.bin", f++ );
        printf( "%s\n", fname );

        FILE *fd = fopen( fname, "rb" );
        if ( !fd )
            sz = 0;
        else
        {
            sz = fread( buf, 1, sizeof( buf ) - FF_INPUT_BUFFER_PADDING_SIZE, fd );
            if ( 0 < sz )
            {
                memset( &buf[ sz ], 0, FF_INPUT_BUFFER_PADDING_SIZE );

                if ( !fc )
                    create( buf, sz );

                if ( fc )
                    write_frame( buf, sz );

            } // end if

            fclose( fd );

        } // end else

    } while ( 0 < sz );

    destroy();
}
</code>```

Body:
I would really appreciate some help with the following issue:

I have a gadget with a camera, producing H264 compressed video frames, these frames are being sent to my application. These frames are not in a container, just raw data.

I want to use ffmpeg and libav functions to create a video file, which can be used later.

If I decode the frames, then encode them, everything works fine, I get a valid video file. (the decode/encode steps are the usual libav commands, nothing fancy here, I took them from the almighty internet, they are rock solid)... However, I waste a lot of time by decoding and encoding, so I would like to skip this step and directly put the frames in the output stream. Now, the problems come.

Here is the code I came up with for producing the encoding:

AVFrame* picture;

avpicture_fill((AVPicture*) picture, (uint8_t*)frameData,
                 codecContext->pix_fmt, codecContext->width,
                 codecContext->height);
int outSize = avcodec_encode_video(codecContext, videoOutBuf,
                 sizeof(videoOutBuf), picture);
if (outSize > 0)
{
    AVPacket packet;
    av_init_packet(&packet);
    packet.pts = av_rescale_q(codecContext->coded_frame->pts,
                  codecContext->time_base, videoStream->time_base);
    if (codecContext->coded_frame->key_frame)
    {
        packet.flags |= PKT_FLAG_KEY;
    }
    packet.stream_index = videoStream->index;
    packet.data =  videoOutBuf;
    packet.size =  outSize;

    av_interleaved_write_frame(context, &packet);
    put_flush_packet(context->pb);
}

Where the variables are like:

frameData is the decoded frame data, that came from the camera, it was decoded in a previous step and videoOutBuf is a plain uint8_t buffer for holding the data

I have modified the application in order to not to decode the frames, but simply pass through the data like:

    AVPacket packet;
    av_init_packet(&packet);

    packet.stream_index = videoStream->index;
    packet.data = (uint8_t*)frameData;
    packet.size = currentFrameSize;

    av_interleaved_write_frame(context, &packet);
    put_flush_packet(context->pb);

where

frameData is the raw H264 frame
and currentFrameSize is the size of the raw H264 frame, ie. the number of bytes I get from the gadget for every frame.

And suddenly the application is not working correctly anymore, the produced video is unplayable. This is obvious, since I was not setting a correct PTS for the packet. What I did was the following (I'm desperate, you can see it from this approach :) )

    packet.pts = timestamps[timestamp_counter ++];

where timestamps is actually a list of PTS's produced by the working code above, and written to a file (yes, you read it properly, I logged all the PTS's for a 10 minute session, and wanted to use them).

The application still does not work.

Now, here I am without any clue what to do, so here is the question:

I would like to create an "mpegts" video stream using libav functions, insert in the stream already encoded video frames and create a video file with it. How do I do it?

Thanks,
f.

Body:
I believe if you set the following, you will see video playback.

packet.flags |= AV_PKT_FLAG_KEY;
packet.pts = packet.dts = 0;

You should really set packet.flags according to the h264 packet headers.  You might try this fellow stack overflowian's suggestion for extracting directly from the stream.

If you are also adding audio, then pts/dts is going to be more important.  I suggest you study this tutorial

EDIT

I found time to extract out what is working for me from my test app.  For some reason, dts/pts values of zero works for me, but values other than 0 or AV_NOPTS_VALUE do not.  I wonder if we have different versions of ffmpeg.  I have the latest from git://git.videolan.org/ffmpeg.git.

fftest.cpp

#include <string>

#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif

//#define _M
#define _M printf( "%s(%d) : MARKER\n", __FILE__, __LINE__ )

extern "C"
{
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
};

AVFormatContext *fc = 0;
int vi = -1, waitkey = 1;

// < 0 = error
// 0 = I-Frame
// 1 = P-Frame
// 2 = B-Frame
// 3 = S-Frame
int getVopType( const void *p, int len )
{
    if ( !p || 6 >= len )
        return -1;

    unsigned char *b = (unsigned char*)p;

    // Verify NAL marker
    if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
    {   b++;
        if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
            return -1;
    } // end if

    b += 3;

    // Verify VOP id
    if ( 0xb6 == *b )
    {   b++;
        return ( *b & 0xc0 ) >> 6;
    } // end if

    switch( *b )
    {   case 0x65 : return 0;
        case 0x61 : return 1;
        case 0x01 : return 2;
    } // end switch

    return -1;
}

void write_frame( const void* p, int len )
{
    if ( 0 > vi )
        return;

    AVStream *pst = fc->streams[ vi ];

    // Init packet
    AVPacket pkt;
    av_init_packet( &pkt );
    pkt.flags |= ( 0 >= getVopType( p, len ) ) ? AV_PKT_FLAG_KEY : 0;
    pkt.stream_index = pst->index;
    pkt.data = (uint8_t*)p;
    pkt.size = len;

    // Wait for key frame
    if ( waitkey )
        if ( 0 == ( pkt.flags & AV_PKT_FLAG_KEY ) )
            return;
        else
            waitkey = 0;

    pkt.dts = AV_NOPTS_VALUE;
    pkt.pts = AV_NOPTS_VALUE;

//  av_write_frame( fc, &pkt );
    av_interleaved_write_frame( fc, &pkt );
}

void destroy()
{
    waitkey = 1;
    vi = -1;

    if ( !fc )
        return;

_M; av_write_trailer( fc );

    if ( fc->oformat && !( fc->oformat->flags & AVFMT_NOFILE ) && fc->pb )
        avio_close( fc->pb );

    // Free the stream
_M; av_free( fc );

    fc = 0;
_M;
}

int get_nal_type( void *p, int len )
{
    if ( !p || 5 >= len )
        return -1;

    unsigned char *b = (unsigned char*)p;

    // Verify NAL marker
    if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
    {   b++;
        if ( b[ 0 ] || b[ 1 ] || 0x01 != b[ 2 ] )
            return -1;
    } // end if

    b += 3;

    return *b;
}

int create( void *p, int len )
{
    if ( 0x67 != get_nal_type( p, len ) )
        return -1;

    destroy();

    const char *file = "test.avi";
    CodecID codec_id = CODEC_ID_H264;
//  CodecID codec_id = CODEC_ID_MPEG4;
    int br = 1000000;
    int w = 480;
    int h = 354;
    int fps = 15;

    // Create container
_M; AVOutputFormat *of = av_guess_format( 0, file, 0 );
    fc = avformat_alloc_context();
    fc->oformat = of;
    strcpy( fc->filename, file );

    // Add video stream
_M; AVStream *pst = av_new_stream( fc, 0 );
    vi = pst->index;

    AVCodecContext *pcc = pst->codec;
_M; avcodec_get_context_defaults2( pcc, AVMEDIA_TYPE_VIDEO );
    pcc->codec_type = AVMEDIA_TYPE_VIDEO;

    pcc->codec_id = codec_id;
    pcc->bit_rate = br;
    pcc->width = w;
    pcc->height = h;
    pcc->time_base.num = 1;
    pcc->time_base.den = fps;

    // Init container
_M; av_set_parameters( fc, 0 );

    if ( !( fc->oformat->flags & AVFMT_NOFILE ) )
        avio_open( &fc->pb, fc->filename, URL_WRONLY );

_M; av_write_header( fc );

_M; return 1;
}

int main( int argc, char** argv )
{
    int f = 0, sz = 0;
    char fname[ 256 ] = { 0 };
    char buf[ 128 * 1024 ];

    av_log_set_level( AV_LOG_ERROR );
    av_register_all();

    do
    {
        // Raw frames in v0.raw, v1.raw, v2.raw, ...
//      sprintf( fname, "rawvideo/v%lu.raw", f++ );
        sprintf( fname, "frames/frame%lu.bin", f++ );
        printf( "%s\n", fname );

        FILE *fd = fopen( fname, "rb" );
        if ( !fd )
            sz = 0;
        else
        {
            sz = fread( buf, 1, sizeof( buf ) - FF_INPUT_BUFFER_PADDING_SIZE, fd );
            if ( 0 < sz )
            {
                memset( &buf[ sz ], 0, FF_INPUT_BUFFER_PADDING_SIZE );

                if ( !fc )
                    create( buf, sz );

                if ( fc )
                    write_frame( buf, sz );

            } // end if

            fclose( fd );

        } // end else

    } while ( 0 < sz );

    destroy();
}


问:
Where Can I give Entities in Amazon Lex ? Is Slot the other name for entity mentioned in Amazon Lex?
Every Bot works on NLP. So, Intent and Entities are must to create a bot. I found Intents in the Amazon Lex. but i didnt find entities. Slot is the other name for entity? Can anyone explain me what is intent and entity in detail with Lex?</p>

答:
Following explanation may help you understand the concepts Intent and Entity:

Intent is a task or an action a user want to perform, for example, I want to book a cab or want to order the food.

Book a cab and order the food are intents. These intents have the entities called cab(vehicle), food(pizza). Intents will tell you what user wants to do whereas entities will help you with how to do?

In Amazon lex, Slot is a section where you can mention the entity and the values for the entity.

Example:

Intent: Book a cab

This is a task a user wants to do.

Entity: Cab

Values for the entity is Micro, Mini, Prime.

You can check out this link for complete flow and more details.


问:
Values above the bars in a barchart in Matplotlib
I have the following code for a barchart in matplotlib

```<code>import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()
</code>```

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

答:
In your ax.text call, replace:

```<code>performance - 0
</code>```

With:

```<code>i - 0.15
</code>```

Body:
I have the following code for a barchart in matplotlib

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

Body:
In your ax.text call, replace:

performance - 0

With:

i - 0.15


问:
Compare two arrays and add matching strings to another array
So I have two arrays. One of them is 1D (AllAssigneesUnique) and the other is 2D (DB_Array). I want to compare (AllAssigneesUnique) with the first column of (DB_Array) and when there is an exact match, store the string from the first and second column of (DB_Array) to a third 3D Array called (NewAssigneesArray). Additionally, the third column of (NewAssigneesArray) should have the string "New". Below is my code so far.
P.S. How can I re-dimension the new array automatically since the number of matching strings will not always be the same? At the moment, I am using a previously made dictionary to get the exact number of matching strings. </p>

```<code>Dim NewAssigneesArray() As Variant
ReDim NewAssigneesArray(1 To NewAssigneesList.count, 1 To 3)

For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
    For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
        If AllAssigneesUnique(a) = DB_Array(b, 1) Then
            For i = LBound(NewAssigneesArray) To UBound(NewAssigneesArray)
                NewAssigneesArray(i, 1) = DB_Array(b, 1)
                NewAssigneesArray(i, 2) = DB_Array(b, 2)
                NewAssigneesArray(i, 3) = "New"
            Next i
        End If
    Next b
Next a
</code>```

答:
Alternative to ReDim Preserve

The correct solution of @Variatus uses an array with reversed row/column dimensions to overcome the limitation that ReDim Preserve only works at the last (here: 2nd) dimension.

Alternatively, I demonstrate a workaround which restructures the 1st dimension /i.e. rows/ directly (leaving the 2nd untouched) via Application.Index() function:

```<code>NewAssigneesArray= Application.Index(NewAssigneesArray, Evaluate("row(1:" & i & ")"), Array(1, 2, 3))
</code>```

Related link

Read about some peculiarities of the the Application.Index() function" at Insert first column in datafield array without loops or API call

Body:
So I have two arrays. One of them is 1D (AllAssigneesUnique) and the other is 2D (DB_Array). I want to compare (AllAssigneesUnique) with the first column of (DB_Array) and when there is an exact match, store the string from the first and second column of (DB_Array) to a third 3D Array called (NewAssigneesArray). Additionally, the third column of (NewAssigneesArray) should have the string "New". Below is my code so far.
P.S. How can I re-dimension the new array automatically since the number of matching strings will not always be the same? At the moment, I am using a previously made dictionary to get the exact number of matching strings.

Dim NewAssigneesArray() As Variant
ReDim NewAssigneesArray(1 To NewAssigneesList.count, 1 To 3)

For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
    For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
        If AllAssigneesUnique(a) = DB_Array(b, 1) Then
            For i = LBound(NewAssigneesArray) To UBound(NewAssigneesArray)
                NewAssigneesArray(i, 1) = DB_Array(b, 1)
                NewAssigneesArray(i, 2) = DB_Array(b, 2)
                NewAssigneesArray(i, 3) = "New"
            Next i
        End If
    Next b
Next a

Body:
Alternative to ReDim Preserve

The correct solution of @Variatus uses an array with reversed row/column dimensions to overcome the limitation that ReDim Preserve only works at the last (here: 2nd) dimension.

Alternatively, I demonstrate a workaround which restructures the 1st dimension /i.e. rows/ directly (leaving the 2nd untouched) via Application.Index() function:

NewAssigneesArray= Application.Index(NewAssigneesArray, Evaluate("row(1:" & i & ")"), Array(1, 2, 3))

Related link

Read about some peculiarities of the the Application.Index() function" at Insert first column in datafield array without loops or API call


问:
What is the difference between database caching and pooling
I am mostly interested in the general concept, but specifically I need to understand this concept in order to learn server side programming with Swift/Vapor. But it's fine to get a generic answer even if you don't know Swift/Vapor.

I found out that in order to connect to a database, I can use these two methods:

```<code>func requestPooledConnection<Database>(to dbid: DatabaseIdentifier<Database>) -> Future<Database.Connection>

func requestCachedConnection<Database>(to database: DatabaseIdentifier<Database>) -> Future<Database.Connection>
</code>```

Now what I understand from the documentation (Source: https://docs.vapor.codes/3.0/database-kit/overview/#pools) is:

With pooling I can reuse an existing connection, or create a new one if none exists

With pooling connections are not shared between event loops, in order to prevent race conditions

There is usually one pool per database per event loop

With caching, you get one connection per database ID

Now that's a bit confusing, specially the term 'usually' and I also tried to search more documentation about the general concept (e.g. https://en.wikipedia.org/wiki/Connection_pool), and it looks like the words 'caching' and 'pooling' are used interchangeably sometimes. Now I am interested in understanding the difference because this would be useful in order to optimise correctly my web services. But to me it looks like - at least for how I understand Vapor's documentation - they're very similar concepts, and I don't get the difference. Can somebody clarify that?

答: Caching is saving database SQL Temporarily and pooling is keep connection to database </p>

Body:
I am mostly interested in the general concept, but specifically I need to understand this concept in order to learn server side programming with Swift/Vapor. But it's fine to get a generic answer even if you don't know Swift/Vapor.

I found out that in order to connect to a database, I can use these two methods:

func requestPooledConnection<Database>(to dbid: DatabaseIdentifier<Database>) -> Future<Database.Connection>

func requestCachedConnection<Database>(to database: DatabaseIdentifier<Database>) -> Future<Database.Connection>

Now what I understand from the documentation (Source: https://docs.vapor.codes/3.0/database-kit/overview/#pools) is:

With pooling I can reuse an existing connection, or create a new one if none exists

With pooling connections are not shared between event loops, in order to prevent race conditions

There is usually one pool per database per event loop

With caching, you get one connection per database ID

Now that's a bit confusing, specially the term 'usually' and I also tried to search more documentation about the general concept (e.g. https://en.wikipedia.org/wiki/Connection_pool), and it looks like the words 'caching' and 'pooling' are used interchangeably sometimes. Now I am interested in understanding the difference because this would be useful in order to optimise correctly my web services. But to me it looks like - at least for how I understand Vapor's documentation - they're very similar concepts, and I don't get the difference. Can somebody clarify that?


问:
Limit file format when using <input type="file">?
I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <input type="file"> element in HTML. I have a feeling it's impossible, but I'd like to know if there is a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.

答:
I may suggest following:

If you have to make user select any of image files by default, the use accept="image/*"

<input type="file" accept="image/*" />

if you want to restrict to specific image types then use accept="image/bmp, image/jpeg, image/png"

<input type="file" accept="image/bmp, image/jpeg, image/png" />

if you want to restrict to specific types then use accept=".bmp, .doc, .pdf"

<input type="file" accept=".bmp, .doc, .pdf" />

You cannot restrict user to change file filer to all files, so always validate file type in script and server


问:
Autodesk Forge how to save and show Markups
response data for svg markups

markups in model

I want to save all svg Markups on model and show them.
I try to save Markups with this code
    ```markupsPersist = markup.generateData();
    viewerStatePersist = markup.viewer.getState();
    markup.viewer.restoreState(viewerStatePersist);```
and try to get it with this
    markup.viewer.restoreState(viewerStatePersist);
    markup.show();
    markup.loadMarkups(markupsPersist, "markups-svg");
but Markups dont appear.

答: You should also call showMarkups after loading them using loadMarkups.


问:
Flutter: no connected devices
I'm developing flutter project and I'm a newbie to flutter, My Avd manager shows only virtual device except real, whereas my another android project shows my real device and my Android WIFI ADB Here is Image is also showing a connected device, but flutter device selection showing nothing, What should I do? I'm following these steps but nothing is happening. I'm opening Emulator from AVD manager but whenever I run the project it does not show any device, Here is another image.

When I choose MainActivity to run than Android Studio shows device but it shows error like

Cannot start compilation: the output path is not specified for module "flutter_app1_android".
  Specify the output path in Configure Project.

I solved the problem then another problem occur

Unable to determine application id: com.android.tools.idea.run.ApkProvisionException: ERROR: APK path is not specified for module "flutter_app2_android"
  Client not ready yet.

I searched it for this problem but unable to set path because of Project Structure Does not show Module tool, It is showing only SDK Location and project, Here is the image

答:
Make sure  USB debugging on your phone is ON (you can turn it on in Settings -> Developer Options ->Usb Debugging)

Connect your phone to your PC

You can download ADB Driver Installer 2.0, extract it, click the ADBDriverInstaller.exe and just click INSTALL then.

Hope this will help

Title: Flutter: no connected devices


问:
Make a square with letters
I have this:

```<code>ooooo
ooooo
ooooo
ooooo
ooooo
</code>```

Put o on everything except the middle so it turns into this:

```<code>ooooo
o   o
o   o
o   o
ooooo
</code>```

Is there anyway I can do that in Javascript?
My code currently is:
HTML:

```<code><input type = 'text' id = 'box' placeholder = 'Enter n'  onkeyup = 'bigbox();'/>
        <br><br>

        <div id="output"></div>
</code>```

Script:

```<code> function bigbox() {

            number = document.getElementById('box').value;
            display = document.getElementById("output");

        for(let j = 0; j<number; j++) {
            for(let i = 0; i<number; i++)
            text += "o";
            text += "<br>";

            }

        display.innerHTML = text;
</code>```

答:
```<code>function bigbox() {

        number = document.getElementById('box').value;
        display = document.getElementById("output");
    text="";
    for(let j = 0; j<number; j++) {
        for(let i = 0; i<number; i++)
        if(j != 0 && j != number - 1)
            if(i==0)
                    text += "o";
            else if(i == number-1){
                text += "o";
                text += "<br/>";
            }else
            text += "  "
        else{
            text += "o";
        }
        text += "<br/>";

        }

    display.style.lineHeight = 0.5;
    display.innerHTML = text;
}
</code>```

Title: Make a square with letters

Body:
I have this:

ooooo
ooooo
ooooo
ooooo
ooooo

Put o on everything except the middle so it turns into this:

ooooo
o   o
o   o
o   o
ooooo

Is there anyway I can do that in Javascript?
My code currently is:
HTML:

<input type = 'text' id = 'box' placeholder = 'Enter n'  onkeyup = 'bigbox();'/>

Script:

 function bigbox() {

            number = document.getElementById('box').value;
            display = document.getElementById("output");

        for(let j = 0; j<number; j++) {
            for(let i = 0; i<number; i++)
            text += "o";
            text += "
";

            }

        display.innerHTML = text;

Body:
function bigbox() {

        number = document.getElementById('box').value;
        display = document.getElementById("output");
    text="";
    for(let j = 0; j<number; j++) {
        for(let i = 0; i<number; i++)
        if(j != 0 && j != number - 1)
            if(i==0)
                    text += "o";
            else if(i == number-1){
                text += "o";
                text += "<br/>";
            }else
            text += "&nbsp;&nbsp;"
        else{
            text += "o";
        }
        text += "<br/>";

        }

    display.style.lineHeight = 0.5;
    display.innerHTML = text;
}


问:
Unable to understand why the following JavaScript function is not working
I am new to Java Script and I am unable to understand why the following function is not working, what am I doing wrong here? Its prompting me to enter the var gender value but once I enter it is not executing any further. Given below the JavaScript code I am trying to run.

var gender = prompt('What is your gender..?');

function name(fname = 'Sayantan', mname, lname = 'Choudhury') {
  if (gender == male) {
    document.write('Hello Mr. ' + fname + ' ' + mname + ' ' + lname + '
');
  } else {
    document.write('Hello Mrs. ' + fname + ' ' + mname + ' ' + lname + '
');
  }
}

name('Mridula', 'Dutta', 'Chowdhury');
name('Mridula');```

答:
Attention in your code gender == male : whether male is a variable or male is a string 'male' ?

I suggest that you want to write the string 'male' because I don't see the declaration of the variable male. So in this case, you must write the code : gender === "male"

Moreover, I don't neither see the declaration of the variable gender in your code. I recommend you be attention for declaration of identifier names (variables and functions) in the code. Example : so you could respect the camelCase. It's a good pratice !

An example :

```<code>function fncCheckName (name, mName, lName) { }
</code>```

You could view also my answer in the another post : https://stackoverflow.com/a/60037641/4386148

Body:
Attention in your code gender == male : whether male is a variable or male is a string 'male' ?

I suggest that you want to write the string 'male' because I don't see the declaration of the variable male. So in this case, you must write the code : gender === "male"

Moreover, I don't neither see the declaration of the variable gender in your code. I recommend you be attention for declaration of identifier names (variables and functions) in the code. Example : so you could respect the camelCase. It's a good pratice !

An example :

function fncCheckName (name, mName, lName) { }

You could view also my answer in the another post : https://stackoverflow.com/a/60037641/4386148


问:
How to create a dynamic array button in Android?
I have a button.  I want to write the function "onClick" for the button.
Each time that I click on it I want a new button to be created on screen.
And also that new button to be added into an array list of buttons.

I searched but I couldn't find any answer. All of the answers talk about creating buttons with drop and drag, not with dynamic creation of them.

Thanks

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click to add"
        android:id="@+id/B1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="clicktoaddcode"
        />
</RelativeLayout>

package com.example.yas.dynamicbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clicktoaddcode(View V){
        Toast.makeText(MainActivity.this, "Created", Toast.LENGTH_SHORT).show();
    }
}
</code>```

答:
The most simple method to create an unlimited size array is using String Builder. This allows you to add many elements in runtime. It has 3 major components.

Declaration and Initialization.

Value addition/ Append

Print out/ Usage

Use the bellow code anywhere in Android Studio.

//Basic Decleration
        StringBuilder myString = new StringBuilder();

//Adding data
       myString.append("Hello text
");
        myString.append("some more data
");
        myString.append("more data to store
");

//Displaying in already created text view
        deviceDetails.setText(Html.fromHtml(callLogs+""));```

Note: I'm treating this as HTML string and "
" tags will create the next line in text view. So, all added data will be displayed in a new line.

Body:
I have a button.  I want to write the function "onClick" for the button.
Each time that I click on it I want a new button to be created on screen.
And also that new button to be added into an array list of buttons.

I searched but I couldn't find any answer. All of the answers talk about creating buttons with drop and drag, not with dynamic creation of them.

Thanks

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click to add"
        android:id="@+id/B1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="clicktoaddcode"
        />
</RelativeLayout>

package com.example.yas.dynamicbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clicktoaddcode(View V){
        Toast.makeText(MainActivity.this, "Created", Toast.LENGTH_SHORT).show();
    }
}

Body:
The most simple method to create an unlimited size array is using String Builder. This allows you to add many elements in runtime. It has 3 major components.

Declaration and Initialization.

Value addition/ Append

Print out/ Usage

Use the bellow code anywhere in Android Studio.

//Basic Decleration
        StringBuilder myString = new StringBuilder();

//Adding data
       myString.append("Hello text <br>");
        myString.append("some more data <br>");
        myString.append("more data to store <br>");

//Displaying in already created text view
        deviceDetails.setText(Html.fromHtml(callLogs+""));

Note: I'm treating this as HTML string and "
" tags will create the next line in text view. So, all added data will be displayed in a new line.


问:
Split SQL Server Column value
I have a SQL Server table which name is AbundanceImpact.

```<code>Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95
</code>```

So I want the all integer values only with SUM.

答:
Use this logic

```<code>right('Monetary~120', len('Monetary~120')-CHARINDEX('~','Monetary~120'))
</code>```

for your column with sum function.

Title: Split SQL Server Column value

Body:
I have a SQL Server table which name is AbundanceImpact.

Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95

So I want the all integer values only with SUM.

Body:
Use this logic

right('Monetary~120', len('Monetary~120')-CHARINDEX('~','Monetary~120'))

for your column with sum function.