问:
Use an explicit return of undefined as type guard and/or filter?
I am trying to combine the array methods filter and map into one function called malter. I have come so far:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  malter<S = any>(mapFn: mapFn<T, S>): S[];
}

function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S = any>(mapFn: mapFn<T, S>): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
};
```

<p>It basically works.
But when using it, it throws a TypeError in line 5-7.
Another test function that did implicitly return undefined did also throw that error.</p>

```Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'."
```

<pre class="lang-ts prettyprint-override"><code>const test = [2, 3, 4, 5, 3];

function test1(): string[] {
   return test.malter<number, string>(num =>
      num > 3
       ? num.toFixed(2)
       : undefined
   );
}
</code>```

A solution that would work type savely, is to provide 2 arguments for malter. A filter and a map function and call them seperately. That would ensure type savety, but also make it less simple.

Sure I could simply do that in line 5-7:

(num > 3 ? num.toFixed(2) : undefined) as string
```

It may be the best compromise?
What do you think? Is there a solution I didn't think of, or do you go with a compromise?

答:
@TitianCernicova-Dragomir's answer is correct, but I'd also like to give a slightly different solution.  The main difference is that instead of using conditional types to turn S (which possibly includes undefined) into to Exclude<S, undefined> (which doesn't), we take S as the return type (which doesn't include undefined) and use the input type as S | undefined.  They will act the same (or nearly so) from the caller's point of view (the compiler will do its own Exclude-like analysis on the input type), but the compiler will likely be able to reason about types inside the implementation of malter better in the latter case:

```<code>type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  // S will not include undefined when inferred from mapFn
  malter<S>(mapFn: mapFn<T, S | undefined>): S[];
}

// hey, look, this works the same way, with T|undefined => T
// instead of T => Exclude<T, undefined>
function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined";
}

Array.prototype.malter = function malter<T, S>(
  this: Array<T>, // inform the compiler that this is an array
  mapFn: mapFn<T, S | undefined>
): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
}; // inference in implementation works

const test = [2, 3, 4, 5, 3];

// don't need any type parameters
function test1(): string[] {
  return test.malter(num => (num > 3 ? num.toFixed(2) : undefined));
}
</code>```

Okay, hope that helps.  Good luck!

Link to code

Body:
I am trying to combine the array methods filter and map into one function called malter. I have come so far:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  malter<S = any>(mapFn: mapFn<T, S>): S[];
}

function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S = any>(mapFn: mapFn<T, S>): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
};

It basically works.
But when using it, it throws a TypeError in line 5-7.
Another test function that did implicitly return undefined did also throw that error.

Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'."

const test = [2, 3, 4, 5, 3];

function test1(): string[] {
   return test.malter<number, string>(num =>
      num > 3
       ? num.toFixed(2)
       : undefined
   );
}

A solution that would work type savely, is to provide 2 arguments for malter. A filter and a map function and call them seperately. That would ensure type savety, but also make it less simple.

Sure I could simply do that in line 5-7:

(num > 3 ? num.toFixed(2) : undefined) as string

It may be the best compromise?
What do you think? Is there a solution I didn't think of, or do you go with a compromise?

Body:
@TitianCernicova-Dragomir's answer is correct, but I'd also like to give a slightly different solution.  The main difference is that instead of using conditional types to turn S (which possibly includes undefined) into to Exclude<S, undefined> (which doesn't), we take S as the return type (which doesn't include undefined) and use the input type as S | undefined.  They will act the same (or nearly so) from the caller's point of view (the compiler will do its own Exclude-like analysis on the input type), but the compiler will likely be able to reason about types inside the implementation of malter better in the latter case:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  // S will not include undefined when inferred from mapFn
  malter<S>(mapFn: mapFn<T, S | undefined>): S[];
}

// hey, look, this works the same way, with T|undefined => T
// instead of T => Exclude<T, undefined>
function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined";
}

Array.prototype.malter = function malter<T, S>(
  this: Array<T>, // inform the compiler that this is an array
  mapFn: mapFn<T, S | undefined>
): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
}; // inference in implementation works

const test = [2, 3, 4, 5, 3];

// don't need any type parameters
function test1(): string[] {
  return test.malter(num => (num > 3 ? num.toFixed(2) : undefined));
}

Okay, hope that helps.  Good luck!

<a href="https://typescript-play.js.org/#code/C4TwDgpgBAtghmAYgOwDwBUA0UDKA+KAXigAoA3OAGwFcIAuKLKAS2QBMIAPB5amAIwgAnbAHshzAOasqAQSFC4IBgCUIcNqOSUQGANoBdPAEoiBHAG4AUFdbBhAMzgBjaPMW70BAN5WoUAHoA3CgAd2ZKSihkUWAWZGcaDihqdggHVgg2MIALCGR4h2EhLKgHIVEYWAQUP2rKeyFUfBJ4JGQGNpQMbBwoAB8UtIzkLJMGHENrAF8bIKg8kGxKUVEAa2xgHOYAZzDxNb2t6B24GGhQpWxwrcZ+1I4R0sICdCt51h37DShRB0YzFAAKKcRLUDg9IaPTJsPBWBypZzAZhaaKxACqwxhGDw5AY6AGUPSMOMDDILD2BN8-hKwGoQgKoEgfyg5IAhIRiAAiB7E0ZsLkzGzuJQAOjAFWAsXAEFF8AawiIZURyNR8sakJadS2uwYIs8eGwH2QDnEVWOUGclTAEUVWzgcR1e12UDgBTgCiUdS6HWq7U1hN5T1hVlJuEMUGpUFp9MZ2x2opKbGorhICISquQJBczgmhmwFEo+OwrA43GifEEIl+Qkk7nxhlMUf8VuQXygECixB95CoJbSnDEtfcxms-n8zH+JBiwEx0P5JE7xibdXHrucznF1B2OUXlFHq6gszXMYZ6+cY6P2EbMwsgWCrCKJQS0FYLBgYEoEHOyGADpRBShAcOw2K27b2O2xB6AATNgADM2AACzYAArPBBjWO8wSaMgADkcSjKUbogFATLQGAHpnBAjQgemSIAaREBfAAjCQYZfBIyCSBGUanoyTHAHKVCNNOfCAqJVQEHBUAAPwVjAopSogzCcFkJDQaYDBBiSB6zEAA" rel="nofollow noreferrer">Link to code


来源: stackexchange

问:
javascript: Trying to flatten array only one level
I am trying to write a function to flatten an array. I have part of the function working and I need help in the other half.

```<code>flatten: function(anyArray, singleLevel) {
  if (singleLevel == true) {
      flatArray = Array.prototype.concat.apply([], anyArray);
      return flatArray;
  }
  flatArray = Array.prototype.concat.apply([], anyArray);
  if (flatArray.length != anyArray.length) {
      flatArray = someObject.array.flatten(flatArray);
  }
  return flatArray;
}
</code>```

if I type

```<code>.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);
</code>```

I want it to flatten only one level:

```<code>[[1],[1,2,3,[4,5],4],[2,3]]
</code>```

答:
Modern JavaScript allows us to handle this very easily using a variety of techniques

Using Array.prototype.flat -

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  arr.flat(1) // 1 is default depth

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]```
</div>
</div>
</p>

<p>Using <code>Array.prototype.flatMap</code> -</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>const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  arr.flatMap(x => x)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]</code>```

Using a spread argument to Array.prototype.concat

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  [].concat(...arr)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]```
</div>
</div>
</p>

<hr>

<p>Older version of JavaScript (ECMAScript 5 and below) can use techniques like <code>Function.prototype.apply</code> -</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>var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  Array.prototype.concat.apply([], arr)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]</code>```

Using Array.prototype.reduce -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  arr.reduce((r, a) => r.concat(a), [])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]```
</div>
</div>
</p>

<p>Using a primitive <code>for</code> loop -</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>var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  []

for (var i = 0; i < arr.length; i = i + 1)
  flatArr = flatArr.concat(arr[i])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a function to flatten an array. I have part of the function working and I need help in the other half.

flatten: function(anyArray, singleLevel) {
  if (singleLevel == true) {
      flatArray = Array.prototype.concat.apply([], anyArray);
      return flatArray;
  }
  flatArray = Array.prototype.concat.apply([], anyArray);
  if (flatArray.length != anyArray.length) {
      flatArray = someObject.array.flatten(flatArray);
  }
  return flatArray;
}

if I type

.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);

I want it to flatten only one level:

[[1],[1,2,3,[4,5],4],[2,3]]

Body:
Modern JavaScript allows us to handle this very easily using a variety of techniques

Using Array.prototype.flat -

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  arr.flat(1) // 1 is default depth

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Using Array.prototype.flatMap -

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  arr.flatMap(x => x)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Using a spread argument to Array.prototype.concat

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

const flatArr =
  [].concat(...arr)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Older version of JavaScript (ECMAScript 5 and below) can use techniques like Function.prototype.apply -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  Array.prototype.concat.apply([], arr)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Using Array.prototype.reduce -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  arr.reduce((r, a) => r.concat(a), [])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Using a primitive for loop -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  []

for (var i = 0; i < arr.length; i = i + 1)
  flatArr = flatArr.concat(arr[i])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

ContentLicense: CC BY-SA 4.0


问:
Add "New Folder" button to datasource picker in Sitecore
I'd like to enable content editors to better structure their local datasources in the Sitecore Editor when using the experience editor to select datasources for renderings.

I'd like them to be able to create a new folder underneath which ever item they have selected in the tree that is show in the dialogue.

This might work by right click and pressing "add new folder", or a new button in the left hand pane which says "Add folder under selected item".

Could anyone point me in the right direction to how I might achieve this? Image attached for better context.

答: When configuring a module, there is a Datasource Location field in the Editor Options section allowing to specify one or more content locations from where content editors can select content for the rendering. More locations can be specified using a piped query: syntax, for example


问:
named parameter to npm run script
I would like to pass a named parameter to an npm run script so I can do something like the following:

```<code>"scripts":{
    "say-hello":"echo $greeting && ls"
 }

 npm run hello --greeting=hello
</code>```

I'd like it to then put 'hello' in place of the $greeting variable, echo the command and then do the ls (this is obviously just a simple example of a chained command)

答:
Another way is to simply add the following '--' followed by your desired param(s). This would be for named parameters that '=' a value. Please note the underlying process in this example, a protractor call, expects a Url arg. </p>

```<code>npm run e2e -- --Url="https://yoururlhere.com"
</code>```

Title: named parameter to npm run script

Body:
I would like to pass a named parameter to an npm run script so I can do something like the following:

"scripts":{
    "say-hello":"echo $greeting && ls"
 }

 npm run hello --greeting=hello

I'd like it to then put 'hello' in place of the $greeting variable, echo the command and then do the ls (this is obviously just a simple example of a chained command)

Body:
Another way is to simply add the following '--' followed by your desired param(s). This would be for named parameters that '=' a value. Please note the underlying process in this example, a protractor call, expects a Url arg.

npm run e2e -- --Url="https://yoururlhere.com"


问:
split xml value with xpath and check string position
I have the following xml file:

```<code> <courses>
   <course>
    <name>Course 1</name>
    <code>00162</code>
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>
</code>```

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

```<code>Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next
</code>```

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

答:
In XSLT 1.0, you would use a recursive template to split the string.

Borrowing from @Tomalak's answer to a similar question, is an example:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    <!--Call the recursive template to split the string-->
        <xsl:call-template name="split">
            <xsl:with-param name="list" select="/courses/course/questions" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="split">
        <xsl:param name="list"      select="''" />
        <xsl:param name="separator" select="','" />
        <xsl:if test="not($list = '' or $separator = '')">
            <xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)" />
            <xsl:variable name="tail" select="substring-after($list, $separator)" />

            <!--Use the parsed value to do something-->
            <xsl:call-template name="handleQuestion">
                <xsl:with-param name="value" select="$head"/>
            </xsl:call-template>

            <xsl:call-template name="split">
                <xsl:with-param name="list"      select="$tail" />
                <xsl:with-param name="separator" select="$separator" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

    <xsl:template name="handleQuestion">
        <xsl:param name="value" />
        <xsl:choose>
            <xsl:when test="$value=2">
                <!--Do something-->
            </xsl:when>
            <xsl:otherwise>
                <!--Do something else-->
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>
</code>```

In XSLT 2.0, you can use the tokenize() function:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="/">
        <xsl:for-each select="tokenize(/courses/course/questions,',')">
            <xsl:choose>
                <xsl:when test="number(.)=2">
                    <!--Do something-->
                </xsl:when>
                <xsl:otherwise>
                    <!--Do something else-->
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have the following xml file:

 <courses>
   <course>
    <name>Course 1</name>
    00162
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

Body:
In XSLT 1.0, you would use a recursive template to split the string.

Borrowing from @Tomalak's answer to a similar question, is an example:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    <!--Call the recursive template to split the string-->
        <xsl:call-template name="split">
            <xsl:with-param name="list" select="/courses/course/questions" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="split">
        <xsl:param name="list"      select="''" />
        <xsl:param name="separator" select="','" />
        <xsl:if test="not($list = '' or $separator = '')">
            <xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)" />
            <xsl:variable name="tail" select="substring-after($list, $separator)" />

            <!--Use the parsed value to do something-->
            <xsl:call-template name="handleQuestion">
                <xsl:with-param name="value" select="$head"/>
            </xsl:call-template>

            <xsl:call-template name="split">
                <xsl:with-param name="list"      select="$tail" />
                <xsl:with-param name="separator" select="$separator" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

    <xsl:template name="handleQuestion">
        <xsl:param name="value" />
        <xsl:choose>
            <xsl:when test="$value=2">
                <!--Do something-->
            </xsl:when>
            <xsl:otherwise>
                <!--Do something else-->
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

In XSLT 2.0, you can use the tokenize() function:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="/">
        <xsl:for-each select="tokenize(/courses/course/questions,',')">
            <xsl:choose>
                <xsl:when test="number(.)=2">
                    <!--Do something-->
                </xsl:when>
                <xsl:otherwise>
                    <!--Do something else-->
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


问:
Retrieving Classes of Beans prior/during instantiation phase
In an Spring Application it is possible to retrieve all (?) Beans with applicationContext.getBeansOfType(Object.class). This is of course only possible, after all Beans have been created.

So, if I call this method in the constructor of a Bean, I have to be lucky, to be the last Bean to be created, to have access to all of them.

As far as I understand the life cycle of Spring Beans, there is a phase in which BeanDefinitions are created, before the Beans are initialized.

How is it possible to retrive all created BeanDefinitions in the constructor of a Bean?

Can I also retrive the types (as Class) of those BeanDefinitions? The type BeanDefinition seems to only provide the "current bean class name of this bean definition".

Or is the only way to get those types after all Beans have been constructed (e.g. @PostConstruct)?

答:
You can create a last bean by putting it for example in an @Configuration class with a minimum initialization order, so that it is the last one with
@Order(Ordered.LOWEST_PRECEDENCE), that would be it:

```<code>@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class Last {

    @Autowired
    ApplicationContext applicationContext;

    @Bean
    public String lastBean() {

        applicationContext.getBeanDefinitionNames();    //retrive all created BeanDefinitions in the constructor of a Bean

        applicationContext.getBeansOfType(Object.class); //retrive the types (as Class)

        return "lastBean";
    }

}
</code>```

Body:
You can create a last bean by putting it for example in an @Configuration class with a minimum initialization order, so that it is the last one with
@Order(Ordered.LOWEST_PRECEDENCE), that would be it:

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class Last {

    @Autowired
    ApplicationContext applicationContext;

    @Bean
    public String lastBean() {

        applicationContext.getBeanDefinitionNames();    //retrive all created BeanDefinitions in the constructor of a Bean

        applicationContext.getBeansOfType(Object.class); //retrive the types (as Class)

        return "lastBean";
    }

}


问:
Convert single line RSA private ssh key to multi line
I have these private keys that have been converted to single line equivalent.

These keys are quite a lot.

So I decided to invest some time to write a script to convert.

This has not yielded to much.

```<code>-----BEGIN RSA PRIVATE KEY----pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= -----END RSA PRIVATE KEY-----
</code>```

I am using echo ~/.ssh/id_rsa | tr " " "\n"

This returns:

```<code>-----BEGIN
RSA
PRIVATE
KEY-----
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
-----END
RSA
PRIVATE
KEY-----

</code>```

I have been trying to figure out the best possible way to get this back to the right format.

答:
@robby Thanks from your answer I adapted the following which worked for me.</p>

```<code>sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/" -e "s/\S\{64\}/&\n/g" | sed "s/^\s//g" ~/.ssh/id_rsa
</code>```

Body:
I have these private keys that have been converted to single line equivalent.

These keys are quite a lot.

So I decided to invest some time to write a script to convert.

This has not yielded to much.

-----BEGIN RSA PRIVATE KEY----pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= -----END RSA PRIVATE KEY-----

I am using echo ~/.ssh/id_rsa | tr " " "\n"

This returns:

-----BEGIN
RSA
PRIVATE
KEY-----
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
-----END
RSA
PRIVATE
KEY-----

I have been trying to figure out the best possible way to get this back to the right format.

Body:
@robby Thanks from your answer I adapted the following which worked for me.

sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/" -e "s/\S\{64\}/&\n/g" | sed "s/^\s//g" ~/.ssh/id_rsa


问:
How to initialize Object of a class with primitive types
I have seen various threads and most of them talk about default values like primitive are initialized with 0 and Wrappers are initialized with null.
My question is specific and with example rather than just concept.

My class:

```<code>public class Subject {
    int subCode;
    int marks;
    long CGPA;

    public Subject(int subCode, int marks, long CGPA) {
        this.subCode = subCode;
        this.marks = marks;
        this.CGPA = CGPA;
    }

}
</code>```

Now here goes my Map in Main class:

```<code>Map<Integer,List<Subject>> map1 = new HashMap<>();
        map1.put(Integer.valueOf(1),new Subject(001,70,29l));
</code>```

I am getting error in 29l, i tried various forms like Long.Valueof(29), but they dont work.

Can anyone tell me the concept of when there is primitive types in filed of a class then how to make instance of class using constructor.

Note: I am fully aware that i should use Wrapper class here, but now i wanna try with primitive, it is just for my learning.

Thank you.

答:
Here:

```<code>Map<Integer,List<Subject>> map1 = new HashMap<>();
</code>```

You declare that the value of the map are: lists.

Then you try to add a single instance of the subject class!

```<code>    map1.put(Integer.valueOf(1),new Subject(001,70,29l));
</code>```

Cant work!

```<code>    map1.put(1, Collections.singletonList(new Subject(001,70,29l)));
    map1.put(1, Arrays.asList(new Subject(001,70,29l)));
    map1.put(1, new ArrayList<>(Arrays.asList(new Subject(001,70,29l))));
</code>```

should all work. (note: I didnt run the above through a compiler, so ignore stupid typos and such. And: the first two examples will give you lines that will not allow you to add/remove items from those lists)

And your wording implies a misconception on your side: a List isn't a "wrapper". It is a container. A box in which you put things. And when you say: my map shall hold egg-boxes, then that map wants egg-boxes, and not individual eggs!

Body:
I have seen various threads and most of them talk about default values like primitive are initialized with 0 and Wrappers are initialized with null.
My question is specific and with example rather than just concept.

My class:

public class Subject {
    int subCode;
    int marks;
    long CGPA;

    public Subject(int subCode, int marks, long CGPA) {
        this.subCode = subCode;
        this.marks = marks;
        this.CGPA = CGPA;
    }

}

Now here goes my Map in Main class:

Map<Integer,List<Subject>> map1 = new HashMap<>();
        map1.put(Integer.valueOf(1),new Subject(001,70,29l));

I am getting error in 29l, i tried various forms like Long.Valueof(29), but they dont work.

Can anyone tell me the concept of when there is primitive types in filed of a class then how to make instance of class using constructor.

Note: I am fully aware that i should use Wrapper class here, but now i wanna try with primitive, it is just for my learning.

Thank you.

Body:
Here:

Map<Integer,List<Subject>> map1 = new HashMap<>();

You declare that the value of the map are: lists.

Then you try to add a single instance of the subject class!

    map1.put(Integer.valueOf(1),new Subject(001,70,29l));

Cant work!

    map1.put(1, Collections.singletonList(new Subject(001,70,29l)));
    map1.put(1, Arrays.asList(new Subject(001,70,29l)));
    map1.put(1, new ArrayList<>(Arrays.asList(new Subject(001,70,29l))));

should all work. (note: I didnt run the above through a compiler, so ignore stupid typos and such. And: the first two examples will give you lines that will not allow you to add/remove items from those lists)

And your wording implies a misconception on your side: a List isn't a "wrapper". It is a container. A box in which you put things. And when you say: my map shall hold egg-boxes, then that map wants egg-boxes, and not individual eggs!


问:
Error while unit test - TypeError: Cannot read property 'cityWeather' of undefined
In Component.ts,

```<code>this.dataService.currentCity.subscribe(info => {
  this.cities = info;
});

this.dataService.currentSelectedCity.subscribe(index => {
  this.selectedCityIndex = index;
});

this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
</code>```

I am trying to test this piece of code in ngOnInit(). But I am unsure how to test this code. Here, my other component is sending me an array of objects and also the index of the selected item using Behavior subject to which I am subscribing in this component's `ngOnInit(). And trying to access cityWeather property in the selected object.

In Spec.ts I am tried something like this which I am sure is not a correct way of testing this.

```<code>it("should handle ngOnInit", async(() => {
        let response;
        const dataService = fixture.debugElement.injector.get(DataService);
        spyOn(dataService, 'currentCity').and.returnValue(of(response));
        component.ngOnInit();
        expect(component.cities).toEqual(response);
    }));
</code>```

When I run the application, I am getting the output but when I test ngoninit function then I am not getting the response from subscribe. I am getting the below error. Failed: Cannot read property 'cityWeather' of undefined TypeError: Cannot read property 'cityWeather' of undefined

In data.service.ts

```<code>private citySubject = new BehaviorSubject<any>('');
currentCity = this.citySubject.asObservable();
private selectedCity = new BehaviorSubject<any>('');
currentSelectedCity= this.selectedCitySubject.asObservable();

sendCityWeatherInfo(info,index) {
  this.citySubject.next(info);
  this.selectedCitySubject.next(index);
}
</code>```

I am calling this in a component like this (passing an array of objects and index)

```<code>this.dataService.sendCityWeatherInfo(this.cities, index);
</code>```

答:
The error isn't in your test, it's in this line:

```<code>this.selectedCityInfo = this.cities[this.selectedCityIndex];
</code>```

this.cities and this.selectedCityIndex haven't been defined yet - you subscribed to dataService which will update them, but the service didn't run. Also, when the service does run, this.selectedCityInfo won't be updated.

Instead, update these values whenever you receive new data. A simple solution is:

```<code>  this.dataService.currentCity.subscribe(info => {
    this.cities = info;
    this.updateSelectedCity();
  });

  this.dataService.currentSelectedCity.subscribe(index => {
    this.selectedCityIndex = index;
    this.updateSelectedCity();
  });
}

...

updateSelectedCity() {
  this.selectedCityInfo = this.cities[this.selectedCityIndex];
  this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
}
</code>```

For testing, this.selectedCityInfo and this.selectedCityWeatherList aren't being tested. I'm not familiar with the testing library but you probably want something like expect(component.selectedCityInfo).toEqual(...), ditto with this.selectedCityWeatherList.

Body:
In Component.ts,

this.dataService.currentCity.subscribe(info => {
  this.cities = info;
});

this.dataService.currentSelectedCity.subscribe(index => {
  this.selectedCityIndex = index;
});

this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;

I am trying to test this piece of code in ngOnInit(). But I am unsure how to test this code. Here, my other component is sending me an array of objects and also the index of the selected item using Behavior subject to which I am subscribing in this component's `ngOnInit(). And trying to access cityWeather property in the selected object.

In Spec.ts I am tried something like this which I am sure is not a correct way of testing this.

it("should handle ngOnInit", async(() => {
        let response;
        const dataService = fixture.debugElement.injector.get(DataService);
        spyOn(dataService, 'currentCity').and.returnValue(of(response));
        component.ngOnInit();
        expect(component.cities).toEqual(response);
    }));

When I run the application, I am getting the output but when I test ngoninit function then I am not getting the response from subscribe. I am getting the below error. Failed: Cannot read property 'cityWeather' of undefined TypeError: Cannot read property 'cityWeather' of undefined

In data.service.ts

private citySubject = new BehaviorSubject<any>('');
currentCity = this.citySubject.asObservable();
private selectedCity = new BehaviorSubject<any>('');
currentSelectedCity= this.selectedCitySubject.asObservable();

sendCityWeatherInfo(info,index) {
  this.citySubject.next(info);
  this.selectedCitySubject.next(index);
}

I am calling this in a component like this (passing an array of objects and index)

this.dataService.sendCityWeatherInfo(this.cities, index);

Body:
The error isn't in your test, it's in this line:

this.selectedCityInfo = this.cities[this.selectedCityIndex];

this.cities and this.selectedCityIndex haven't been defined yet - you subscribed to dataService which will update them, but the service didn't run. Also, when the service does run, this.selectedCityInfo won't be updated.

Instead, update these values whenever you receive new data. A simple solution is:

  this.dataService.currentCity.subscribe(info => {
    this.cities = info;
    this.updateSelectedCity();
  });

  this.dataService.currentSelectedCity.subscribe(index => {
    this.selectedCityIndex = index;
    this.updateSelectedCity();
  });
}

...

updateSelectedCity() {
  this.selectedCityInfo = this.cities[this.selectedCityIndex];
  this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
}

For testing, this.selectedCityInfo and this.selectedCityWeatherList aren't being tested. I'm not familiar with the testing library but you probably want something like expect(component.selectedCityInfo).toEqual(...), ditto with this.selectedCityWeatherList.


问:
How to make Vue auto-instantiate components on init?
I'm new to Vue, I'm doing some tests.

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <select v-for="select in selects">
        <option>test</option>
      </select>
    </div>
  `,
  props:['selects']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[{name:'select-1'},{name:'select-2'}]
  }
  ,mounted: function(){
  }
  ,created: function(){
  }
  ,methods: {

  }
});
</code>```

...And later in html:

```<code><area-selectors-box></area-selectors-box>
</code>```

But it will only output

, not the selects.

Why? What am I doing wrong?

答: I'm glad :) If you ever encounter rendering issues, speaking from experience with JS frameworks, often its the data not being able to be found or loaded. Good luck! </p>

Body:
I'm new to Vue, I'm doing some tests.

Vue.component('area-selectors-box', {
  template: `

      <select v-for="select in selects">
        <option>test</option>
      </select>

  `,
  props:['selects']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[{name:'select-1'},{name:'select-2'}]
  }
  ,mounted: function(){
  }
  ,created: function(){
  }
  ,methods: {

  }
});

...And later in html:

<area-selectors-box></area-selectors-box>

But it will only output

, not the selects.

Why? What am I doing wrong?


问:
Android On Touch
I have been trying to make a program draw circles as I touch the screen with no luck, can anyone please tell me how I can do this? or GOOD tutorial that shows me how... I keep getting errors in my code

```<code>import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Math;

public class GameView extends View{

        private final float x;
        private final float y;
        private final int r;
        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public GameView(Context context, float x, float y, int r) {
            super(context);
            setFocusable(true);
            mPaint.setColor(0xFFFF0000);
            this.x = x;
            this.y = y;
            this.r = r;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(x, y, r, mPaint);
        }

}
</code>```

GameActivity.java

```<code>import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

public class GameActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

        main.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(final View v, MotionEvent e) {

                 final float x = e.getX();
                 final float y = e.getY();
                  final Handler handler = new Handler()
                  {
                    public void handleMessage(Message msg) {

                      }
                    };
                    Thread graphicThread = new Thread()
                    {
                        public void run() {

                            try {

                                //Do the drop
                                   FrameLayout flView = (FrameLayout) v;
                                 GameView gm = new GameView(getParent(), x,y,25);
                                  flView.addView(gm);

                                     Thread.sleep(1000);

                                     handler.sendMessage(handler.obtainMessage());
                                }
                             catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                        };
                         boolean isRunning=true;
                        graphicThread.start();
                        return true;

                        }

        });

      }
    }
</code>```

答:
You shouldn't be using getParent() in your activity if it's not a child Activity.

Use this instead:

GameView gm = new GameView(this, x, y, 25);

Title: Android On Touch

Body:
I have been trying to make a program draw circles as I touch the screen with no luck, can anyone please tell me how I can do this? or GOOD tutorial that shows me how... I keep getting errors in my code

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Math;

public class GameView extends View{

        private final float x;
        private final float y;
        private final int r;
        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public GameView(Context context, float x, float y, int r) {
            super(context);
            setFocusable(true);
            mPaint.setColor(0xFFFF0000);
            this.x = x;
            this.y = y;
            this.r = r;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(x, y, r, mPaint);
        }

}

GameActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

public class GameActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

        main.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(final View v, MotionEvent e) {

                 final float x = e.getX();
                 final float y = e.getY();
                  final Handler handler = new Handler()
                  {
                    public void handleMessage(Message msg) {

                      }
                    };
                    Thread graphicThread = new Thread()
                    {
                        public void run() {

                            try {

                                //Do the drop
                                   FrameLayout flView = (FrameLayout) v;
                                 GameView gm = new GameView(getParent(), x,y,25);
                                  flView.addView(gm);

                                     Thread.sleep(1000);

                                     handler.sendMessage(handler.obtainMessage());
                                }
                             catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                        };
                         boolean isRunning=true;
                        graphicThread.start();
                        return true;

                        }

        });

      }
    }


问:
why scrollview with views is not able to scroll to till last?
I am adding UIScrollView in storyboard with all sides(trailing,leading,top,bottom) constraints. I have added a contentView inside a UIScrollView added constraints all sides(trailing,leading,top,bottom) and Equal width and Heights to SuperView(not scrollView) and changed height constraint priority to 250.

I have kept 3 views insdie content view for all views I have mentioned height and 3 sides(except bottom) but for last view I have kept all four sides and height.

But why i am not able to scroll till last view bottom.

]2

答:
Hey @santhosh I think you set a Equal height with SuperView is wrong
 1. Remove ComentView Height constrains

 2. set  all(Three view) height and all constrains  trailing,leading,top,bottom
  Automatically remove(scrollview) constrains error.


问:
concatenate several lines in one with a delimiter with pandas
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

```<code>val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1
</code>```

It works with loops.
i need this result,

```<code>val
Cat Tiger Ball
Bat bill
dog
</code>```

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

答:
You can also create an array like so :

```<code>a = np.array(range(len(df)))
</code>```

Then you create a third column which equals to your id minus the previous array. This third column will show you which val are together.

```<code>df['regroup'] = df['id'].subtract(a)
</code>```

Out:

```<code>id  val regroup
0   1   Cat 1
1   2   Tiger   1
2   3   Ball    1
3   1   Bat -2
</code>```

You can now use a group by to have your desired output :

```<code>In [1] : df.groupby(['regroup'])['val'].apply(' '.join)
Out[1] : regroup
-2               Bat
 1    Cat Tiger Ball
</code>```

Body:
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1

It works with loops.
i need this result,

val
Cat Tiger Ball
Bat bill
dog

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

Body:
You can also create an array like so :

a = np.array(range(len(df)))

Then you create a third column which equals to your id minus the previous array. This third column will show you which val are together.

df['regroup'] = df['id'].subtract(a)

Out:

id  val regroup
0   1   Cat 1
1   2   Tiger   1
2   3   Ball    1
3   1   Bat -2

You can now use a group by to have your desired output :

In [1] : df.groupby(['regroup'])['val'].apply(' '.join)
Out[1] : regroup
-2               Bat
 1    Cat Tiger Ball


问:
Saving List of Numpy 2D arrays using numpy.save (the arrays together are jagged)
I have a large image dataset.  When I use the images, I have several components--a mirrored image, a regular image, an eigenvector matrix and an eigenvalue vector.

I would like to store it like:

```<code>training_sunsets_data = [cropped_training_sunsets,
                         mirrored_training_sunsets,
                         rgb_cov_eigvec_training_sunsets,
                         rgb_cov_eigval_training_sunsets]

np.save('training_sunsets_data',training_sunsets_data)
</code>```

And as I was writing this I was testing it (because I was sure it would fail), and the strangest thing happened when I did this: it worked.

Further, when I loaded it back up into the code, it was type ndarray, but it is a jagged array.

How is this possible if numpy does not allow jagged multidimensional arrays?  Did I just find a backdoor way to create a jagged array in numpy?

答: np.savez() would work in your situation. save each as a variable.</p>

Body:
I have a large image dataset.  When I use the images, I have several components--a mirrored image, a regular image, an eigenvector matrix and an eigenvalue vector.

I would like to store it like:

training_sunsets_data = [cropped_training_sunsets,
                         mirrored_training_sunsets,
                         rgb_cov_eigvec_training_sunsets,
                         rgb_cov_eigval_training_sunsets]

np.save('training_sunsets_data',training_sunsets_data)

And as I was writing this I was testing it (because I was sure it would fail), and the strangest thing happened when I did this: it worked.

Further, when I loaded it back up into the code, it was type ndarray, but it is a jagged array.

How is this possible if numpy does not allow jagged multidimensional arrays?  Did I just find a backdoor way to create a jagged array in numpy?


问:
How to fix "- _tkinter.TclError: no events specified in binding"
I found the source code somewhere on the internet
a simple program to create a window with the option
entering mathematical operations and displaying from the keyboard
the result.This is code:

```<code>import tkinter as tk
from math import *

def evaluate(event):
    res.configure(text="Result: " + str(eval(entry.get())))

w = tk.Tk()
tk.Label(w, text="Your Expression:").pack()
entry = tk.Entry(w)
entry.bind("event", evaluate)
entry.pack()
res = tk.Label(w)
res.pack()
w.mainloop()
</code>```

I'm getting an error:

C:\Users\rob\PycharmProjects\untitled2\venv\Scripts\python.exe
  "C:/Users/rob/Desktop/new test.py" Traceback (most recent call last):
  File "C:/Users/rob/Desktop/new test.py", line 12, in
      entry.bind("", evaluate)   File "C:\Users\rob\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py",
  line 1248, in bind
      return self._bind(('bind', self._w), sequence, func, add)   File "C:\Users\rob\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py",
  line 1203, in _bind
      self.tk.call(what + (sequence, cmd))
  _tkinter.TclError: no events specified in binding

Please help. Im starting learning Python and I don't know a solution.

答:
it's clear in your reported error,

"...no events specified in binding"

change this

    entry.bind('<event>', evaluate)
```

<p>with this</p>

<pre class="lang-py prettyprint-override"><code>    entry.bind("<Return>",evaluate)
</code>```

Body:
I found the source code somewhere on the internet
a simple program to create a window with the option
entering mathematical operations and displaying from the keyboard
the result.This is code:

import tkinter as tk
from math import *

def evaluate(event):
    res.configure(text="Result: " + str(eval(entry.get())))

w = tk.Tk()
tk.Label(w, text="Your Expression:").pack()
entry = tk.Entry(w)
entry.bind("event", evaluate)
entry.pack()
res = tk.Label(w)
res.pack()
w.mainloop()

I'm getting an error:

C:\Users\rob\PycharmProjects\untitled2\venv\Scripts\python.exe
  "C:/Users/rob/Desktop/new test.py" Traceback (most recent call last):
  File "C:/Users/rob/Desktop/new test.py", line 12, in
      entry.bind("", evaluate)   File "C:\Users\rob\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py",
  line 1248, in bind
      return self._bind(('bind', self._w), sequence, func, add)   File "C:\Users\rob\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py",
  line 1203, in _bind
      self.tk.call(what + (sequence, cmd))
  _tkinter.TclError: no events specified in binding

Please help. Im starting learning Python and I don't know a solution.

Body:
it's clear in your reported error,

"...no events specified in binding"

change this

    entry.bind('<event>', evaluate)

with this

    entry.bind("<Return>",evaluate)


问:
Run-time error 5981, Application-defined or object defined error
I'm trying to create scripts in Excel and Word that create Word documents from rows in Excel. I'm basing the Word Documents from a 'dotm' template. Everything was working fine (and still does) with the 'dotx' file format, but as soon as I use the Macro-Enabled, I get the 5981 run-time error application-defined or object-defined error.

I've done research online and tried all fixes from enabling Macros, Trusted Locations and Trusted Documents in Word. I've tried DoEvent before trying to access. I need to access the 'dotm' file as there are Macros in Word I need to run on opening to format the document.

Can someone PLEASE help me? I'm not experienced in VBA and I'm reaching the end of my thread with this.

```<code>    Set objword = GetObject(, "Word.Application")

        If objword Is Nothing Then
            Set objword = CreateObject("Word.Application")
        End If

    On Error GoTo 0

    Set objDoc = objword.Documents.Add("C:\Users\OMITTED FOR PRIVACY\Test Report.dotm")
</code>```

Results ...
Expected: Word Documents created and formatted
Actual: Run-time error '5981': Application-defined or object-defined error

Updated
Code from the Test Report.dotm file:

```<code>Sub conditionalFormat()

    Dim oCell As Word.Cell
    Dim oColumn As Word.Column

    'First set of tables
    For intI = 2 To 5
        Set oColumn = ActiveDocument.Tables(intI).Range.Columns(3)

        For Each oCell In oColumn.Cells

            If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then

                If Val(oCell.Range.Text) < 55 Then
                    oCell.Shading.ForegroundPatternColor = wdColorRed
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 55 And Val(oCell.Range.Text) < 75 Then
                    oCell.Shading.ForegroundPatternColor = wdColorLightOrange
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 75 Then
                    oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                End If
            End If

        Next
    Next intI

    'Analysis set of tables
    For intI = 8 To 28 Step 3
        Set oColumn = ActiveDocument.Tables(intI).Range.Columns(4)

        For Each oCell In oColumn.Cells

            If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then

                If Val(oCell.Range.Text) < 33.3 Then
                    oCell.Shading.ForegroundPatternColor = wdColorRed
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 33.3 And Val(oCell.Range.Text) < 66.6 Then
                    oCell.Shading.ForegroundPatternColor = wdColorLightOrange
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 66.6 Then
                    oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                End If
            End If

        Next
    Next intI

End Sub
</code>```

答:
Change ActiveDocument into ThisDocument.

ActiveDocument is the document that has the focus (which can be any document a user clicks on).

ThisDocument is the document this code is running in.

Body:
I'm trying to create scripts in Excel and Word that create Word documents from rows in Excel. I'm basing the Word Documents from a 'dotm' template. Everything was working fine (and still does) with the 'dotx' file format, but as soon as I use the Macro-Enabled, I get the 5981 run-time error application-defined or object-defined error.

I've done research online and tried all fixes from enabling Macros, Trusted Locations and Trusted Documents in Word. I've tried DoEvent before trying to access. I need to access the 'dotm' file as there are Macros in Word I need to run on opening to format the document.

Can someone PLEASE help me? I'm not experienced in VBA and I'm reaching the end of my thread with this.

    Set objword = GetObject(, "Word.Application")

        If objword Is Nothing Then
            Set objword = CreateObject("Word.Application")
        End If

    On Error GoTo 0

    Set objDoc = objword.Documents.Add("C:\Users\OMITTED FOR PRIVACY\Test Report.dotm")

Results ...
Expected: Word Documents created and formatted
Actual: Run-time error '5981': Application-defined or object-defined error

Updated
Code from the Test Report.dotm file:

Sub conditionalFormat()

    Dim oCell As Word.Cell
    Dim oColumn As Word.Column

    'First set of tables
    For intI = 2 To 5
        Set oColumn = ActiveDocument.Tables(intI).Range.Columns(3)

        For Each oCell In oColumn.Cells

            If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then

                If Val(oCell.Range.Text) < 55 Then
                    oCell.Shading.ForegroundPatternColor = wdColorRed
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 55 And Val(oCell.Range.Text) < 75 Then
                    oCell.Shading.ForegroundPatternColor = wdColorLightOrange
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 75 Then
                    oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                End If
            End If

        Next
    Next intI

    'Analysis set of tables
    For intI = 8 To 28 Step 3
        Set oColumn = ActiveDocument.Tables(intI).Range.Columns(4)

        For Each oCell In oColumn.Cells

            If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then

                If Val(oCell.Range.Text) < 33.3 Then
                    oCell.Shading.ForegroundPatternColor = wdColorRed
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 33.3 And Val(oCell.Range.Text) < 66.6 Then
                    oCell.Shading.ForegroundPatternColor = wdColorLightOrange
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                ElseIf Val(oCell.Range.Text) > 66.6 Then
                    oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
                    oCell.Range.Font.TextColor = wdColorWhite
                    oCell.Range.Font.Bold = True
                    oCell.Range.InsertAfter Text:="%"
                End If
            End If

        Next
    Next intI

End Sub


问:
multiple variable in python regex
I have seen several related posts and several forums to find an answer for my question, but nothing has come up to what I need.

I am trying to use variable instead of hard-coded values in regex which search for either word in a line.

However i am able to get desired result if i don't use variable.

```<code><http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub2/a2#dell>
<http://www.somesite.com/software/sub3/a3#Notepad>

re.search(r"\#Msoffice|#vlc|#Notepad", line)
</code>```

This regex will return the line which has #Msoffice OR #vlc OR #Notepad.

I tried defining a single variable using re.escape and that worked absolutely fine. However i have tried many combination using | and , (pipe and comma) but no success.

Is there any way i can specify #Msoffice , #vlc and #Notepad in different variables and so later i can change those ?

Thanks in advance!!

答:
If I did understand you the right way you'd like to insert variables in your regex.

You are actually using a raw string using r' ' to make the regex more readable, but if you're using f' ' it allows you to insert any variables using {your_var} then construct your regex as you like:

```<code>var1 = '#Msoffice'
var2 = '#vlc'
var3 = '#Notepad'

re.search(f'{var1}|{var2}|{var3}', line)
</code>```

The most annoying issue is that you will have to add \ to escaped char, to look for \ it will be \\

Hope it helped

Title: multiple variable in python regex

Body:
I have seen several related posts and several forums to find an answer for my question, but nothing has come up to what I need.

I am trying to use variable instead of hard-coded values in regex which search for either word in a line.

However i am able to get desired result if i don't use variable.

<http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub2/a2#dell>
<http://www.somesite.com/software/sub3/a3#Notepad>

re.search(r"\#Msoffice|#vlc|#Notepad", line)

This regex will return the line which has #Msoffice OR #vlc OR #Notepad.

I tried defining a single variable using re.escape and that worked absolutely fine. However i have tried many combination using | and , (pipe and comma) but no success.

Is there any way i can specify #Msoffice , #vlc and #Notepad in different variables and so later i can change those ?

Thanks in advance!!

Body:
If I did understand you the right way you'd like to insert variables in your regex.

You are actually using a raw string using r' ' to make the regex more readable, but if you're using f' ' it allows you to insert any variables using {your_var} then construct your regex as you like:

var1 = '#Msoffice'
var2 = '#vlc'
var3 = '#Notepad'

re.search(f'{var1}|{var2}|{var3}', line)

The most annoying issue is that you will have to add \ to escaped char, to look for \ it will be \\

Hope it helped


问:
JS Drag and Drop: Make a div with specific classname not droppable
Im having some trouble implementing drag and drop to my project. Im making a Kanban tool like trello. I have divs that are "lists" and those lists have other divs inside that are "cards". When functioning ideally I would be able to put cards inside different lists, but not a list inside a list. However with my code right now I'm able to drag a list inside a list.

I would like to know how to find the html class of what I'm dragging, so that I can use that to validate.

So what I want to happen is that I can be able to drag a list, but not drop it inside another. I should however be able to rearrange the lists with cards inside, and move cards to different lists.

Thanks!

This is the Javascript:

```<code>function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list")  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function allowDrop1(ev) {
    ev.preventDefault();
}

function drag1(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" ) {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}
´´´´
And this is a list from the html:
```

 test

 test 2

```

答:
I fixed it! Also added functionality to drag a list inside the list-wrapper of a another list and make them switch places.

Here is the new code:

```<code>var dragget;
var source;
var dragged;

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id)
    dragget = event.target.className;
    dragged = event.target;
    source = ev.target.parentElement;
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list" && dragget == "card" )  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" && dragget == "list" ) {

        var data = ev.dataTransfer.getData("text");
        source.innerHTML = ev.target.innerHTML;
        ev.target.innerHTML = "";
        ev.target.appendChild(dragged);
    }
}
</code>```

HTML:

```<code><div class="listWrap" ondrop="drop1(event)" ondragover="allowDrop(event)">
                <div class="list" ondrop="drop(event)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event)" id=list_1 >

                    <div class="card" id=card_1 draggable="true" ondragstart="drag(event)">
                        <p> test </p>
                    </div>
                    <div class=card id=card_2 draggable="true" ondragstart="drag(event)">
                        <p> test 2 </p>
                    </div>
                </div>
            </div>
</code>```

Body:
Im having some trouble implementing drag and drop to my project. Im making a Kanban tool like trello. I have divs that are "lists" and those lists have other divs inside that are "cards". When functioning ideally I would be able to put cards inside different lists, but not a list inside a list. However with my code right now I'm able to drag a list inside a list.

I would like to know how to find the html class of what I'm dragging, so that I can use that to validate.

So what I want to happen is that I can be able to drag a list, but not drop it inside another. I should however be able to rearrange the lists with cards inside, and move cards to different lists.

Thanks!

This is the Javascript:

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list")  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function allowDrop1(ev) {
    ev.preventDefault();
}

function drag1(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" ) {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}
´´´´
And this is a list from the html:
```

 test

 test 2

Body:
I fixed it! Also added functionality to drag a list inside the list-wrapper of a another list and make them switch places.

Here is the new code:

var dragget;
var source;
var dragged;

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id)
    dragget = event.target.className;
    dragged = event.target;
    source = ev.target.parentElement;
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list" && dragget == "card" )  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" && dragget == "list" ) {

        var data = ev.dataTransfer.getData("text");
        source.innerHTML = ev.target.innerHTML;
        ev.target.innerHTML = "";
        ev.target.appendChild(dragged);
    }
}

HTML:

<div class="listWrap" ondrop="drop1(event)" ondragover="allowDrop(event)">
                <div class="list" ondrop="drop(event)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event)" id=list_1 >

                    <div class="card" id=card_1 draggable="true" ondragstart="drag(event)">
                        <p> test </p>
                    </div>
                    <div class=card id=card_2 draggable="true" ondragstart="drag(event)">
                        <p> test 2 </p>
                    </div>
                </div>
            </div>


问:
How to access the
 items using Selenium webdriver
I want to access
 items in a webpage.

From the given HTML, how can I access the list items such as User, Make & Model??

I am not able to retrieve the content of the list. My code is not executing the codes added inside the for loop.

HTML:

```<code><li class="nav-item"> <span class="nav-link add-items" data-toggle="collapse" data-target="#add"> <i class="fas fa-plus"></i>   Add</span>
  <ul class="add-menu collapse" id="add">
    <li><span data-toggle="modal" data-target="#add-user-modal">User</span></li>
    <li><span data-toggle="modal" data-target="#add-make-modal">Make</span></li>
    <li><span data-toggle="modal" data-target="#add-model-modal">Model</span></li>
  </ul>
</li>
</code>```

答:
To print the list items such as User, Make & Model you can use the following solution:

Java:

Using cssSelector:

```<code>List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li.nav-item ul.add-menu.collapse li>span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
System.out.println(myItems);
</code>```

Using xpath:

```<code>List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
System.out.println(myItems);
</code>```

Python:

Using CSS_SELECTOR:

```<code>print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.nav-item ul.add-menu.collapse li>span")))])
</code>```

Using XPATH:

```<code>print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span")))])
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: How to access the <li> items using Selenium webdriver

Body:
I want to access
 items in a webpage.

From the given HTML, how can I access the list items such as User, Make & Model??

I am not able to retrieve the content of the list. My code is not executing the codes added inside the for loop.

HTML:

     Add

User

Make

Model

Body:
To print the list items such as User, Make & Model you can use the following solution:

Java:

Using cssSelector:

List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li.nav-item ul.add-menu.collapse li>span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
System.out.println(myItems);

Using xpath:

List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
System.out.println(myItems);

Python:

Using CSS_SELECTOR:

print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.nav-item ul.add-menu.collapse li>span")))])

Using XPATH:

print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span")))])

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
How to convert array of objects to object containing that data
I need to convert an array of objects to an object of objects in JavaScript.
The ID of the book should be the ID of each object from the array.

Array that I have:

```<code>[{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]
</code>```

Object that I need:

```<code> {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}
</code>```

答:
The problem with the approach given above is it is limited to objects where the new object key is going to be id. Lets abstract this so the function is re-usable in all situations!

As stated above in your query, you want to convert a JSON Array called BookArray into a JSON Object called BookObject as follows.

```<code>const bookArray = [{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]

Your resulting bookObject after processing should look like this.
const bookObject = {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}

const arrayToObject = (array, keyField) =>
   array.reduce((obj, item) => {
     obj[item[keyField]] = item
     return obj
   }, {})

const bookObject = arrayToObject(bookArray, "id")
console.log(bookObject[idToSelect])
</code>```

The above code now accepts a keyField which allows us to use this function to convert any array of objects. Not just those who have the field id. This is important for reusability of our code.

Body:
I need to convert an array of objects to an object of objects in JavaScript.
The ID of the book should be the ID of each object from the array.

Array that I have:

[{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]

Object that I need:

 {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}

Body:
The problem with the approach given above is it is limited to objects where the new object key is going to be id. Lets abstract this so the function is re-usable in all situations!

As stated above in your query, you want to convert a JSON Array called BookArray into a JSON Object called BookObject as follows.

const bookArray = [{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]

Your resulting bookObject after processing should look like this.
const bookObject = {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}

const arrayToObject = (array, keyField) =>
   array.reduce((obj, item) => {
     obj[item[keyField]] = item
     return obj
   }, {})

const bookObject = arrayToObject(bookArray, "id")
console.log(bookObject[idToSelect])

The above code now accepts a keyField which allows us to use this function to convert any array of objects. Not just those who have the field id. This is important for reusability of our code.


问:
Materialize css dropdown in input field issue
My project required auto-suggestion in when user input their query in the input field. I have tried to implement using materialize CSS, Ajax, Django, Jquery as follows:

HTML PAGE:

```<code> <div class="row" id ="adddiv">
        <div class="input-field col s3">
          <input placeholder="Stock Item" type="text" name="StockItem-1" class="validate dropdown-trigger" data-target="dropdown1" id="stockitem">
          <ul id="dropdown1" class="dropdown-content">
          </ul>
        </div>
</code>```

JS Snippet:

```<code>$(function(){
  // $("#stockitem").change(function(){
    $('.dropdown-trigger').keyup(function(){
    $('.dropdown-content').html("")
    var query = $('.dropdown-trigger').val();
    var data = {'query':query}
    var url = 'auto_suggest'
    $.ajax({
     type: "GET",
     url: url,
     dataType : 'json',
     data: data,
     contentType: 'application/x-www-form-urlencoded;charset=utf-8',
     success: function(data)
     {
      var results = data["resultlist"]
      $.each(results, function(index,value){
          $('.dropdown-content').append("<li>"+ value +"</li>");
        });

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

I am able to get the data from backend and li elements are appending with selected ul elements, but it's not displaying as dropdown in front-end.

Refer materialize CSS dropdown:

I suspect the problem with CSS please here

答:
You shouldn't be using the drop down for that, you should be using the autocomplete

https://materializecss.com/autocomplete.html

Also remember to call the Initialization functions as that's what it looks like you are currently missing.  With the below modifications it should work.  But again, you should be using the autocomplete for this.

$(function(){

    ///////////////////////////////////////////////
    // YOU HAVE TO INITIALIZE THE DROPDOWN
    const dropDownEl = $('.dropdown-trigger')[0]
    M.Dropdown.init(dropDownEl)
    ///////////////////////////////////////////////////

  // $("#stockitem").change(function(){
    $('.dropdown-trigger').keyup(function(){
    $('.dropdown-content').html("")
    var query = $('.dropdown-trigger').val();
    var data = {'query':query}
    var url = 'auto_suggest'
    $.ajax({
     type: "GET",
     url: url,
     dataType : 'json',
     data: data,
     contentType: 'application/x-www-form-urlencoded;charset=utf-8',
     success: function(data)
     {
      var results = data["resultlist"]
      $.each(results, function(index,value){
          $('.dropdown-content').append("
"+ value +"
");
        });

    ///////////////////////////////////////////////
    // YOU HAVE TO OPEN THE DROPDOWN
    M.Dropdown.getInstance(dropDownEl).open();
    ///////////////////////////////////////////////////

    }
  });
  });
});```

Body:
My project required auto-suggestion in when user input their query in the input field. I have tried to implement using materialize CSS, Ajax, Django, Jquery as follows:

HTML PAGE:

          <input placeholder="Stock Item" type="text" name="StockItem-1" class="validate dropdown-trigger" data-target="dropdown1" id="stockitem">

JS Snippet:

$(function(){
  // $("#stockitem").change(function(){
    $('.dropdown-trigger').keyup(function(){
    $('.dropdown-content').html("")
    var query = $('.dropdown-trigger').val();
    var data = {'query':query}
    var url = 'auto_suggest'
    $.ajax({
     type: "GET",
     url: url,
     dataType : 'json',
     data: data,
     contentType: 'application/x-www-form-urlencoded;charset=utf-8',
     success: function(data)
     {
      var results = data["resultlist"]
      $.each(results, function(index,value){
          $('.dropdown-content').append("
"+ value +"
");
        });

    }
  });
  });
});

I am able to get the data from backend and li elements are appending with selected ul elements, but it's not displaying as dropdown in front-end.

Refer materialize CSS dropdown:

I suspect the problem with CSS please here

Body:
You shouldn't be using the drop down for that, you should be using the autocomplete

https://materializecss.com/autocomplete.html

Also remember to call the Initialization functions as that's what it looks like you are currently missing.  With the below modifications it should work.  But again, you should be using the autocomplete for this.

$(function(){

    ///////////////////////////////////////////////
    // YOU HAVE TO INITIALIZE THE DROPDOWN
    const dropDownEl = $('.dropdown-trigger')[0]
    M.Dropdown.init(dropDownEl)
    ///////////////////////////////////////////////////

  // $("#stockitem").change(function(){
    $('.dropdown-trigger').keyup(function(){
    $('.dropdown-content').html("")
    var query = $('.dropdown-trigger').val();
    var data = {'query':query}
    var url = 'auto_suggest'
    $.ajax({
     type: "GET",
     url: url,
     dataType : 'json',
     data: data,
     contentType: 'application/x-www-form-urlencoded;charset=utf-8',
     success: function(data)
     {
      var results = data["resultlist"]
      $.each(results, function(index,value){
          $('.dropdown-content').append("<li>"+ value +"</li>");
        });

    ///////////////////////////////////////////////
    // YOU HAVE TO OPEN THE DROPDOWN
    M.Dropdown.getInstance(dropDownEl).open();
    ///////////////////////////////////////////////////

    }
  });
  });
});


问:
How to measure time taken between lines of code in python?
So in Java, we can do How to measure time taken by a function to execute

But how is it done in python? To measure the time start and end time between lines of code?
Something that does this:

```<code>import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured()
endtime = some_time_library.some_module()

time_taken = endtime - starttime
</code>```

答:
I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

```<code>from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken)
</code>```

output:

```<code>Time:  0:00:00.000019
</code>```

Body:
So in Java, we can do How to measure time taken by a function to execute

But how is it done in python? To measure the time start and end time between lines of code?
Something that does this:

import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured()
endtime = some_time_library.some_module()

time_taken = endtime - starttime

Body:
I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken)

output:

Time:  0:00:00.000019


问:
Can' access content of an array in react-native
I'm trying to get data from a SQLite Database in React-Native (android). The function returns an Array with data.
If I try logging the array to the console, it works fine, but when I log the length of the Array to the console, it suddenly prints "0".

Functions:

```<code>getActByButton(category) {
        return new Promise((resolve) => {
            const activities = [];
            const request = 'SELECT activity FROM activity_button WHERE category = ? AND activity IS NOT NULL';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    tx.executeSql(request, [category]).then(([tx, results]) => {
                        //console.log('Query COMPLETED');
                        var len = results.rows.length;
                        for (let i = len; i > 0; i--) {
                            activities.push(results.rows.item(i - 1));
                        }
                        resolve(activities);
                    })
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

    getIconByAct(activity_ids) {
        return new Promise((resolve) => {
            const icons = [];
            const request = 'SELECT name, icon FROM activity WHERE id = ?';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    for (let id in activity_ids) {
                        tx.executeSql(request, [id]).then(([tx, results]) => {
                            console.log('Query COMPLETED');
                            var len = results.rows.length;
                            let icon = results.rows.item(0).icon;
                            let description = results.rows.item(0).name;
                            icons.push({ icon, description });
                        })
                    }
                    resolve(icons);
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

</code>```

Function-call:

```<code>db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log('DATA:');
        console.log(data);
        console.log(data.length);
        console.log(data[1]);
    })
})
</code>```

Console:

How is this possible?
And how can I fix it?

答:
Try this:</p>

```<code>db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log(JSON.stringify(data));
        console.log(JSON.stringify(data.length));
    })
})
</code>```

Body:
I'm trying to get data from a SQLite Database in React-Native (android). The function returns an Array with data.
If I try logging the array to the console, it works fine, but when I log the length of the Array to the console, it suddenly prints "0".

Functions:

getActByButton(category) {
        return new Promise((resolve) => {
            const activities = [];
            const request = 'SELECT activity FROM activity_button WHERE category = ? AND activity IS NOT NULL';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    tx.executeSql(request, [category]).then(([tx, results]) => {
                        //console.log('Query COMPLETED');
                        var len = results.rows.length;
                        for (let i = len; i > 0; i--) {
                            activities.push(results.rows.item(i - 1));
                        }
                        resolve(activities);
                    })
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

    getIconByAct(activity_ids) {
        return new Promise((resolve) => {
            const icons = [];
            const request = 'SELECT name, icon FROM activity WHERE id = ?';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    for (let id in activity_ids) {
                        tx.executeSql(request, [id]).then(([tx, results]) => {
                            console.log('Query COMPLETED');
                            var len = results.rows.length;
                            let icon = results.rows.item(0).icon;
                            let description = results.rows.item(0).name;
                            icons.push({ icon, description });
                        })
                    }
                    resolve(icons);
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

Function-call:

db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log('DATA:');
        console.log(data);
        console.log(data.length);
        console.log(data[1]);
    })
})

Console:

How is this possible?
And how can I fix it?

Body:
Try this:

db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log(JSON.stringify(data));
        console.log(JSON.stringify(data.length));
    })
})


问:
RESTEASY - returning the same object with and without a list
I have a bean that includes several properties and a list. E.g.

```<code>public class Person {
    @XmlElement
    public String getName() { }

    @XmlElement
    public List getFriends() { }
}
</code>```

I now want to have an interface that sometimes returns a list of Persons with their friends sometimes without:

```<code>@GET
@Path("getPersonOnly")
public List<Person> getPersonOnly();

@GET
@Path("getPersonWithFriends")
public List<Person> getPersonWithFriends();
</code>```

The implementation of these methods is very similar. The only difference is that one of them will not include in the xml returned the list of friends.

Any ideas on how to solve this? My initial thought was to subclass Person to PersonWithNoFriends which will not have the getFriends annotated.

Thanks,

Assaf

答: In your getPersonOnly(), load the person, setFriends to NULL and the element won't be in the output.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a bean that includes several properties and a list. E.g.

public class Person {
    @XmlElement
    public String getName() { }

    @XmlElement
    public List getFriends() { }
}

I now want to have an interface that sometimes returns a list of Persons with their friends sometimes without:

@GET
@Path("getPersonOnly")
public List<Person> getPersonOnly();

@GET
@Path("getPersonWithFriends")
public List<Person> getPersonWithFriends();

The implementation of these methods is very similar. The only difference is that one of them will not include in the xml returned the list of friends.

Any ideas on how to solve this? My initial thought was to subclass Person to PersonWithNoFriends which will not have the getFriends annotated.

Thanks,

Assaf


问:
Can't send mail through php in html
I'm trying to develope a personal website as a projecet to one of my classes.
I don't understand much of html so i actually can't make my php work.
Please Help.

I've already tried copying and changing php codes from other fonts but nothing works...

This is the html code:

```<code><div class="container">
   <form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" value="Send">
   </form>
</div>
</code>```

答:
```<code><form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" name="submit" value="Send">
</form>

<?php
   if(isset($_POST['submit'])){
      $name = $_POST['name'];
      $email = $_POST['email'];
      $message = $_POST['message'];

      $to_email = $email; // mail whom you want to send
      $subject = ''; // your subject for sending email
      $message = $name.' sent you message. <br><br>'.$message;
      $headers = 'From: noreply@company.com'; // your mail id

      mail($to_email,$subject,$message,$headers);

      echo "This email is sent using PHP Mail";
   }
?>
</code>```

Use this above code, this will pass the name, email, message to mail function.
Hope this helps you.

Title: Can't send mail through php in html

Body:
I'm trying to develope a personal website as a projecet to one of my classes.
I don't understand much of html so i actually can't make my php work.
Please Help.

I've already tried copying and changing php codes from other fonts but nothing works...

This is the html code:

   <form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" value="Send">
   </form>

Body:
<form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" name="submit" value="Send">
</form>

<?php
   if(isset($_POST['submit'])){
      $name = $_POST['name'];
      $email = $_POST['email'];
      $message = $_POST['message'];

      $to_email = $email; // mail whom you want to send
      $subject = ''; // your subject for sending email
      $message = $name.' sent you message. <br><br>'.$message;
      $headers = 'From: noreply@company.com'; // your mail id

      mail($to_email,$subject,$message,$headers);

      echo "This email is sent using PHP Mail";
   }
?>

Use this above code, this will pass the name, email, message to mail function.
Hope this helps you.


问:
Chaining promises but with different parameters
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

```<code>app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});
</code>```

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

答:
As everybody else already said you should use async / await since the readability is superior to Promises / callbacks but i wanted to add that if your Promises doesn't depend on each other you can actually request them both simultaneity instead of waiting for one to finish before firing the next request using Promise.all</p>

```<code>const loadTextFile = file => new Promise((resolve, reject) => {
  const fileData = getFileData(file);
  resolve(data);
}

const loadFiles = async () => {
  const [measureList, roleList] = await Promise.all([
    loadTextFile('tables'),
    loadTextFile('roles')
  ]);
};
</code>```

Body:
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

Body:
As everybody else already said you should use async / await since the readability is superior to Promises / callbacks but i wanted to add that if your Promises doesn't depend on each other you can actually request them both simultaneity instead of waiting for one to finish before firing the next request using Promise.all

const loadTextFile = file => new Promise((resolve, reject) => {
  const fileData = getFileData(file);
  resolve(data);
}

const loadFiles = async () => {
  const [measureList, roleList] = await Promise.all([
    loadTextFile('tables'),
    loadTextFile('roles')
  ]);
};