问:
Enhance layout integration of react-select into material-ui
I'm using the new material-ui 4.0(.1) and I want to push forward the react-select integration documented in the official docs.

What is missing is a user interface support for the disabled status (isDisabled prop from react-select). The disable status works, but there's no good materialui style integration for it.

If I look at a classic select component I see that a disabled one is:

grayed font

bottom line is dotted

So, I want to have the same behavior for the react-select once.

Without manually customizing the styles, I see that simply adding the Mui-disabled CSS class on the proper div does the trick using the browser inspector.

So this is probably the best way to go, so I automatically inherith the disabled style, but I cannot find a way to inject this class at that div.

Is this possible someway or it's better for me to just manually re-apply the style?

By copy-pasting the code from the documentation seems that the core of the issue is in this snippet:

```<code>
  return (
    <TextField
      fullWidth
      className="Mui-disabled"
      InputProps={{
        inputComponent,
        inputProps: {
          className: clsx(props.selectProps.classes.input, {
            'Mui-disabled': true,
          }),
          inputRef: props.innerRef,
          children: props.children,
          ...props.innerProps,
        },
      }}
      {...props.selectProps.TextFieldProps}
    />
  );
</code>```

(hard-coded Mui-disabledhere is just for text purpose).

Unluckily both Mui-disabled classes attempt fails. They are added to the direct container and direct children of the proper node.

Looking at the code of FormControl at https://github.com/mui-org/material-ui/blob/60071b8b6d4406af3c0a7a332ff86ca02cffa32d/packages/material-ui/src/FormControl/FormControl.js#L149 (the component that's render the div I need to modify) I see no way of doing this.

Please note I'm perfectly aware that simply customizing the style is an order of magnitude simpler, but I'm still learning the whole framework here.

答:
You could do one of two things:

Provide disabled: true to TextFieldProps:

```<code><Select
    classes={classes}
    styles={selectStyles}
    isDisabled={true}
    TextFieldProps={{
        label: 'Label',
        disabled: true, //<---- add this row
        InputLabelProps: {
            shrink: true,
        },
    }}
    options={suggestions}
    components={components}
    value={multi}
    onChange={handleChangeMulti}
    placeholder="Select multiple countries"
    isMulti
/>
</code>```

Or slightly change Control component:

```<code>function Control(props) {
  return (
    <TextField
      fullWidth
      InputProps={{
        inputComponent,
        inputProps: {
          className: props.selectProps.classes.input,
          inputRef: props.innerRef,
          children: props.children,
          ...props.innerProps,
        },
      }}
      disabled={props.isDisabled} //<---- add this row
      {...props.selectProps.TextFieldProps}
    />
  );
}

</code>```

Body:
I'm using the new material-ui 4.0(.1) and I want to push forward the react-select integration documented in the official docs.

What is missing is a user interface support for the disabled status (isDisabled prop from react-select). The disable status works, but there's no good materialui style integration for it.

If I look at a classic select component I see that a disabled one is:

grayed font

bottom line is dotted

So, I want to have the same behavior for the react-select once.

Without manually customizing the styles, I see that simply adding the Mui-disabled CSS class on the proper div does the trick using the browser inspector.

So this is probably the best way to go, so I automatically inherith the disabled style, but I cannot find a way to inject this class at that div.

Is this possible someway or it's better for me to just manually re-apply the style?

By copy-pasting the code from the documentation seems that the core of the issue is in this snippet:

  return (
    <TextField
      fullWidth
      className="Mui-disabled"
      InputProps={{
        inputComponent,
        inputProps: {
          className: clsx(props.selectProps.classes.input, {
            'Mui-disabled': true,
          }),
          inputRef: props.innerRef,
          children: props.children,
          ...props.innerProps,
        },
      }}
      {...props.selectProps.TextFieldProps}
    />
  );

(hard-coded Mui-disabledhere is just for text purpose).

Unluckily both Mui-disabled classes attempt fails. They are added to the direct container and direct children of the proper node.

Looking at the code of FormControl at https://github.com/mui-org/material-ui/blob/60071b8b6d4406af3c0a7a332ff86ca02cffa32d/packages/material-ui/src/FormControl/FormControl.js#L149 (the component that's render the div I need to modify) I see no way of doing this.

Please note I'm perfectly aware that simply customizing the style is an order of magnitude simpler, but I'm still learning the whole framework here.

Body:
You could do one of two things:

Provide disabled: true to TextFieldProps:

<Select
    classes={classes}
    styles={selectStyles}
    isDisabled={true}
    TextFieldProps={{
        label: 'Label',
        disabled: true, //<---- add this row
        InputLabelProps: {
            shrink: true,
        },
    }}
    options={suggestions}
    components={components}
    value={multi}
    onChange={handleChangeMulti}
    placeholder="Select multiple countries"
    isMulti
/>

Or slightly change Control component:

function Control(props) {
  return (
    <TextField
      fullWidth
      InputProps={{
        inputComponent,
        inputProps: {
          className: props.selectProps.classes.input,
          inputRef: props.innerRef,
          children: props.children,
          ...props.innerProps,
        },
      }}
      disabled={props.isDisabled} //<---- add this row
      {...props.selectProps.TextFieldProps}
    />
  );
}


来源: stackexchange

问:
Facebook login using RxSwift
I'm trying to implement the following RxSwift example:

Login in with facebook in my application -> retrieve the user information -> retrieve user's profile photo.

I have these three functions and they must be executed in this order: requestAccess() -> fetchUserInformation() -> fetchUserPhoto()

```<code>func requestAccess() -> Observable<(ACAccount)> {
    return create { observer -> Disposable in
        let accountStore = ACAccountStore()
        let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)
        let dictionary: [NSObject : AnyObject] = [ACFacebookAppIdKey:"***APPID***", ACFacebookPermissionsKey:["public_profile", "email", "user_friends"]]

        accountStore.requestAccessToAccountsWithType(accountType, options: dictionary) { granted, error in
            if granted == false || error != nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let accounts = accountStore.accountsWithAccountType(accountType)
                let account = accounts.last as! ACAccount
                sendNext(observer, account)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}

func fetchUserInformation(account: ACAccount) -> Observable<User> {
    return create { observer -> Disposable in
        let url = NSURL(string: "https://graph.facebook.com/me")
        let request = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: url, parameters: nil)
        request.account = account

        request.performRequestWithHandler { (data, response, error) -> Void in
            if data == nil || response == nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
                let user = User()
                user.updateInformationWithJSON(result! as! JSONObject)

                sendNext(observer, user)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}

func fetchUserPhoto(user: User) -> Observable<AnyObject> {
    return create { observer -> Disposable in
        let url = NSURL(string: "https://graph.facebook.com/***myid***/picture")
        let params = ["redirect":"false", "height":"200", "width":"200"]

        let request = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: url, parameters: params)
        request.account = SocialController.account

        request.performRequestWithHandler { (data, response, error) -> Void in
            if data == nil || response == nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
                sendNext(observer, result!)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}
</code>```

I already tried to implement this flow but it doesn't feel right. What is the best way to solve this problem?

```<code>        requestAccess()
        >- subscribeNext { account in
            fetchUserInformation(account)
                >- map { user in return UserViewModel(model: user) }
                >- subscribeNext { viewModel in self.viewModel = viewModel }
        }
</code>```

答:
```<code>private
func requestFacebookAccess(_ viewController: UIViewController) -> Observable<LoginManagerLoginResult?> {

    return Observable.create { observer -> Disposable in

        let loginManager = LoginManager()
        loginManager.logIn(permissions: ["public_profile", "email"], from: viewController, handler: { result, error in
            observer.onNext(result)
            observer.onCompleted()

        })

        return Disposables.create()
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Facebook login using RxSwift

Body:
I'm trying to implement the following RxSwift example:

Login in with facebook in my application -> retrieve the user information -> retrieve user's profile photo.

I have these three functions and they must be executed in this order: requestAccess() -> fetchUserInformation() -> fetchUserPhoto()

func requestAccess() -> Observable<(ACAccount)> {
    return create { observer -> Disposable in
        let accountStore = ACAccountStore()
        let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)
        let dictionary: [NSObject : AnyObject] = [ACFacebookAppIdKey:"***APPID***", ACFacebookPermissionsKey:["public_profile", "email", "user_friends"]]

        accountStore.requestAccessToAccountsWithType(accountType, options: dictionary) { granted, error in
            if granted == false || error != nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let accounts = accountStore.accountsWithAccountType(accountType)
                let account = accounts.last as! ACAccount
                sendNext(observer, account)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}

func fetchUserInformation(account: ACAccount) -> Observable<User> {
    return create { observer -> Disposable in
        let url = NSURL(string: "https://graph.facebook.com/me")
        let request = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: url, parameters: nil)
        request.account = account

        request.performRequestWithHandler { (data, response, error) -> Void in
            if data == nil || response == nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
                let user = User()
                user.updateInformationWithJSON(result! as! JSONObject)

                sendNext(observer, user)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}

func fetchUserPhoto(user: User) -> Observable<AnyObject> {
    return create { observer -> Disposable in
        let url = NSURL(string: "https://graph.facebook.com/***myid***/picture")
        let params = ["redirect":"false", "height":"200", "width":"200"]

        let request = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: url, parameters: params)
        request.account = SocialController.account

        request.performRequestWithHandler { (data, response, error) -> Void in
            if data == nil || response == nil {
                sendError(observer, error ?? UnknownError)
            } else {
                let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
                sendNext(observer, result!)
                sendCompleted(observer)
            }
        }

        return AnonymousDisposable({})
    }
}

I already tried to implement this flow but it doesn't feel right. What is the best way to solve this problem?

        requestAccess()
        >- subscribeNext { account in
            fetchUserInformation(account)
                >- map { user in return UserViewModel(model: user) }
                >- subscribeNext { viewModel in self.viewModel = viewModel }
        }

ContentLicense: CC BY-SA 4.0


问:
How to apply a function to an input of integers in Golang
For example, if the input was this

```<code>1 3 4 5
</code>```

all separated by a space, I want to apply the function of squaring each individual number then adding it.

I just don't know how to apply the function to each number. All I can figure is that I have to put the numbers into a slice then apply the function to each of the numbers. I have looked everywhere and can't find out how to do this.

in Python I just do it like this and I already put the values into a list called "n".

```<code>#The list is pasted from the initial puzzle
n=[10, 10, 9, 8, 10, 10, 10]

# The list is first squared
b = (list(map(lambda x:x**2,n)))
</code>```

b becomes the new list where the function is done to each number.

答:
```<code>package main

import (
 "strconv"
 "fmt"
 "strings"
)

func main() {
stringwithnumbers := "1 2 3 4 5"
numberarray := strings.Split(stringwithnumbers, " ")

stringwithnumbers = ""

for _, number := range numberarray {
    numbernew,err := strconv.Atoi(number)
    if err != nil{
    return
    }

    numbernew = numbernew * 2
    stringwithnumbers += strconv.Itoa(numbernew)
    stringwithnumbers += " "
}

stringwithnumbers = strings.Trim(stringwithnumbers, " ")

//You can check the result...
fmt.Print(stringwithnumbers)
}
</code>```

You can check the code and your changes here:
https://play.golang.org/

Body:
For example, if the input was this

1 3 4 5

all separated by a space, I want to apply the function of squaring each individual number then adding it.

I just don't know how to apply the function to each number. All I can figure is that I have to put the numbers into a slice then apply the function to each of the numbers. I have looked everywhere and can't find out how to do this.

in Python I just do it like this and I already put the values into a list called "n".

#The list is pasted from the initial puzzle
n=[10, 10, 9, 8, 10, 10, 10]

# The list is first squared
b = (list(map(lambda x:x**2,n)))

b becomes the new list where the function is done to each number.

Body:
package main

import (
 "strconv"
 "fmt"
 "strings"
)

func main() {
stringwithnumbers := "1 2 3 4 5"
numberarray := strings.Split(stringwithnumbers, " ")

stringwithnumbers = ""

for _, number := range numberarray {
    numbernew,err := strconv.Atoi(number)
    if err != nil{
    return
    }

    numbernew = numbernew * 2
    stringwithnumbers += strconv.Itoa(numbernew)
    stringwithnumbers += " "
}

stringwithnumbers = strings.Trim(stringwithnumbers, " ")

//You can check the result...
fmt.Print(stringwithnumbers)
}

You can check the code and your changes here:
https://play.golang.org/


问:
XSLT Add Type to Specific Tags
I have an XML doc where some of the tags include the type in the tag name. For the tags within the <TXT> tags I've successfully appended the type to the tag name, i.e. <NUMEX type="CASENUM"> becomes <NUMEX_CASENUM>. However, within the <SUBJECT> tag I need to add the type to <SubjectPhone> but not to any of the tags related to subject name.

I tried to read up on conditionally appending the type to the tag name but I didn't have much success.

Below I've included my XML, the current state of my XSLT, the actual output, and the output I would like to see.

XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
            <SubjectPhone type="Mobile">123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
</NORMDOC>
</code>```

XSLT

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFOS>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFOS>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Actual Output

```<code><NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI>
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI>
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject>
            <SubjectFullName>SMITH/JANE/C</SubjectFullName>
            ...
            <SubjectPhone>123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         ...
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>
</code>```

Expected Output

```<code><NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI>
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI>
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject>
            <SubjectFullName>SMITH/JANE/C</SubjectFullName>
            ...
            <SubjectPhone_Mobile>123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         ...
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>
</code>```

答:
I think all you need to do is add this template into your XSLT

```<code><xsl:template match="SubjectPhone">
   <xsl:apply-templates select="." mode="extra" />
</xsl:template>
</code>```

Alternatively, remove the template that matches S, along with template that matches * for mode "extra", and replace them with this template instead:

```<code><xsl:template match="S/*|SubjectPhone">
    <xsl:element name="{name()}_{@type}">
       <xsl:apply-templates/>
    </xsl:element>
</xsl:template>
</code>```

See http://xsltfiddle.liberty-development.net/bFN1y9K for this latter case.

Do note that this template in your XSLT is redundant

```<code><xsl:template match="*">
    <xsl:copy>
       <xsl:apply-templates/>
   </xsl:copy>
</xsl:template>
</code>```

You already have a template matching @*|node() later on in your XSLT, and node() is short-hand *|text()|comment()|processing-instruction(). (Strictly speaking it is an error to have two templates matching the same thing with equal priority. XSLT processors may signal the error, or just use the last template, which is what is happening here).

Title: XSLT Add Type to Specific Tags

Body:
I have an XML doc where some of the tags include the type in the tag name. For the tags within the <TXT> tags I've successfully appended the type to the tag name, i.e. <NUMEX type="CASENUM"> becomes <NUMEX_CASENUM>. However, within the <SUBJECT> tag I need to add the type to <SubjectPhone> but not to any of the tags related to subject name.

I tried to read up on conditionally appending the type to the tag name but I didn't have much success.

Below I've included my XML, the current state of my XSLT, the actual output, and the output I would like to see.

XML

<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
            <SubjectPhone type="Mobile">123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
</NORMDOC>

XSLT

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFOS>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFOS>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Actual Output

<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI>
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI>
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject>
            <SubjectFullName>SMITH/JANE/C</SubjectFullName>
            ...
            <SubjectPhone>123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         ...
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

Expected Output

<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI>
         <FIName>BANK OF FURY, N.A.</FIName>
      </FI>
      <OIs>
         <OI>
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject>
            <SubjectFullName>SMITH/JANE/C</SubjectFullName>
            ...
            <SubjectPhone_Mobile>123-456-7890</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         ...
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

Body:
I think all you need to do is add this template into your XSLT

<xsl:template match="SubjectPhone">
   <xsl:apply-templates select="." mode="extra" />
</xsl:template>

Alternatively, remove the template that matches S, along with template that matches * for mode "extra", and replace them with this template instead:

<xsl:template match="S/*|SubjectPhone">
    <xsl:element name="{name()}_{@type}">
       <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

See http://xsltfiddle.liberty-development.net/bFN1y9K for this latter case.

Do note that this template in your XSLT is redundant

<xsl:template match="*">
    <xsl:copy>
       <xsl:apply-templates/>
   </xsl:copy>
</xsl:template>

You already have a template matching @*|node() later on in your XSLT, and node() is short-hand *|text()|comment()|processing-instruction(). (Strictly speaking it is an error to have two templates matching the same thing with equal priority. XSLT processors may signal the error, or just use the last template, which is what is happening here).


问:
Trying to pass a key to argument on custom function to display all values from the data
When I call the function with the argument, it doesn't show anything.

I tried below and it works but when I added it inside the function it stopped working.

WORKING

```<code>var data = [

  {"blue": ['Volvo','Saab','Mercedes']},
  {"wheel": ['Saab','Mercedes','BMW']},
  {"fast": ['Saab','BMW','Ford']}

];

$.each(data, function(i) {
  var plans = data[i].blue;
    $.each(plans, function(b,qf) {
      console.log(qf);
    });
});
</code>```

NOT WORKING

```<code>var data = [

  {"blue": ['Volvo','Saab','Mercedes']},
  {"wheel": ['Saab','Mercedes','BMW']},
  {"fast": ['Saab','BMW','Ford']}

];

function aData(selected) {
  $.each(data, function(i) {
    var plans = data[i].selected;
      $.each(plans, function(b,qf) {
        console.log(qf);
      });
  });
}

aData(blue);
</code>```

I expect it to show all values for the key: blue. But nothing appears.

答:
Two errors:

1) The .selected is messing you up.  Use [selected].

2) Make sure you're using a string for your input on the last line.  It breaks the example, but I am guessing you're calling this from elsewhere in your actual application.

Body:
When I call the function with the argument, it doesn't show anything.

I tried below and it works but when I added it inside the function it stopped working.

WORKING

var data = [

  {"blue": ['Volvo','Saab','Mercedes']},
  {"wheel": ['Saab','Mercedes','BMW']},
  {"fast": ['Saab','BMW','Ford']}

];

$.each(data, function(i) {
  var plans = data[i].blue;
    $.each(plans, function(b,qf) {
      console.log(qf);
    });
});

NOT WORKING

var data = [

  {"blue": ['Volvo','Saab','Mercedes']},
  {"wheel": ['Saab','Mercedes','BMW']},
  {"fast": ['Saab','BMW','Ford']}

];

function aData(selected) {
  $.each(data, function(i) {
    var plans = data[i].selected;
      $.each(plans, function(b,qf) {
        console.log(qf);
      });
  });
}

aData(blue);

I expect it to show all values for the key: blue. But nothing appears.


问:
Expression #29 of SELECT list is not in GROUP BY clause and contains nonaggregated column
I am using a GoDaddy VPS server, after the server setup I can see that they have provided MySql version 5.7. I am getting the below error in MySql query, but this query is running perfectly in MySql 5.6

I have root access.

Error -> Expression #29 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sephecom_ecom.v2.secondary_colors' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

答:
It is not a version problem, it is a configuration problem

The problem is that you have the only_full_group_by activated. That means that all your select columns must be either on the GROUP BY or must use an aggregation function (like sum, avg, count, etc). If you want to avoid it you can change it doing

```<code>SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
</code>```

If you modify your group by condition, you may get strange results in your query

Body:
It is not a version problem, it is a configuration problem

The problem is that you have the only_full_group_by activated. That means that all your select columns must be either on the GROUP BY or must use an aggregation function (like sum, avg, count, etc). If you want to avoid it you can change it doing

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

If you modify your group by condition, you may get strange results in your query


问:
Create multiple files with Powershell?
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

```<code>touch {a..z}.txt
</code>```

Or 152 with:

```<code>touch {{a..z},{A..Z},{0..99}}.txt
</code>```

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

答:
Not quite as concise as bash, but it can be done.

```<code>@(97..(97+25)) + @(48..(48+9)) |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
</code>```

Another way...

```<code>@([int][char]'a'..[int][char]'z') + @([int][char]'0'..[int][char]'9') |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
</code>```

And one more...

```<code>function rng { @($([int][char]$args[0])..$([int][char]$args[1])) }

(rng 'a' 'z') + (rng '0' '9') |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
</code>```

If you are desperate to do this in a cmd.exe shell, this might work. When it looks like the correct commands are produced, delete or comment out the echo line and remove the rem from the next line.

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "CLIST=abcdefghijklmnopqrstuvwxyz0123456789"
FOR /L %%i IN (0,1,35) DO (
    CALL SET "S=%%CLIST:~%%i,1%%.txt"
    echo TYPE NUL ^>"!S!"
    rem TYPE NUL >"!S!"
)
</code>```

Title: Create multiple files with Powershell?

Body:
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

touch {a..z}.txt

Or 152 with:

touch {{a..z},{A..Z},{0..99}}.txt

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

Body:
Not quite as concise as bash, but it can be done.

@(97..(97+25)) + @(48..(48+9)) |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }

Another way...

@([int][char]'a'..[int][char]'z') + @([int][char]'0'..[int][char]'9') |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }

And one more...

function rng { @($([int][char]$args[0])..$([int][char]$args[1])) }

(rng 'a' 'z') + (rng '0' '9') |
    ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }

If you are desperate to do this in a cmd.exe shell, this might work. When it looks like the correct commands are produced, delete or comment out the echo line and remove the rem from the next line.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "CLIST=abcdefghijklmnopqrstuvwxyz0123456789"
FOR /L %%i IN (0,1,35) DO (
    CALL SET "S=%%CLIST:~%%i,1%%.txt"
    echo TYPE NUL ^>"!S!"
    rem TYPE NUL >"!S!"
)


问:
Why cannot create partitioning table
I'm trying to create simple table with partitions.

this is my command:

```<code>CREATE TABLE measurement (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
) PARTITION BY RANGE (logdate);
</code>```

this is the error I got:

SQL Error [42601]: ERROR: syntax error at or near "PARTITION"

Unable to understand with is the problem..

I am using PostgreSQL 9.6.3

答:
Here is the example of automatically creating monthly partition for 9.6 version, may be compatible with other versions:</p>

```<code>`----------Function to create partitions by system------------------
CREATE OR REPLACE FUNCTION schema.insert_function()
RETURNS TRIGGER
AS $$
DECLARE
partition_date TEXT;
partition_schema TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_month TEXT;
BEGIN
partition_date := to_char(NEW.created_dtm,'YYYY_MM');
partition_schema := 'temp';
partition_name := 'patition_name_' || partition_date;
start_of_month := to_char((NEW.created_dtm),'YYYY-MM'|| '-01');
end_of_month := to_char((NEW.created_dtm + interval '1 month'),'YYYY-MM'|| '-01');
IF NOT EXISTS
(SELECT 1
 FROM   information_schema.tables
 WHERE  table_name = partition_name
 AND table_schema = partition_schema)
THEN
EXECUTE 'CREATE TABLE '|| partition_schema ||' . '|| partition_name ||' (check (created_dtm >= ''' || start_of_month || ''' and created_dtm < ''' || end_of_month || ''' ), ' || 'LIKE master_schema.master_table  INCLUDING ALL) INHERITS (master_schema.master_table)';
EXECUTE format('ALTER TABLE %I.%I OWNER TO role1', partition_schema, partition_name);
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO read_only_role', partition_schema, partition_name);
EXECUTE format('GRANT INSERT, SELECT, UPDATE, DELETE ON TABLE %I.%I TO read_write_role', partition_schema, partition_name);
EXECUTE format('CREATE INDEX ON %I.%I(column1, column2, column3)', partition_schema, partition_name);
EXECUTE format('CREATE UNIQUE INDEX ON %I.%I(column4)', partition_schema, partition_name);
........
RAISE NOTICE 'A partition has been created %.%', partition_schema, partition_name;
RAISE NOTICE 'All necessary indices are created on %.%', partition_schema, partition_name;
END IF;
EXECUTE format('INSERT INTO %I.%I VALUES($1.*)', partition_schema, partition_name) using NEW;
RETURN NULL;
END
$$
LANGUAGE plpgsql;

ALTER FUNCTION schema.insert_function()
OWNER TO super_user;

-----------------------------------------Trigger on master table--------------
CREATE TRIGGER insert_trigger
BEFORE INSERT
ON master_schema.master_table
FOR EACH ROW
EXECUTE PROCEDURE schema.insert_function();`
</code>```

Title: Why cannot create partitioning table

Body:
I'm trying to create simple table with partitions.

this is my command:

CREATE TABLE measurement (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
) PARTITION BY RANGE (logdate);

this is the error I got:

SQL Error [42601]: ERROR: syntax error at or near "PARTITION"

Unable to understand with is the problem..

I am using PostgreSQL 9.6.3

Body:
Here is the example of automatically creating monthly partition for 9.6 version, may be compatible with other versions:

`----------Function to create partitions by system------------------
CREATE OR REPLACE FUNCTION schema.insert_function()
RETURNS TRIGGER
AS $$
DECLARE
partition_date TEXT;
partition_schema TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_month TEXT;
BEGIN
partition_date := to_char(NEW.created_dtm,'YYYY_MM');
partition_schema := 'temp';
partition_name := 'patition_name_' || partition_date;
start_of_month := to_char((NEW.created_dtm),'YYYY-MM'|| '-01');
end_of_month := to_char((NEW.created_dtm + interval '1 month'),'YYYY-MM'|| '-01');
IF NOT EXISTS
(SELECT 1
 FROM   information_schema.tables
 WHERE  table_name = partition_name
 AND table_schema = partition_schema)
THEN
EXECUTE 'CREATE TABLE '|| partition_schema ||' . '|| partition_name ||' (check (created_dtm >= ''' || start_of_month || ''' and created_dtm < ''' || end_of_month || ''' ), ' || 'LIKE master_schema.master_table  INCLUDING ALL) INHERITS (master_schema.master_table)';
EXECUTE format('ALTER TABLE %I.%I OWNER TO role1', partition_schema, partition_name);
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO read_only_role', partition_schema, partition_name);
EXECUTE format('GRANT INSERT, SELECT, UPDATE, DELETE ON TABLE %I.%I TO read_write_role', partition_schema, partition_name);
EXECUTE format('CREATE INDEX ON %I.%I(column1, column2, column3)', partition_schema, partition_name);
EXECUTE format('CREATE UNIQUE INDEX ON %I.%I(column4)', partition_schema, partition_name);
........
RAISE NOTICE 'A partition has been created %.%', partition_schema, partition_name;
RAISE NOTICE 'All necessary indices are created on %.%', partition_schema, partition_name;
END IF;
EXECUTE format('INSERT INTO %I.%I VALUES($1.*)', partition_schema, partition_name) using NEW;
RETURN NULL;
END
$$
LANGUAGE plpgsql;

ALTER FUNCTION schema.insert_function()
OWNER TO super_user;

-----------------------------------------Trigger on master table--------------
CREATE TRIGGER insert_trigger
BEFORE INSERT
ON master_schema.master_table
FOR EACH ROW
EXECUTE PROCEDURE schema.insert_function();`


问:
What are the differences between extern, abstract, and partial for methods in an abstract class?
I am writing an abstract class because I want to provide a few commonly used methods, require a few methods that will be too specific, and allow some methods to "extended".  After bumping into a compiler error I am wondering if anybody can explain the differences between the extern, abstract, and partial keywords.  What do they mean and when/where should I use them?

答:
An extern method is typically being implemented via a dll-import (P/Invoke) - so it does have an implementation - you just can't see it.

A partial method is useful mainly with code-generation as a way to inject functionality into the generated code. They are optional, private only, and only exist if you provide the other half. As such there are also some limitations around return/out values to assure definite assignment. Calls to partial methods will be omitted entirely by the compiler if there is no implementation.

An abstract method is where the implementation has to be provided by a derived type. The runtime ensures you can't have an instance if there are still unimplemented abstract methods, so you are assured that they will exist at runtime.


问:
AWS Cloudwatch can not publish to SNS Topic with SSE
I have a Route53 health check, which submits its metrics into Cloudwatch, and finally Cloudwatch specifies thresholds and should send alerts through SNS.

However, I would like my SNS Topic to be encrypted. When I turn on SNS Topic encryption using the alias/aws/sns key I receive these messages in the Cloudwatch message history:

```<code>{
  "actionState": "Failed",
  "stateUpdateTimestamp": 123456778899,
  "notificationResource": "arn:aws:sns:xx-region-y:zzzzzzzzzz:topic_name",
  "publishedMessage": null,
  "error": "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)"
}
</code>```

This appears to not be an IAM issue with Cloudwatch, but with SNS itself being unauthorized to use the KMS resources.

I enjoy using the IAM Policy Simulator for IAM users to identify where their permissions are lacking, but there doesn't seem to be a way to validate a Service's access to other services. Is that a thing I can manage?

https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html

I have also tried this with a CMK with the following policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "route53.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXX:role/OrganizationAccountAccessRole"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}
</code>```

I'm pretty much throwing darts at a wall with the principals, but I think there's validation for sns.amazonaws.comfor SNS and events.amazonaws.com for Cloudwatch.

I received the exact same error, "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)", when using a CMK in this manner as well. I can understand my CMK not working properly, but the Amazon managed key I think should just work out of the box.

I've tried using a CMK which grants sns.amazonaws.com and events.amazonaws.com with kms:* permissions. Same error.

答:
While some AWS services use an IAM Role in your account, others use a specific principal to be granted access instead.  See https://aws.amazon.com/blogs/compute/encrypting-messages-published-to-amazon-sns-with-aws-kms/.

I think in your case you need to allow the cloudwatch principal, events.amazonaws.com, to be allowed to use the KMS key you specified, in the key's policy.   See the section "Enabling compatibility between encrypted topics and event sources" in the above link.

Note that as the document says, "Several AWS services publish events to Amazon SNS topics. To allow these event sources to work with encrypted topics, you must first create a customer-managed CMK and then add the following statement to the policy of the CMK."  This only works with customer managed keys.

Body:
I have a Route53 health check, which submits its metrics into Cloudwatch, and finally Cloudwatch specifies thresholds and should send alerts through SNS.

However, I would like my SNS Topic to be encrypted. When I turn on SNS Topic encryption using the alias/aws/sns key I receive these messages in the Cloudwatch message history:

{
  "actionState": "Failed",
  "stateUpdateTimestamp": 123456778899,
  "notificationResource": "arn:aws:sns:xx-region-y:zzzzzzzzzz:topic_name",
  "publishedMessage": null,
  "error": "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)"
}

This appears to not be an IAM issue with Cloudwatch, but with SNS itself being unauthorized to use the KMS resources.

I enjoy using the IAM Policy Simulator for IAM users to identify where their permissions are lacking, but there doesn't seem to be a way to validate a Service's access to other services. Is that a thing I can manage?

https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html

I have also tried this with a CMK with the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "route53.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXX:role/OrganizationAccountAccessRole"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}

I'm pretty much throwing darts at a wall with the principals, but I think there's validation for sns.amazonaws.comfor SNS and events.amazonaws.com for Cloudwatch.

I received the exact same error, "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)", when using a CMK in this manner as well. I can understand my CMK not working properly, but the Amazon managed key I think should just work out of the box.

I've tried using a CMK which grants sns.amazonaws.com and events.amazonaws.com with kms:* permissions. Same error.


问:
Searching a value in a nested Map in Java8
I am trying to look through a nested map for a specific value using java8.
Example:
The map is a

```<code>Map<Integer, Map<String,String>> classStudentGrp;
</code>```

and some of the records are like

```<code>StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx

StudentId1:
StudentName:Anna
StudentAge:11
StudentAddress:yyyy
</code>```

and so on.

I am looking at something like

```<code>classStudentGrp.forEach((sid,stu)->stu.forEach((sAttr,val)->val.equals("Andy")));
</code>```

and I want to either return a boolean (true) or set a variable if 'Andy' is found. I know the traditional approach using entry keys and values, but trying to do this in lambda.

答:
refer to below example

List<String> result = lines.stream()                // convert list to stream
  .filter(line -> "mkyong".equals(line))            // we dont like mkyong
  .collect(Collectors.toList());
```

coming from https://www.mkyong.com/java8/java-8-streams-filter-examples/

Body:
I am trying to look through a nested map for a specific value using java8.
Example:
The map is a

Map<Integer, Map<String,String>> classStudentGrp;

and some of the records are like

StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx

StudentId1:
StudentName:Anna
StudentAge:11
StudentAddress:yyyy

and so on.

I am looking at something like

classStudentGrp.forEach((sid,stu)->stu.forEach((sAttr,val)->val.equals("Andy")));

and I want to either return a boolean (true) or set a variable if 'Andy' is found. I know the traditional approach using entry keys and values, but trying to do this in lambda.

Body:
refer to below example

List<String> result = lines.stream()                // convert list to stream
  .filter(line -> "mkyong".equals(line))            // we dont like mkyong
  .collect(Collectors.toList());

coming from https://www.mkyong.com/java8/java-8-streams-filter-examples/


问:
How to get day month and year in integer from given string date in pattern dd-MMM-yyyy
I have a string date in format (dd-MMM-yyyy) like (23-SEP-2019). I want to seperate day month and year from above string in integer like day = 23, month = 09, year = 2019.

答:
You can use java 8 LocalDate feature. I provide below the code, you can check.</p>

```<code>String dateStr = "23-Sep-2019";
    DateTimeFormatter formatter_1 = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
    LocalDate localDate = LocalDate.parse(dateStr, formatter_1);
    System.out.println("localDate_1 = " + localDate);
    int day = localDate.getDayOfMonth();
    int month = localDate.getMonthValue();
    int year = localDate.getYear();
    System.out.println(day + "-" + month + "-" + year);
</code>```

Body:
You can use java 8 LocalDate feature. I provide below the code, you can check.

String dateStr = "23-Sep-2019";
    DateTimeFormatter formatter_1 = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
    LocalDate localDate = LocalDate.parse(dateStr, formatter_1);
    System.out.println("localDate_1 = " + localDate);
    int day = localDate.getDayOfMonth();
    int month = localDate.getMonthValue();
    int year = localDate.getYear();
    System.out.println(day + "-" + month + "-" + year);


答:
try this</p>

```<code>var data = [

      {"blue": ['Volvo','Saab','Mercedes']},
      {"wheel": ['Saab','Mercedes','BMW']},
      {"fast": ['Saab','BMW','Ford']}

    ];

    function aData(selected) {
      $.each(data, function(i) {
        var plans = data[i][selected];
        if (plans) {
          $.each(plans, function(b,qf) {
            console.log(qf);
          });
          }
      });
    }

    aData('blue');
</code>```

Title: Trying to pass a key to argument on custom function to display all values from the data

Body:
try this

var data = [

      {"blue": ['Volvo','Saab','Mercedes']},
      {"wheel": ['Saab','Mercedes','BMW']},
      {"fast": ['Saab','BMW','Ford']}

    ];

    function aData(selected) {
      $.each(data, function(i) {
        var plans = data[i][selected];
        if (plans) {
          $.each(plans, function(b,qf) {
            console.log(qf);
          });
          }
      });
    }

    aData('blue');


答:
I highly recommend you create a Student class instead of just having a String in the format:

```<code>StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx
</code>```

Java is an Object Oriented language, and it is best to use it as such. You can create a class like:

```<code>class Student {
   private String name;
   private String id;
   private int age;
   private String address;
   //Getters and setters
   //Appropriate constructors
}
</code>```

Then you could do:

```<code>boolean value = classStudentGrp.values().stream()
                                        .anyMatch(e -> e.getName().equals("Andy"));
</code>```

Which will take a Stream of the values of classStudentGrp (The Map<String, Student), take the values of that Map (A Stream<Students>) and then use anyMatch to determine if any of the Students have the name "Andy"

Title: Searching a value in a nested Map in Java8

Body:
I highly recommend you create a Student class instead of just having a String in the format:

StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx

Java is an Object Oriented language, and it is best to use it as such. You can create a class like:

class Student {
   private String name;
   private String id;
   private int age;
   private String address;
   //Getters and setters
   //Appropriate constructors
}

Then you could do:

boolean value = classStudentGrp.values().stream()
                                        .anyMatch(e -> e.getName().equals("Andy"));

Which will take a Stream of the values of classStudentGrp (The Map<String, Student), take the values of that Map (A Stream<Students>) and then use anyMatch to determine if any of the Students have the name "Andy"


问:
jquery scroll to div and focus a textbox
I am trying to achieve two things with a single onclick of anchor tag. First, when I click on search, I am scrolling to a particular div, and then trying to focus on the textbox within that div. Below is the link to the sample code. I am able to scroll to the div, but somehow the textbox is losing focus. What is wrong with the code?

http://jsfiddle.net/e9tJ5/1/

答: I've added second $("#searchtext").focus(); and it works in firefox. not elegant but works.


问:
Automatic refactoring based on levels beginning with a certain character?
I'm looking for a method to  automatically recode factors within a variable based on some pattern in the levels. I intend on iterating the solution to the larger data set.

I have a larger dataset that has multiple instances of the example I show below. The levels tend to have the following pattern:

The main categories are 1, 2, 3 and 4. Levels 11, 12, 13, and 14 are subcategories of level 1. I wish to be able to streamline the grouping process. I've successfully performed the refactoring using fct_recode, but my intent is to extend this procedure to other variables that follow a similar coding pattern.

library(tidyverse)

dat <- tribble(
  ~Ethnicity,
  "1",
  "2",
  "3",
  "4",
  "11",
  "12",
  "13",
  "14",
  "11",
  "13",
  "12",
  "12",
  "11",
  "13")

dat <- mutate_at(dat, vars(Ethnicity), factor)

count(dat, Ethnicity)
#> # A tibble: 8 x 2
#>   Ethnicity     n
#>   <fct>     <int>
#> 1 1             1
#> 2 11            3
#> 3 12            3
#> 4 13            3
#> 5 14            1
#> 6 2             1
#> 7 3             1
#> 8 4             1

dat %>%
  mutate(Ethnicity = fct_recode(Ethnicity,
                                "1" = "1",
                                "1" = "11",
                                "1" = "12",
                                "1" = "13",
                                "1" = "14"
                                )) %>%
  count(Ethnicity)
#> # A tibble: 4 x 2
#>   Ethnicity     n
#>   <fct>     <int>
#> 1 1            11
#> 2 2             1
#> 3 3             1
#> 4 4             1
```

Created on 2019-05-31 by the reprex package (v0.2.1)

This method succesfully groups the subcategories of 11, 12, 13, and 14 into 1, as expected. Is there a way to do this without changing the levels manually for each subcategory? And what would be the general method of extending this process to several variables that have the same pattern? Thank you.

答:
An option is to create a named vector and evaluate (!!!)

```<code>library(dplyr)
library(forcats)
lvls <- levels(dat$Ethnicity)[substr(levels(dat$Ethnicity), 1, 1) == 1]
nm1 <- setNames(lvls, rep(1, length(lvls)))
dat %>%
     mutate(Ethnicity = fct_recode(Ethnicity, !!!nm1)) %>%
     count(Ethnicity)
# A tibble: 4 x 2
#  Ethnicity     n
#  <fct>     <int>
#1 1            11
#2 2             1
#3 3             1
#4 4             1
</code>```

Or another option is to set the levels based on the substring

```<code>levels(dat$Ethnicity)[substr(levels(dat$Ethnicity), 1, 1) == 1] <- 1
dat %>%
   count(Ethnicity)
</code>```

For multiple columns, use mutate_at and specify the variables of interest

```<code>dat %>%
    mutate_at(vars(colsOfInterst), list(~ fct_recode(., !!! nm1)))
</code>```

Body:
I'm looking for a method to  automatically recode factors within a variable based on some pattern in the levels. I intend on iterating the solution to the larger data set.

I have a larger dataset that has multiple instances of the example I show below. The levels tend to have the following pattern:

The main categories are 1, 2, 3 and 4. Levels 11, 12, 13, and 14 are subcategories of level 1. I wish to be able to streamline the grouping process. I've successfully performed the refactoring using fct_recode, but my intent is to extend this procedure to other variables that follow a similar coding pattern.

library(tidyverse)

dat <- tribble(
  ~Ethnicity,
  "1",
  "2",
  "3",
  "4",
  "11",
  "12",
  "13",
  "14",
  "11",
  "13",
  "12",
  "12",
  "11",
  "13")

dat <- mutate_at(dat, vars(Ethnicity), factor)

count(dat, Ethnicity)
#> # A tibble: 8 x 2
#>   Ethnicity     n
#>   <fct>     <int>
#> 1 1             1
#> 2 11            3
#> 3 12            3
#> 4 13            3
#> 5 14            1
#> 6 2             1
#> 7 3             1
#> 8 4             1

dat %>%
  mutate(Ethnicity = fct_recode(Ethnicity,
                                "1" = "1",
                                "1" = "11",
                                "1" = "12",
                                "1" = "13",
                                "1" = "14"
                                )) %>%
  count(Ethnicity)
#> # A tibble: 4 x 2
#>   Ethnicity     n
#>   <fct>     <int>
#> 1 1            11
#> 2 2             1
#> 3 3             1
#> 4 4             1

Created on 2019-05-31 by the reprex package (v0.2.1)

This method succesfully groups the subcategories of 11, 12, 13, and 14 into 1, as expected. Is there a way to do this without changing the levels manually for each subcategory? And what would be the general method of extending this process to several variables that have the same pattern? Thank you.

Body:
An option is to create a named vector and evaluate (!!!)

library(dplyr)
library(forcats)
lvls <- levels(dat$Ethnicity)[substr(levels(dat$Ethnicity), 1, 1) == 1]
nm1 <- setNames(lvls, rep(1, length(lvls)))
dat %>%
     mutate(Ethnicity = fct_recode(Ethnicity, !!!nm1)) %>%
     count(Ethnicity)
# A tibble: 4 x 2
#  Ethnicity     n
#  <fct>     <int>
#1 1            11
#2 2             1
#3 3             1
#4 4             1

Or another option is to set the levels based on the substring

levels(dat$Ethnicity)[substr(levels(dat$Ethnicity), 1, 1) == 1] <- 1
dat %>%
   count(Ethnicity)

For multiple columns, use mutate_at and specify the variables of interest

dat %>%
    mutate_at(vars(colsOfInterst), list(~ fct_recode(., !!! nm1)))


问:
Write Powershell function, that can be called with pipeline input AND "normal" input"
I've a simple function:

```<code>    function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            Write-Host $_
        }
    }
</code>```

Based on ValueFromPipeline in can use the function with pipeline input, e.g.

```<code> "a","b", "c" | Write-Log
 a
 b
 c
</code>```

That's ok. But if I want to use my function in that way:

```<code> Write-Log -message "a", "b", "c"
</code>```

the automatic $_ variable is empty, and nothing is printed.

I also found these two stackoverflow links:

Handling pipeline and parameter input in a Powershell function

How do I write a PowerShell script that accepts pipeline input?

Both of them suggest the following pattern:

```<code>  function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            foreach ($message in $messages){
                Write-Host $message
            }
        }
    }
</code>```

Above pattern works for my use case. But from my point of view is feels weird to call foreach in the `process´ block, since (as far as I've understood) the process block is called for every pipeline item. As there a better cleaner way to write functions supporting both use cases?

Thx.

答:
That's the way you have to do it if you want to pass an array to a parameter like

```<code>Write-Log -Messages a,b,c
</code>```

Otherwise you can only do

```<code>Write-Log -Messages a
</code>```

You can still pipe an array in without the foreach:

```<code>Echo a b c | Write-Log
</code>```

I appreciate cmdlets that can do both, like get-process.

Body:
I've a simple function:

    function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            Write-Host $_
        }
    }

Based on ValueFromPipeline in can use the function with pipeline input, e.g.

 "a","b", "c" | Write-Log
 a
 b
 c

That's ok. But if I want to use my function in that way:

 Write-Log -message "a", "b", "c"

the automatic $_ variable is empty, and nothing is printed.

I also found these two stackoverflow links:

Handling pipeline and parameter input in a Powershell function

How do I write a PowerShell script that accepts pipeline input?

Both of them suggest the following pattern:

  function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            foreach ($message in $messages){
                Write-Host $message
            }
        }
    }

Above pattern works for my use case. But from my point of view is feels weird to call foreach in the `process´ block, since (as far as I've understood) the process block is called for every pipeline item. As there a better cleaner way to write functions supporting both use cases?

Thx.

Body:
That's the way you have to do it if you want to pass an array to a parameter like

Write-Log -Messages a,b,c

Otherwise you can only do

Write-Log -Messages a

You can still pipe an array in without the foreach:

Echo a b c | Write-Log

I appreciate cmdlets that can do both, like get-process.


问:
Using FileProvider to open PDF included in my app?
I have included two PDFs that I want to open from my app. They should open with whatever PDF viewer the user has installed. I placed the PDFs in /res/raw. I used this code:

```<code>File file = new File(getContext().getFilesDir().getPath(), s);
            Uri pdfUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
</code>```

My filepaths.xml looks like this:

```<code><paths>
<files-path path="raw/" name="raw" />
</code>```

I'm getting an error that says:

```<code>java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.dsv2019.pvt15.prepapp/files/hjartlugnraddning.pdf
</code>```

Why is this happening?

答:
You have a few problems.

First, <files-path path="raw/" name="raw" /> says that it serves files from a raw/ subdirectory under getFilesDir(). However, new File(getContext().getFilesDir().getPath(), s) will not have such a directory, unless it is in s somehow, and the error suggests that it is not. BTW, you can simplify this as new File(getContext().getFilesDir(), s).

Second, I think that you are assuming the existence of a raw/ directory in getFilesDir(). Unless you create that directory, it will not exist.

Third, I think that you are thinking that raw resources are files on the device. They are not. They are files on your development machine. They are just entries in the APK file on the device.

So, to make this work, you need to add code to:

Create a raw/ subdirectory off of getFilesDir()

Use openRawResource() on a Resources object to copy the resource to a file in that newly-created raw/ subdirectory

Use that File object from the preceding step with FileProvider.getUriForFile()

Body:
I have included two PDFs that I want to open from my app. They should open with whatever PDF viewer the user has installed. I placed the PDFs in /res/raw. I used this code:

File file = new File(getContext().getFilesDir().getPath(), s);
            Uri pdfUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

My filepaths.xml looks like this:

<paths>
<files-path path="raw/" name="raw" />

I'm getting an error that says:

java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.dsv2019.pvt15.prepapp/files/hjartlugnraddning.pdf

Why is this happening?


问:
Most 'functional' way to sum pairs of elements from a vector using C++17 or later?
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])
```

<p>In Perl 5 I can peel off pairs with</p>

<pre class="lang-perl prettyprint-override"><code>use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);
</code>```

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }
```

<p>and in R I can wrap the vector into a 2-column array and sum the rows with</p>

<pre class="lang-r prettyprint-override"><code>s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))
</code>```

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}
```

<p>The output of course should be some variant of </p>

```3
7
11
15
19
```

答:
Using range-v3:

```<code>for (auto v : view::iota(1, 11) | view::chunk(2)) {
    std::cout << v[0] + v[1] << '\n';
}
</code>```

Note that chunk(2) doesn't give you a compile-time-fixed size view, so you can't do:

```<code>for (auto [x,y] : view::iota(1, 11) | view::chunk(2)) { ... }
</code>```

Body:
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])

In Perl 5 I can peel off pairs with

use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }

and in R I can wrap the vector into a 2-column array and sum the rows with

s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}

The output of course should be some variant of

3
7
11
15
19

Body:
Using range-v3:

for (auto v : view::iota(1, 11) | view::chunk(2)) {
    std::cout << v[0] + v[1] << '\n';
}

Note that chunk(2) doesn't give you a compile-time-fixed size view, so you can't do:

for (auto [x,y] : view::iota(1, 11) | view::chunk(2)) { ... }


问:
Background of items change incorrectly. Log show correct values. How to fix it?
I am trying to add a change of the item background color in the adapter recyclerview after selecting the product through multi select, however, after selecting the second and subsequent products, the background color changes incorrectly. The logs show correctly selected products, however the background changes randomly for different products from recyclerview. After disabling the multiselect and simultaneously clearing the list of selected products, the background of randomly selected items continues to change.

...

```<code>   @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        ...

        if (dayOfNotification.after(expirationDateDt))
            viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_expired_products));
        if (multiSelectList.contains(productList.get(position))) {
            viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_selected));
            Log.d(String.valueOf(productList.get(position).getId()), productList.get(position).getName());
        }
</code>```

...

I want to change background colors of only selected products.

答:
For your condition in onBindViewHolder method, you have to set background if-else both cases. Check here...

```<code>if (dayOfNotification.after(expirationDateDt)){
             viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_expired_products));
    }
else{
  viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_not_expired_products));
          //for not expired item color as background_not_expired_products
 }
if (multiSelectList.contains(productList.get(position))) {
                viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_selected));
 Log.d(String.valueOf(productList.get(position).getId()), productList.get(position).getName());
            }
else{
    viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_not_selected));
    //say background_product_not_selected as your color for not selected item

    }
</code>```

Body:
I am trying to add a change of the item background color in the adapter recyclerview after selecting the product through multi select, however, after selecting the second and subsequent products, the background color changes incorrectly. The logs show correctly selected products, however the background changes randomly for different products from recyclerview. After disabling the multiselect and simultaneously clearing the list of selected products, the background of randomly selected items continues to change.

...

   @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        ...

        if (dayOfNotification.after(expirationDateDt))
            viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_expired_products));
        if (multiSelectList.contains(productList.get(position))) {
            viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_selected));
            Log.d(String.valueOf(productList.get(position).getId()), productList.get(position).getName());
        }

...

I want to change background colors of only selected products.

Body:
For your condition in onBindViewHolder method, you have to set background if-else both cases. Check here...

if (dayOfNotification.after(expirationDateDt)){
             viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_expired_products));
    }
else{
  viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_not_expired_products));
          //for not expired item color as background_not_expired_products
 }
if (multiSelectList.contains(productList.get(position))) {
                viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_selected));
 Log.d(String.valueOf(productList.get(position).getId()), productList.get(position).getName());
            }
else{
    viewHolder.itemView.setBackgroundColor(resources.getColor(R.color.background_product_not_selected));
    //say background_product_not_selected as your color for not selected item

    }


问:
Returning non-NaN values when calling df.X in pandas
This is a rather specific follow up to this question on creating pandas dataframes when entries have different lengths.

I have a dataset where I have:

general environmental variables that apply to the whole problem (e.g. avg precipitation)

values at, say, specific depth (e.g. average amount of water at any depth after rainfall)

so my data looks like

d = dict{'depth': [1,2,3], 'var1',[.01,.009,.002],'globalvar',[2.5]}
df = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ]))

>>
 depth  globalvar   var1
0   1   2.5     0.010
1   2   NaN     0.009
2   3   NaN     0.002

```

Is there a way to call globalvar, e.g. df.globalvar without calling df.globalvar[1]? Is there a more pythonic way to do this?

答:
You can do with stack

```<code>df.stack().loc[pd.IndexSlice[:,'globalvar']]
Out[445]:
0    2.5
dtype: float64
</code>```

Or dropna

```<code>df.globalvar.dropna()
</code>```

Body:
This is a rather specific follow up to this question on creating pandas dataframes when entries have different lengths.

I have a dataset where I have:

general environmental variables that apply to the whole problem (e.g. avg precipitation)

values at, say, specific depth (e.g. average amount of water at any depth after rainfall)

so my data looks like

d = dict{'depth': [1,2,3], 'var1',[.01,.009,.002],'globalvar',[2.5]}
df = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ]))

>>
 depth  globalvar   var1
0   1   2.5     0.010
1   2   NaN     0.009
2   3   NaN     0.002

Is there a way to call globalvar, e.g. df.globalvar without calling df.globalvar[1]? Is there a more pythonic way to do this?

Body:
You can do with stack

df.stack().loc[pd.IndexSlice[:,'globalvar']]
Out[445]:
0    2.5
dtype: float64

Or dropna

df.globalvar.dropna()


问:
Create a cursor adapter to display more items than in cursor itself

Possible Duplicate:

  Android: custom separator (or even item) in ListView depening on content of item

I've got a cursor from database query. Imagine it contains N items. Each of these items are of the same view type, but they differ in some cursor's field value (let's name it a data type).

I want to draw a list view with the following content (drawing a some "separator" before each of data type group).

```<code>--DataType1---------
Item1
Item2
--DataType2---------
Item3
--DataType3---------
Item4
Item5
</code>```

The problem is what i have only 5 rows in cursor but need to draw 8 items in ListView (3 of one view type - a separator, and 5 of another view type).

Is there an ability to do this?

P.S. I know how to implement custom adapter, i know what getItemViewType and getViewTypeCount is for.

答:
I believe this is a duplicate, answered here.

I also do something similar in my public domain Dhammapada app, in HeadingAdapter.java.

Body:
Possible Duplicate:

  Android: custom separator (or even item) in ListView depening on content of item

I've got a cursor from database query. Imagine it contains N items. Each of these items are of the same view type, but they differ in some cursor's field value (let's name it a data type).

I want to draw a list view with the following content (drawing a some "separator" before each of data type group).

--DataType1---------
Item1
Item2
--DataType2---------
Item3
--DataType3---------
Item4
Item5

The problem is what i have only 5 rows in cursor but need to draw 8 items in ListView (3 of one view type - a separator, and 5 of another view type).

Is there an ability to do this?

P.S. I know how to implement custom adapter, i know what getItemViewType and getViewTypeCount is for.


问:
Does memory allocation and initialisation take place separatelty during compile time and runtime?
When we declare a variable, say an int, I would like to know the steps involved during the memory allocation and initialisation. and also for a pointer

```<code>int x = 5;
</code>```

now during compile time, 4-bytes is allocated to the integer x. but when does the memory gets filled with the value 5? does the initialisation take place during compilation or runtime execution.
similarly, consider

```<code>int x = 5;
int* p = &x;
</code>```

in these 2 lines what is process of allocation and initialisation.

答:
Variables initialization depends on the kind of variables. Global or static variables are initialised at compile time, while automatic variables are entirely managed at run time.

Global variables

At compile time, the value of all global variables is known. These values are written by the compiler to specific sections of an object file.

At link time, all the object files are gathered and memory locations are determined for each variable. This allows to know the address of every variable, in case one of these addresses is assigned to another variable.

As a result, an executable file is generated that contains a description of the content of every section ( text, data, rodata, etc). In the data or rodata section, are written the values of all initialized global variables.

at run time, the loader reads the description of the different sections and asks to the OS memory. It then will copy the content of all sections to their respective memory locations.

This is the way variable are initialised with a value determined at compile or link time.

The only exception is for variables that are initialized at zero (or not initialized). They are located in a special section (frequently named bss). To reduce the size of executable files, these zero values are not written in the executable. Instead, before executing main(), a runtime procedure will memset to zero all the content of the bss section.

Automatic variables

The procedure is completely different. One does not know the location of these variable before the program runs and the only way is to compute their values by machine instructions.

So the compiler first determines if theses vars will be located in register or memory, and when entering the function, the first instructions will be to reserve stack space for local variables and to initialize their values. This is done by means of regular machine instructions.

In case the value is the address of another variable (say y=&x),

* if x is a local (automatic) variable, the address will be computed by writing to y the sum of the content of the stack pointer register and a given offset determined by the compiler

* if x is a global or static variable, at link time, once the addresses of global variables are known, the linker modifies the instructions generated by the compiler to write the proper address in the register or stack location used to represent y.

Body:
When we declare a variable, say an int, I would like to know the steps involved during the memory allocation and initialisation. and also for a pointer

int x = 5;

now during compile time, 4-bytes is allocated to the integer x. but when does the memory gets filled with the value 5? does the initialisation take place during compilation or runtime execution.
similarly, consider

int x = 5;
int* p = &x;

in these 2 lines what is process of allocation and initialisation.


问:
how to create a function that gives a prime number + bool value?
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

```<code>func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))
</code>```

expected output:

```<code>print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false
</code>```

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

答:
You can use map or reduce(into:_:) methods to generate the primeList array of tuples.

Using reduce(into:_:)

```<code>func primeList(maxP:Int) -> [(num1:Int, num2:Bool)] {
    return (1...maxP).reduce(into: [(num1:Int, num2:Bool)](), { $0.append((num1:$1, num2:primecheck(number:$1))) })
}
</code>```

And you don't need to check till n-1 for finding whether a number is prime or not. You can check till the square root of n

```<code>func primecheck(number: Int) -> Bool {
    if number < 2 { return false }
    if 2...3 ~= number { return true }
    return !(2...Int(sqrt(Double(number)))).contains { number % $0 == 0 }
}
</code>```

Body:
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))

expected output:

print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Body:
You can use map or reduce(into:_:) methods to generate the primeList array of tuples.

Using reduce(into:_:)

func primeList(maxP:Int) -> [(num1:Int, num2:Bool)] {
    return (1...maxP).reduce(into: [(num1:Int, num2:Bool)](), { $0.append((num1:$1, num2:primecheck(number:$1))) })
}

And you don't need to check till n-1 for finding whether a number is prime or not. You can check till the square root of n

func primecheck(number: Int) -> Bool {
    if number < 2 { return false }
    if 2...3 ~= number { return true }
    return !(2...Int(sqrt(Double(number)))).contains { number % $0 == 0 }
}


问:
"DeferCommit was set to false for this upload session" Error
I am trying to implement Upload large files with an upload session.

For now I have (getting the upload session):

```<code>UploadSession uploadSession = await graphClient
    .Users["user3@myComp.onmicrosoft.com"]
    .Drive
    .Root
    .ItemWithPath(@"\someFolder\file.txt")
    .CreateUploadSession()
    .Request()
    .PostAsync();
</code>```

The response from this request is some session URL but when I upload the file chunk to this URL I'm getting an error:

```<code>{
  "error": {
    "code": "invalidRequest",
    "message": "DeferCommit was set to false for this upload session."
  }
}
</code>```

Does anyone know what causes this error?

答: Without seeing how the request to upload the bytes was made I'm left to guess a little - but I believe the issue is that you used a POST instead of a PUT. The session URL returned needs to have PUT requests made to it, with appropriate Content-Range headers, in order to upload and commit the data.

Body:
I am trying to implement Upload large files with an upload session.

For now I have (getting the upload session):

UploadSession uploadSession = await graphClient
    .Users["user3@myComp.onmicrosoft.com"]
    .Drive
    .Root
    .ItemWithPath(@"\someFolder\file.txt")
    .CreateUploadSession()
    .Request()
    .PostAsync();

The response from this request is some session URL but when I upload the file chunk to this URL I'm getting an error:

{
  "error": {
    "code": "invalidRequest",
    "message": "DeferCommit was set to false for this upload session."
  }
}

Does anyone know what causes this error?


答:
You could use fct_collapse with grep / regex and adjust the regex pattern as needed:

```<code>dat %>%
  mutate(Ethnicity = fct_collapse(Ethnicity,
                                  "1" = unique(grep("^1", Ethnicity, value = T)))) %>%
  count(Ethnicity)

# A tibble: 4 x 2
  Ethnicity     n
  <fct>     <int>
1 1            11
2 2             1
3 3             1
4 4             1
</code>```

Or, this feels a little hackish, but you could always use ifelse or case_when:

```<code>dat %>%
  mutate(Ethnicity = factor(ifelse(startsWith(as.character(Ethnicity), "1"), 1, Ethnicity))) %>%
  count(Ethnicity)

# A tibble: 4 x 2
  Ethnicity     n
  <fct>     <int>
1 1            11
2 2             1
3 3             1
4 4             1
</code>```

Title: Automatic refactoring based on levels beginning with a certain character?

Body:
You could use fct_collapse with grep / regex and adjust the regex pattern as needed:

dat %>%
  mutate(Ethnicity = fct_collapse(Ethnicity,
                                  "1" = unique(grep("^1", Ethnicity, value = T)))) %>%
  count(Ethnicity)

# A tibble: 4 x 2
  Ethnicity     n
  <fct>     <int>
1 1            11
2 2             1
3 3             1
4 4             1

Or, this feels a little hackish, but you could always use ifelse or case_when:

dat %>%
  mutate(Ethnicity = factor(ifelse(startsWith(as.character(Ethnicity), "1"), 1, Ethnicity))) %>%
  count(Ethnicity)

# A tibble: 4 x 2
  Ethnicity     n
  <fct>     <int>
1 1            11
2 2             1
3 3             1
4 4             1


问:
Change cursor style depending on sort or not
I'm using the jqGrid and have 3 columns that can NOT be sorted.  At this point the cursor changes to a hand when the user hovers over the headers regardless of sorting set to true or false.  I'd like that cursor to be something other than a hand (text or pointer) on those column heads.  It's confusing to the users this way. Is this something that can be set?

Thanks,
Mark

答:
Welcome to SO.

Absolutely.  CSS:

```<code>th.unsortableclass {
cursor: default;
}
</code>```

Now apply that class to your column headers that aren't sortable.

Body:
Welcome to SO.

Absolutely.  CSS:

th.unsortableclass {
cursor: default;
}

Now apply that class to your column headers that aren't sortable.


问:
Spreadsheet - Conditional formatting cells based on other cells
Conditional formatting a cell is simple enough. It's also simple enough to conditionally format a single cell based on another single cell. What I'm not sure about is doing it for many cells in such a way that I don't have to format each individual cell. For example:

Suppose the cells in column A either have a string, or are blank. How can I set conditional formatting on the cells in column B, such that the formatting is only applied if the A column cell on the same row (ie, the adjacent cell) is blank?

So far, I've been working around this issue by wrapping the formulas of the cells in B with IF(ISBLANK(A1),0,"FORMULA"), then applying conditional formatting to the B cells based on whether the cell values equal 0. Is there a better solution than this?

答:
Yes, in my opinion. For LibreOffice Calc select ColumnB, Format > Conditional Formatting..., choose Formula is and enter:

```<code>A1=""
</code>```

then a style of your choice and OK.

You might want to reduce the upper limit of Cell Range.

Body:
Yes, in my opinion. For LibreOffice Calc select ColumnB, Format > Conditional Formatting..., choose Formula is and enter:

A1=""

then a style of your choice and OK.

You might want to reduce the upper limit of Cell Range.


问:
How can I make the button clickable on a semi-transparent path geometry which passes all mouse events through?
I need to control behind semi-transparent background with mouse.
In detail, my app fills up the whole screen with semi-transparent background and it has got a button on it.
I wanted to be able to click on any parts behind the semi-transparent background and the solution for this I found is this:
How to create a semi transparent window in WPF that allows mouse events to pass through

With this solution, I was able to click and do everything with mouse behind the background but unfortunately, I cannot click on that button anymore because the button also passed the mouse events through itself.

How can I make the button clickable?
Any help would be appreciated.
You can try the example app on the provided link above.
Thanks

答:
I managed to solve the problem myself.
The solution was mouse hook.
Perhaps, @montonero's idea is right.
When mouse is over the desired region, I removed WS_EX_TRANSPARENT.</p>