问:
Upload large files in chunks using nodejs
I'm trying to upload very large files in chunks to a server.  The server side works great.  In the function I've come up with, it tries to upload all the files at once.  I'm new to async/await and am unsure how to proceed.  The goal is to just upload one at a time in chunks.

Note that I've stripped this out of a class, updated for clarity, and remove all the unnecessary bits.

Using node-fetch to add fetch().

Thanks for any help or advice :)

let tree = []

const start = () => {
    scan('/foo/bar', err => {
        tree.forEach(file => {
            upload(file)
        })
    })
}

const scan = dir => { ... } // assigns array of files to tree

const upload = file => {
    const stream = fs.createReadStream(file)
    stream.on('data', async chunk => {
        stream.pause()
        try {
            let response = await fetch('https://some/endpoint', {
                method: 'post',
                body: JSON.stringify({
                    file: file,
                    chunk: chunk.toString('base64')
                })
            })
            stream.resume()
        } catch(e) {
            // handle errors
        }
    })
    stream.on('end', () => {
       console.log('end', file)
    })
    stream.on('error', err => {
        console.log('error', err)
    })
}```

答:
Array.prototype.forEach runs synchronously until all elements of an array have been processed, discarding any value returned by the argument function it calls.

To upload one file at a time, try using await (inside an asynchronous function) to wait for each file to upload, in combination with returning a promise from the upload process that becomes fulfilled when an upload has been completed.  Conceptually (with no graceful error handling) it might look like

```<code>const uploadTree = async tree => {
    for( file of tree) {
         await uploadFile( file); // process files one at a time
    }
}

// wrap the existing upload code in a promise executor:

const uploadFile = file => new Promise( (resolve, reject) => {
     const stream = fs.createReadStream(file)
     stream.on('data' ...
        ...
     } catch(e) {
        console.log( "Error uploading chunk of %s", file)
        reject(e) // handle errors
     }
     stream.on('end', resolve)
     stream.on('error', e=> {
        console.log(" Error reading %s", file)
        reject (e)
     })
});

// upload complete tree array files:

uploadTree(tree)
.then( ()=> console.log( "tree uploaded successfully"));
.catch( err=> console.log("An upload failed: ", err));
</code>```

Body:
Array.prototype.forEach runs synchronously until all elements of an array have been processed, discarding any value returned by the argument function it calls.

To upload one file at a time, try using await (inside an asynchronous function) to wait for each file to upload, in combination with returning a promise from the upload process that becomes fulfilled when an upload has been completed.  Conceptually (with no graceful error handling) it might look like

const uploadTree = async tree => {
    for( file of tree) {
         await uploadFile( file); // process files one at a time
    }
}

// wrap the existing upload code in a promise executor:

const uploadFile = file => new Promise( (resolve, reject) => {
     const stream = fs.createReadStream(file)
     stream.on('data' ...
        ...
     } catch(e) {
        console.log( "Error uploading chunk of %s", file)
        reject(e) // handle errors
     }
     stream.on('end', resolve)
     stream.on('error', e=> {
        console.log(" Error reading %s", file)
        reject (e)
     })
});

// upload complete tree array files:

uploadTree(tree)
.then( ()=> console.log( "tree uploaded successfully"));
.catch( err=> console.log("An upload failed: ", err));


来源: stackexchange

问:
How to use Regedit utility to see Virtual Registry for a win32 uwp app
Is it possible to see the Virtual Registry of my win32 UWP App (desktop-bridge converted)? I know that all programmatic access goes to the virtual registry and that works. But I want to view it with RegEdit. Any solutions?

I remember viewing it about a year back but don't remember the details.

答:
Based on the document, App packages contain a registry.dat file, which serves as the logical equivalent of HKLM\Software in the real registry. But there is no clear explanation about where it is stored. And all writes under HKCU are copy-on-written to a private per-user, per-app location.  For more information here: Registry

So currently, there is no good way to check that.

ContentLicense: CC BY-SA 4.0


问:
Replace null values from a select command in jq with the value of another field
Goal is to search for null values of part_description and insert in part field value.

```<code>[
  {
    "part": "brake-01982",
    "part_description": null,
  }
]
</code>```

Expected Output

```<code>[
  {
    "part": "brake-01982",
    "part_description": "brake-01982",
  }
]
</code>```

Command:
jq '(.[] | select(.part_description==null).part_description) |= .part'

Results in no change

What does work is if I try to insert a string value. The double quoted string results in what I would expect. Demo below. How do I pass another fields value into this command vs a quoted string?

Command: jq '(.[] | select(.part_description==null).part_description) |= "test"'

Demo

Output

```<code>[
  {
    "part": "brake-01982",
    "part_description": "test"
  }
]
</code>```

答:
Goal is to search for null values of part_description ....

If this is indeed the goal, then you would need to test for null rather than relying on // or //=.  So you could write:

```<code>map( if has("part_description") and .part_description == null
     then .part_description = .part else . end )
</code>```

Body:
Goal is to search for null values of part_description and insert in part field value.

[
  {
    "part": "brake-01982",
    "part_description": null,
  }
]

Expected Output

[
  {
    "part": "brake-01982",
    "part_description": "brake-01982",
  }
]

Command:
jq '(.[] | select(.part_description==null).part_description) |= .part'

Results in no change

What does work is if I try to insert a string value. The double quoted string results in what I would expect. Demo below. How do I pass another fields value into this command vs a quoted string?

Command: jq '(.[] | select(.part_description==null).part_description) |= "test"'

Demo

Output

[
  {
    "part": "brake-01982",
    "part_description": "test"
  }
]

Body:
Goal is to search for null values of part_description ....

If this is indeed the goal, then you would need to test for null rather than relying on // or //=.  So you could write:

map( if has("part_description") and .part_description == null
     then .part_description = .part else . end )


问:
Why does space appear at the top of listview?
recently i have making app and found problem on listview,

i want locationed container on the bottom and in it have listview.

and a space will appear on the top of the listview

i don't want space on the top of listview

how can i remove the space??

```<code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:run_flutter/controller.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MainPage(),
    );
  }
}

class MainPage extends StatelessWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    TestController testController = TestController();
    return Scaffold(
      body: Container(
        width: Get.width,
        height: Get.height,
        child: Stack(
          children: [
            Positioned(
              bottom: 0,
              child: AnimatedContainer(
                height: 50,
                width: Get.width,
                color: Colors.amber,
                duration: Duration(milliseconds: 100),
                child: ListView(
                  children: [
                    Text("data"),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
According to docs,

By default, [ListView] will automatically pad the list's scrollable
extremities to avoid partial obstructions indicated by [MediaQuery]'s
padding. To avoid this behavior, override with a zero [padding]
property.

You've to add MediaQuery with removePadding constructor (with removeTop to true) parent to remove the intentional extra top margin.

Here's code snippet:

```<code> MediaQuery.removePadding(
    context: context,
    removeTop: true,
    child: ListView.builder(
     .......
   )
 );
</code>```

For more information, follow this issue.

Body:
recently i have making app and found problem on listview,

i want locationed container on the bottom and in it have listview.

and a space will appear on the top of the listview

i don't want space on the top of listview

how can i remove the space??

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:run_flutter/controller.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MainPage(),
    );
  }
}

class MainPage extends StatelessWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    TestController testController = TestController();
    return Scaffold(
      body: Container(
        width: Get.width,
        height: Get.height,
        child: Stack(
          children: [
            Positioned(
              bottom: 0,
              child: AnimatedContainer(
                height: 50,
                width: Get.width,
                color: Colors.amber,
                duration: Duration(milliseconds: 100),
                child: ListView(
                  children: [
                    Text("data"),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Body:
According to docs,

By default, [ListView] will automatically pad the list's scrollable
extremities to avoid partial obstructions indicated by [MediaQuery]'s
padding. To avoid this behavior, override with a zero [padding]
property.

You've to add MediaQuery with removePadding constructor (with removeTop to true) parent to remove the intentional extra top margin.

Here's code snippet:

 MediaQuery.removePadding(
    context: context,
    removeTop: true,
    child: ListView.builder(
     .......
   )
 );

For more information, follow this issue.


问:
Python - Pandas CSV file with error when converting mixed data types string to number
So I have a large csv file with lots of data. The main column 'Results', that I am interested in has integers, float, NaN data types and also number as text. I need to aggregate 'Results' but before I do I want to convert the column to float data type. The values that are text have trailing spaces like the following:
["1.07  ", "8.22     ", "8.6      ", "11.41     ", "7.93       "]

The error I get is...

AttributeError: Can only use .str accessor with string values!

```<code>import pandas as pd
import os
import numpy as np

csv_file = 'c:/path/to/file/big.csv'
# ... more lines of code ...

df = pd.read_csv(csv_file, usecols=my_cols, parse_dates=['Date'])
df = df[df['Company ID'].str.contains(my_company)]
print('df of csv created')
# Above code works great.

# the below 2 tries did not work for me
# df['Result'] = pd.to_numeric(df['Result'].str.replace(' ', ''), errors='ignore')
# df['Result'] = df['Result'].str.strip() # causes an error

# now let's try np.where...
# the below causes AttributeError: Can only use .str accessor with string values!
df['Result'] = np.where(df['Result'].dtype == np.str, df['Result'].str.strip(),
df['Result'])
df['Result'] = pd.to_numeric(df['Result'], downcast="float", errors='raise')
</code>```

How should I resolve this?

答:
Why don't you try this code to explicitly convert all the value as stirng using astype(str).

```<code>import pandas as pd

df = pd.DataFrame({
    'Result': [' a ', ' b', 'c ']
})

df['Result'] = df['Result'].astype(str).str.strip()
print(df['Result'])

#0    a
#1    b
#2    c
#Name: Result, dtype: object
</code>```

Sometime, I use this code if NaN or numbers are included in a Series to avoid getting the error msg.

Body:
So I have a large csv file with lots of data. The main column 'Results', that I am interested in has integers, float, NaN data types and also number as text. I need to aggregate 'Results' but before I do I want to convert the column to float data type. The values that are text have trailing spaces like the following:
["1.07  ", "8.22     ", "8.6      ", "11.41     ", "7.93       "]

The error I get is...

AttributeError: Can only use .str accessor with string values!

import pandas as pd
import os
import numpy as np

csv_file = 'c:/path/to/file/big.csv'
# ... more lines of code ...

df = pd.read_csv(csv_file, usecols=my_cols, parse_dates=['Date'])
df = df[df['Company ID'].str.contains(my_company)]
print('df of csv created')
# Above code works great.

# the below 2 tries did not work for me
# df['Result'] = pd.to_numeric(df['Result'].str.replace(' ', ''), errors='ignore')
# df['Result'] = df['Result'].str.strip() # causes an error

# now let's try np.where...
# the below causes AttributeError: Can only use .str accessor with string values!
df['Result'] = np.where(df['Result'].dtype == np.str, df['Result'].str.strip(),
df['Result'])
df['Result'] = pd.to_numeric(df['Result'], downcast="float", errors='raise')

How should I resolve this?

Body:
Why don't you try this code to explicitly convert all the value as stirng using astype(str).

import pandas as pd

df = pd.DataFrame({
    'Result': [' a ', ' b', 'c ']
})

df['Result'] = df['Result'].astype(str).str.strip()
print(df['Result'])

#0    a
#1    b
#2    c
#Name: Result, dtype: object

Sometime, I use this code if NaN or numbers are included in a Series to avoid getting the error msg.


问:
ethereum solidity: from concatenated hexadecimal strings to uint64[]
I want my API to return an array of uint64 to my on-chain contract.

I tried 2 response formats for my API:

The array of uint64 itself (BN string here, but I need it in true uint64 not strings in my contract):

```<code>{"data":["629343835796877311","629343835797458943","629343835797471231"]}
</code>```

concatenated hexadecimal strings (a new value every 16 chars):

```<code>{"data":"08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff"}
</code>```

I discarded using the first approach because having ["629343835796877311","629343835797458943","629343835797471231"] as bytes is actually difficult to extract. I might be wrong! Maybe there is a base64 approach to encode and decode the data back into solidity data types, maybe?

I will use the second approach bellow.

Chainlink will pass the response as bytes memory _data:

```<code>  function fulfill(bytes32 _requestId, bytes memory _data)
    public
    recordChainlinkFulfillment(_requestId)
  {
      data = string(_data);
  }
</code>```

Those bytes memory _data are successfully received and converted to a string (in storage data). The string value looks like this

```<code>08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff ...
</code>```

In this example each 16 chars represent a uint64 number.
The first one: 08bbe0e25e412fff is 629343835796877311 for instance.

In solidity, I need to split the string each 16 chars and then convert it into their uint64 value.
I could use the bytes memory _data instead of the string(_data) if the code would be simpler or consume less gas. I am not sure

Please I need help with this I have been struggling.
Thanks

答:
I got this contract working

COMMENTS:

the method hexBytesToInt is going to get a string representing hexa value like ffa0 for instance and return it's decimal value.

the method getSlice is just going to slice a string. In my case I have a new hexa value every 16 chars so I need to slice (0,16) than (16,32) etc...

the method hexStringToIntArray is managing the increments to slice every 16 chars and call the hexBytesToInt to transform the hex string in uint.

If you really want to dig into this solution, you are better off starting by understanding the test cases.

```<code>pragma solidity >=0.4.22 <0.8.11;

contract Serializer {

    function hexStringToIntArray(string memory s) public pure returns (uint64[] memory) {
        uint size = bytes(s).length / 16;
        uint64[] memory result = new uint64[](size);
        for (uint i = 0; i< size; i++) {
            string memory strSlice = getSlice(i*16, (i+1)*16, s);
            result[i] = hexStringToInt(strSlice);
        }
        return result;
    }

    function getSlice(uint startIndex, uint endIndex, string memory str) public pure returns (string memory) {
        bytes memory strBytes = bytes(str);
        bytes memory result = new bytes(endIndex-startIndex);
        for(uint i = startIndex; i < endIndex; i++) {
            result[i-startIndex] = strBytes[i];
        }
        return string(result);
    }

    function hexBytesToInt(bytes memory ss) public pure returns (uint64){
        uint64 val = 0;
        uint8 a = uint8(97); // a
        uint8 zero = uint8(48); //0
        uint8 nine = uint8(57); //9
        uint8 A = uint8(65); //A
        uint8 F = uint8(70); //F
        uint8 f = uint8(102); //f
        for (uint i=0; i<ss.length; ++i) {
            uint8 byt = uint8(ss[i]);
            if (byt >= zero && byt <= nine) byt = byt - zero;
            else if (byt >= a && byt <= f) byt = byt - a + 10;
            else if (byt >= A && byt <= F) byt = byt - A + 10;
            val = (val << 4) | (byt & 0xF);
        }
        return val;
    }

    function hexStringToInt(string memory s) public pure returns (uint64) {
        bytes memory ss = bytes(s);
        uint64 val = hexBytesToInt(ss);
        return val;
    }
}
</code>```

the tests:

```<code>const Serializer = artifacts.require("Serializer");
const truffleAssert = require("truffle-assertions");
const fs = require("fs");
const { readLines } = require("./utils.js");
const BN = web3.utils.BN;

contract("Serializer", (accounts) => {
  const [deployerAddress, tokenHolderOneAddress, tokenHolderTwoAddress] = accounts;

  it("hexStringToInt", async () => {
    let s = await Serializer.deployed();
    let result = await s.hexStringToInt.call("08bbe0e25e412fff");
    let expected = new BN("629343835796877311");
    assert.equal(result.toString(10), expected.toString(10));
    result = await s.hexStringToInt.call("08bbe0e25e4a0fff");
    expected = new BN("629343835797458943");
    assert.equal(result.toString(10), expected.toString(10));
    result = await s.hexStringToInt.call("08bbe0e25e4a3fff");
    expected = new BN("629343835797471231");
    assert.equal(result.toString(10), expected.toString(10));
  });
  it("getSlice1", async () => {
    let s = await Serializer.deployed();
    let result = await s.getSlice.call(0, 16, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    let expected = "08bbe0e25e412fff";
    assert.equal(result, expected);
  });
  it("getSlice2", async () => {
    let s = await Serializer.deployed();
    const result = await s.getSlice.call(16, 32, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    const expected = "08bbe0e25e4a0fff";
    assert.equal(result, expected);
  });
  it("getSlice3", async () => {
    let s = await Serializer.deployed();
    const result = await s.getSlice.call(32, 48, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    const expected = "08bbe0e25e4a3fff";
    assert.equal(result, expected);
  });
  it("hexStringToIntArray", async () => {
    let s = await Serializer.deployed();
    let result = await s.hexStringToIntArray.call("08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    console.log(result);
    let expected = [
      new BN("629343835796877311").toString(),
      new BN("629343835797458943").toString(),
      new BN("629343835797471231").toString(),
    ];
    const resultS = result.map((x) => x.toString());
    assert.deepEqual(resultS, expected);
  });
});
</code>```

Body:
I want my API to return an array of uint64 to my on-chain contract.

I tried 2 response formats for my API:

The array of uint64 itself (BN string here, but I need it in true uint64 not strings in my contract):

{"data":["629343835796877311","629343835797458943","629343835797471231"]}

concatenated hexadecimal strings (a new value every 16 chars):

{"data":"08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff"}

I discarded using the first approach because having ["629343835796877311","629343835797458943","629343835797471231"] as bytes is actually difficult to extract. I might be wrong! Maybe there is a base64 approach to encode and decode the data back into solidity data types, maybe?

I will use the second approach bellow.

Chainlink will pass the response as bytes memory _data:

  function fulfill(bytes32 _requestId, bytes memory _data)
    public
    recordChainlinkFulfillment(_requestId)
  {
      data = string(_data);
  }

Those bytes memory _data are successfully received and converted to a string (in storage data). The string value looks like this

08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff ...

In this example each 16 chars represent a uint64 number.
The first one: 08bbe0e25e412fff is 629343835796877311 for instance.

In solidity, I need to split the string each 16 chars and then convert it into their uint64 value.
I could use the bytes memory _data instead of the string(_data) if the code would be simpler or consume less gas. I am not sure

Please I need help with this I have been struggling.
Thanks

Body:
I got this contract working

COMMENTS:

the method hexBytesToInt is going to get a string representing hexa value like ffa0 for instance and return it's decimal value.

the method getSlice is just going to slice a string. In my case I have a new hexa value every 16 chars so I need to slice (0,16) than (16,32) etc...

the method hexStringToIntArray is managing the increments to slice every 16 chars and call the hexBytesToInt to transform the hex string in uint.

If you really want to dig into this solution, you are better off starting by understanding the test cases.

pragma solidity >=0.4.22 <0.8.11;

contract Serializer {

    function hexStringToIntArray(string memory s) public pure returns (uint64[] memory) {
        uint size = bytes(s).length / 16;
        uint64[] memory result = new uint64[](size);
        for (uint i = 0; i< size; i++) {
            string memory strSlice = getSlice(i*16, (i+1)*16, s);
            result[i] = hexStringToInt(strSlice);
        }
        return result;
    }

    function getSlice(uint startIndex, uint endIndex, string memory str) public pure returns (string memory) {
        bytes memory strBytes = bytes(str);
        bytes memory result = new bytes(endIndex-startIndex);
        for(uint i = startIndex; i < endIndex; i++) {
            result[i-startIndex] = strBytes[i];
        }
        return string(result);
    }

    function hexBytesToInt(bytes memory ss) public pure returns (uint64){
        uint64 val = 0;
        uint8 a = uint8(97); // a
        uint8 zero = uint8(48); //0
        uint8 nine = uint8(57); //9
        uint8 A = uint8(65); //A
        uint8 F = uint8(70); //F
        uint8 f = uint8(102); //f
        for (uint i=0; i<ss.length; ++i) {
            uint8 byt = uint8(ss[i]);
            if (byt >= zero && byt <= nine) byt = byt - zero;
            else if (byt >= a && byt <= f) byt = byt - a + 10;
            else if (byt >= A && byt <= F) byt = byt - A + 10;
            val = (val << 4) | (byt & 0xF);
        }
        return val;
    }

    function hexStringToInt(string memory s) public pure returns (uint64) {
        bytes memory ss = bytes(s);
        uint64 val = hexBytesToInt(ss);
        return val;
    }
}

the tests:

const Serializer = artifacts.require("Serializer");
const truffleAssert = require("truffle-assertions");
const fs = require("fs");
const { readLines } = require("./utils.js");
const BN = web3.utils.BN;

contract("Serializer", (accounts) => {
  const [deployerAddress, tokenHolderOneAddress, tokenHolderTwoAddress] = accounts;

  it("hexStringToInt", async () => {
    let s = await Serializer.deployed();
    let result = await s.hexStringToInt.call("08bbe0e25e412fff");
    let expected = new BN("629343835796877311");
    assert.equal(result.toString(10), expected.toString(10));
    result = await s.hexStringToInt.call("08bbe0e25e4a0fff");
    expected = new BN("629343835797458943");
    assert.equal(result.toString(10), expected.toString(10));
    result = await s.hexStringToInt.call("08bbe0e25e4a3fff");
    expected = new BN("629343835797471231");
    assert.equal(result.toString(10), expected.toString(10));
  });
  it("getSlice1", async () => {
    let s = await Serializer.deployed();
    let result = await s.getSlice.call(0, 16, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    let expected = "08bbe0e25e412fff";
    assert.equal(result, expected);
  });
  it("getSlice2", async () => {
    let s = await Serializer.deployed();
    const result = await s.getSlice.call(16, 32, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    const expected = "08bbe0e25e4a0fff";
    assert.equal(result, expected);
  });
  it("getSlice3", async () => {
    let s = await Serializer.deployed();
    const result = await s.getSlice.call(32, 48, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    const expected = "08bbe0e25e4a3fff";
    assert.equal(result, expected);
  });
  it("hexStringToIntArray", async () => {
    let s = await Serializer.deployed();
    let result = await s.hexStringToIntArray.call("08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
    console.log(result);
    let expected = [
      new BN("629343835796877311").toString(),
      new BN("629343835797458943").toString(),
      new BN("629343835797471231").toString(),
    ];
    const resultS = result.map((x) => x.toString());
    assert.deepEqual(resultS, expected);
  });
});


问:
Azure DevOps self hosted agent reports wrong version for NPM
We have updated Node to version 10.16.3 and NPM to version 6.11.3 (all the latest at this time) on our Windows based self hosted agent.

However, in a job run logs, we see that the agent reports version 6.9.0 for NPM, which is the default version for Node 10.16.3 installation.

Inside the VM where the hosted agent is, if I run 'npm' in the CMD, I get the latest version for NPM. Also, if I run the same command that the agent is running to get the version, I still get the correct version for NPM:

What could be wrong here?
The reason we want the latest version of NPM is because our builds run faster with it.

Thank you!

答:
Yeah, I got caught out by this too. Because it runs under the NetworkService account, it can't read the global folder, so has it's own little copy/cache at

```<code>C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\npm
</code>```

My easiest way to get back up and running, was to just manually upgrade the npm at that location using the following command:

```<code>npm install --prefix C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\npm  npm
</code>```

Body:
Yeah, I got caught out by this too. Because it runs under the NetworkService account, it can't read the global folder, so has it's own little copy/cache at

C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\npm

My easiest way to get back up and running, was to just manually upgrade the npm at that location using the following command:

npm install --prefix C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\npm  npm


问:
How to use exiftool to set Windows specific metadata on a file
I'm using the exiftool from my java application to modify the metadata of different file. Mainly DOC, PDF, and JPEG.

I want to set the "comments" windows metadata property shown in this image to some information I grab from the database.

Question

Is there a way I can use ExifTool from my java application or from command line such that I can change the "comments" metadata properties on a file?

答:
While the link to your image is broken (not surprising 9 years on) I assume it's the 'Comments' section from the file's Properties context menu option.

For at least JPEG files:

exiftool -XPComment="Data can include spaces" filename.jpg

ContentLicense: CC BY-SA 3.0


问:
Using global variables in a function
How do I create or use a global variable inside a function?

How do I use a global variable that was defined in one function inside other functions?

Failing to use the global keyword where appropriate often causes UnboundLocalError. The precise rules for this are explained at UnboundLocalError on local variable when reassigned after first use. Generally, please close other questions as a duplicate of that question when an explanation is sought, and this question when someone simply needs to know the global keyword.

答:
Like this code:

```<code>myVar = 12

def myFunc():
  myVar += 12
</code>```

Key:

If you declare a variable outside the strings, it become global.

If you declare a variable inside the strings, it become local.

If you want to declare a global variable inside the strings, use the keyword global before the variable you want to declare:

```<code>myVar = 124
def myFunc():
  global myVar2
  myVar2 = 100
myFunc()
print(myVar2)
</code>```

and then you have 100 in the document.

Title: Using global variables in a function

LastEditorDisplayName: Gerald Kaszuba

Body:
Like this code:

myVar = 12

def myFunc():
  myVar += 12

Key:

If you declare a variable outside the strings, it become global.

If you declare a variable inside the strings, it become local.

If you want to declare a global variable inside the strings, use the keyword global before the variable you want to declare:

myVar = 124
def myFunc():
  global myVar2
  myVar2 = 100
myFunc()
print(myVar2)

and then you have 100 in the document.


问:
Android Security Exception on imageView.setImageUri with album image Uri
The image source is a Uri which is stored in Firestore.
If a user saves their profile photo from either camera or album, it gets its Uri then stores as a string in the Firestore. There's no problem until this point.

I'll say the photo taken from Camera as CameraImage, and the photo chosen from the album as AlbumImage.

But when displaying the AlbumImage's Uri(as String) retrieved from Firestore, Security Exception is thrown.

Possible solutions I'm assuming are:

need to save the Uri in a different way.

need to load Uri in a different way.

Loding the image(error on this line):

```<code>iv_photo.setImageURI(Uri.parse(mUser.getPhotoString()));
</code>```

Activity for result:

```<code>Intent selectIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        selectIntent.setType("image/*");
        galleryResultLauncher.launch(selectIntent);
</code>```
```<code>    ActivityResultLauncher<Intent> galleryResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {

                @Override
                public void onActivityResult(ActivityResult result) {

                    if(result.getResultCode() == Activity.RESULT_OK){

                        Uri selectedImg = result.getData().getData();
                        iv_photo.setImageURI(selectedImg);
                        mUri = selectedImg.toString();
                    }
                }
            });
</code>```

Security Exception:

```<code>Permission Denial: opening provider com.google.android.apps.photos.contentprovider.impl.MediaContentProvider from ProcessRecord{c7fba1f 23624:com.example.seanlee_thefootballgallery_2201/u0a165} (pid=23624, uid=10165) that is not exported from UID 10118
</code>```

AlbumImage URIs is similar to this.

```<code>content://com.example.seanlee_thefootballgallery_2201/app_images/10-02-2022-09-17-01.jpg
</code>```

CameraImage URIs is similar to this.

```<code>content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F25/ORIGINAL/NONE/image%2Fjpeg/967503137
</code>```

Manifest:

```<code>    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="28" />
</code>```

答:
you can upload your photo to firebase storage first, you can read this upload file to firebase storage .after that you can add more code like this to get Url from storage

```<code>StorageReference storageReference = FirebaseStorage.getInstance().getReference().child()
        //that child is up to you
        storageReference.putFile(imageUri).addOnCompleteListener(task ->
                storageReference.getDownloadUrl().addOnSuccessListener(uri -> {
            String url = uri.toString();
        }));
</code>```

after that you can save url into firestore. if you want show it into your app you should get url from firestore first after that download it from firebase storage. for download file you can read this download file from firebase storage

hope it can solve your problem :)

Body:
The image source is a Uri which is stored in Firestore.
If a user saves their profile photo from either camera or album, it gets its Uri then stores as a string in the Firestore. There's no problem until this point.

I'll say the photo taken from Camera as CameraImage, and the photo chosen from the album as AlbumImage.

But when displaying the AlbumImage's Uri(as String) retrieved from Firestore, Security Exception is thrown.

Possible solutions I'm assuming are:

need to save the Uri in a different way.

need to load Uri in a different way.

Loding the image(error on this line):

iv_photo.setImageURI(Uri.parse(mUser.getPhotoString()));

Activity for result:

Intent selectIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        selectIntent.setType("image/*");
        galleryResultLauncher.launch(selectIntent);

    ActivityResultLauncher<Intent> galleryResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {

                @Override
                public void onActivityResult(ActivityResult result) {

                    if(result.getResultCode() == Activity.RESULT_OK){

                        Uri selectedImg = result.getData().getData();
                        iv_photo.setImageURI(selectedImg);
                        mUri = selectedImg.toString();
                    }
                }
            });

Security Exception:

Permission Denial: opening provider com.google.android.apps.photos.contentprovider.impl.MediaContentProvider from ProcessRecord{c7fba1f 23624:com.example.seanlee_thefootballgallery_2201/u0a165} (pid=23624, uid=10165) that is not exported from UID 10118

AlbumImage URIs is similar to this.

content://com.example.seanlee_thefootballgallery_2201/app_images/10-02-2022-09-17-01.jpg

CameraImage URIs is similar to this.

content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F25/ORIGINAL/NONE/image%2Fjpeg/967503137

Manifest:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="28" />

Body:
you can upload your photo to firebase storage first, you can read this upload file to firebase storage .after that you can add more code like this to get Url from storage

StorageReference storageReference = FirebaseStorage.getInstance().getReference().child()
        //that child is up to you
        storageReference.putFile(imageUri).addOnCompleteListener(task ->
                storageReference.getDownloadUrl().addOnSuccessListener(uri -> {
            String url = uri.toString();
        }));

after that you can save url into firestore. if you want show it into your app you should get url from firestore first after that download it from firebase storage. for download file you can read this download file from firebase storage

hope it can solve your problem :)


问:
How to order by, a json_object in mysql
I've a problem sorting a JSON_OBJECT:

How can I sort the objects as they are in the JSON OBJECT?

答:
As workaround, instead:

select json_arrayagg(...) from someTable order by ...
```
<p>You can:</p>
<pre class="lang-sql prettyprint-override"><code>select json_arrayagg(...) from (select someFields from someTable order by ...) as t1
</code>```

Title: How to order by, a json_object in mysql

Body:
As workaround, instead:

select json_arrayagg(...) from someTable order by ...

You can:

select json_arrayagg(...) from (select someFields from someTable order by ...) as t1


问:
Method Syntax in Objective-C
Can someone explain this method declaration syntax for me?  In this function, the number of rows of a UIPickerView (slot machine UI on the iPhone) is being returned.  From my understanding, the Method is called 'pickerView', and returns an NSInteger.

It passes in a pointer to the UIPickerview called 'pickerView' ... first, why is the method called the same name as the parameter?

Next there is NSInteger parameter called component that tells us which component we are counting the rows for.  The logic to decide which is in the body of the method.

What is 'numberOfRowsInComponent? It seems to describe the value we are returning, but it is in the middle of the parameters.

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component
{
    if (component == kStateComponent)
        return [self.states count];

    return[self.zips count];
}
</code>```

答:
Adding to the previous answers, I'd just like to say that Objective-C methods (or messages if you prefer) have external and internal parameter names.

So in this case:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component
</code>```

numberOfRowsInComponent is the external name, the one that you would use when calling this method from the outside.

And component is the internal name of the parameter, the one you use to refer to the parameter from inside of the method.

Hope that clears it up a bit.

Title: Method Syntax in Objective-C

Body:
Can someone explain this method declaration syntax for me?  In this function, the number of rows of a UIPickerView (slot machine UI on the iPhone) is being returned.  From my understanding, the Method is called 'pickerView', and returns an NSInteger.

It passes in a pointer to the UIPickerview called 'pickerView' ... first, why is the method called the same name as the parameter?

Next there is NSInteger parameter called component that tells us which component we are counting the rows for.  The logic to decide which is in the body of the method.

What is 'numberOfRowsInComponent? It seems to describe the value we are returning, but it is in the middle of the parameters.

- (NSInteger) pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component
{
    if (component == kStateComponent)
        return [self.states count];

    return[self.zips count];
}

LastEditorDisplayName: epatel

Body:
Adding to the previous answers, I'd just like to say that Objective-C methods (or messages if you prefer) have external and internal parameter names.

So in this case:

- (NSInteger) pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component

numberOfRowsInComponent is the external name, the one that you would use when calling this method from the outside.

And component is the internal name of the parameter, the one you use to refer to the parameter from inside of the method.

Hope that clears it up a bit.

OwnerDisplayName: Karolis


问:
How do I properly unwrap FLV video into raw and valid h264 segments for gstreamer buffers?
I have written an RTMP server in rust that successfully allows RTMP publishers to connect, push a video stream, and RTMP clients can connect and watch those video streams successfully.

When a video RTMP packet comes in, I attempt to unwrap the video from the FLV container via:

    // TODO: The FLV spec has the AVCPacketType and composition time as the first parts of the
    // AVCPACKETTYPE.  It's unclear if these two fields are part of h264 or FLV specific.
    let flv_tag = data.split_to(1);
    let is_sequence_header;
    let codec = if flv_tag[0] & 0x07 == 0x07 {
        is_sequence_header = data[0] == 0x00;
        VideoCodec::H264
    } else {
        is_sequence_header = false;
        VideoCodec::Unknown
    };

    let is_keyframe = flv_tag[0] & 0x10 == 0x10;
```
<p>After this runs <code>data</code> contains the <code>AVCVIDEOPACKET</code> with the flv tag removed.  When I send this video to other RTMP clients i just prepend the correct flv tag to it and send it off.</p>
<p>Now I am trying to pass the video packets to gstreamer in order to do in process transcoding.  To do this I set up an <code>appsrc | avdec_264</code> pipeline, and gave the <code>appsrc</code> component the following caps:</p>
<pre class="lang-rust prettyprint-override"><code>        video_source.set_caps(Some(
            &Caps::builder("video/x-h264")
                .field("alignment", "nal")
                .field("stream-format", "byte-stream")
                .build()
        ));
</code>```

Now when an RTMP publisher sends a video packet, I take the (attempted) unwrapped video packet and pass it to my appsrc via

    pub fn push_video(&self, data: Bytes, timestamp: RtmpTimestamp) {
        let mut buffer = Buffer::with_size(data.len()).unwrap();
        {
            let buffer = buffer.get_mut().unwrap();
            buffer.set_pts(ClockTime::MSECOND * timestamp.value as u64);

            let mut samples = buffer.map_writable().unwrap();
            {
                let samples = samples.as_mut_slice();
                for index in 0..data.len() {
                    samples[index] = data[index];
                }
            }
        }

        self.video_source.push_buffer(buffer).unwrap();
    }
```
<p>When this occurs the following gstreamer debug output appears</p>
```2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #0 (is_sequence_header:true, is_keyframe=true)
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Connection 63397d56-16fb-4b54-a622-d991b5ad2d8e sent audio data
0:00:05.531722000  7516 000001C0C04011C0 INFO               GST_EVENT gstevent.c:973:gst_event_new_segment: creating segment event bytes segment start=0, offset=0, stop=-1, rate=1.000000, applied_rate=1.000000, flags=0x00, time=0, base=0, position 0, duration -1
0:00:05.533525000  7516 000001C0C04011C0 INFO                 basesrc gstbasesrc.c:3018:gst_base_src_loop:<video_source> marking pending DISCONT
0:00:05.535385000  7516 000001C0C04011C0 WARN            videodecoder gstvideodecoder.c:2818:gst_video_decoder_chain:<video_decode> Received buffer without a new-segment. Assuming timestamps start from 0.
0:00:05.537381000  7516 000001C0C04011C0 INFO               GST_EVENT gstevent.c:973:gst_event_new_segment: creating segment event time segment start=0:00:00.000000000, offset=0:00:00.000000000, stop=99:99:99.999999999, rate=1.000000, applied_rate=1.000000, flags=0x00, time=0:00:00.000000000, base=0:00:00.000000000, position 0:00:00.000000000, duration 99:99:99.999999999
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #1 (is_sequence_header:false, is_keyframe=true)
0:00:05.563445000  7516 000001C0C04011C0 INFO                   libav :0:: Invalid NAL unit 0, skipping.
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #2 (is_sequence_header:false, is_keyframe=false)
0:00:05.579274000  7516 000001C0C04011C0 ERROR                  libav :0:: No start code is found.
0:00:05.581338000  7516 000001C0C04011C0 ERROR                  libav :0:: Error splitting the input into NAL units.
0:00:05.583337000  7516 000001C0C04011C0 WARN                   libav gstavviddec.c:2068:gst_ffmpegviddec_handle_frame:<video_decode> Failed to send data for decoding
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #3 (is_sequence_header:false, is_keyframe=false)
0:00:05.595253000  7516 000001C0C04011C0 ERROR                  libav :0:: No start code is found.
0:00:05.597204000  7516 000001C0C04011C0 ERROR                  libav :0:: Error splitting the input into NAL units.
0:00:05.599262000  7516 000001C0C04011C0 WARN                   libav gstavviddec.c:2068:gst_ffmpegviddec_handle_frame:<video_decode> Failed to send data for decoding
```
<p>Based on this I figured this might be caused by the non-data portions of the <code>AVCVIDEOPACKET</code> not being part of the h264 flow, but an FLV specific flow.  So I tried ignoring  the first 4 bytes (<code>AVCPacketType</code> and <code>CompositionTime</code> fields) of each packet I wrote to the buffer:</p>
<pre class="lang-rust prettyprint-override"><code>    pub fn push_video(&self, data: Bytes, timestamp: RtmpTimestamp) {
        let mut buffer = Buffer::with_size(data.len() - 4).unwrap();
        {
            let buffer = buffer.get_mut().unwrap();
            buffer.set_pts(ClockTime::MSECOND * timestamp.value as u64);

            let mut samples = buffer.map_writable().unwrap();
            {
                let samples = samples.as_mut_slice();
                for index in 4..data.len() {
                    samples[index - 4] = data[index];
                }
            }
        }

        self.video_source.push_buffer(buffer).unwrap();
    }
</code>```

This essentially gave me the same logging output and errors.  This is reproducible with the h264parse plugin as well.

What am I missing in the unwrapping process to pass raw h264 video to gstreamer?

Edit:

Realizing I misread the pad template I tried the following caps instead

        video_source.set_caps(Some(
            &Caps::builder("video/x-h264")
                .field("alignment", "au")
                .field("stream-format", "avc")
                .build()
        ));
```

This also failed with pretty simmilar output.

答:
I think I finally figured this out.

The first thing is that I need to include removing the AVCVIDEOPACKET headers (packet type and composition time fields).  These are not part of the h264 format and thus cause parsing errors.

The second thing I needed to do was to not pass the sequence header as a buffer to the source.  Instead the sequence header bytes need to be set as the codec_data field for the appsrc's caps.  This now allows for no parsing errors when passing the video data to h264parse, and even gives me a correctly sized window.

The third thing I was missing is the correct dts and pts values.  It turns out the RTMP timestamp I'm given is the dts, and pts = AVCVIDEOPACKET.CompositionTime + dts.

Body:
I have written an RTMP server in rust that successfully allows RTMP publishers to connect, push a video stream, and RTMP clients can connect and watch those video streams successfully.

When a video RTMP packet comes in, I attempt to unwrap the video from the FLV container via:

    // TODO: The FLV spec has the AVCPacketType and composition time as the first parts of the
    // AVCPACKETTYPE.  It's unclear if these two fields are part of h264 or FLV specific.
    let flv_tag = data.split_to(1);
    let is_sequence_header;
    let codec = if flv_tag[0] & 0x07 == 0x07 {
        is_sequence_header = data[0] == 0x00;
        VideoCodec::H264
    } else {
        is_sequence_header = false;
        VideoCodec::Unknown
    };

    let is_keyframe = flv_tag[0] & 0x10 == 0x10;

After this runs data contains the AVCVIDEOPACKET with the flv tag removed.  When I send this video to other RTMP clients i just prepend the correct flv tag to it and send it off.

Now I am trying to pass the video packets to gstreamer in order to do in process transcoding.  To do this I set up an appsrc | avdec_264 pipeline, and gave the appsrc component the following caps:

        video_source.set_caps(Some(
            &Caps::builder("video/x-h264")
                .field("alignment", "nal")
                .field("stream-format", "byte-stream")
                .build()
        ));

Now when an RTMP publisher sends a video packet, I take the (attempted) unwrapped video packet and pass it to my appsrc via

    pub fn push_video(&self, data: Bytes, timestamp: RtmpTimestamp) {
        let mut buffer = Buffer::with_size(data.len()).unwrap();
        {
            let buffer = buffer.get_mut().unwrap();
            buffer.set_pts(ClockTime::MSECOND * timestamp.value as u64);

            let mut samples = buffer.map_writable().unwrap();
            {
                let samples = samples.as_mut_slice();
                for index in 0..data.len() {
                    samples[index] = data[index];
                }
            }
        }

        self.video_source.push_buffer(buffer).unwrap();
    }

When this occurs the following gstreamer debug output appears

2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #0 (is_sequence_header:true, is_keyframe=true)
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Connection 63397d56-16fb-4b54-a622-d991b5ad2d8e sent audio data
0:00:05.531722000  7516 000001C0C04011C0 INFO               GST_EVENT gstevent.c:973:gst_event_new_segment: creating segment event bytes segment start=0, offset=0, stop=-1, rate=1.000000, applied_rate=1.000000, flags=0x00, time=0, base=0, position 0, duration -1
0:00:05.533525000  7516 000001C0C04011C0 INFO                 basesrc gstbasesrc.c:3018:gst_base_src_loop:<video_source> marking pending DISCONT
0:00:05.535385000  7516 000001C0C04011C0 WARN            videodecoder gstvideodecoder.c:2818:gst_video_decoder_chain:<video_decode> Received buffer without a new-segment. Assuming timestamps start from 0.
0:00:05.537381000  7516 000001C0C04011C0 INFO               GST_EVENT gstevent.c:973:gst_event_new_segment: creating segment event time segment start=0:00:00.000000000, offset=0:00:00.000000000, stop=99:99:99.999999999, rate=1.000000, applied_rate=1.000000, flags=0x00, time=0:00:00.000000000, base=0:00:00.000000000, position 0:00:00.000000000, duration 99:99:99.999999999
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #1 (is_sequence_header:false, is_keyframe=true)
0:00:05.563445000  7516 000001C0C04011C0 INFO                   libav :0:: Invalid NAL unit 0, skipping.
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #2 (is_sequence_header:false, is_keyframe=false)
0:00:05.579274000  7516 000001C0C04011C0 ERROR                  libav :0:: No start code is found.
0:00:05.581338000  7516 000001C0C04011C0 ERROR                  libav :0:: Error splitting the input into NAL units.
0:00:05.583337000  7516 000001C0C04011C0 WARN                   libav gstavviddec.c:2068:gst_ffmpegviddec_handle_frame:<video_decode> Failed to send data for decoding
[2022-02-09T18:25:15Z INFO  gstreamer_mmids_scratchpad] Pushing packet #3 (is_sequence_header:false, is_keyframe=false)
0:00:05.595253000  7516 000001C0C04011C0 ERROR                  libav :0:: No start code is found.
0:00:05.597204000  7516 000001C0C04011C0 ERROR                  libav :0:: Error splitting the input into NAL units.
0:00:05.599262000  7516 000001C0C04011C0 WARN                   libav gstavviddec.c:2068:gst_ffmpegviddec_handle_frame:<video_decode> Failed to send data for decoding

Based on this I figured this might be caused by the non-data portions of the AVCVIDEOPACKET not being part of the h264 flow, but an FLV specific flow.  So I tried ignoring  the first 4 bytes (AVCPacketType and CompositionTime fields) of each packet I wrote to the buffer:

    pub fn push_video(&self, data: Bytes, timestamp: RtmpTimestamp) {
        let mut buffer = Buffer::with_size(data.len() - 4).unwrap();
        {
            let buffer = buffer.get_mut().unwrap();
            buffer.set_pts(ClockTime::MSECOND * timestamp.value as u64);

            let mut samples = buffer.map_writable().unwrap();
            {
                let samples = samples.as_mut_slice();
                for index in 4..data.len() {
                    samples[index - 4] = data[index];
                }
            }
        }

        self.video_source.push_buffer(buffer).unwrap();
    }

This essentially gave me the same logging output and errors.  This is reproducible with the h264parse plugin as well.

What am I missing in the unwrapping process to pass raw h264 video to gstreamer?

Edit:

Realizing I misread the pad template I tried the following caps instead

        video_source.set_caps(Some(
            &Caps::builder("video/x-h264")
                .field("alignment", "au")
                .field("stream-format", "avc")
                .build()
        ));

This also failed with pretty simmilar output.


问:
Flutter: Need help displaying videos
I am trying to create a tik tok ui clone in flutter. I want to display videos from my assets but the videos are not being displayed when I run the code. Can someone look over my code and give any recommendations?</p>
```<code>import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoTile extends StatefulWidget {
  const VideoTile({Key? key}) : super(key: key);

  @override
  _VideoTileState createState() => _VideoTileState();
}

class _VideoTileState extends State<VideoTile> {
  late VideoPlayerController _videoController;
  late Future _intitializeVideoPlayer;

  @override
  void initState() {
    _videoController = VideoPlayerController.asset('assets/nft_vid1.mp4');
    _intitializeVideoPlayer = _videoController.initialize();
    _videoController.setLooping(true);
    _videoController.play();
    super.initState();
  }

  @override
  void dispose() {
    _videoController.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: FutureBuilder(
        future: _intitializeVideoPlayer,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return VideoPlayer(_videoController);
          } else {
            return Container(color: Colors.pink);
          }
        },
      ),
    );
  }
}
</code>```

答:
You can try this code:</p>
```<code>import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';

class AssetVideo extends StatefulWidget {
  @override
  AssetVideoState createState() => AssetVideoState();
}

class AssetVideoState extends State<AssetVideo> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.asset('assets/nft_vid1.mp4');

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

   @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Demo',
      home: Scaffold(
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(_controller),
                )
              : Container(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
            });
          },
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          ),
        ),
      ),
    );
  }
</code>```

Title: Flutter: Need help displaying videos

Body:
I am trying to create a tik tok ui clone in flutter. I want to display videos from my assets but the videos are not being displayed when I run the code. Can someone look over my code and give any recommendations?

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoTile extends StatefulWidget {
  const VideoTile({Key? key}) : super(key: key);

  @override
  _VideoTileState createState() => _VideoTileState();
}

class _VideoTileState extends State<VideoTile> {
  late VideoPlayerController _videoController;
  late Future _intitializeVideoPlayer;

  @override
  void initState() {
    _videoController = VideoPlayerController.asset('assets/nft_vid1.mp4');
    _intitializeVideoPlayer = _videoController.initialize();
    _videoController.setLooping(true);
    _videoController.play();
    super.initState();
  }

  @override
  void dispose() {
    _videoController.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: FutureBuilder(
        future: _intitializeVideoPlayer,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return VideoPlayer(_videoController);
          } else {
            return Container(color: Colors.pink);
          }
        },
      ),
    );
  }
}

Body:
You can try this code:

import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';

class AssetVideo extends StatefulWidget {
  @override
  AssetVideoState createState() => AssetVideoState();
}

class AssetVideoState extends State<AssetVideo> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.asset('assets/nft_vid1.mp4');

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

   @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Demo',
      home: Scaffold(
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(_controller),
                )
              : Container(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
            });
          },
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          ),
        ),
      ),
    );
  }


问:
What is the difference between buffers and registers in vim?
In vim, command :reg[ister] shows me the list of registers while :ls shows the list of buffers but I'm not sure what the exact difference between registers and buffers is. I think that registers are virtual memory and are used with "(double quotation mark)+{a-zA-Z0-9.%#:-"}+{motion}.

So, what is a buffer? I confuse buffers and registers as of now.

(The only thing I know is that registers are in CPU, buffers in RAM. I need to make both concepts clear to use vim well.

This is what I found about registers in the documentation:

```<code>There are nine types of registers:
1. The unnamed register ""
2. 10 numbered registers "0 to "9
3. The small delete register "-
4. 26 named registers "a to "z or "A to "Z
5. four read-only registers ":, "., "% and "#
6. the expression register "=
7. The selection and drop registers "*, "+ and "~
8. The black hole register "_
9. Last search pattern register "/
</code>```

答:
They look similar but are different:

there is a register (act like a clipboard) called unnamed register (")

there is a buffer  called [No Name]  (contains the content of a non existing file / to be written to a file)

some misuse:

Body:
In vim, command :reg[ister] shows me the list of registers while :ls shows the list of buffers but I'm not sure what the exact difference between registers and buffers is. I think that registers are virtual memory and are used with "(double quotation mark)+{a-zA-Z0-9.%#:-"}+{motion}.

So, what is a buffer? I confuse buffers and registers as of now.

(The only thing I know is that registers are in CPU, buffers in RAM. I need to make both concepts clear to use vim well.

This is what I found about registers in the documentation:

There are nine types of registers:
1. The unnamed register ""
2. 10 numbered registers "0 to "9
3. The small delete register "-
4. 26 named registers "a to "z or "A to "Z
5. four read-only registers ":, "., "% and "#
6. the expression register "=
7. The selection and drop registers "*, "+ and "~
8. The black hole register "_
9. Last search pattern register "/


问:
Selenium Firefox webdriver cannot see webelement given but Chrome can?
I have a test case that changes the time value in the dialog pop-up. To do so, I created a method named setDateInput.

```<code>public void setDateInput(Object date, WebElement input_date, String format) throws InterruptedException {
        if(date == null) {
            //leave the date as it is.
            return;
        } else if( (date instanceof Date) ) { //arg date is passed.
            String new_date = new SimpleDateFormat(format).format(date);
            input_date.clear();
            input_date.sendKeys(new_date);
            return;
        } else if(date instanceof String) {
            input_date.clear();
            input_date.sendKeys((String)date);
            return;
        }

    }
</code>```

When it is called by this code below, Chrome driver changed the startInput to 23:55 but firefox does neither clear() nor sendKeys().

```<code>setDateInput("23:55", startInput, "HH:mm");
</code>```

So, my question is, is there a different way to handle the text type input in Firefox webdriver?

Thank you in advance.

Update:
The start_time element in HTML code as following

```<code><input type="text" id="StartTime" value="00:01" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]" placeholder="HH:MM" class="form-control input-text time-field-hm" required="" inputmode="numeric">
</code>```

答:
I found an answer by myself. This solution is not exactly fixing the issue but this is more of workaround.

I just added a method click() before clear() method. Firefox webdriver then manages to focus on that element. And it clears and sends a 23:55 String to the input field. Weird way to resolve the issue.

Or simply sendKeys("") will do as well. Hope this helpful.

Body:
I have a test case that changes the time value in the dialog pop-up. To do so, I created a method named setDateInput.

public void setDateInput(Object date, WebElement input_date, String format) throws InterruptedException {
        if(date == null) {
            //leave the date as it is.
            return;
        } else if( (date instanceof Date) ) { //arg date is passed.
            String new_date = new SimpleDateFormat(format).format(date);
            input_date.clear();
            input_date.sendKeys(new_date);
            return;
        } else if(date instanceof String) {
            input_date.clear();
            input_date.sendKeys((String)date);
            return;
        }

    }

When it is called by this code below, Chrome driver changed the startInput to 23:55 but firefox does neither clear() nor sendKeys().

setDateInput("23:55", startInput, "HH:mm");

So, my question is, is there a different way to handle the text type input in Firefox webdriver?

Thank you in advance.

Update:
The start_time element in HTML code as following

<input type="text" id="StartTime" value="00:01" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]" placeholder="HH:MM" class="form-control input-text time-field-hm" required="" inputmode="numeric">


问:
Mocking just one function in Go
I've read a bunch about this and don't understand why mocking is so complicated in Go. Is there a simple way to mock just one function?

For example:

```<code>func addB(num int) int {
  return b() + num;
}

func getB() int {
  return 3;
}
</code>```

If I want to test addB but change getB to respond with 6 or something instead, in other languages I'd write a unit test like:

```<code>expect(getB).toBeCalled.andRespond(5);
assertEqual(addB(2), 7);
</code>```

I don't see a way to do the mocking in Go without creating an object with getB as one of its methods, creating an interface for that object, and then including a test interface sent with addB. Is that really the best way to do it?

答:
You can declare a function as a variable and inject a mock implementation for the tests.

Example:

```<code>package main

import "fmt"

var getB = func() int {
    return 3
}

func main() {
    fmt.Println(getB())

    getB = func() int {
        return 5
    }

    fmt.Println(getB())
}
</code>```

Title: Mocking just one function in Go

Body:
I've read a bunch about this and don't understand why mocking is so complicated in Go. Is there a simple way to mock just one function?

For example:

func addB(num int) int {
  return b() + num;
}

func getB() int {
  return 3;
}

If I want to test addB but change getB to respond with 6 or something instead, in other languages I'd write a unit test like:

expect(getB).toBeCalled.andRespond(5);
assertEqual(addB(2), 7);

I don't see a way to do the mocking in Go without creating an object with getB as one of its methods, creating an interface for that object, and then including a test interface sent with addB. Is that really the best way to do it?

Body:
You can declare a function as a variable and inject a mock implementation for the tests.

Example:

package main

import "fmt"

var getB = func() int {
    return 3
}

func main() {
    fmt.Println(getB())

    getB = func() int {
        return 5
    }

    fmt.Println(getB())
}


问:
git push error: repository not found even though remote url is added
I have added repository url using
git remote add origin https://github.com/**.git
If I check with git remote -v I can able to see repo url , but still when pushing to same url,using git push origin master I found that
remote: Repository not found.
fatal: repository 'https://github.com/**.git/' not found. Above repository url still alive and  I can able to clone but when pushing I stuck with this error What could may be the reason?

答:
Follow these steps to avoid the issues.

Adding a project to GitHub without GitHub CLI.

Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or ignore files. You can add these files after your project has been pushed to GitHub.

Create New Repository drop-down. Open Git Bash. Change the current working directory to your local project.

Initialize the local directory as a Git repository.

```<code>$ git init -b main
</code>```

Add the files in your new local repository. This stages them for the first commit.

```<code>$ git add .
# Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
</code>```

Commit the files that you've staged in your local repository.

```<code>$ git commit -m "First commit"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
</code>```

At the top of your repository on GitHub.com's Quick Setup page, click  to copy the remote repository URL.
Copy remote repository URL field
In the Command prompt, add the URL for the remote repository where your local repository will be pushed.

```<code>$ git remote add origin  <REMOTE_URL>
# Sets the new remote
$ git remote -v
# Verifies the new remote URL
Push the changes in your local repository to GitHub.com.
$ git push origin main
# Pushes the changes in your local repository up to the remote repository you specified as the origin
</code>```

Body:
Follow these steps to avoid the issues.

Adding a project to GitHub without GitHub CLI.

Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or ignore files. You can add these files after your project has been pushed to GitHub.

Create New Repository drop-down. Open Git Bash. Change the current working directory to your local project.

Initialize the local directory as a Git repository.

$ git init -b main

Add the files in your new local repository. This stages them for the first commit.

$ git add .
# Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.

Commit the files that you've staged in your local repository.

$ git commit -m "First commit"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.

At the top of your repository on GitHub.com's Quick Setup page, click  to copy the remote repository URL.
Copy remote repository URL field
In the Command prompt, add the URL for the remote repository where your local repository will be pushed.

$ git remote add origin  <REMOTE_URL>
# Sets the new remote
$ git remote -v
# Verifies the new remote URL
Push the changes in your local repository to GitHub.com.
$ git push origin main
# Pushes the changes in your local repository up to the remote repository you specified as the origin


问:
How does the linker or loader deal with broken soft links for shared libraries?
I have the same shared library in three different paths in the system. Let's say the paths are PATH1, PATH2 & PATH3.

Shared library name is libmylib.so

Now, in PATH1 if I replace the libmylib.so with a broken soft link, it goes and searches in PATH2 for the library.

But, in PATH1 if I replace libmylib.so with some other text file (or some unrelated file) which has the name libmylib.so, then application execution fails stating "not an ELF Header"

I am a little confused by the behaviour? Why does it search the other paths incase of a broken soft link and fails in case of an incorrect file. I was expecting it to search other paths for incorrect file also.

答:
with some other text file (or some unrelated file) which has the name libmylib.so

this file is not a broken soft link, this is just a regular file (such as shared object file should be)
symbolic link is a special filesystem element (like directory), VFS knows it's nature because of information stored in corresponding inode, but not because of file content.

summary:

broken symlink is still symlink

real file with extension .so is treated as shared object (in this case - broken)

check out their attributes (d,-,l):

```
drwxr-xr-x   2 Ibadinov  staff   68 18 aoû 15:21 dir
-rw-r--r--   1 Ibadinov  staff    0 18 aoû 15:21 file
lrwxr-xr-x   1 Ibadinov  staff    4 18 aoû 15:22 link -> file
```

basic info:

http://en.wikipedia.org/wiki/Inode

http://en.wikipedia.org/wiki/Symbolic_link#Storage_of_symbolic_links

ContentLicense: CC BY-SA 2.5

Body:
with some other text file (or some unrelated file) which has the name libmylib.so

this file is not a broken soft link, this is just a regular file (such as shared object file should be)
symbolic link is a special filesystem element (like directory), VFS knows it's nature because of information stored in corresponding inode, but not because of file content.

summary:

broken symlink is still symlink

real file with extension .so is treated as shared object (in this case - broken)

check out their attributes (d,-,l):

drwxr-xr-x   2 Ibadinov  staff   68 18 aoû 15:21 dir
-rw-r--r--   1 Ibadinov  staff    0 18 aoû 15:21 file
lrwxr-xr-x   1 Ibadinov  staff    4 18 aoû 15:22 link -> file

basic info:

http://en.wikipedia.org/wiki/Inode

http://en.wikipedia.org/wiki/Symbolic_link#Storage_of_symbolic_links


问:
How to create a new column in R using if statements?
Df1:

```<code>    Gene  Value  Label
    geneA  2    NA
    geneB  3    NA
    geneC  4    NA
    geneD  5    NA
</code>```

Df2:

```<code>    Gene
    geneA
    geneD
</code>```

I want to write script to say that if Df1$Gene is present in Df2$Gene, then replace "NA" in Df1$Label with that gene name.

Help!

答:
```<code>Df1 <- data.frame(Gene = paste0("Gene",LETTERS[1:4]), Value = 2:5, Label = NA)
Df2 <- data.frame(Gene = c("GeneA", "GeneD"))
Df1[Df1$Gene %in% Df2$Gene, ]['Label'] <- Df2$Gene
Df1
</code>```

Body:
Df1:

    Gene  Value  Label
    geneA  2    NA
    geneB  3    NA
    geneC  4    NA
    geneD  5    NA

Df2:

    Gene
    geneA
    geneD

I want to write script to say that if Df1$Gene is present in Df2$Gene, then replace "NA" in Df1$Label with that gene name.

Help!


问:
Implementing IEnumerable in WCF
I'm learning about WCF, and made a C# fiddle of custom class in the interface that has its own GetEnumerator() method to customize the class' foreach behaviour. The class is as shown:

ProductClass.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ProductInterfaces
{
    public class ProductData : IEnumerable
    {
        public string Name { get; set; }
        public string ProductNumber { get; set; }
        public string Color { get; set; }
        public double ListPrice { get; set; }

        List<string> myData = new List<string>(new string[] { "test1", "test2", "test3", "test4" });

        public IEnumerator<string> GetEnumerator()
        {
            foreach(string val in myData)
            {
                yield return val;
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
</code>```

And the contract is as shown (IWCFProductService.cs):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ProductInterfaces
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IWCFProductService" in both code and config file together.
    [ServiceContract]
    public interface IWCFProductService
    {
        [OperationContract]
        ProductData GetProduct(string productNumber);
    }
}
</code>```

The implementation of the GetProduct() method is as shown:

```<code>using ProductInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ProductService

{
    public class WCFProductService : IWCFProductService
    {
        public ProductData GetProduct(string productNumber)
        {
            using (adventureworksEntities database = new adventureworksEntities())
            {
                var table_of_products = database.products;
                ProductData desired_product = new ProductData();
                foreach (var p in table_of_products)
                {
                    if (p.ProductNumber == productNumber)
                    {
                        Console.WriteLine("Test using a custom foreach of ProductData class");
                        foreach (string i in desired_product)
                        {
                            Console.WriteLine(i);
                        }
                        desired_product.Name = p.Name;
                        desired_product.ProductNumber = p.ProductNumber;
                        desired_product.Color = p.Color;
                        desired_product.ListPrice = p.ListPrice;
                        return desired_product;
                    }
                }
                throw new Exception();
            }
        }
    }
}
</code>```

When called by the client:

```<code>using ProductInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace ProductClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // Client creates channel factory by passing in the name of the endpoint (i.e. ProductServiceEndpoint)
            ChannelFactory<IWCFProductService> channelFactory = new ChannelFactory<IWCFProductService>("ProductServiceEndpoint");

            // Create a proxy i.e. create a channel
            IWCFProductService proxy = channelFactory.CreateChannel();

            Console.WriteLine("Input product name to be searched:");
            string input = Console.ReadLine();
            var searchResult = proxy.GetProduct(input);

            Console.WriteLine(searchResult.Name);
            Console.ReadLine();
        }
    }
}
</code>```

It fails at var searchResult = proxy.GetProduct(input);, with exception saying

```<code>System.ServiceModel.CommunicationException: 'An error occurred while receiving the HTTP response to http://localhost:9999/ProductService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.'
</code>```

I did some trial and error, and if I remove IEnumerable and the foreach loop, there is no issue and searchResult is a valid object. Why is this happening? Am I understanding something wrong?

答:
I think it should be a serialization issue, WCF needs to have concrete classes to pass data.

It cannot return IEnumerable - try using List (or T[] array) or concrete types.

You can also use the Service Trace Viewer to find specific issues.

Posts with similar questions

WCF Web Service error: "Service endpoint binding not using HTTP protocol"?

This could be due to the service endpoint binding not using the HTTP protocol

Title: Implementing IEnumerable in WCF

Body:
I'm learning about WCF, and made a C# fiddle of custom class in the interface that has its own GetEnumerator() method to customize the class' foreach behaviour. The class is as shown:

ProductClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ProductInterfaces
{
    public class ProductData : IEnumerable
    {
        public string Name { get; set; }
        public string ProductNumber { get; set; }
        public string Color { get; set; }
        public double ListPrice { get; set; }

        List<string> myData = new List<string>(new string[] { "test1", "test2", "test3", "test4" });

        public IEnumerator<string> GetEnumerator()
        {
            foreach(string val in myData)
            {
                yield return val;
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

And the contract is as shown (IWCFProductService.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ProductInterfaces
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IWCFProductService" in both code and config file together.
    [ServiceContract]
    public interface IWCFProductService
    {
        [OperationContract]
        ProductData GetProduct(string productNumber);
    }
}

The implementation of the GetProduct() method is as shown:

using ProductInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ProductService

{
    public class WCFProductService : IWCFProductService
    {
        public ProductData GetProduct(string productNumber)
        {
            using (adventureworksEntities database = new adventureworksEntities())
            {
                var table_of_products = database.products;
                ProductData desired_product = new ProductData();
                foreach (var p in table_of_products)
                {
                    if (p.ProductNumber == productNumber)
                    {
                        Console.WriteLine("Test using a custom foreach of ProductData class");
                        foreach (string i in desired_product)
                        {
                            Console.WriteLine(i);
                        }
                        desired_product.Name = p.Name;
                        desired_product.ProductNumber = p.ProductNumber;
                        desired_product.Color = p.Color;
                        desired_product.ListPrice = p.ListPrice;
                        return desired_product;
                    }
                }
                throw new Exception();
            }
        }
    }
}

When called by the client:

using ProductInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace ProductClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // Client creates channel factory by passing in the name of the endpoint (i.e. ProductServiceEndpoint)
            ChannelFactory<IWCFProductService> channelFactory = new ChannelFactory<IWCFProductService>("ProductServiceEndpoint");

            // Create a proxy i.e. create a channel
            IWCFProductService proxy = channelFactory.CreateChannel();

            Console.WriteLine("Input product name to be searched:");
            string input = Console.ReadLine();
            var searchResult = proxy.GetProduct(input);

            Console.WriteLine(searchResult.Name);
            Console.ReadLine();
        }
    }
}

It fails at var searchResult = proxy.GetProduct(input);, with exception saying

System.ServiceModel.CommunicationException: 'An error occurred while receiving the HTTP response to http://localhost:9999/ProductService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.'

I did some trial and error, and if I remove IEnumerable and the foreach loop, there is no issue and searchResult is a valid object. Why is this happening? Am I understanding something wrong?


问:
Unable to identify Button in hybrid page in android app appium
I have tried to identify 'Send' button but Appium doesn't shown source of that page. This page is a webpage in hybrid android app. Is there any way to get source of this button and verify/inspect it?

I have tried with chrome://inspect/#devices and able to inspect this button in Developer tools but don't know where verify? This is what DOM has inspected.

<button id="btnSaveForm" type="button" ng-click="submitForm(1)" class="btn btn-danger" ng-disabled="isXhrPending() || mainCtrl.isAttachUploading">Send</button>

What could be the Xpath of this and how do I verify it?

答:
When dealing with dynamic rendering you should try to keep your xpath as simple as possible.

How about selecting by buttons function: //button[contains(@ng-click,"submitForm")]?


问:
No matching version found
npm ERR! code ETARGET
npm ERR! notarget No matching version found for tagcloud@^2.0.2.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

But  "TagCloud"  is in package.json.

答: Maybe the best solution is, if the npm install command doesn't work, to run npm i -S TagCloud@2.0.2 if you need to use that specific version, otherwise, just run npm i -S TagCloud.

Title: No matching version found


问:
Wrong execution order in Azure Data Factory Pipeline
The pipeline is called from a main pipeline. But for some reason that I do not understand the execution is starting in the second component (notebook) and is skipping the first one (lookUp) that is used to update a status throught a simple query.

What could be happening?

答:
If you have published all the changes to the pipeline and yet see this issue, I can only imagine it to be a generic issue related to browser or cache.

I am able to repro this multiple time without any issue or find it executing as you described.

Maybe if you could share what you have configured in lookup (datastore type..etc.), we can try understand this scenario.


问:
How to create a text component where first word of sentence to be bold?
I'm trying to create a text component where first word of the sentence to be bold. Right now with my solution, when a user enter "Tips: favourite vacation", I get " Tips: favouritevacation", where rest of sentence becomes mess and no space is created after Tips:. This isn't elegant solution. I thought about creating another component like TextBold and use it like this < Text >< TextBold >Tips:< /TextBold > Your Vacation< /Text >, but this seems unnecessary. Is there a way to get this working within Text component alone? https://codesandbox.io/s/text-component-v2dbt?file=/src/App.tsx

```<code>import * as React from "react";

export interface TextProps {
  children?: string;
}

export const Text: React.FunctionComponent<TextProps> = ({
  children
}: TextProps) => {
  return (
    <>
      <span style={{ fontWeight: "bold" }}>{children?.split(" ")[0]}</span>
      <span>{children?.split(" ").slice(1)}</span>
    </>
  );
};

export default function App() {
  return (
    <div>
      <Text>Tips: favourite vacation</Text>
    </div>
  );
}
</code>```

答:
You could make use of first space char index and .substring

```<code>export const Text: React.FunctionComponent<TextProps> = ({
  children = ""
}: TextProps) => {
  const firstSpaceIndex = children.indexOf(" ");
  return (
    <>
      <span style={{ fontWeight: "bold" }}>
        {children.substring(0, firstSpaceIndex)}
      </span>
      <span>{children.substring(firstSpaceIndex)}</span>
    </>
  );
};
</code>```

Body:
I'm trying to create a text component where first word of the sentence to be bold. Right now with my solution, when a user enter "Tips: favourite vacation", I get " Tips: favouritevacation", where rest of sentence becomes mess and no space is created after Tips:. This isn't elegant solution. I thought about creating another component like TextBold and use it like this < Text >< TextBold >Tips:< /TextBold > Your Vacation< /Text >, but this seems unnecessary. Is there a way to get this working within Text component alone? https://codesandbox.io/s/text-component-v2dbt?file=/src/App.tsx

import * as React from "react";

export interface TextProps {
  children?: string;
}

export const Text: React.FunctionComponent<TextProps> = ({
  children
}: TextProps) => {
  return (
    <>
      {children?.split(" ")[0]}
      {children?.split(" ").slice(1)}
    </>
  );
};

export default function App() {
  return (

      <Text>Tips: favourite vacation</Text>

  );
}

Body:
You could make use of first space char index and .substring

export const Text: React.FunctionComponent<TextProps> = ({
  children = ""
}: TextProps) => {
  const firstSpaceIndex = children.indexOf(" ");
  return (
    <>
      <span style={{ fontWeight: "bold" }}>
        {children.substring(0, firstSpaceIndex)}
      </span>
      <span>{children.substring(firstSpaceIndex)}</span>
    </>
  );
};


问:
Java, converting string to integers then add all the integers together
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.</p>

```<code>String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

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

// Stuck

}
</code>```

答:
This pseudo code should do it without splitting, arrays etc.

```<code>String s = "1234.56";
int sum = 0;
int i = 0;
while (i < s.length()) {
    char c = s.charAt(i)
    if (c >= '0' && c <= '9') sum += c - '0';
    i++;
}
</code>```

Should result in sum = 21

Body:
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.

String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

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

// Stuck

}

Body:
This pseudo code should do it without splitting, arrays etc.

String s = "1234.56";
int sum = 0;
int i = 0;
while (i < s.length()) {
    char c = s.charAt(i)
    if (c >= '0' && c <= '9') sum += c - '0';
    i++;
}

Should result in sum = 21


问:
Laravel project auto refresh after changes
Does anyone know if there is a way to run the code changes in a Laravel project without refreshing the page every time.

I know that to see the changes I need to

```<code>php artisan serve
</code>```

but I do it every time and it is kind of frustrating.

Thank you anyways.

答:
To achieve this you can use Laravel Mix

Ensure that Node.js and NPM are installed:

run node -v and npm -v.

Install Laravel Mix

npm install.

Install browser-sync and browser-sync-webpack-plugin

npm install browser-sync browser-sync-webpack-plugin --save-dev --production=false

Open webpack.mix.js and add this line

mix.browserSync('127.0.0.1:8000');.

Run Project with these two commands: The npm run watch command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change

php artisan serve. and then npm run watch.

Body:
Does anyone know if there is a way to run the code changes in a Laravel project without refreshing the page every time.

I know that to see the changes I need to

php artisan serve

but I do it every time and it is kind of frustrating.

Thank you anyways.


问:
File upload makes Node JS unresponsive with Multer
I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})```

But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.

Whats the best way to tackle this ?

答:
i can give you an example of how i implemented an imageupload in my app. it the code to upload a profile image for a user. i am also using multer middleware so it shoulder be similiar for you:

code is as follows:

```<code>// multer middleware:
const multer = require('multer');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpg',
  'image/jpg': 'jpg',
};

module.exports = storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error('invalid mime type');
    if (isValid) {
      error = null;
    }
    cb(error, 'images');
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');
    const ext = MIME_TYPE_MAP[file.mimetype];
    if (name.includes('.' + ext)) {
      cb(null, name)
    } else {
      cb(null, name + '.' + ext);
    }
  },
});
</code>```

and here the code in the service handling the fileupload

```<code>// profile service in backend written in express
exports.uploadImage = (req, res, next) => {
  const url = req.protocol + '://' + req.get('host');
  profileRepository
    .findOne({ _id: req.params.id })
    .then((response) => {
      const fetchedUser = response;
      fetchedUser.imagePath = url + '/images/' + req.file.filename;
      profileRepository
        .updateOne({ _id: req.params.id }, fetchedUser)
        .then((response) => {
          return res.status(200).json({
            message: 'profileimage updated',
          });
        })
        .catch((error) => {
          return res.status(500).json({
            message: 'uploading image failed',
          });
        });
    })
    .catch((error) => {
      return res.status(404).json({
        message: 'fetching user failed',
      });
    });
};
</code>```

then i use the middleware in my profile routes file like this:

```<code>// profile.routes.js
const express = require('express');
const ProfileController = require('./profileController');
const checkAuth = require('../middleware/checkAuth');
const router = express.Router();
const fileStorage = require('../middleware/fileStorage');
const multer = require('multer');
// imageUpload
router.post('/user/image/:id', checkAuth, multer({storage: fileStorage}).single('image'), ProfileController.image);
</code>```

my Controller then calls the service function with the actual business logic like this:

```<code>// profile.controller.js
const profileService = require('./profileService');
exports.image = (req, res, next) => {
  return profileService.uploadImage(req, res);
};
</code>```

and finally my route is used by my app.js file like this:

```<code>// app.js
const express = require('express');
const profileRoutes = require('./profile/profileRoutes');

const app = express();

// set images path for saving images on server
app.use('/images', express.static(path.join('images')));

app.use('/api', profileRoutes);

module.exports = app;
</code>```

i hope i was able to point you in the right direction with my example

Body:
I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.

Whats the best way to tackle this ?

Body:
i can give you an example of how i implemented an imageupload in my app. it the code to upload a profile image for a user. i am also using multer middleware so it shoulder be similiar for you:

code is as follows:

// multer middleware:
const multer = require('multer');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpg',
  'image/jpg': 'jpg',
};

module.exports = storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error('invalid mime type');
    if (isValid) {
      error = null;
    }
    cb(error, 'images');
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');
    const ext = MIME_TYPE_MAP[file.mimetype];
    if (name.includes('.' + ext)) {
      cb(null, name)
    } else {
      cb(null, name + '.' + ext);
    }
  },
});

and here the code in the service handling the fileupload

// profile service in backend written in express
exports.uploadImage = (req, res, next) => {
  const url = req.protocol + '://' + req.get('host');
  profileRepository
    .findOne({ _id: req.params.id })
    .then((response) => {
      const fetchedUser = response;
      fetchedUser.imagePath = url + '/images/' + req.file.filename;
      profileRepository
        .updateOne({ _id: req.params.id }, fetchedUser)
        .then((response) => {
          return res.status(200).json({
            message: 'profileimage updated',
          });
        })
        .catch((error) => {
          return res.status(500).json({
            message: 'uploading image failed',
          });
        });
    })
    .catch((error) => {
      return res.status(404).json({
        message: 'fetching user failed',
      });
    });
};

then i use the middleware in my profile routes file like this:

// profile.routes.js
const express = require('express');
const ProfileController = require('./profileController');
const checkAuth = require('../middleware/checkAuth');
const router = express.Router();
const fileStorage = require('../middleware/fileStorage');
const multer = require('multer');
// imageUpload
router.post('/user/image/:id', checkAuth, multer({storage: fileStorage}).single('image'), ProfileController.image);

my Controller then calls the service function with the actual business logic like this:

// profile.controller.js
const profileService = require('./profileService');
exports.image = (req, res, next) => {
  return profileService.uploadImage(req, res);
};

and finally my route is used by my app.js file like this:

// app.js
const express = require('express');
const profileRoutes = require('./profile/profileRoutes');

const app = express();

// set images path for saving images on server
app.use('/images', express.static(path.join('images')));

app.use('/api', profileRoutes);

module.exports = app;

i hope i was able to point you in the right direction with my example