问:
Does Embarcadero RAD Studio XE license allow use on multiple machines?
In the past the Borland "no nonsense" license allowed one developer to do multiple installs.

I'm tempted to upgrade to Embarcadero RAD Studio XE, professional edition, but am worried about licensing restrictions, and whether it will allow me to work in the same way as before.

I downloaded a 30 day trial, and that will only allow one install, so I'm a bit concerned the upgrade would enforce a similar restriction.

I use a small and a large laptop and a PC and would like to install RAD Studio on all 3, as well as in VMs. I've posted a question asking about this on the vendor website, but there's no response yet, and I wonder if people could answer from their own experience please?

I'd also be interested to know if the upgrade will only run if there is an existing installation of an earlier product on the same machine.

答: Yes you can, and you do not need to have a previous version installed. I use it on several machines myself.</p>


来源: stackexchange

问:
Excel 2010 COUNTIF(): The formula you typed contains an error
This thing is breaking my head. Please, take a look and get me out a solution !

tried using (comma (,) ) instead of ;

tried using this  ==COUNTIF($J$2:$j$51;"<40")

my-setup  :
platform : windows 7
application name : Microsoft excel 2010

答:
The formula looks fine. You may have an issue with your regional/language settings.

To view or modify your language settings within Excel, go to File > Options > Language.

ContentLicense: CC BY-SA 4.0


问:
Where to put test data in R package for R CMD CHECK
This question is a near duplicate of Q32328802 - testdata for testthat. The difference is that I'm looking for a more specific answer as it relates to devtools::check. Specifically, how do I get devtools::check() to recognize and load my test data?

My package structure for tests/testthat.R and tests/testthat/setup-testdata.R is described below (and github is linked at the bottom of the post). I have tried the following:

Following the above linked question, I have placed the test data in inst/testdata. As this is not working, I have also tried other locations (eg. tests/, tests/testthat). None of these locations work.

I have also tried renaming helper-testdata.R as setup-testdata.R and get the same failing results.

devtools::check() does not appear to accurately recognize the load(system.file(...)) command. It similarly does not recognize if I spell the file name out (ie. do not use system.file()). Omitting the load command also doesn't work.

tests/:

testthat.R

```<code>library(synthACS)
library(testthat)

test_check("synthACS")
</code>```

testthat/setup-testdata.R has a single line in it:

```<code>load(system.file("testdata", 'dat-acsdata.Rda', package= "synthACS"))
# run interactively, this line of code loads the data accurately.
# within devtools::check() it appears to return an empty string ("") for
# file location
</code>```

Checking my package

```<code>R> devtools::test(synthACS)
══ Results ═════════════════════════

OK:       388
Failed:   0
Warnings: 0
Skipped:  0

R> devtools::check(synthACS)
...
─  checking tests ...
E  Running ‘testthat.R’ (1.5s)

── Test failures ─────────────────────

> library(testthat)
>
> load(system.file("testdata", 'acsdata.rda', package= "synthACS"))
> test_check("synthACS")
 ----------- FAILURE REPORT --------------
... indicates that the data is not loaded ...

</code>```

Any help appreciated!

Edit links to full code:

package: https://github.com/alexWhitworth/synthACS

failing travis-ci build: https://travis-ci.org/github/alexWhitworth/synthACS

答:
The correct answer is to use readRDS, which means saving each object separately via saveRDS

eg.

my_data <- readRDS(file= system.file("testdata", 'dat-mydata.rds', package= "synthACS"))

Body:
This question is a near duplicate of Q32328802 - testdata for testthat. The difference is that I'm looking for a more specific answer as it relates to devtools::check. Specifically, how do I get devtools::check() to recognize and load my test data?

My package structure for tests/testthat.R and tests/testthat/setup-testdata.R is described below (and github is linked at the bottom of the post). I have tried the following:

Following the above linked question, I have placed the test data in inst/testdata. As this is not working, I have also tried other locations (eg. tests/, tests/testthat). None of these locations work.

I have also tried renaming helper-testdata.R as setup-testdata.R and get the same failing results.

devtools::check() does not appear to accurately recognize the load(system.file(...)) command. It similarly does not recognize if I spell the file name out (ie. do not use system.file()). Omitting the load command also doesn't work.

tests/:

testthat.R

library(synthACS)
library(testthat)

test_check("synthACS")

testthat/setup-testdata.R has a single line in it:

load(system.file("testdata", 'dat-acsdata.Rda', package= "synthACS"))
# run interactively, this line of code loads the data accurately.
# within devtools::check() it appears to return an empty string ("") for
# file location

Checking my package

R> devtools::test(synthACS)
══ Results ═════════════════════════

OK:       388
Failed:   0
Warnings: 0
Skipped:  0

R> devtools::check(synthACS)
...
─  checking tests ...
E  Running ‘testthat.R’ (1.5s)

── Test failures ─────────────────────

> library(testthat)
>
> load(system.file("testdata", 'acsdata.rda', package= "synthACS"))
> test_check("synthACS")
 ----------- FAILURE REPORT --------------
... indicates that the data is not loaded ...

Any help appreciated!

Edit links to full code:

package: https://github.com/alexWhitworth/synthACS

failing travis-ci build: https://travis-ci.org/github/alexWhitworth/synthACS


问:
How do I set colors for three js instanced objects?
I have an a-frame component that leverages three js instancing to render a large number of spheres efficiently. Based on examples from the three js library such as https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_scatter.html, I should be able to set the colors for each of the instanced renderings individually. I thought I had followed the example but my per instance colors are not taking effect.

```<code>AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        const material = new THREE.MeshNormalMaterial();

        const geometry = new THREE.SphereBufferGeometry( radius, 3, 2 );
        const instancedGeometry = new THREE.InstancedBufferGeometry().copy(geometry);
        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }
        instancedGeometry.setAttribute("instanceColor", new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ))

        instancedGeometry.computeVertexNormals();

        material.vertexColors = true;

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( instancedGeometry, material, count );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },
</code>```

What am I doing wrong?

答:
Did you try with the actual same attribute 'color', like in the example (which is

blossomGeometry.setAttribute( 'color', new THREE.InstancedBufferAttribute( color, 3 ) );

Because I think it's quite important that the name of the attribute is 'color'.

Body:
I have an a-frame component that leverages three js instancing to render a large number of spheres efficiently. Based on examples from the three js library such as https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_scatter.html, I should be able to set the colors for each of the instanced renderings individually. I thought I had followed the example but my per instance colors are not taking effect.

AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        const material = new THREE.MeshNormalMaterial();

        const geometry = new THREE.SphereBufferGeometry( radius, 3, 2 );
        const instancedGeometry = new THREE.InstancedBufferGeometry().copy(geometry);
        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }
        instancedGeometry.setAttribute("instanceColor", new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ))

        instancedGeometry.computeVertexNormals();

        material.vertexColors = true;

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( instancedGeometry, material, count );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },

What am I doing wrong?


问:
Print an array of only the first cells
I have array that i want to make print but with only with the frist cells .

this is my array :

```<code>var arr = [ {x: 123, y:987}, {x: 456, y:654}, {x: 789,  y:100200300}, {x: 101112, y:400500600} ];
</code>```

I want to print :

```<code>123,456,789,101112
</code>```

How can i do this ?

答:
Use with the function map() , try this :

```<code>console.log(arr.map(item => item.x));
</code>```

The output :

```<code>Array(4)
0: 123
1: 456
2: 789
3: 101112
</code>```

Now you can print in as you want ..

Title: Print an array of only the first cells

Body:
I have array that i want to make print but with only with the frist cells .

this is my array :

var arr = [ {x: 123, y:987}, {x: 456, y:654}, {x: 789,  y:100200300}, {x: 101112, y:400500600} ];

I want to print :

123,456,789,101112

How can i do this ?

Body:
Use with the function map() , try this :

console.log(arr.map(item => item.x));

The output :

Array(4)
0: 123
1: 456
2: 789
3: 101112

Now you can print in as you want ..


问:
JavaScript: Find Matches AND Differences in two Arrays of Objects
Okay, so this is a tough one. I think.

I have two arrays of objects that contain some information about pods. I'm looking to provide a side by side comparison of environments to show where pods contain the exact same image; the trick is that I also need to catch the pods where the images aren't matching. The results are going to be rendered on a table which will look something like this (at least as a first iteration):

```<code>|---------------------|------------------|------------------|
|      Pod Name       | Image from Env1  |  Image from Env2 |
|---------------------|------------------|------------------|
|          foo        |     foo:1.0.0    |     foo:1.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          foo        |   foobar:1.0.0   |                  |   <---- No match for image tag; image name different from the pod name as the pods may contain multiple images
|---------------------|------------------|------------------|
|          foo        |                  |    foobar:2.0.0  |   <---- As above
|---------------------|------------------|------------------|
|          bar        |     bar:2.0.0    |     bar:2.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          baz        |     baz:1.0.0    |                  |   <----
|---------------------|------------------|------------------|         Note the 'no match'; so own row for now
|          baz        |                  |     baz:2.0.0    |   <----
|---------------------|------------------|------------------|
</code>```

I will later use CSS to highlight the matches vs. differences.

The things that I'm struggling with most are:

Pods may have more than 1 image. 1 of those images may match between environments, but the other may not. When there is more than one image the tags inside that pod differ (see foo pod in table above)

How to check the objects match between environments whilst still capturing the ones that don't match. Using nested loops cause a whole bunch of issues with duplicates and false negatives

I'm unsure on the best way to store the output. Likely something like: [{ "Pod Name": "foo", "Image_Env_1": foo:1.0.0", "Image_Env_2": foo:1.0.0"}... and leaving blank strings (like the blank cell in the table) for a value in the non-matching cases. But this may clash with the other image in the foo pod that has different image tags.

So Env1 array looks something like this snippet:

[
    {
        "Image": {
            "S": "foo:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:1.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    },
    {
        "Image": {
            "S": "qux:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    }
]```
</div>
</div>
</p>

<p><code>Env2</code> array:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
    {
        "Image": {
            "S": "foo:2.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:3.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    }
]</code>```

答:
You could write a little helper method which aggregates the infos from your env-files, i.e. first group by pod and then aggregate the used images. Filtering entries where an image is used in multiple environments should be trivial then.

Something like (note that this would work for an arbitrary amount of environments):

```<code>function getAggregatedPodInfos(...environments) {
    const aggregatedInfos = {pods: {}, environments: []};
    environments.forEach(env => addEnvironmentInfos(env, aggregatedInfos))
    return aggregatedInfos;
}

function addImageInfoByEnvironment(pod, environment, imageName) {
    if (!pod.imageInfo[environment.envName]) {
        pod.imageInfo[environment.envName] = [];
    }
    pod.imageInfo[environment.envName].push(imageName)
}

function addEnvironmentInfos(environment, envInfo) {
    envInfo.environments.push(environment.envName);
    for (const envEntry of environment.data) {
        const podName = envEntry["Pod Name"]["S"];
        const imageName = envEntry["Image"]["S"];
        if (!envInfo.pods[podName]) {
            envInfo.pods[podName] = {imageInfo: {}};
        }
        addImageInfoByEnvironment(envInfo.pods[podName], environment, imageName);
    }
}

const res = getAggregatedPodInfos({envName: 'env1', data: env1}, {envName: 'env2', data: env2});
console.log(JSON.stringify(res))
</code>```

This would print:

```<code>{
    "pods": {
        "foo": {
            "imageInfo": {
                "env1": ["foo:1.0.0", "foobar:0.2.0", "qux:1.0.0"],
                "env2": ["foo:2.0.0", "foobar:0.2.0"]
            }
        },
        "bar": {
            "imageInfo": {
                "env1": ["bar:1.0.0"],
                "env2": ["bar:1.0.0"]
            }
        },
        "baz": {
            "imageInfo": {
                "env1": ["baz:1.0.0"],
                "env2": ["baz:3.0.0"]
            }
        }
    },
    "environments": ["env1", "env2"]
}
</code>```

Body:
Okay, so this is a tough one. I think.

I have two arrays of objects that contain some information about pods. I'm looking to provide a side by side comparison of environments to show where pods contain the exact same image; the trick is that I also need to catch the pods where the images aren't matching. The results are going to be rendered on a table which will look something like this (at least as a first iteration):

|---------------------|------------------|------------------|
|      Pod Name       | Image from Env1  |  Image from Env2 |
|---------------------|------------------|------------------|
|          foo        |     foo:1.0.0    |     foo:1.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          foo        |   foobar:1.0.0   |                  |   <---- No match for image tag; image name different from the pod name as the pods may contain multiple images
|---------------------|------------------|------------------|
|          foo        |                  |    foobar:2.0.0  |   <---- As above
|---------------------|------------------|------------------|
|          bar        |     bar:2.0.0    |     bar:2.0.0    |   <---- images match
|---------------------|------------------|------------------|
|          baz        |     baz:1.0.0    |                  |   <----
|---------------------|------------------|------------------|         Note the 'no match'; so own row for now
|          baz        |                  |     baz:2.0.0    |   <----
|---------------------|------------------|------------------|

I will later use CSS to highlight the matches vs. differences.

The things that I'm struggling with most are:

Pods may have more than 1 image. 1 of those images may match between environments, but the other may not. When there is more than one image the tags inside that pod differ (see foo pod in table above)

How to check the objects match between environments whilst still capturing the ones that don't match. Using nested loops cause a whole bunch of issues with duplicates and false negatives

I'm unsure on the best way to store the output. Likely something like: [{ "Pod Name": "foo", "Image_Env_1": foo:1.0.0", "Image_Env_2": foo:1.0.0"}... and leaving blank strings (like the blank cell in the table) for a value in the non-matching cases. But this may clash with the other image in the foo pod that has different image tags.

So Env1 array looks something like this snippet:

[
    {
        "Image": {
            "S": "foo:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:1.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    },
    {
        "Image": {
            "S": "qux:1.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    }
]

Env2 array:

[
    {
        "Image": {
            "S": "foo:2.0.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "foobar:0.2.0"
        },
        "Pod Name": {
            "S": "foo"
        }
    },
    {
        "Image": {
            "S": "bar:1.0.0"
        },
        "Pod Name": {
            "S": "bar"
        }
    },
    {
        "Image": {
            "S": "baz:3.0.0"
        },
        "Pod Name": {
            "S": "baz"
        }
    }
]

Body:
You could write a little helper method which aggregates the infos from your env-files, i.e. first group by pod and then aggregate the used images. Filtering entries where an image is used in multiple environments should be trivial then.

Something like (note that this would work for an arbitrary amount of environments):

function getAggregatedPodInfos(...environments) {
    const aggregatedInfos = {pods: {}, environments: []};
    environments.forEach(env => addEnvironmentInfos(env, aggregatedInfos))
    return aggregatedInfos;
}

function addImageInfoByEnvironment(pod, environment, imageName) {
    if (!pod.imageInfo[environment.envName]) {
        pod.imageInfo[environment.envName] = [];
    }
    pod.imageInfo[environment.envName].push(imageName)
}

function addEnvironmentInfos(environment, envInfo) {
    envInfo.environments.push(environment.envName);
    for (const envEntry of environment.data) {
        const podName = envEntry["Pod Name"]["S"];
        const imageName = envEntry["Image"]["S"];
        if (!envInfo.pods[podName]) {
            envInfo.pods[podName] = {imageInfo: {}};
        }
        addImageInfoByEnvironment(envInfo.pods[podName], environment, imageName);
    }
}

const res = getAggregatedPodInfos({envName: 'env1', data: env1}, {envName: 'env2', data: env2});
console.log(JSON.stringify(res))

This would print:

{
    "pods": {
        "foo": {
            "imageInfo": {
                "env1": ["foo:1.0.0", "foobar:0.2.0", "qux:1.0.0"],
                "env2": ["foo:2.0.0", "foobar:0.2.0"]
            }
        },
        "bar": {
            "imageInfo": {
                "env1": ["bar:1.0.0"],
                "env2": ["bar:1.0.0"]
            }
        },
        "baz": {
            "imageInfo": {
                "env1": ["baz:1.0.0"],
                "env2": ["baz:3.0.0"]
            }
        }
    },
    "environments": ["env1", "env2"]
}


问:
Unable to get data in human readable format from private data collection using node sdk
So I am trying to explore private data collection and I have written the chaincode in javascript. I am passing the proper collections file while instantiating the chaincode and while invoking the chaincode I am adding the transient data in request payload which looks like this :

```<code>const proposal_request = {
  chaincodeId: chaincodeId,
  fcn: functionName,
  args: args,
  chainId: channelCode,
  txId: tx_id,
  transientMap : { "private" : "test data"}
};
</code>```

My chaincode file looks like this :

```<code>const shim = require('fabric-shim');
const util = require('util');

var PrivateDataChaincode = class {

 // Initialize the chaincode
 async Init(stub) {
  console.log('<================> ::Private Data Chaincode Instantion:: <=================>');
  return shim.success();
 }

 async Invoke(stub) {
  console.log('<================> ::Private Data Chaincode Invocation:: <=================>');
  let ret = stub.getFunctionAndParameters();
  console.info(ret);
  let method = this[ret.fcn];
  console.info('methodName');
  console.info(method);

  if (!method) {
   console.error('No method of name:' + ret.fcn + ' found');
   return shim.error('No method of name:' + ret.fcn + ' found. \n UNKNOWN FUNCTION INVOCATION: ' + ret.fcn);
  }
  console.info('\nCalling method : ' + ret.fcn);
  try {
   let payload = await method(stub, ret.params);
   return shim.success(payload);
  } catch (err) {
   console.log(err);
   return shim.error(err);
  }
 }

 async createPrivateDataInCollection(stub, args) {
  if (args.length != 2) {
   throw new Error('Incorrect number of arguments. Expecting 2');
  }

  // arg[0] has the collection name
  // arg[1] has the key

  console.info("============= START : Create Private data ===========");
  // get the transient map
  let transientData = stub.getTransient();
  await stub.putPrivateData(args[0], args[1], transientData.map.private.value);
  console.info('============= END : Create private data ===========');
 }

 async queryPrivateDataInCollection(stub, args) {
  console.info('============= START : Query private Data ===========');
  // arg[0] has the collection name
  // arg[1] has the key
  // query private data with argument
  let allResults = await stub.getPrivateData(args[0], args[1]);
  if (!allResults) {
   throw shim.error("Can't get data from state");
  }
  console.log(allResults);
  return allResults;
 }
};

shim.start(new PrivateDataChaincode());
</code>```

I am storing data using createPrivateDataInCollection method and fetching the data using queryPrivateDataInCollection. Apparently, the data is converted to some Buffer implicitily before it gets inserted and I am having trouble to convert this data back to readable format when it is read. Any idea how to convert the data to a readable format?

When I tried to print the value of transientData.map.private.value that I am storing, I got this :

```<code>ByteBuffer {
  buffer: <Buffer 0a e7 07 0a 97 01 08 03 10 01 1a 0b 08 8b f8 d3 f6 05 10 c0 d3 b4 16 22 0d 74 72 61 64 65 2d 63 68 61 6e 6e 65 6c 2a 40 39 36 35 34 61 36 31 39 63 30 ... >,
  offset: 1126,
  markedOffset: -1,
  limit: 1147,
  littleEndian: true,
  noAssert: false }
</code>```

And when I print the result in queryPrivateDataInCollection, I get this :

```<code><Buffer b5 eb 2d b6 18 ac 8a ca 6b 8a f6 ad 79 d6 ad 6a d7 ac b7 68 62>
</code>```

答:
convert your buffer data to string using toString method.

transientData.map.private.value.buffer.toString();

Body:
So I am trying to explore private data collection and I have written the chaincode in javascript. I am passing the proper collections file while instantiating the chaincode and while invoking the chaincode I am adding the transient data in request payload which looks like this :

const proposal_request = {
  chaincodeId: chaincodeId,
  fcn: functionName,
  args: args,
  chainId: channelCode,
  txId: tx_id,
  transientMap : { "private" : "test data"}
};

My chaincode file looks like this :

const shim = require('fabric-shim');
const util = require('util');

var PrivateDataChaincode = class {

 // Initialize the chaincode
 async Init(stub) {
  console.log('<================> ::Private Data Chaincode Instantion:: <=================>');
  return shim.success();
 }

 async Invoke(stub) {
  console.log('<================> ::Private Data Chaincode Invocation:: <=================>');
  let ret = stub.getFunctionAndParameters();
  console.info(ret);
  let method = this[ret.fcn];
  console.info('methodName');
  console.info(method);

  if (!method) {
   console.error('No method of name:' + ret.fcn + ' found');
   return shim.error('No method of name:' + ret.fcn + ' found. \n UNKNOWN FUNCTION INVOCATION: ' + ret.fcn);
  }
  console.info('\nCalling method : ' + ret.fcn);
  try {
   let payload = await method(stub, ret.params);
   return shim.success(payload);
  } catch (err) {
   console.log(err);
   return shim.error(err);
  }
 }

 async createPrivateDataInCollection(stub, args) {
  if (args.length != 2) {
   throw new Error('Incorrect number of arguments. Expecting 2');
  }

  // arg[0] has the collection name
  // arg[1] has the key

  console.info("============= START : Create Private data ===========");
  // get the transient map
  let transientData = stub.getTransient();
  await stub.putPrivateData(args[0], args[1], transientData.map.private.value);
  console.info('============= END : Create private data ===========');
 }

 async queryPrivateDataInCollection(stub, args) {
  console.info('============= START : Query private Data ===========');
  // arg[0] has the collection name
  // arg[1] has the key
  // query private data with argument
  let allResults = await stub.getPrivateData(args[0], args[1]);
  if (!allResults) {
   throw shim.error("Can't get data from state");
  }
  console.log(allResults);
  return allResults;
 }
};

shim.start(new PrivateDataChaincode());

I am storing data using createPrivateDataInCollection method and fetching the data using queryPrivateDataInCollection. Apparently, the data is converted to some Buffer implicitily before it gets inserted and I am having trouble to convert this data back to readable format when it is read. Any idea how to convert the data to a readable format?

When I tried to print the value of transientData.map.private.value that I am storing, I got this :

ByteBuffer {
  buffer: <Buffer 0a e7 07 0a 97 01 08 03 10 01 1a 0b 08 8b f8 d3 f6 05 10 c0 d3 b4 16 22 0d 74 72 61 64 65 2d 63 68 61 6e 6e 65 6c 2a 40 39 36 35 34 61 36 31 39 63 30 ... >,
  offset: 1126,
  markedOffset: -1,
  limit: 1147,
  littleEndian: true,
  noAssert: false }

And when I print the result in queryPrivateDataInCollection, I get this :

<Buffer b5 eb 2d b6 18 ac 8a ca 6b 8a f6 ad 79 d6 ad 6a d7 ac b7 68 62>


问:
Flutter : Check GPS Location Mode
I have project related using maps and tracking location user , for this i used Geolocator Package. I need to check current location of user , in my flow project first i check last position of user , if last position null then i check current position of user.

Code

```<code>  Position _currentPosition;
  Position get currentPosition => _currentPosition;

  Future<void> getCurrentPosition() async {
    try {
      Position lastPosition = await Geolocator().getLastKnownPosition();
      if (lastPosition != null) {
        print("Success Get Last Position...");
        _currentPosition = lastPosition;
      } else {
        final currentPosition = await Geolocator().getCurrentPosition();
        if (currentPosition != null) {
          print("Success Get Your Current Position...");
          _currentPosition = currentPosition;
        } else {
          throw "Can't Get Your Position";
        }
      }
    } catch (e) {
      throw e;
    }
    notifyListeners();
  }
</code>```

Then i calling getCurrentPosition Function on my button OnPressed to get location user like this :

Button GetLocation

```<code>void goToMaps() async {
    final mapsProvider = context.read<MapsProvider>();
    try {

      print('Get Location User');
      await mapsProvider.getCurrentPosition();
      print('Success Get location User');

    } catch (e) {
      globalF.showToast(message: e.toString(), isError: true, isLongDuration: true);
    }
  }
</code>```

First Problem is , When GPS Location Mode is Device Only I can't get LastPosition or Current Position it never print Success Get Location User and still print Get Location User.

Second Problem is , When Gps Location Mode is Battery Saving user location i got is very inaccurate, compared i used mode High Accuracy.

My question is , How can i check if gps location mode != High Accuracy , then i can show warning user to set the gps to High Accuracy.

Similiar Like this question

Thank's.

答:
For the second problem, it happens because in High Accuracy mode android uses both GPS and network location, but in Battery Saving mode GPS module is turned off. If it was native Android, you could check provider of the location if you get location from LocationManager. But provider is not available in Flutter in Position class. You can instead use accuracy. If it is greater than a threshold and not suitable for your application, you can suggest the user to turn on High Accuracy mode.

Another options would be to use other package than Geolocator (however I'm not aware of any package that provides necessary interface) or to modify source code of Geolocatior so that it provides information about which mode is currently active.

Title: Flutter : Check GPS Location Mode

Body:
I have project related using maps and tracking location user , for this i used Geolocator Package. I need to check current location of user , in my flow project first i check last position of user , if last position null then i check current position of user.

Code

  Position _currentPosition;
  Position get currentPosition => _currentPosition;

  Future<void> getCurrentPosition() async {
    try {
      Position lastPosition = await Geolocator().getLastKnownPosition();
      if (lastPosition != null) {
        print("Success Get Last Position...");
        _currentPosition = lastPosition;
      } else {
        final currentPosition = await Geolocator().getCurrentPosition();
        if (currentPosition != null) {
          print("Success Get Your Current Position...");
          _currentPosition = currentPosition;
        } else {
          throw "Can't Get Your Position";
        }
      }
    } catch (e) {
      throw e;
    }
    notifyListeners();
  }

Then i calling getCurrentPosition Function on my button OnPressed to get location user like this :

Button GetLocation

void goToMaps() async {
    final mapsProvider = context.read<MapsProvider>();
    try {

      print('Get Location User');
      await mapsProvider.getCurrentPosition();
      print('Success Get location User');

    } catch (e) {
      globalF.showToast(message: e.toString(), isError: true, isLongDuration: true);
    }
  }

First Problem is , When GPS Location Mode is Device Only I can't get LastPosition or Current Position it never print Success Get Location User and still print Get Location User.

Second Problem is , When Gps Location Mode is Battery Saving user location i got is very inaccurate, compared i used mode High Accuracy.

My question is , How can i check if gps location mode != High Accuracy , then i can show warning user to set the gps to High Accuracy.

Similiar Like this question

Thank's.


问:
Travis CI build process - TypeScript catching an error before Mocha does
This isn't so much a bug as the TypeScript compiler doing its job, however it is causing my Travis builds to fail.

In my package I have a function completeRound which takes a number as its first argument, then 3 optional arguments, and because I've written it in TypeScript I tell it that it needs to have a number passed in as the first argument:

function completeRound( number: number, rounding = 1, direction = 'closest', offset = 0 ): number {
  let n: number = +number,
      r: number = Math.abs(+rounding),
      d: string = direction,
      o: number = +offset;

  if (typeof n !== 'number') {
    throw new TypeError('You need to round a number!');
  }

  // Rest of the code goes here
}
```

<p>It all works fine, the only trouble is when it comes to testing. In my testing script I have:</p>

<pre class="lang-js prettyprint-override"><code>import completeRound from '../src/completeRound';
import { expect } from 'chai';
import 'mocha';

const expectedResults = [
  {
    testVal : {
      number    : 3.5,
      rounding  : 1,
      direction : 'down'
    },
    eR      : 3
  },
  // 40-something different tests, all passing fine
];

expectedResults.map(t => describe(`completeRound(${t.testVal.number}, ${t.testVal.rounding}, '${t.testVal.direction}', ${t.testVal.offset})`,() => {
  it(`should return ${t.eR}`, () => {
    const result = completeRound(t.testVal.number,t.testVal.rounding,t.testVal.direction,t.testVal.offset);
    expect(result).to.equal(t.eR);
  });
})); // For testing results where it shouldn't throw an error

/* This one is the problem line */
expect(() => completeRound([5])).to.throw(TypeError, /a number/);
/* ---------------------------- */

expect(() => completeRound(5,1,'arriba')).to.throw(Error, /valid rounding direction/);
</code>```

So I'm passing it an array instead of a number, where I want JavaScript to throw the TypeError. Obviously I want people using this either in JavaScript or in TypeScript to be equally covered. Plus I'm after that sweet 100% figure in my coverage report. BUT, from the below report in Travis, we can see that the TypeScript compiler is getting there first and throwing a compilation error.

```<code>TSError: ⨯ Unable to compile TypeScript:

dev/test/completeRound.spec.ts:414:28 - error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'number'.

414 expect(() => completeRound([5])).to.throw(TypeError, /a number/);
</code>```

I don't see a way that I can test the compiled code because that means, well, compiling it, I'm using webpack to compile it which straightaway put it in my ./dist folder, browserifies it and everything else, so I can't see how to import from that, and I don't really want a 2-step process where I compile it then bundle it.

I guess the short version is, I want to test JavaScript error throwing for an error where TypeScript would catch it automatically, but JavaScript wouldn't.

Can anyone help?

答:
I saw at least 2 problems:

At function completeRound(), you are using unary plus (n = +number), which means n always has type number (AFAIK). You need check "number" (the first function parameter) first. Or you can use isNaN() to check, if you still want to check it later. Example (simplified version):

function completeRound(number: number): number|TypeError {
  // Check the type of the first argument.
  if (typeof number !== 'number') {
    throw new TypeError('You need to round a number!');
  }
  // Before assign it.
  const n: number = +number;
  // For example if first parameter is function, n still has type number, but NaN.
  if (Number.isNaN(n)) {
    throw new TypeError('You need to round a number!');
  }
  // Rest of the code goes here
  return n;
}
```

<ol start="2">
<li>You can define unknown and then do type assertion. For example:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>// Use unknown testVar.
const testVar:unknown = [5];
// Do type assertion on testVar.
expect(() => completeRound(testVar as number)).to.throw(TypeError, /a number/);
// Try again with function.
const testVarAgain: unknown = () => false;
expect(() => completeRound(testVarAgain as number)).to.throw(TypeError, /a number/);
</code>```

Hope this helps. Good luck.

Body:
This isn't so much a bug as the TypeScript compiler doing its job, however it is causing my Travis builds to fail.

In my package I have a function completeRound which takes a number as its first argument, then 3 optional arguments, and because I've written it in TypeScript I tell it that it needs to have a number passed in as the first argument:

function completeRound( number: number, rounding = 1, direction = 'closest', offset = 0 ): number {
  let n: number = +number,
      r: number = Math.abs(+rounding),
      d: string = direction,
      o: number = +offset;

  if (typeof n !== 'number') {
    throw new TypeError('You need to round a number!');
  }

  // Rest of the code goes here
}

It all works fine, the only trouble is when it comes to testing. In my testing script I have:

import completeRound from '../src/completeRound';
import { expect } from 'chai';
import 'mocha';

const expectedResults = [
  {
    testVal : {
      number    : 3.5,
      rounding  : 1,
      direction : 'down'
    },
    eR      : 3
  },
  // 40-something different tests, all passing fine
];

expectedResults.map(t => describe(`completeRound(${t.testVal.number}, ${t.testVal.rounding}, '${t.testVal.direction}', ${t.testVal.offset})`,() => {
  it(`should return ${t.eR}`, () => {
    const result = completeRound(t.testVal.number,t.testVal.rounding,t.testVal.direction,t.testVal.offset);
    expect(result).to.equal(t.eR);
  });
})); // For testing results where it shouldn't throw an error

/* This one is the problem line */
expect(() => completeRound([5])).to.throw(TypeError, /a number/);
/* ---------------------------- */

expect(() => completeRound(5,1,'arriba')).to.throw(Error, /valid rounding direction/);

So I'm passing it an array instead of a number, where I want JavaScript to throw the TypeError. Obviously I want people using this either in JavaScript or in TypeScript to be equally covered. Plus I'm after that sweet 100% figure in my coverage report. BUT, from the below report in Travis, we can see that the TypeScript compiler is getting there first and throwing a compilation error.

TSError: ⨯ Unable to compile TypeScript:

dev/test/completeRound.spec.ts:414:28 - error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'number'.

414 expect(() => completeRound([5])).to.throw(TypeError, /a number/);

I don't see a way that I can test the compiled code because that means, well, compiling it, I'm using webpack to compile it which straightaway put it in my ./dist folder, browserifies it and everything else, so I can't see how to import from that, and I don't really want a 2-step process where I compile it then bundle it.

I guess the short version is, I want to test JavaScript error throwing for an error where TypeScript would catch it automatically, but JavaScript wouldn't.

Can anyone help?

Body:
I saw at least 2 problems:

At function completeRound(), you are using unary plus (n = +number), which means n always has type number (AFAIK). You need check "number" (the first function parameter) first. Or you can use isNaN() to check, if you still want to check it later. Example (simplified version):

function completeRound(number: number): number|TypeError {
  // Check the type of the first argument.
  if (typeof number !== 'number') {
    throw new TypeError('You need to round a number!');
  }
  // Before assign it.
  const n: number = +number;
  // For example if first parameter is function, n still has type number, but NaN.
  if (Number.isNaN(n)) {
    throw new TypeError('You need to round a number!');
  }
  // Rest of the code goes here
  return n;
}

You can define unknown and then do type assertion. For example:

// Use unknown testVar.
const testVar:unknown = [5];
// Do type assertion on testVar.
expect(() => completeRound(testVar as number)).to.throw(TypeError, /a number/);
// Try again with function.
const testVarAgain: unknown = () => false;
expect(() => completeRound(testVarAgain as number)).to.throw(TypeError, /a number/);

Hope this helps. Good luck.


问:
LinkedIn JS API Share
I am trying to figure out if it's possible to pass in more than a URL to share when using the LinkedIn JS API.

My code is:

```<code>IN.UI.Share().params({
    url: 'http://www.example.com'
}).place.();
</code>```

Now I have tried to pass in other params like:

```<code>IN.UI.Share().params({
    url: 'http://www.example.com',
    title: 'A Title',
    summary: 'A Small summary'
}).place.();
</code>```

But that did wot work. It seems to just ignore those extra params.

I know I can do it using the custom share functionality:

```<code>http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}
</code>```

But I want to use the JS API so I can get back a token to verify if it was posted properly. With the shareArticle way it takes about 20-30 seconds to actually verify if it was shared using this: (https://developer.linkedin.com/retrieving-share-counts-custom-buttons).

答:
Just set the og: property tags on the page that you are sharing, that way LinkedIn knows that the title, image, etc., fields, are all actually appropriate and right for the site.  You can set them like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Works for my site!

You can always use the LinkedIn Poster Inspector on your site's URL to make sure you did it right!

Title: LinkedIn JS API Share

Body:
I am trying to figure out if it's possible to pass in more than a URL to share when using the LinkedIn JS API.

My code is:

IN.UI.Share().params({
    url: 'http://www.example.com'
}).place.();

Now I have tried to pass in other params like:

IN.UI.Share().params({
    url: 'http://www.example.com',
    title: 'A Title',
    summary: 'A Small summary'
}).place.();

But that did wot work. It seems to just ignore those extra params.

I know I can do it using the custom share functionality:

http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}

But I want to use the JS API so I can get back a token to verify if it was posted properly. With the shareArticle way it takes about 20-30 seconds to actually verify if it was shared using this: (https://developer.linkedin.com/retrieving-share-counts-custom-buttons).


问:
Parse Json Array on new lines correctly in StreamDeckSDK
I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting.  But now everything is on one line. How do iterate through the array and put them on new lines?

Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.

```<code>   function setTitleStatus(context, settings) {
        $SD.api.setTitle(context, "Updating...");
        getResults(result => resultCallback(result, context));
    }

    function resultCallback(result, context) {
        if (!result.hasOwnProperty("Object")) {
           $SD.api.setTitle(context, JSON.stringify(result));
           console.log(JSON.stringify(result, '%c%s'));
           return;
        }
        // This is where I'd like all 3 objects to be split on new lines.
        // $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.Platform + " ")
        // $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.PU + " ")
        // $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.EA + " ")
    }

    function getResults(updateTitleFn) {
        let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
        $.getJSON(endPoint)
            .done(function (response) {

                updateTitleFn({
                    "Platform": response[0].status,
                    "PU": response[1].status,
                    "EA": response[2].status,
                });

                console.log("Platform", response[0].status)
                console.log("PU", response[1].status)
                console.log("EA", response[2].status)

            })
    }
</code>```

Update
If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
         "\n" + result.EA + " ")
Via Screenshot

答:
To get nicely formatted output from JSON.stringify, supply the optional arguments:

```<code>JSON.stringify(obj, null, 2)
</code>```

let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];

document.getElementById('result').innerHTML =
  'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
  'Stringify formatted: ' + JSON.stringify(arr, null, 2);
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="result">``````

Body:
I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting.  But now everything is on one line. How do iterate through the array and put them on new lines?

Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.

   function setTitleStatus(context, settings) {
        $SD.api.setTitle(context, "Updating...");
        getResults(result => resultCallback(result, context));
    }

    function resultCallback(result, context) {
        if (!result.hasOwnProperty("Object")) {
           $SD.api.setTitle(context, JSON.stringify(result));
           console.log(JSON.stringify(result, '%c%s'));
           return;
        }
        // This is where I'd like all 3 objects to be split on new lines.
        // $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.Platform + " ")
        // $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.PU + " ")
        // $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.EA + " ")
    }

    function getResults(updateTitleFn) {
        let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
        $.getJSON(endPoint)
            .done(function (response) {

                updateTitleFn({
                    "Platform": response[0].status,
                    "PU": response[1].status,
                    "EA": response[2].status,
                });

                console.log("Platform", response[0].status)
                console.log("PU", response[1].status)
                console.log("EA", response[2].status)

            })
    }

Update
If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
         "\n" + result.EA + " ")
Via Screenshot

Body:
To get nicely formatted output from JSON.stringify, supply the optional arguments:

JSON.stringify(obj, null, 2)

let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];

document.getElementById('result').innerHTML =
  'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
  'Stringify formatted: ' + JSON.stringify(arr, null, 2);

<pre id="result"></pre>


问:
how to get full path with os.walk function in python
i am using os.walk to find directories, but it does not show the full path

code:

```<code>for root, subdirs, files in os.walk(path):
    print(subdirs)
</code>```

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

答:
To quote the documentation:

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

Putting it together, you get the following:

```<code>for root, subdirs, files in os.walk(path):
    for dir in subdirs:
        print(os.path.join(root, dir))
</code>```

Body:
i am using os.walk to find directories, but it does not show the full path

code:

for root, subdirs, files in os.walk(path):
    print(subdirs)

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

Body:
To quote the documentation:

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

Putting it together, you get the following:

for root, subdirs, files in os.walk(path):
    for dir in subdirs:
        print(os.path.join(root, dir))


问:
uninstall shopify app any callback or setting
I have create a shopify app but when user delete that app in his store then can we call back any api so that we could delete his  data?</p>

答:
There is a webhook that you can listen for called app/uninstalled.

This fires when an app is uninstalled and you can delete the store data in your database.

Refer to the docs here: https://shopify.dev/docs/admin-api/rest/reference/events/webhook?api[version]=2020-04


问:
Markdown how to change the default Text size Android Markwon
Where can I set the configuration to set a custom font and text size for "regular text" while rendering Markdown with the Markwon dependency?

Setting custom multipliers for the headings and setting the codeBlock text sizes don't work. Neither works setting the <item name="android:textAppearance">@style/mytextappearance</item> in the application theme

答:
Nevermind; I found it:

When building the Markwon instance you do:

Markwon
    .builder(context)
    .usePlugin(object : AbstractMarkwonPlugin(){
          override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
               super.configureSpansFactory(builder)
               builder.setFactory(Text::class.java) { _, _ -> TextAppearanceSpan(context, R.style.my_text_style)}

          }
    })
    .build()
```


问:
Trouble downloading files in Google Apps Script web app after Chrome update
I've had a Google Apps Script web app running for a bit over a year which gave users an option to download a csv file. It worked perfectly fine, although in the console it gave a warning about downloading from an iFrame being deprecated.

After updating Chrome, I now get the following error when trying to download:

Download is disallowed. The frame initiating or instantiating the
  download is sandboxed, but the flag ‘allow-downloads’ is not set. See
  https://www.chromestatus.com/feature/5706745674465280 for more
  details.

When following the above link, it provides the following information:

Chrome is planning on removing this capability - i.e. Chrome is going
  to block all downloads initiated from or instantiated in a sandboxed
  iframe by default. The embedder may add "allow-downloads" to the
  sandbox attributes list to opt in. This allows content providers to
  restrict malicious or abusive downloads.

How can I add "allow-downloads" to the sandbox attributes in the Google Apps Script environment? Alternatively, is there a workaround to enable downloading files?

答: There is one work around that I found if you have a download button, you can right click and open in a new tab.  You have to rename the file but at least you can get it, until there is a fix. </p>


问:
Python checking if all item in nested list are the same
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

```<code>a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break
</code>```

is there any other better way to do this? without importing any libraries

答:
The following expression returns True if all elements are 0 (or False), else return False

```<code>not any(any(x) for x in a)
</code>```

Body:
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break

is there any other better way to do this? without importing any libraries

Body:
The following expression returns True if all elements are 0 (or False), else return False

not any(any(x) for x in a)


问:
Using Module and path
I am running into some issues with loading a PSM1 file. The PSM1 is always in the same folder as the PS1, but that folder can change. It works if I use a literal path like this...

```<code>Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'
</code>```

But that's useless since the code could be installed anywhere. And the code is signed, so it can't change.

It also doesn't work to use the new (in PS3.0) $PSScriptRoot automatic variable...

```<code>Using module "$PSScriptRoot\library.psm1"
</code>```

Nor does a relative path or simple file name, as in...

```<code>Using module ".\library.psm1"
</code>```

or...

```<code>Using module "library.psm1"
</code>```

What am I missing, other than perhaps it's time to call it a day?

Also, note that the library contains classes, so other module loading options like Import-Module don't work. This has me wondering if perhaps classes are better supported in a later version, and I should really be targeting PS 6.0, rather than 5.1?

答:
you should run import-module first.
in PS1, I have add code to call import-module
like this:

```<code>ForEach($_ in  Get-ChildItem "$env:TEMP\*.psm1") {
    $checkModuleName = $_.Name -replace ".psm1"
    $importModule = $_.Name

    if (Get-Module $checkModuleName) {
        Write-Host "Update Module $importModule" -ForegroundColor Green

        Remove-Module $checkModuleName
        Import-Module "$env:TEMP\$importModule"
    }
    else {
        Write-Host "Import Module $importModule" -ForegroundColor Green

        Import-Module "$env:TEMP\$importModule"
    }
}
</code>```

when import done, I can used all module.

Title: Using Module and path

Body:
I am running into some issues with loading a PSM1 file. The PSM1 is always in the same folder as the PS1, but that folder can change. It works if I use a literal path like this...

Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'

But that's useless since the code could be installed anywhere. And the code is signed, so it can't change.

It also doesn't work to use the new (in PS3.0) $PSScriptRoot automatic variable...

Using module "$PSScriptRoot\library.psm1"

Nor does a relative path or simple file name, as in...

Using module ".\library.psm1"

or...

Using module "library.psm1"

What am I missing, other than perhaps it's time to call it a day?

Also, note that the library contains classes, so other module loading options like Import-Module don't work. This has me wondering if perhaps classes are better supported in a later version, and I should really be targeting PS 6.0, rather than 5.1?

Body:
you should run import-module first.
in PS1, I have add code to call import-module
like this:

ForEach($_ in  Get-ChildItem "$env:TEMP\*.psm1") {
    $checkModuleName = $_.Name -replace ".psm1"
    $importModule = $_.Name

    if (Get-Module $checkModuleName) {
        Write-Host "Update Module $importModule" -ForegroundColor Green

        Remove-Module $checkModuleName
        Import-Module "$env:TEMP\$importModule"
    }
    else {
        Write-Host "Import Module $importModule" -ForegroundColor Green

        Import-Module "$env:TEMP\$importModule"
    }
}

when import done, I can used all module.


问:
Trying to combine a list of lists in python
I have a list of lists containing tuples of x and y coordinates such as
[ [(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)] ] and I want to combine them in such a way where the output contains all the x coordinates together and all the y coordinates together. Essentially I'm trying to make the output be [(1,3,5,7,0), (2,4,6,8,5)] so that it is a 2xN matrix. I tried to do list(zip(*b) where b = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]] (the original list), but that has not given me the correct output.

答:
You first need to flatten the nested list. You can use itertools.chain:

```<code>from itertools import chain

list(zip(*chain.from_iterable(b)))
# [(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]
</code>```

Body:
You first need to flatten the nested list. You can use itertools.chain:

from itertools import chain

list(zip(*chain.from_iterable(b)))
# [(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]


问:
maven - filtering files under src/main/webapp/jsp while building the war
In my java webapp project I have all the jsp files placed at src/main/webapp/jsp.
How do I enable the filtering and replace property placeholders with actual values while building the war?

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <filters><filter>${basedir}/src/main/resources/filter.properties</filter></filters>
        <webResources>
            <resource>
                <directory>src/main/webapp/jsp</directory>
                <targetPath>/jsp/</targetPath>
                <filtering>true</filtering>
            </resource>
        </webResources>
    </configuration>
</plugin>
</code>```

Attaching the console output of mvn package command :

```<code>[exec] [INFO] Copying webapp webResources [projectbasedir/src/main/webapp/jsp] to [projectbasedir/target/myapp]
[exec] [INFO] Copying webapp resources [projectbasedir/src/main/webapp]
</code>```

The jsp files are getting filtered properly in "Copying webapp webResources" step but "Copying webapp resources" step overwrites all these changes since it copies everything from src/main/webapp folder to target folder afresh.

How do I make this filtering work?

答:
Try to replace it with this config, the difference is to use directory as src/main/webapp and include subfolder in includes.
For whatever reasons when directory matches with warSourceDirectory it works fine.

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <filters><filter>${basedir}/src/main/resources/filter.properties</filter></filters>
        <webResources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>/jsp/</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>jsp/**</include>
                </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my java webapp project I have all the jsp files placed at src/main/webapp/jsp.
How do I enable the filtering and replace property placeholders with actual values while building the war?

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <filters><filter>${basedir}/src/main/resources/filter.properties</filter></filters>
        <webResources>
            <resource>
                <directory>src/main/webapp/jsp</directory>
                <targetPath>/jsp/</targetPath>
                <filtering>true</filtering>
            </resource>
        </webResources>
    </configuration>
</plugin>

Attaching the console output of mvn package command :

[exec] [INFO] Copying webapp webResources [projectbasedir/src/main/webapp/jsp] to [projectbasedir/target/myapp]
[exec] [INFO] Copying webapp resources [projectbasedir/src/main/webapp]

The jsp files are getting filtered properly in "Copying webapp webResources" step but "Copying webapp resources" step overwrites all these changes since it copies everything from src/main/webapp folder to target folder afresh.

How do I make this filtering work?

Body:
Try to replace it with this config, the difference is to use directory as src/main/webapp and include subfolder in includes.
For whatever reasons when directory matches with warSourceDirectory it works fine.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <filters><filter>${basedir}/src/main/resources/filter.properties</filter></filters>
        <webResources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>/jsp/</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>jsp/**</include>
                </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>


答:
Your approach is correct, you just have to flatten your input list first.</p>

```<code>>>> lst = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]
>>> lst_flat = [x for sublist in lst for x in sublist]
>>> list(zip(*lst_flat))
[(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]
</code>```

Title: Trying to combine a list of lists in python

Body:
I have a list of lists containing tuples of x and y coordinates such as
[ [(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)] ] and I want to combine them in such a way where the output contains all the x coordinates together and all the y coordinates together. Essentially I'm trying to make the output be [(1,3,5,7,0), (2,4,6,8,5)] so that it is a 2xN matrix. I tried to do list(zip(*b) where b = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]] (the original list), but that has not given me the correct output.

Body:
Your approach is correct, you just have to flatten your input list first.

>>> lst = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]
>>> lst_flat = [x for sublist in lst for x in sublist]
>>> list(zip(*lst_flat))
[(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]


问:
Playing sounds in WPF app using MediaPlayer
I wanted to play sounds in WPF app using MediaPlayer. The problem is that I can't use the file directly from resources file like in SoundPlayer

```<code>SoundPlayer player = new SoundPlayer(R.testSound);
</code>```

So I used path to sound like this:

```<code>mediaPlayer.Open(new Uri("../../Resources/testSound.wav", UriKind.Relative)); //working
mediaPlayer.Open(new Uri("pack://application:,,,/Resources/testSound.wav")); //not wroking
</code>```

Is there any possibility to do this without a relative path? Is Relative path bad idea?

答:
If you register to the MediaFailed event, you will see that it returns a message that says "System.NotSupportedException: Only site-of-origin pack URIs are supported for media."

Solution

Edit your testsound.wav's Build Action to "Content" and "Copy Always".  This is needed for site-of-origin solutions.

Use "siteoforigin" pack URI instead of "application" when you open the media player.  Here's working code:

```<code>using System;
using System.Windows;
using System.Windows.Media;

namespace SoundTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MediaPlayer mp;

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Console.WriteLine("Dispatcher called");
                mp = new MediaPlayer();
                mp.MediaOpened += Mp_MediaOpened;
                mp.MediaFailed += Mp_MediaFailed;
                mp.Open(new Uri("pack://siteoforigin:,,,/Resources/testsound.wav"));

            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.GetType()}: {ex.Message}\n{ex.StackTrace}");
            }
        }

        private void Mp_MediaFailed(object sender, ExceptionEventArgs e)
        {
            var ex = e.ErrorException;
            Console.WriteLine($"MEDIA FAILED: {ex.GetType()}: {ex.Message}\n{ex.StackTrace}");
        }

        private void Mp_MediaOpened(object sender, EventArgs e)
        {
            mp.Play();
            Console.WriteLine("Play called");
        }
    }
}

</code>```

Body:
I wanted to play sounds in WPF app using MediaPlayer. The problem is that I can't use the file directly from resources file like in SoundPlayer

SoundPlayer player = new SoundPlayer(R.testSound);

So I used path to sound like this:

mediaPlayer.Open(new Uri("../../Resources/testSound.wav", UriKind.Relative)); //working
mediaPlayer.Open(new Uri("pack://application:,,,/Resources/testSound.wav")); //not wroking

Is there any possibility to do this without a relative path? Is Relative path bad idea?

Body:
If you register to the MediaFailed event, you will see that it returns a message that says "System.NotSupportedException: Only site-of-origin pack URIs are supported for media."

Solution

Edit your testsound.wav's Build Action to "Content" and "Copy Always".  This is needed for site-of-origin solutions.

Use "siteoforigin" pack URI instead of "application" when you open the media player.  Here's working code:

using System;
using System.Windows;
using System.Windows.Media;

namespace SoundTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MediaPlayer mp;

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Console.WriteLine("Dispatcher called");
                mp = new MediaPlayer();
                mp.MediaOpened += Mp_MediaOpened;
                mp.MediaFailed += Mp_MediaFailed;
                mp.Open(new Uri("pack://siteoforigin:,,,/Resources/testsound.wav"));

            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.GetType()}: {ex.Message}\n{ex.StackTrace}");
            }
        }

        private void Mp_MediaFailed(object sender, ExceptionEventArgs e)
        {
            var ex = e.ErrorException;
            Console.WriteLine($"MEDIA FAILED: {ex.GetType()}: {ex.Message}\n{ex.StackTrace}");
        }

        private void Mp_MediaOpened(object sender, EventArgs e)
        {
            mp.Play();
            Console.WriteLine("Play called");
        }
    }
}


问:
Title of localnotifiaction
I want to show local notification with different message title( "Error" ) and not as of the application's name.
How can i achieve this.

Please help

答:
I check and doing this is not possible. No property available for that.

Ravi Kumar Singh

ContentLicense: CC BY-SA 2.5

Title: Title of localnotifiaction


问:
Screen does not get widgets
I have a screen that loads some widgets according to a csv. But the screen just gets empty.

```<code>Column(
   children: getPlates(),
),
</code>```

```<code>  List<Widget> getPlates() {
    List<Widget> listWidgets = [];
    listWidgets.add(Text('dew'));
    loadAsset('assets/Postres.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });
    setState(() {

    });
    return listWidgets;
  }

  Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }
</code>```

I think it is because of the async method loadAsset that returns something when the screen is already bult. I tried loading it in initState but only works if I press hot reload

答:
Using a FutureBuilder should solve your problem.

FutureBuilder<String>(
  future: loadAsset('assets/Postres.csv'),
  builder: (context, snapshot){
    if(snapshot.hasData){
      final output = snapshot.data;
      final list = output.split('\n');

      return ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index){
          final sublist = list[index].split(';');
          return CardPlate(
            name: sublist[0],
            ingredients: sublist[1],
            price: sublist[2],
          );
        }
      );
    } else {
      return Text('awaiting the future');
    }
  },
),
```

Title: Screen does not get widgets

Body:
I have a screen that loads some widgets according to a csv. But the screen just gets empty.

Column(
   children: getPlates(),
),

  List<Widget> getPlates() {
    List<Widget> listWidgets = [];
    listWidgets.add(Text('dew'));
    loadAsset('assets/Postres.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });
    setState(() {

    });
    return listWidgets;
  }

  Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }

I think it is because of the async method loadAsset that returns something when the screen is already bult. I tried loading it in initState but only works if I press hot reload


问:
Passing a single row of a 2d array as an input to a module in verilog
I was wondering if there is any way to pass a single row of a 2d array of values as the input to a module in Verilog.

Say my array is defined like this:

```<code>   reg[15:0] arr[0:9][0:63];
   ...
   ...
   mod1 m(..., arr[5], ....);
</code>```

mod1 has the definition of:

```<code>module mod1 (..., input[15:0] arr[0:63],...);
...
...
endmodule
</code>```

I use icarus verilog as my compiler. When I compile using the -g2012 flag, it throws the following error:

```<code>assert: elaborate.cc:1456: failed assertion rval_net->pin_count() == prts[0]->pin_count()
</code>```

Can someone help me with this?

答:
iverilog's SystemVerilog support is limited. With the -g2012 flag enabled it can pass multi-dimensional arrays across ports. The version you are using and the version available on EDAplayground, cannot automatically convert multi-dimensional structure into another multi-dimensional structure. This is a tool limitation, not a limitation in the IEEE1800 LRM.

With the version available to me (which is from 2014), I had to create an intermediate translation.

```<code>reg[15:0] arr[0:9][0:63];
reg[15:0] arr5[0:63];
...
always @* begin // should be always_comb; 2014 version does not support it
  foreach(arr5[idx])
    arr5[idx] = arr[5][idx];
end
...
mod1 m(..., arr5, ....);
</code>```

Body:
I was wondering if there is any way to pass a single row of a 2d array of values as the input to a module in Verilog.

Say my array is defined like this:

   reg[15:0] arr[0:9][0:63];
   ...
   ...
   mod1 m(..., arr[5], ....);

mod1 has the definition of:

module mod1 (..., input[15:0] arr[0:63],...);
...
...
endmodule

I use icarus verilog as my compiler. When I compile using the -g2012 flag, it throws the following error:

assert: elaborate.cc:1456: failed assertion rval_net->pin_count() == prts[0]->pin_count()

Can someone help me with this?

Body:
iverilog's SystemVerilog support is limited. With the -g2012 flag enabled it can pass multi-dimensional arrays across ports. The version you are using and the version available on EDAplayground, cannot automatically convert multi-dimensional structure into another multi-dimensional structure. This is a tool limitation, not a limitation in the IEEE1800 LRM.

With the version available to me (which is from 2014), I had to create an intermediate translation.

reg[15:0] arr[0:9][0:63];
reg[15:0] arr5[0:63];
...
always @* begin // should be always_comb; 2014 version does not support it
  foreach(arr5[idx])
    arr5[idx] = arr[5][idx];
end
...
mod1 m(..., arr5, ....);


问:
How to make an EC2 instance automatically reboot when ELB says it's unavailable?
Every now and then Elastic Load Balancer (ELB) kicks out one of my servers for being unavailable.  Which is good -- hardly any interruption.

Usually, just rebooting the instance through the AWS Console fixes the problem.

I would like to have my EC2 instance automatically reboot when it becomes unavailable.

What's the best way to do this?  (it happens to be a Windows instance, but ideally that shouldn't matter)

答:
You can automatically do this via a CloudWatch Alarm. When the alarm is triggered because an instance is dead, one of the actions you can then have the alarm take is to reboot the instance. No need to spend time making a lambda or having a micro instance handle this for you.

https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html#AddingRebootActions


问:
Error trying to implement IValueConverter in PowerShell - XAML GUI script
What am I missing? I was trying to implement converters to my XAML-based PowerShell script but with no luck.
I've picked up pieces of information from sites like StackOverflow. but couldn't find one successful implementation of a converter in powershell XAML-based GUI script.

in the code I am testing the converter, and it works (you can see 2 examples for conversion) so that means that powershell itself accepted the new converter type, buy this converter cannot be implemented in my xaml code.

```<code>$src = @'
    using System;
    using System.Windows;
    using System.Windows.Data;
    using System.Globalization;

    namespace MyProject
    {

        public class DemoConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                {
                    return "kuku";
                }
                else
                {
                    return "bobo";
                }
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return value;
            }
        }
    }
'@

Add-Type -AssemblyName PresentationFramework
Add-Type -TypeDefinition $src -ReferencedAssemblies PresentationFramework

#Checking that the new type works and convert is done...
$c = new-object MyProject.DemoConverter
$c.Convert("gg", $null, $null, $null)
$c.Convert(55, $null, $null, $null)

#Now declaring and loading the xaml
[xml]$XAML = @'

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cnv="clr-namespace:MyProject" >
    <Window.Resources>
        <cnv:DemoConverter x:Key="TestConverter" />
    </Window.Resources>
    <Grid>
        <TextBox x:Name="txtTestValue" Text="I'm here to show that xaml loading works!" />
    </Grid>
</Window>
'@

$reader=(New-Object System.Xml.XmlNodeReader $xaml)

$Window=[Windows.Markup.XamlReader]::Load( $reader )

$Window.ShowDialog() | out-null
</code>```

I keep getting this error:

Exception calling "Load" with "1" argument(s): "Cannot create unknown type '{clr-namespace:MyProject}DemoConverter'."

If I remove the line: <cnv:DemoConverter x:Key="TestConverter" />
It will not give the above error and the window will show (but of course, convertion in xaml will not be available), so I guess I'm doing something wrong with namespace and/or assembly deceleration that XAML doesn't like.

Note that on my xaml I'm not yet using the converter. I just want to overcome the above error before trying to use the converter.

Thank you so much in advance!

答:
I signed up for Stackoverflow just so I could participate in this question.

I searched for HOURS for a solution to this before I ran across this question here, and then my hopes were dashed to see it's been sitting out here almost a year with no answer.

I had found this related question earlier, and it gives the basic solution we're trying to implement with this question, but doesn't give any details on making it actually work.
How to use IValueConverter from powershell?

Luckily, after several more hours, and piecing together a lot of other info, I finally solved it!

There are 3 pieces to it.

The converter type being added via the C# code is not part of the same namespace of the form, even if you specify the form's namespace in the C# class code.  So an extra xmlns: line is needed to include the converter type's namespace in the form.  Then when defining the converter in the form resources, you reference that namespace instead of the form's own namespace (usually "local", but I see your example you used "cnv").  Also though, for the reason below, you want your namespace in your C# code to be different from your form's own namespace.  (I don't know for sure, but the system might get confused having 2 different namespaces that are really physically separate.)

BUT, even with the added xmlns: line to include the converter's namespace, the form still can't find it.  This is becuase, I discovered, the added converter type is also added to a different Assembly.  Apparently when adding custom types with "Add-Type -TypeDefinition", PowerShell creates its own in-memory Assembly and adds the type to that.  So, in the added xmlns: line to include the converter's namespace, we also have to specify the assembly for the custom converter type.

BUT, BUT...   What's worse is that this "made-up" Assembly has a randomly generated name, AND that Assembly name is different every time you run the script.  (I could not find this fact documented anywhere.  I discovered it entirely by accident.)  So how can you include an assembly name if you don't know the name?  Basically do what you did, create an instance of your new converter object in a variable, then check the properties of that new object variable to determine the Assembly name.  Then use string Replace to update your XAML string with the Assembly name.

SO, see the updated code I posted which has the following changes.  As the original poster indicated, this example doesn't show the converter in action, but the script will at least run and display the form without error, indicating the the form itself accepted the converter definition and usage in the TextBox.

Changed namespace in the C# code to MyConverter so it's different
from the form's MyProject namespace.

In the line that creates the $c instance of the converter object, I changed the namespace to MyConverter instead of MyProject, to match the new namespace as above.

Added $AssemblyName variable to pull out the random assembly name.  (I also commented out the calls to Convert and ConvertBack.)

Changed the Here-String for the XAML code to a string variable, $inputXML so we can use Replace on it.  Will convert to xml document later.

xlmns:Converter line added to include MyConverter namespace.  Note the ";assembly=myassembly" piece.  The "myassembly" name is simply aplaceholder for the string Replace to easily find later.

In the declaration of the converter Window.Resources, changed the "cnv:" to "Converter:" to match the Converter type's namespace declaration.

Added another TextBox to show including the Converter and that the form build accepts this.

Added [xml]$XAML = $inputXML.... line to convert to xml and replace with the actual assembly name.

Code

```<code>$src = @'
    using System;
    using System.Windows;
    using System.Windows.Data;
    using System.Globalization;

    namespace MyConverter
    {

        public class DemoConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                {
                    return "kuku";
                }
                else
                {
                    return "bobo";
                }
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return value;
            }
        }
    }
'@

Add-Type -AssemblyName PresentationFramework
Add-Type -TypeDefinition $src -ReferencedAssemblies PresentationFramework

#Checking that the new type works and convert is done...
$c = new-object MyConverter.DemoConverter
$AssemblyName = $c.gettype().Assembly.FullName.Split(',')[0]
#$c.Convert("gg", $null, $null, $null)
#$c.Convert(55, $null, $null, $null)

#Now declaring and loading the xaml
$inputXML = @'

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Converter="clr-namespace:MyConverter;assembly=myassembly"
xmlns:cnv="clr-namespace:MyProject" >
    <Window.Resources>
        <Converter:DemoConverter x:Key="TestConverter" />
    </Window.Resources>
    <Grid>
        <TextBox x:Name="txtTestValue" Text="I'm here to show that xaml loading works!" />
        <TextBox x:Name="txtTestValue2" Text="{Binding Path=Whatever, Converter={StaticResource TestConverter}}" />
   </Grid>
</Window>
'@

[xml]$XAML = $inputXML -replace 'myassembly', $AssemblyName

$reader=(New-Object System.Xml.XmlNodeReader $xaml)

$Window=[Windows.Markup.XamlReader]::Load( $reader )

$Window.ShowDialog() | out-null
</code>```

Body:
What am I missing? I was trying to implement converters to my XAML-based PowerShell script but with no luck.
I've picked up pieces of information from sites like StackOverflow. but couldn't find one successful implementation of a converter in powershell XAML-based GUI script.

in the code I am testing the converter, and it works (you can see 2 examples for conversion) so that means that powershell itself accepted the new converter type, buy this converter cannot be implemented in my xaml code.

$src = @'
    using System;
    using System.Windows;
    using System.Windows.Data;
    using System.Globalization;

    namespace MyProject
    {

        public class DemoConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                {
                    return "kuku";
                }
                else
                {
                    return "bobo";
                }
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return value;
            }
        }
    }
'@

Add-Type -AssemblyName PresentationFramework
Add-Type -TypeDefinition $src -ReferencedAssemblies PresentationFramework

#Checking that the new type works and convert is done...
$c = new-object MyProject.DemoConverter
$c.Convert("gg", $null, $null, $null)
$c.Convert(55, $null, $null, $null)

#Now declaring and loading the xaml
[xml]$XAML = @'

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cnv="clr-namespace:MyProject" >
    <Window.Resources>
        <cnv:DemoConverter x:Key="TestConverter" />
    </Window.Resources>
    <Grid>
        <TextBox x:Name="txtTestValue" Text="I'm here to show that xaml loading works!" />
    </Grid>
</Window>
'@

$reader=(New-Object System.Xml.XmlNodeReader $xaml)

$Window=[Windows.Markup.XamlReader]::Load( $reader )

$Window.ShowDialog() | out-null

I keep getting this error:

Exception calling "Load" with "1" argument(s): "Cannot create unknown type '{clr-namespace:MyProject}DemoConverter'."

If I remove the line: <cnv:DemoConverter x:Key="TestConverter" />
It will not give the above error and the window will show (but of course, convertion in xaml will not be available), so I guess I'm doing something wrong with namespace and/or assembly deceleration that XAML doesn't like.

Note that on my xaml I'm not yet using the converter. I just want to overcome the above error before trying to use the converter.

Thank you so much in advance!

Body:
I signed up for Stackoverflow just so I could participate in this question.

I searched for HOURS for a solution to this before I ran across this question here, and then my hopes were dashed to see it's been sitting out here almost a year with no answer.

I had found this related question earlier, and it gives the basic solution we're trying to implement with this question, but doesn't give any details on making it actually work.
How to use IValueConverter from powershell?

Luckily, after several more hours, and piecing together a lot of other info, I finally solved it!

There are 3 pieces to it.

The converter type being added via the C# code is not part of the same namespace of the form, even if you specify the form's namespace in the C# class code.  So an extra xmlns: line is needed to include the converter type's namespace in the form.  Then when defining the converter in the form resources, you reference that namespace instead of the form's own namespace (usually "local", but I see your example you used "cnv").  Also though, for the reason below, you want your namespace in your C# code to be different from your form's own namespace.  (I don't know for sure, but the system might get confused having 2 different namespaces that are really physically separate.)

BUT, even with the added xmlns: line to include the converter's namespace, the form still can't find it.  This is becuase, I discovered, the added converter type is also added to a different Assembly.  Apparently when adding custom types with "Add-Type -TypeDefinition", PowerShell creates its own in-memory Assembly and adds the type to that.  So, in the added xmlns: line to include the converter's namespace, we also have to specify the assembly for the custom converter type.

BUT, BUT...   What's worse is that this "made-up" Assembly has a randomly generated name, AND that Assembly name is different every time you run the script.  (I could not find this fact documented anywhere.  I discovered it entirely by accident.)  So how can you include an assembly name if you don't know the name?  Basically do what you did, create an instance of your new converter object in a variable, then check the properties of that new object variable to determine the Assembly name.  Then use string Replace to update your XAML string with the Assembly name.

SO, see the updated code I posted which has the following changes.  As the original poster indicated, this example doesn't show the converter in action, but the script will at least run and display the form without error, indicating the the form itself accepted the converter definition and usage in the TextBox.

Changed namespace in the C# code to MyConverter so it's different
from the form's MyProject namespace.

In the line that creates the $c instance of the converter object, I changed the namespace to MyConverter instead of MyProject, to match the new namespace as above.

Added $AssemblyName variable to pull out the random assembly name.  (I also commented out the calls to Convert and ConvertBack.)

Changed the Here-String for the XAML code to a string variable, $inputXML so we can use Replace on it.  Will convert to xml document later.

xlmns:Converter line added to include MyConverter namespace.  Note the ";assembly=myassembly" piece.  The "myassembly" name is simply aplaceholder for the string Replace to easily find later.

In the declaration of the converter Window.Resources, changed the "cnv:" to "Converter:" to match the Converter type's namespace declaration.

Added another TextBox to show including the Converter and that the form build accepts this.

Added [xml]$XAML = $inputXML.... line to convert to xml and replace with the actual assembly name.

Code

$src = @'
    using System;
    using System.Windows;
    using System.Windows.Data;
    using System.Globalization;

    namespace MyConverter
    {

        public class DemoConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                {
                    return "kuku";
                }
                else
                {
                    return "bobo";
                }
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return value;
            }
        }
    }
'@

Add-Type -AssemblyName PresentationFramework
Add-Type -TypeDefinition $src -ReferencedAssemblies PresentationFramework

#Checking that the new type works and convert is done...
$c = new-object MyConverter.DemoConverter
$AssemblyName = $c.gettype().Assembly.FullName.Split(',')[0]
#$c.Convert("gg", $null, $null, $null)
#$c.Convert(55, $null, $null, $null)

#Now declaring and loading the xaml
$inputXML = @'

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Converter="clr-namespace:MyConverter;assembly=myassembly"
xmlns:cnv="clr-namespace:MyProject" >
    <Window.Resources>
        <Converter:DemoConverter x:Key="TestConverter" />
    </Window.Resources>
    <Grid>
        <TextBox x:Name="txtTestValue" Text="I'm here to show that xaml loading works!" />
        <TextBox x:Name="txtTestValue2" Text="{Binding Path=Whatever, Converter={StaticResource TestConverter}}" />
   </Grid>
</Window>
'@

[xml]$XAML = $inputXML -replace 'myassembly', $AssemblyName

$reader=(New-Object System.Xml.XmlNodeReader $xaml)

$Window=[Windows.Markup.XamlReader]::Load( $reader )

$Window.ShowDialog() | out-null


问:
Strip the First Four Rows of a CSV in Python?
I have a batch of 50-60 csv files which, for whatever reason, have total junk data for the first four rows of each file. After the junk data, however, the column headers are properly listed, and the rest of the file is fine. How could I go about stripping each file of these first four files in python? Here is my code thus far:

```<code>import csv
total = open('C:\\Csv\\201.csv', 'rb')
for row in csv.reader(total):
    print row
</code>```

As you can see, all I have done is opened the file and printed its contents. I have searched around for solutions of deleting certain aspects of csv files, but most either delete entire columns, or hinge on a particular condition for the row to be deleted. In my case, it is simply a matter of order, and every file needs to be stripped of its first four rows. Any and all  help is greatly appreciated.

答:
I surprised no one mentioned the parameter available to skiprows while calling the read function.

```<code>df = pd.read_csv('somefile.csv',skiprows=4)
</code>```

You can check the file for rows containing the header and give value to **skiprows** as per it removes the first k rows if the value is k.

Body:
I have a batch of 50-60 csv files which, for whatever reason, have total junk data for the first four rows of each file. After the junk data, however, the column headers are properly listed, and the rest of the file is fine. How could I go about stripping each file of these first four files in python? Here is my code thus far:

import csv
total = open('C:\\Csv\\201.csv', 'rb')
for row in csv.reader(total):
    print row

As you can see, all I have done is opened the file and printed its contents. I have searched around for solutions of deleting certain aspects of csv files, but most either delete entire columns, or hinge on a particular condition for the row to be deleted. In my case, it is simply a matter of order, and every file needs to be stripped of its first four rows. Any and all  help is greatly appreciated.

Body:
I surprised no one mentioned the parameter available to skiprows while calling the read function.

df = pd.read_csv('somefile.csv',skiprows=4)

You can check the file for rows containing the header and give value to **skiprows** as per it removes the first k rows if the value is k.


问:
Bulma: Unable to use both is-static and is-primary modifies on a button
I want to create a button using Bulma that is non-interactive and a "primary" button.  Here is my attempt:

```<code><span class="button is-primary is-static">Hello World</span>
</code>```

When I do this, I get a standard looking non-interactive button.  It's gray in color and not clickable (this is NOT a disabled button).  The is-primary modifier seems to have no effect on the button and I am unsure why.  If I were to instead remove the is-static modifier, I get a normal looking "primary" button.

I found a hack-ish solution (by doing the following) but would prefer to use the modifiers provided by Bulma instead.

.button.non-interactive {
    background-color: $my-custom-primary-color !important;
    color: $white !important;
    border: hsl(0, 0%, 86%);
}
```

```Hello World
```

答:
That's because the color properties of is-static overrides is-primary.

I find this behavior normal because a static button with a color doesn't really looks like a static button...

To be sure, I've created the following buttons : on the left it's a button with is-primary, and on the right a button with is-static and non-reactive reproduced with your code adapted with my primary color.

And I didn't see any difference on the design, I just noticed that the pointer events were disabled and the right one, so I checked in the console to verify the changes made by is-static on the right button :

And indeed, is-static is just disabling pointer-events and box-shadow (useless for box-shadow in this case).

So if you want a non-interactive button with a color, I would advice you to use this class :

```<code>.button.non-interactive {
    pointer-events: none;  /* Imitate the behavior of is-static class */
    box-shadow: none;  /* Optional, it might be useful in cases where the button is in a container with a box-shadow */
}
</code>```

And use it in your button with is-primary or any other color class :

```<code><span class="button non-interactive is-primary">Hello World</span>
</code>```

Body:
I want to create a button using Bulma that is non-interactive and a "primary" button.  Here is my attempt:

Hello World

When I do this, I get a standard looking non-interactive button.  It's gray in color and not clickable (this is NOT a disabled button).  The is-primary modifier seems to have no effect on the button and I am unsure why.  If I were to instead remove the is-static modifier, I get a normal looking "primary" button.

I found a hack-ish solution (by doing the following) but would prefer to use the modifiers provided by Bulma instead.

.button.non-interactive {
    background-color: $my-custom-primary-color !important;
    color: $white !important;
    border: hsl(0, 0%, 86%);
}

Hello World

Body:
That's because the color properties of is-static overrides is-primary.

I find this behavior normal because a static button with a color doesn't really looks like a static button...

To be sure, I've created the following buttons : on the left it's a button with is-primary, and on the right a button with is-static and non-reactive reproduced with your code adapted with my primary color.

And I didn't see any difference on the design, I just noticed that the pointer events were disabled and the right one, so I checked in the console to verify the changes made by is-static on the right button :

And indeed, is-static is just disabling pointer-events and box-shadow (useless for box-shadow in this case).

So if you want a non-interactive button with a color, I would advice you to use this class :

.button.non-interactive {
    pointer-events: none;  /* Imitate the behavior of is-static class */
    box-shadow: none;  /* Optional, it might be useful in cases where the button is in a container with a box-shadow */
}

And use it in your button with is-primary or any other color class :

<span class="button non-interactive is-primary">Hello World</span>