问:
What kind of Twiml XML does Twilio need for a basic two-way call?
I'm a new developer and am researching implementing Twilio into my companies application. In researching and working with Twilio's Voice  API I've gotten the basic programmable voice running as seen below.

I know the URL contains the basic TWIML demo instructions for what Twilio should do with the call, my question is what if I just want a regular two-way call? No programmable voice or automated response just two people talking until one hangs up. Is that even possible with Twilio? Thanks in advance.

```<code>    client.calls
      .create({
         url: 'http://demo.twilio.com/docs/voice.xml',
         to: `+1${req.body.to}`,
         from: `+1${req.body.from}`
       })
      .then(call => {
          console.log(call.sid);
        }).catch(next)
};
</code>```

答:
In your example, when the recipient answers the call, the code at url: 'http://demo.twilio.com/docs/voice.xml' will run. That's some generic TwiML provided by Twilio.

You'll need to change that to either your webhook (hosted on your server) or with a TwiML Bin (hosted at Twilio)  (https://www.twilio.com/console/runtime/twiml-bins).

To connect two or more people you could put them in a conference if you respond with XML (TwiML) like so:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial>
    <Conference>Room 1234</Conference>
  </Dial>
</Response>

```

<p>For two people you would run your Node.js code twice changing the <code>to:</code> phone number for each recipient. </p>

<hr/>

<p>Docs:</p>

<p>https://www.twilio.com/docs/voice/twiml/conference</p>

<p>https://www.twilio.com/docs/voice/api/conference</p>

<p><hr />
Also, experiment with this, instead of the "conference" TwiML return a "dial" TwiML like this:</p>

<pre class="lang-xml prettyprint-override"><code>
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>415-123-4567</Dial>
</Response>

</code>```

where 415-123-4567 is the number for the second person.

Body:
I'm a new developer and am researching implementing Twilio into my companies application. In researching and working with Twilio's Voice  API I've gotten the basic programmable voice running as seen below.

I know the URL contains the basic TWIML demo instructions for what Twilio should do with the call, my question is what if I just want a regular two-way call? No programmable voice or automated response just two people talking until one hangs up. Is that even possible with Twilio? Thanks in advance.

    client.calls
      .create({
         url: 'http://demo.twilio.com/docs/voice.xml',
         to: `+1${req.body.to}`,
         from: `+1${req.body.from}`
       })
      .then(call => {
          console.log(call.sid);
        }).catch(next)
};

Body:
In your example, when the recipient answers the call, the code at url: 'http://demo.twilio.com/docs/voice.xml' will run. That's some generic TwiML provided by Twilio.

You'll need to change that to either your webhook (hosted on your server) or with a TwiML Bin (hosted at Twilio)  (https://www.twilio.com/console/runtime/twiml-bins).

To connect two or more people you could put them in a conference if you respond with XML (TwiML) like so:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial>
    <Conference>Room 1234</Conference>
  </Dial>
</Response>

For two people you would run your Node.js code twice changing the to: phone number for each recipient.

Docs:

https://www.twilio.com/docs/voice/twiml/conference

https://www.twilio.com/docs/voice/api/conference

Also, experiment with this, instead of the "conference" TwiML return a "dial" TwiML like this:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>415-123-4567</Dial>
</Response>

where 415-123-4567 is the number for the second person.


来源: stackexchange

问:
XML serialization in JSON without excessive escaping

How to avoid solidus and double quote escaping of XML in JSON?

Given that

solidus characters (aka forward slash, /) may, but need not, be
escaped in JSON, and that

XML attributes may use ' rather than " to avoid escaping in JSON string values,

what's the best way to realize these potential serialization improvements in XSLT?

This XML,

```<code><?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <array key="o_array">
    <map>
      <string key="s/1">x/y/z</string>
    </map>
    <map>
      <string key="s2"><![CDATA[<a href="/x/y">Link</a> a/b "test"]]></string>
    </map>
  </array>
</map>
</code>```

input to this XSLT,

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
  <xsl:output method="text"/>
  <xsl:template match="/">
    <xsl:value-of select="xml-to-json(.,map{'indent':true()})"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

yields (via Saxon, XSLT Fiddle demo) this JSON output:

```<code>{ "o_array" :
  [
    { "s\/1" : "x\/y\/z" },

    { "s2" : "<a href=\"\/x\/y\">Link<\/a> a\/b \"test\"" } ] }
</code>```

For purposes of aesthetics (above JSON is unnecessarily ugly) and minimizing file size (after also disabling indentation), I would like to be generating the following JSON instead:

```<code>{ "o_array" :
  [
    { "s/1" : "x/y/z" },

    { "s2" : "<a href='/x/y'>Link</a> a/b \"test\"" } ] }
</code>```

Notes:

Single quotes: A Saxon-specific serialization option, saxon:single-quotes, seems tantalizing close to helping, but how to use this option with xml-to-json() is unclear to me.

Solidus: An XSLT serialization option, map{'method': 'json', 'use-character-maps': map{ '/': '/' }} as described by Martin Honnen, seems tantalizing close to helping, but, again, how to use this option with xml-to-json() escapes (ha) me.

string/@escape and string/@escape-key attributes, per my reading of the spec and confirmed via experimentation, cannot help here.

答:
The linked suggestion with a character map can only be used if you are willing to introduce a parse-json() => serialize(...) step:

```<code>. => xml-to-json() => parse-json() => serialize(map { 'method' : 'json', 'use-character-maps' : map { '/' : '/' } })
</code>```

That way, with

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
      <xsl:value-of select=". => xml-to-json() => parse-json() => serialize(map { 'method' : 'json', 'use-character-maps' : map { '/' : '/' } })"/>
  </xsl:template>

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

at https://xsltfiddle.liberty-development.net/b4GWVd/25 I get

```<code>{"o_array":[{"s/1":"x/y/z"},{"s2":"<a href=\"/x/y\">Link</a> a/b \"test\""}]}
</code>```

To insert the Saxon specific serialization parameter on string values that are XML fragments I think you could try to run the input first through a mode that simply does another parsing and serialization step, only this time as

```<code>. => parse-xml-fragment() => serialize(map {
                        'method': 'xml',
                        QName('http://saxon.sf.net/', 'single-quotes'): true()
                    })
</code>```

With Saxon 9.9 EE in oXygen and

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:value-of
            select="
                $single-quotes => xml-to-json() => parse-json() => serialize(map {
                    'method': 'json',
                    'use-character-maps': map {'/': '/'}
                })"
        />
    </xsl:template>

    <xsl:variable name="single-quotes">
        <xsl:apply-templates mode="serialize-fragments"/>
    </xsl:variable>

    <xsl:mode name="serialize-fragments" on-no-match="shallow-copy"/>

    <xsl:template match="string" mode="serialize-fragments"
        xpath-default-namespace="http://www.w3.org/2005/xpath-functions">
        <xsl:copy>
            <xsl:apply-templates select="@*" mode="#current"/>
            <xsl:try
                select="
                    . => parse-xml-fragment() => serialize(map {
                        'method': 'xml',
                        QName('http://saxon.sf.net/', 'single-quotes'): true()
                    })">
                <xsl:catch select="string()"/>
            </xsl:try>
        </xsl:copy>
    </xsl:template>

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

I get

```<code>{"o_array":[{"s/1":"x/y/z"},{"s2":"<a href='/x/y'>Link</a> a/b \"test\""}]}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to avoid solidus and double quote escaping of XML in JSON?

Given that

solidus characters (aka forward slash, /) may, but need not, be
escaped in JSON, and that

XML attributes may use ' rather than " to avoid escaping in JSON string values,

what's the best way to realize these potential serialization improvements in XSLT?

This XML,

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <array key="o_array">
    <map>
      <string key="s/1">x/y/z</string>
    </map>
    <map>
      <string key="s2"><![CDATA[Link a/b "test"]]></string>
    </map>
  </array>
</map>

input to this XSLT,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
  <xsl:output method="text"/>
  <xsl:template match="/">
    <xsl:value-of select="xml-to-json(.,map{'indent':true()})"/>
  </xsl:template>
</xsl:stylesheet>

yields (via Saxon, XSLT Fiddle demo) this JSON output:

{ "o_array" :
  [
    { "s\/1" : "x\/y\/z" },

    { "s2" : "Link<\/a> a\/b \"test\"" } ] }

For purposes of aesthetics (above JSON is unnecessarily ugly) and minimizing file size (after also disabling indentation), I would like to be generating the following JSON instead:

{ "o_array" :
  [
    { "s/1" : "x/y/z" },

    { "s2" : "Link a/b \"test\"" } ] }

Notes:

Single quotes: A Saxon-specific serialization option, saxon:single-quotes, seems tantalizing close to helping, but how to use this option with xml-to-json() is unclear to me.

Solidus: An XSLT serialization option, map{'method': 'json', 'use-character-maps': map{ '/': '/' }} as described by Martin Honnen, seems tantalizing close to helping, but, again, how to use this option with xml-to-json() escapes (ha) me.

string/@escape and string/@escape-key attributes, per my reading of the spec and confirmed via experimentation, cannot help here.

Body:
The linked suggestion with a character map can only be used if you are willing to introduce a parse-json() => serialize(...) step:

. => xml-to-json() => parse-json() => serialize(map { 'method' : 'json', 'use-character-maps' : map { '/' : '/' } })

That way, with

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
      <xsl:value-of select=". => xml-to-json() => parse-json() => serialize(map { 'method' : 'json', 'use-character-maps' : map { '/' : '/' } })"/>
  </xsl:template>

</xsl:stylesheet>

at https://xsltfiddle.liberty-development.net/b4GWVd/25 I get

{"o_array":[{"s/1":"x/y/z"},{"s2":"<a href=\"/x/y\">Link</a> a/b \"test\""}]}

To insert the Saxon specific serialization parameter on string values that are XML fragments I think you could try to run the input first through a mode that simply does another parsing and serialization step, only this time as

. => parse-xml-fragment() => serialize(map {
                        'method': 'xml',
                        QName('http://saxon.sf.net/', 'single-quotes'): true()
                    })

With Saxon 9.9 EE in oXygen and

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:value-of
            select="
                $single-quotes => xml-to-json() => parse-json() => serialize(map {
                    'method': 'json',
                    'use-character-maps': map {'/': '/'}
                })"
        />
    </xsl:template>

    <xsl:variable name="single-quotes">
        <xsl:apply-templates mode="serialize-fragments"/>
    </xsl:variable>

    <xsl:mode name="serialize-fragments" on-no-match="shallow-copy"/>

    <xsl:template match="string" mode="serialize-fragments"
        xpath-default-namespace="http://www.w3.org/2005/xpath-functions">
        <xsl:copy>
            <xsl:apply-templates select="@*" mode="#current"/>
            <xsl:try
                select="
                    . => parse-xml-fragment() => serialize(map {
                        'method': 'xml',
                        QName('http://saxon.sf.net/', 'single-quotes'): true()
                    })">
                <xsl:catch select="string()"/>
            </xsl:try>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

I get

{"o_array":[{"s/1":"x/y/z"},{"s2":"<a href='/x/y'>Link</a> a/b \"test\""}]}


问:
Joining to tables/columns specified by query results
Maybe I am not searching the correct terms, because I found no other questions/answers re: this.

Is it possible to join to a table/column designated in the results from a query? I have a query with objects that are designated in other tables, and I can create a table of all tables/columns.

Example

Table_1

```<code>        Col1        Col2        Col3
        999         HTML        001
        998         HTML        002
        997         CSS         001
        996         CSS         002
        995         CSS         003
        994         C#          001
</code>```

Table_2 - Table of Tables/Columns

```<code>        Col1        Col2        Col3
        HTML        T_HTML      C_HTML_ID
        CSS         T_CSS       C_CSS_ID
        C#          T_C#        C_C#_ID
</code>```

Table_3 - T_HTML (but could be T_CSS, T_C#, etc.)

```<code>        C_HTML_ID        Col2
        001              blah
        002              blah
        003              blah

</code>```

Is it then possible to somehow do something like this?

```<code>SELECT
    *
FROM
    table_1
    JOIN table_2
        ON table_2.Col1 = table_1.Col2
    JOIN <<table_2.Col2>>
        ON <<table_2.Col2>>.<<Col3>> = table_1.Col3
</code>```

答:
Join doesn't work that way.
Please see how join works in this https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/ for better understanding.

Body:
Maybe I am not searching the correct terms, because I found no other questions/answers re: this.

Is it possible to join to a table/column designated in the results from a query? I have a query with objects that are designated in other tables, and I can create a table of all tables/columns.

Example

Table_1

        Col1        Col2        Col3
        999         HTML        001
        998         HTML        002
        997         CSS         001
        996         CSS         002
        995         CSS         003
        994         C#          001

Table_2 - Table of Tables/Columns

        Col1        Col2        Col3
        HTML        T_HTML      C_HTML_ID
        CSS         T_CSS       C_CSS_ID
        C#          T_C#        C_C#_ID

Table_3 - T_HTML (but could be T_CSS, T_C#, etc.)

        C_HTML_ID        Col2
        001              blah
        002              blah
        003              blah

Is it then possible to somehow do something like this?

SELECT
    *
FROM
    table_1
    JOIN table_2
        ON table_2.Col1 = table_1.Col2
    JOIN <<table_2.Col2>>
        ON <<table_2.Col2>>.<<Col3>> = table_1.Col3


问:
How do I dismiss a rootViewController before presenting a new UITabBarController?
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

```<code>window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()
</code>```

LoginController()

```<code>self.present(MainTabBarController(), animated: true, completion: nil)
</code>```

答:
It's too easy to maintain condition for user logged in or not, and then based on that status. You can navigate to your view.

You can try this way :

1.In AppDelegate you can these methods.

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let isLogin = UserDefaults.standard.bool(forKey: "IS_LOGIN")
    if isLogin == true {
        self.goToDashboardView()
    } else {
        self.goToLoginView()
    }
    return true
}

//MARK:- ------- Global Methods -------

class func sharedInstance() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

func goToLoginView() {

    let sb = UIStoryboard.init(name: "Main", bundle: nil)
    let loginVC = sb.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    let navVC = UINavigationController(rootViewController: loginVC) // You can skip this if you do not want to add navigation bar
    self.window?.rootViewController = navVC // if you skipped above line, then you have to assign 'loginVC' here.
    self.window?.makeKeyAndVisible()
}

func goToDashboardView() {

    let sb = UIStoryboard.init(name: "Main", bundle: nil)
    let tabbarVC = sb.instantiateViewController(withIdentifier: "MyTabBarController") as! MyTabBarController
    self).window?.rootViewController = tabbarVC // if you skipped above line, then you have to assign 'loginVC' here.
    self.window?.makeKeyAndVisible()
}
</code>```

2.In LoginViewController, when user logged in successfully.

```<code>@IBAction func btnLoginClicked(_ sender: UIButton) {

    // Your API call or other code
    // If all things goes well, then login and go to dashboard

    UserDefaults.standard.set(true, forKey: "IS_LOGIN")
    AppDelegate.sharedInstance().goToDashboardView()
}
</code>```

3.And finally, whenever and from wherever you want to log out from app, just call below code.

```<code>@IBAction func btnLogOutClicked(_ sender: UIButton) {

    // Your API call or other code
    // If all things goes well, then logout and go to login view

    UserDefaults.standard.set(false, forKey: "IS_LOGIN")
    AppDelegate.sharedInstance().goToLoginView()
}
</code>```

4.And Main.storyboard should have design something like :

Body:
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()

LoginController()

self.present(MainTabBarController(), animated: true, completion: nil)

Body:
It's too easy to maintain condition for user logged in or not, and then based on that status. You can navigate to your view.

You can try this way :

1.In AppDelegate you can these methods.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let isLogin = UserDefaults.standard.bool(forKey: "IS_LOGIN")
    if isLogin == true {
        self.goToDashboardView()
    } else {
        self.goToLoginView()
    }
    return true
}

//MARK:- ------- Global Methods -------

class func sharedInstance() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

func goToLoginView() {

    let sb = UIStoryboard.init(name: "Main", bundle: nil)
    let loginVC = sb.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    let navVC = UINavigationController(rootViewController: loginVC) // You can skip this if you do not want to add navigation bar
    self.window?.rootViewController = navVC // if you skipped above line, then you have to assign 'loginVC' here.
    self.window?.makeKeyAndVisible()
}

func goToDashboardView() {

    let sb = UIStoryboard.init(name: "Main", bundle: nil)
    let tabbarVC = sb.instantiateViewController(withIdentifier: "MyTabBarController") as! MyTabBarController
    self).window?.rootViewController = tabbarVC // if you skipped above line, then you have to assign 'loginVC' here.
    self.window?.makeKeyAndVisible()
}

2.In LoginViewController, when user logged in successfully.

@IBAction func btnLoginClicked(_ sender: UIButton) {

    // Your API call or other code
    // If all things goes well, then login and go to dashboard

    UserDefaults.standard.set(true, forKey: "IS_LOGIN")
    AppDelegate.sharedInstance().goToDashboardView()
}

3.And finally, whenever and from wherever you want to log out from app, just call below code.

@IBAction func btnLogOutClicked(_ sender: UIButton) {

    // Your API call or other code
    // If all things goes well, then logout and go to login view

    UserDefaults.standard.set(false, forKey: "IS_LOGIN")
    AppDelegate.sharedInstance().goToLoginView()
}

4.And Main.storyboard should have design something like :


问:
The movie game - skipping "The" at the beginning of a movie
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

```<code>def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()
</code>```

答:
Consider using regular expressions

```<code>import re
a = r'^(\bthe\b)'
sts  = ['the incredibles', 'theodore', 'at the mueseum', 'their words' ]
for i in sts:
    b = re.sub(a,'', i)
    print(b)
</code>```

The regular expression I am using seems to work, but you might want to test more examples, using this link https://regex101.com/r/pX5sD5/3

Body:
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()

Body:
Consider using regular expressions

import re
a = r'^(\bthe\b)'
sts  = ['the incredibles', 'theodore', 'at the mueseum', 'their words' ]
for i in sts:
    b = re.sub(a,'', i)
    print(b)

The regular expression I am using seems to work, but you might want to test more examples, using this link https://regex101.com/r/pX5sD5/3


问:
Prevent duplicate keys in combined objects, reverse of { [K in keyof T]: T[K] }
In typescript I want to create a function which accepts 2 objects, and Object.assigns them to a new object, with type checking that ensures neither object has any of the same keys.

I tried using variaous forms of k in keyof T with no success.

function combine<T extends Object, U extends { [K in keyof T]: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}
```

<p>The results have not resulted in proper type checking</p>

<pre class="lang-js prettyprint-override"><code>// setup objects
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}

//  I need this to only error when properties on test 2 exist in test 1

// should pass
const result = combine(test1, test2)

/* Resulting error:
Argument of type '{ something: string; }' is not assignable to parameter of type '{ test: undefined; }'.
  Property 'test' is missing in type '{ something: string; }' but required in type '{ test: undefined; }'.
 */

// should fail and does fail
const result2 = combine(test1, test3)

/* Resulting error:
Argument of type '{ test: {}; }' is not assignable to parameter of type '{ test: undefined; }'.
  Types of property 'test' are incompatible.
    Type '{}' is not assignable to type 'undefined'.
 */
</code>```

答:
Forcing myself to organize enough to organize a question, gave me an idea, which ended up working. I would love to see if someone has a better way though.

```<code>const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}
function combine<T extends Object, U extends Object & { [K in keyof T]?: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}

//  I need this to only error when properties on test 2 exist in test 1
const result = combine(test1, test2)  // should pass
const result2 = combine(test1, test3) // should fail
</code>```

U extends Object & { [K in keyof T]?: undefined} - extending the Object ended up getting rid of the has no properties in common with type error.

Body:
In typescript I want to create a function which accepts 2 objects, and Object.assigns them to a new object, with type checking that ensures neither object has any of the same keys.

<a href="https://www.typescriptlang.org/play/#src=const%20test1%20%3D%20%7B%20test%3A%201%20%7D%0D%0Aconst%20test2%20%3D%20%7B%20something%3A%20'string'%20%7D%0D%0Aconst%20test3%20%3D%20%7B%20test%3A%20%7B%7D%7D%0D%0Afunction%20combine%3CT%20extends%20Object%2C%20U%20extends%20%7B%20%5BK%20in%20keyof%20T%5D%3A%20undefined%20%7D%3E(obj1%3A%20T%2C%20obj2%3A%20U)%20%7B%0D%0A%20%20%20%20return%20%7B%0D%0A%20%20%20%20%20%20%20%20...obj1%2C%0D%0A%20%20%20%20%20%20%20%20...obj2%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A%2F%2F%20%20I%20need%20this%20to%20only%20error%20when%20properties%20on%20test%202%20exist%20in%20test%201%0D%0Aconst%20result%20%3D%20combine(test1%2C%20test2)%20%20%2F%2F%20should%20pass%0D%0Aconst%20result2%20%3D%20combine(test1%2C%20test3)%20%2F%2F%20should%20fail" rel="nofollow noreferrer">I tried using variaous forms of k in keyof T with no success.

function combine<T extends Object, U extends { [K in keyof T]: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}

The results have not resulted in proper type checking

// setup objects
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}

//  I need this to only error when properties on test 2 exist in test 1

// should pass
const result = combine(test1, test2)

/* Resulting error:
Argument of type '{ something: string; }' is not assignable to parameter of type '{ test: undefined; }'.
  Property 'test' is missing in type '{ something: string; }' but required in type '{ test: undefined; }'.
 */

// should fail and does fail
const result2 = combine(test1, test3)

/* Resulting error:
Argument of type '{ test: {}; }' is not assignable to parameter of type '{ test: undefined; }'.
  Types of property 'test' are incompatible.
    Type '{}' is not assignable to type 'undefined'.
 */

Body:
Forcing myself to organize enough to organize a question, <a href="https://www.typescriptlang.org/play/#src=const%20test1%20%3D%20%7B%20test%3A%201%20%7D%0D%0Aconst%20test2%20%3D%20%7B%20something%3A%20'string'%20%7D%0D%0Aconst%20test3%20%3D%20%7B%20test%3A%20%7B%7D%7D%0D%0Afunction%20combine%3CT%20extends%20Object%2C%20U%20extends%20Object%20%26%20%7B%20%5BK%20in%20keyof%20T%5D%3F%3A%20undefined%20%7D%3E(obj1%3A%20T%2C%20obj2%3A%20U)%20%7B%0D%0A%20%20%20%20return%20%7B%0D%0A%20%20%20%20%20%20%20%20...obj1%2C%0D%0A%20%20%20%20%20%20%20%20...obj2%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A%2F%2F%20%20I%20need%20this%20to%20only%20error%20when%20properties%20on%20test%202%20exist%20in%20test%201%0D%0Aconst%20result%20%3D%20combine(test1%2C%20test2)%20%20%2F%2F%20should%20pass%0D%0Aconst%20result2%20%3D%20combine(test1%2C%20test3)%20%2F%2F%20should%20fail" rel="nofollow noreferrer">gave me an idea, which ended up working. I would love to see if someone has a better way though.

const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}
function combine<T extends Object, U extends Object & { [K in keyof T]?: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}

//  I need this to only error when properties on test 2 exist in test 1
const result = combine(test1, test2)  // should pass
const result2 = combine(test1, test3) // should fail

U extends Object & { [K in keyof T]?: undefined} - extending the Object ended up getting rid of the has no properties in common with type error.


问:
ReactJS vs NodeJS - Why do I need to create both?
I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.

For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.

I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.

How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.

答:
NodeJS is just a runtime that allows you to run javascript code outside of the browser.

In order to compile and transpile the react JS app, they use webpack and other tools which runs over NodeJS.


问:
Getting error in my first flutter app while trying to run
I just tried to run my first hello world app with flutter. But its showing error when emulator selected and run clicked.

Here is my code:

```<code>import "package:flutter/material.dart";

void main()
{
  runApp(

      Center(child:Text("Hello world!", textDirection: TextDirection.ltr) ,)
  );
}
</code>```

and the error i get:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> org/apache/commons/codec/binary/Base64

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Finished with error: Gradle task assembleDebug failed with exit code 1
</code>```

Whats wrong? how do i solve it?

答:
I followed and tested Your code and I find No issues App works completely fine and no errors at all

Code:

```<code>import "package:flutter/material.dart";

void main() {
  runApp(Center(
    child: Text("Hello world!", textDirection: TextDirection.ltr),
  ));
}

</code>```

You can try troubleshooting Your sdk/app

Try running the command flutter clean

flutter doctor

Hope This works, Add Your Logs so that We can look into the issues after running this commands

Body:
I just tried to run my first hello world app with flutter. But its showing error when emulator selected and run clicked.

Here is my code:

import "package:flutter/material.dart";

void main()
{
  runApp(

      Center(child:Text("Hello world!", textDirection: TextDirection.ltr) ,)
  );
}

and the error i get:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> org/apache/commons/codec/binary/Base64

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Finished with error: Gradle task assembleDebug failed with exit code 1

Whats wrong? how do i solve it?

Body:
I followed and tested Your code and I find No issues App works completely fine and no errors at all

Code:

import "package:flutter/material.dart";

void main() {
  runApp(Center(
    child: Text("Hello world!", textDirection: TextDirection.ltr),
  ));
}

You can try troubleshooting Your sdk/app

Try running the command flutter clean

flutter doctor

Hope This works, Add Your Logs so that We can look into the issues after running this commands


问:
I can't create files or directories in android studio with kotlin
I need to create a text file in my Android app but it won't let me. The method of verifying that it has been created returns me fake. How could I do that?

I already assigned write permissions on the application manifest.xml but it doesn't work for me either.
I also made the request for permissions.

The permissions on manifest.xml I assigned like this:

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

The code to write the file, I did it this way:

```<code>    fun writeFile() {
        if (ContextCompat.checkSelfPermission(this@GenerateCodeActivity,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    PackageManager.PERMISSION_GRANTED)
        }

        val sd_main = File(Environment.getExternalStorageDirectory().absolutePath+"/FilesMyApp")
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
        }
        if (success) {
            val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
            val hola = "HOLA QUE TAL"
            if (!sd.exists()) {
                success = sd.mkdir()
            }
            if (success) {
                // directory exists or already created
                val dest = File(sd, "${this@GenerateCodeActivity.auth.currentUser?.uid}.txt")
                try {
                    // response is the data written to file
                    FileOutputStream(dest).use { it.write(hola.toByteArray()) }
                } catch (e: Exception) {
                    // handle the exception
                }

            } else {
                // directory creation is not successful
            }
        }
    }
</code>```

I want to type the indicated text string, but it won't let me enter the "if (success)" zone.

答:
```<code>val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
</code>```

You have not specified a directory. Use:

```<code>val sd = File(sd_main, "${this@GenerateCodeActivity.auth.currentUser?.uid}")
</code>```

Body:
I need to create a text file in my Android app but it won't let me. The method of verifying that it has been created returns me fake. How could I do that?

I already assigned write permissions on the application manifest.xml but it doesn't work for me either.
I also made the request for permissions.

The permissions on manifest.xml I assigned like this:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

The code to write the file, I did it this way:

    fun writeFile() {
        if (ContextCompat.checkSelfPermission(this@GenerateCodeActivity,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    PackageManager.PERMISSION_GRANTED)
        }

        val sd_main = File(Environment.getExternalStorageDirectory().absolutePath+"/FilesMyApp")
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
        }
        if (success) {
            val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
            val hola = "HOLA QUE TAL"
            if (!sd.exists()) {
                success = sd.mkdir()
            }
            if (success) {
                // directory exists or already created
                val dest = File(sd, "${this@GenerateCodeActivity.auth.currentUser?.uid}.txt")
                try {
                    // response is the data written to file
                    FileOutputStream(dest).use { it.write(hola.toByteArray()) }
                } catch (e: Exception) {
                    // handle the exception
                }

            } else {
                // directory creation is not successful
            }
        }
    }

I want to type the indicated text string, but it won't let me enter the "if (success)" zone.

Body:
val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")

You have not specified a directory. Use:

val sd = File(sd_main, "${this@GenerateCodeActivity.auth.currentUser?.uid}")


问:
From serial to omp: no speedup
I'm new to openMP. I'm working on All Pair Shortest Path Algorithm and here is the serial C++ routine i need to parallelize (complete code at the end of the post):

```<code>void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for ( i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);

}
</code>```

At execution I get this :

```<code>$ time ./floyd

real    0m0,349s
user    0m0,349s
sys     0m0,000s
</code>```

Now, I try to insert some directives:

```<code>void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{

    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for ( i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }

}
</code>```

Unfortunately, there is no speedup:

```<code>$ grep -c ^processor /proc/cpuinfo
4
$ time ./floyd

real    0m0,547s
user    0m2,073s
sys     0m0,004s
</code>```

What am I doing wrong?

EDIT

Processor: Intel(R) Core(TM) i5-4590 CPU (4 hardware cores)

Complete code :

```<code>#include <cstdio>
#include <vector>
#include <limits>
#include <ctime>
#include <random>
#include <set>
#include <omp.h>

using namespace std;

typedef struct Wedge
{
    int a, b;
    double w;
} Wedge;

typedef pair<int, int> edge;

int randrange(int end, int start=0)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(start, end-1);

    return dis(gen);
}

void relax_omp(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for (i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);

    }
}

void relax_serial(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for (i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);
}

void floyd(vector<vector<double>> &dist, bool serial)
{
    size_t i, k;

    size_t n {dist.size()};

    for (k=0; k<n; k++)
    {
        vector<double> rowk =dist[k];
        vector<double> colk(n);

        for (i=0; i<n; i++)
            colk[i]=dist[i][k];
        if (serial)
            relax_serial(dist, n, rowk, colk);
        else
            relax_omp(dist, n, rowk, colk);
    }

    for (i=0; i<n; i++)
        dist[i][i]=0;
}

vector<Wedge> random_edges(int n, double density, double max_weight)
{
    int M{n*(n-1)/2};
    double m{density*M};
    set<edge> edges;
    vector<Wedge> wedges;

    while (edges.size()<m)
    {
        pair<int,int> L;
        L.first=randrange(n);
        L.second=randrange(n);

        if (L.first!=L.second && edges.find(L) == edges.end())
        {
            double w=randrange(max_weight);
            Wedge wedge{L.first, L.second, w};
            wedges.push_back(wedge);
            edges.insert(L);
        }
    }
    return wedges;
}

vector<vector<double>> fill_distances(vector<Wedge> wedges, int n)
{
    double INF = std::numeric_limits<double>::infinity();
    size_t i, m=wedges.size();
    vector<vector<double>> dist(n, vector<double>(n, INF));
    int a, b;
    double w;
    for (i=0; i<m; i++)
    {   a=wedges[i].a;
        b=wedges[i].b;
        w=wedges[i].w;
        dist[a][b]=w;
    }
    return dist;
}

int main (void)
{
    double density{0.33};
    double max_weight{200};
    int n{800};
    bool serial;

    int ntest=10;
    double avge_serial=0, avge_omp=0;

    for (int i=0; i<ntest; i++)
    {
        vector<Wedge> wedges=random_edges(n, density, max_weight);
        vector<vector<double>> dist=fill_distances(wedges, n);
        double dtime;

        dtime = omp_get_wtime();
        serial=true;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_serial+=dtime;

        dtime = omp_get_wtime();
        serial=false;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_omp+=dtime;
    }
    printf("%d tests, n=%d\n", ntest, n);
    printf("Average serial : %.2lf\n", avge_serial/ntest);
    printf("Average openMP : %.2lf\n", avge_omp/ntest);
    return 0;
}
</code>```

output :

```<code>20 tests, n=800
Average serial : 0.31
Average openMP : 0.61
</code>```

command line:

```<code>g++ -std=c++11 -Wall -O2 -Wno-unused-result -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter floyd.cpp -o floyd -lm -fopenmp
</code>```

答:
There could be many reasons for this, the most obvious being that the work load is too small to notice speed up. The initial work load is 300ms. I would suggest enclosing this in a serial outerloop that repeats this work for at least 20 times, then you are starting with a serial time of (300ms * 20) 6 seconds to test with.

The other factor is the availability of parallel cores on the machine you are running this on. If your cpu has one core, multi-threading will cause slowdown due to the cost of thread-switching. 2 logical cores should show some speed up, 2 physical cores may show close to linear speed up.

Using pragma directives alone also does not guarantee that openMP is used. You have to compile using the -fopenmp command line argument to guarantee that the openmp library is linked to your object code.

Edit

Looking at your code now, the factor that controls the amount of work seems to be N rather than the outer loop. The idea of the outer loop was to artificially increase the amount of work within the same timing period but that can't be done here as you are trying to solve a specific problem. You can try parallelizing the nested loop as well but I think N = 800 is too low for parallelization to make a difference.

```<code>#pragma omp parallel for private(j) collapse(2)
</code>```

j needs to be private to each iteration of the outer loop, hence private(j), otherwise j gets shared across all threads, leading to an inaccurate result.

Your loop is executed 640,000 times which is not much for modern CPUs that clock 3GHZ+, try something around N = 5000 which is 25M iterations.

Title: From serial to omp: no speedup

Body:
I'm new to openMP. I'm working on All Pair Shortest Path Algorithm and here is the serial C++ routine i need to parallelize (complete code at the end of the post):

void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for ( i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);

}

At execution I get this :

$ time ./floyd

real    0m0,349s
user    0m0,349s
sys     0m0,000s

Now, I try to insert some directives:

void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{

    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for ( i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }

}

Unfortunately, there is no speedup:

$ grep -c ^processor /proc/cpuinfo
4
$ time ./floyd

real    0m0,547s
user    0m2,073s
sys     0m0,004s

What am I doing wrong?

EDIT

Processor: Intel(R) Core(TM) i5-4590 CPU (4 hardware cores)

Complete code :

#include <cstdio>
#include <vector>
#include <limits>
#include <ctime>
#include <random>
#include <set>
#include <omp.h>

using namespace std;

typedef struct Wedge
{
    int a, b;
    double w;
} Wedge;

typedef pair<int, int> edge;

int randrange(int end, int start=0)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(start, end-1);

    return dis(gen);
}

void relax_omp(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for (i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);

    }
}

void relax_serial(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for (i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);
}

void floyd(vector<vector<double>> &dist, bool serial)
{
    size_t i, k;

    size_t n {dist.size()};

    for (k=0; k<n; k++)
    {
        vector<double> rowk =dist[k];
        vector<double> colk(n);

        for (i=0; i<n; i++)
            colk[i]=dist[i][k];
        if (serial)
            relax_serial(dist, n, rowk, colk);
        else
            relax_omp(dist, n, rowk, colk);
    }

    for (i=0; i<n; i++)
        dist[i][i]=0;
}

vector<Wedge> random_edges(int n, double density, double max_weight)
{
    int M{n*(n-1)/2};
    double m{density*M};
    set<edge> edges;
    vector<Wedge> wedges;

    while (edges.size()<m)
    {
        pair<int,int> L;
        L.first=randrange(n);
        L.second=randrange(n);

        if (L.first!=L.second && edges.find(L) == edges.end())
        {
            double w=randrange(max_weight);
            Wedge wedge{L.first, L.second, w};
            wedges.push_back(wedge);
            edges.insert(L);
        }
    }
    return wedges;
}

vector<vector<double>> fill_distances(vector<Wedge> wedges, int n)
{
    double INF = std::numeric_limits<double>::infinity();
    size_t i, m=wedges.size();
    vector<vector<double>> dist(n, vector<double>(n, INF));
    int a, b;
    double w;
    for (i=0; i<m; i++)
    {   a=wedges[i].a;
        b=wedges[i].b;
        w=wedges[i].w;
        dist[a][b]=w;
    }
    return dist;
}

int main (void)
{
    double density{0.33};
    double max_weight{200};
    int n{800};
    bool serial;

    int ntest=10;
    double avge_serial=0, avge_omp=0;

    for (int i=0; i<ntest; i++)
    {
        vector<Wedge> wedges=random_edges(n, density, max_weight);
        vector<vector<double>> dist=fill_distances(wedges, n);
        double dtime;

        dtime = omp_get_wtime();
        serial=true;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_serial+=dtime;

        dtime = omp_get_wtime();
        serial=false;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_omp+=dtime;
    }
    printf("%d tests, n=%d\n", ntest, n);
    printf("Average serial : %.2lf\n", avge_serial/ntest);
    printf("Average openMP : %.2lf\n", avge_omp/ntest);
    return 0;
}

output :

20 tests, n=800
Average serial : 0.31
Average openMP : 0.61

command line:

g++ -std=c++11 -Wall -O2 -Wno-unused-result -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter floyd.cpp -o floyd -lm -fopenmp

Body:
There could be many reasons for this, the most obvious being that the work load is too small to notice speed up. The initial work load is 300ms. I would suggest enclosing this in a serial outerloop that repeats this work for at least 20 times, then you are starting with a serial time of (300ms * 20) 6 seconds to test with.

The other factor is the availability of parallel cores on the machine you are running this on. If your cpu has one core, multi-threading will cause slowdown due to the cost of thread-switching. 2 logical cores should show some speed up, 2 physical cores may show close to linear speed up.

Using pragma directives alone also does not guarantee that openMP is used. You have to compile using the -fopenmp command line argument to guarantee that the openmp library is linked to your object code.

Edit

Looking at your code now, the factor that controls the amount of work seems to be N rather than the outer loop. The idea of the outer loop was to artificially increase the amount of work within the same timing period but that can't be done here as you are trying to solve a specific problem. You can try parallelizing the nested loop as well but I think N = 800 is too low for parallelization to make a difference.

#pragma omp parallel for private(j) collapse(2)

j needs to be private to each iteration of the outer loop, hence private(j), otherwise j gets shared across all threads, leading to an inaccurate result.

Your loop is executed 640,000 times which is not much for modern CPUs that clock 3GHZ+, try something around N = 5000 which is 25M iterations.


问:
"smaller or equal" sign in main item for the plot function in r
I would like to use expression or bquote to have the "smaller or equal" (≤) sign in the main of a plot.

Unfortunately my code throughs errors.

Error: unexpected '<=' in "bq.FWGroup<-c(bquote("20cm "~ <="

Could you please help me with this issue.

```<code>FWGroup<-c("20cm <= Length < 30cm, 175g <= Weigth < 225g","20cm <= Length < 30cm, 225g <= Weigth < 275g",
           "30cm <= Length < 40cm, 200g <= Weigth < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")
Köder<-c("lebend","Atrappe")

Versuche<-c(7,3,6,8,6,12,5)
Versuche<-cbind(Versuche,c(3,8,2,1,7,4,9))
Group<-c(1,1,2,1,4,2,3)
#for (i in 1:4)  {
# for (j in 1:2) {
i<-1; j<-1
plot(1:7,Versuche[,1],
     type="n",
     main=paste(FWGroup[i],"Koeder:",Koeder[j],"_______________"))
#bquote:
bq.FWGroup<-c(bquote("20cm "~ <= ~" Length < 30cm, 175g" ~ <= ~ "Weigth < 225g"),bquote("20cm <= Length < 30cm, 225g <= Weigth < 275g"),bquote("30cm <= Length < 40cm, 200g <= Weigth < 250g"),bquote("30cm <= Length < 50cm, 250g <= Weigth <= 300g"))

plot(1:7,Versuche[,1],
     type="n",
     main=paste(bq.FWGroup[i],"Koeder:",Koeder[j],"_______________"))

#exqpression:
ex.FWGroup<-c(paste("20cm ", expression(<=), " Length < 30cm, 175g", expression(<=) , "Weigth < 225g"),"20cm <= Length < 30cm, 225g <= Weigth < 275g","30cm <= Length < 40cm, 200g <= Weigt < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")

ex.FWGroup<-c( expression(paste("20cm ", <=, " Length < 30cm, 175g", <= , "Weigth < 225g")),"20cm <= Length < 30cm, 225g <= Weigth < 275g", "30cm <= Length < 40cm, 200g <= Weigth < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")

plot(1:7,Versuche[,1],
     type="n",
     main=paste(ex.FWGroup[i],"Koeder:",Koeder[j],"_______________"))
#  }
#  }
</code>```

答:
R recognizes Unicode characters so just write the corresponding value in your title.

```<code>plot(iris$Sepal.Width ~ iris$Species, main = "3 \u2264 5")
</code>```

Main Title with ≤

Body:
I would like to use expression or bquote to have the "smaller or equal" (≤) sign in the main of a plot.

Unfortunately my code throughs errors.

Error: unexpected '<=' in "bq.FWGroup<-c(bquote("20cm "~ <="

Could you please help me with this issue.

FWGroup<-c("20cm <= Length < 30cm, 175g <= Weigth < 225g","20cm <= Length < 30cm, 225g <= Weigth < 275g",
           "30cm <= Length < 40cm, 200g <= Weigth < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")
Köder<-c("lebend","Atrappe")

Versuche<-c(7,3,6,8,6,12,5)
Versuche<-cbind(Versuche,c(3,8,2,1,7,4,9))
Group<-c(1,1,2,1,4,2,3)
#for (i in 1:4)  {
# for (j in 1:2) {
i<-1; j<-1
plot(1:7,Versuche[,1],
     type="n",
     main=paste(FWGroup[i],"Koeder:",Koeder[j],"_______________"))
#bquote:
bq.FWGroup<-c(bquote("20cm "~ <= ~" Length < 30cm, 175g" ~ <= ~ "Weigth < 225g"),bquote("20cm <= Length < 30cm, 225g <= Weigth < 275g"),bquote("30cm <= Length < 40cm, 200g <= Weigth < 250g"),bquote("30cm <= Length < 50cm, 250g <= Weigth <= 300g"))

plot(1:7,Versuche[,1],
     type="n",
     main=paste(bq.FWGroup[i],"Koeder:",Koeder[j],"_______________"))

#exqpression:
ex.FWGroup<-c(paste("20cm ", expression(<=), " Length < 30cm, 175g", expression(<=) , "Weigth < 225g"),"20cm <= Length < 30cm, 225g <= Weigth < 275g","30cm <= Length < 40cm, 200g <= Weigt < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")

ex.FWGroup<-c( expression(paste("20cm ", <=, " Length < 30cm, 175g", <= , "Weigth < 225g")),"20cm <= Length < 30cm, 225g <= Weigth < 275g", "30cm <= Length < 40cm, 200g <= Weigth < 250g","30cm <= Length < 50cm, 250g <= Weigth <= 300g")

plot(1:7,Versuche[,1],
     type="n",
     main=paste(ex.FWGroup[i],"Koeder:",Koeder[j],"_______________"))
#  }
#  }

Body:
R recognizes Unicode characters so just write the corresponding value in your title.

plot(iris$Sepal.Width ~ iris$Species, main = "3 \u2264 5")

Main Title with ≤


问:
genetic code and zombies!
In an alien world, the genetic codes of the creatures are in base-4 system(quartenary). The pairs "13" and "22" are considered as genetic disorders. With a genetic code of lenght n, if there are at least n/4 disorders, the creature becomes a zombie!! For example with n=5, the creature with genetic code 01321 has the disorder, but not a zombie while the creature with genetic code 22132 is a zombie( because he has two disorders which is >n/4).

Now I need to write a MATLAB program and get a value n from the user, which is easy, and display the number of creatures and how many of them are zombies

Here is what i've written so far, I can't figure out how to determine the creatures with has genetic codes of a zombie. I'd really appreciate your ideas and help.Thank you

```<code>n=input('Enter the length of the genetic sequence: ');
while (n<4) || (mod(n,1))~=0
disp('Invalid input!')
n=input('Enter the length of the genetic sequence: ');
end
nOfCreatures=4^n;
count=0;
for i=0:nOfCreatures
k=dec2base(i,4);
end
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);
</code>```

答:
I recommended you in my comment to try REGEXP function. But actually STRFIND would suite much better if you want to count overlaps, like count '222' as 2 disorders.

So you need something like this:

```<code>k=dec2base(i,4,n); %# use n to include trailing 0s, just for other possible types of disorders
m = [strfind(k,'13') strfind(k,'22')];
if numel(m) > n/4
    count = count+1;
end
</code>```

In addition, you can do n=0 as the first line instead of duplicating the input line.
And correct for-loop to end at nOfCreatures-1.

EDIT

For the bonus a vectorized solution:

```<code>nOfCreatures=4^n;
k=cellstr(dec2base(0:nOfCreatures-1,4,n));
m = cellfun(@numel,strfind(k,'13')) + cellfun(@numel,strfind(k,'22'));
count = sum(m > n/4);
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);
</code>```

ContentLicense: CC BY-SA 3.0

Title: genetic code and zombies!

Body:
In an alien world, the genetic codes of the creatures are in base-4 system(quartenary). The pairs "13" and "22" are considered as genetic disorders. With a genetic code of lenght n, if there are at least n/4 disorders, the creature becomes a zombie!! For example with n=5, the creature with genetic code 01321 has the disorder, but not a zombie while the creature with genetic code 22132 is a zombie( because he has two disorders which is >n/4).

Now I need to write a MATLAB program and get a value n from the user, which is easy, and display the number of creatures and how many of them are zombies

Here is what i've written so far, I can't figure out how to determine the creatures with has genetic codes of a zombie. I'd really appreciate your ideas and help.Thank you

n=input('Enter the length of the genetic sequence: ');
while (n<4) || (mod(n,1))~=0
disp('Invalid input!')
n=input('Enter the length of the genetic sequence: ');
end
nOfCreatures=4^n;
count=0;
for i=0:nOfCreatures
k=dec2base(i,4);
end
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);

Body:
I recommended you in my comment to try REGEXP function. But actually STRFIND would suite much better if you want to count overlaps, like count '222' as 2 disorders.

So you need something like this:

k=dec2base(i,4,n); %# use n to include trailing 0s, just for other possible types of disorders
m = [strfind(k,'13') strfind(k,'22')];
if numel(m) > n/4
    count = count+1;
end

In addition, you can do n=0 as the first line instead of duplicating the input line.
And correct for-loop to end at nOfCreatures-1.

EDIT

For the bonus a vectorized solution:

nOfCreatures=4^n;
k=cellstr(dec2base(0:nOfCreatures-1,4,n));
m = cellfun(@numel,strfind(k,'13')) + cellfun(@numel,strfind(k,'22'));
count = sum(m > n/4);
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);


问:
PropertyIndex.storeJSON("UserDB") in the same order of Properties or alphabetical order
I have complex PropertyBusinessObjects with lots of Properties.
For my debugging/development purposes, it could be more convenient that the storeJSON method of the PropertyIndex saves the Properties inside the JSON in the same order that I've declared them in the PropertyBusinessObject or, if it's not possible, in alphabetical order.

Currently the Properties are stored in random order, that is fine for the code, but it's not fine for human reading.

How can I do that? Thank you

答: You can't do that but we can. I added a fix that will maintain the natural order of properties: https://github.com/codenameone/CodenameOne/commit/a0a54c7d51ce980710eeecaf91ad4a1253c43e7f</p>


问:
Error when creating S3 bucket policy - Value of property PolicyDocument must be an object
I am trying to create cloudTrail through a serverless application.

```<code>CloudTrail:
  Type: AWS::CloudTrail::Trail
  Properties:
    # CloudWatchLogsLogGroupArn: "String"
    # CloudWatchLogsRoleArn: "String"
    # EnableLogFileValidation: True
    # EventSelectors:
    #   - EventSelector
    # IncludeGlobalServiceEvents: True
    IsLogging: True
    # IsMultiRegionTrail: True
    # KMSKeyId: String
    S3BucketName: {"Ref" : "CloudTrailBucket"}
    # S3KeyPrefix: String
    # SnsTopicName: String
    # Tags:
    #   - Tag
    # TrailName: String
</code>```

First I tried creating the cloudTrail alone and got the following error

```<code>CloudTrail - Incorrect S3 bucket policy is detected for bucket: ....
</code>```

Then I added this code to create a policy

```<code>CloudTrailBucketPolicy:
  # Version : 2012-10-17,
  Type:  AWS::S3::BucketPolicy
  Properties:
    PolicyDocument:
      - Action:
          - "s3:GetBucketAcl"
        Effect:  Allow
        Resource: { "Fn::Join": ["", ["arn:aws:s3:::CloudTrailBucket"] ] }
        Principal:  "*"
      - Action:
          - "s3:PutObject"
        Effect:  Allow
        Resource: { "Fn::Join": ["", ["arn:aws:s3:::CloudTrailBucket", "/*" ] ] }
        Principal:
          Service:  cloudtrail.amazonaws.com
</code>```

But getting this error.

```<code>An error occurred: CloudTrailBucketPolicy - Value of property PolicyDocument must be an object.
</code>```

答:
You forgot Statement:

```<code>CloudTrailBucketPolicy:
  # Version : 2012-10-17,
  Type:  AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CloudTrailBucket
      PolicyDocument:
        Statement:
          - Action:
              - "s3:GetBucketAcl"
            Effect:  Allow
            Resource: { "Fn::Join": ["", ["arn:aws:s3:::", !Ref CloudTrailBucket] ] }
            Principal:  "*"
          - Action:
              - "s3:PutObject"
            Effect:  Allow
            Resource: { "Fn::Join": ["", ["arn:aws:s3:::", !Ref CloudTrailBucket, "/*" ] ] }
            Principal:
              Service:  cloudtrail.amazonaws.com
</code>```

Body:
I am trying to create cloudTrail through a serverless application.

CloudTrail:
  Type: AWS::CloudTrail::Trail
  Properties:
    # CloudWatchLogsLogGroupArn: "String"
    # CloudWatchLogsRoleArn: "String"
    # EnableLogFileValidation: True
    # EventSelectors:
    #   - EventSelector
    # IncludeGlobalServiceEvents: True
    IsLogging: True
    # IsMultiRegionTrail: True
    # KMSKeyId: String
    S3BucketName: {"Ref" : "CloudTrailBucket"}
    # S3KeyPrefix: String
    # SnsTopicName: String
    # Tags:
    #   - Tag
    # TrailName: String

First I tried creating the cloudTrail alone and got the following error

CloudTrail - Incorrect S3 bucket policy is detected for bucket: ....

Then I added this code to create a policy

CloudTrailBucketPolicy:
  # Version : 2012-10-17,
  Type:  AWS::S3::BucketPolicy
  Properties:
    PolicyDocument:
      - Action:
          - "s3:GetBucketAcl"
        Effect:  Allow
        Resource: { "Fn::Join": ["", ["arn:aws:s3:::CloudTrailBucket"] ] }
        Principal:  "*"
      - Action:
          - "s3:PutObject"
        Effect:  Allow
        Resource: { "Fn::Join": ["", ["arn:aws:s3:::CloudTrailBucket", "/*" ] ] }
        Principal:
          Service:  cloudtrail.amazonaws.com

But getting this error.

An error occurred: CloudTrailBucketPolicy - Value of property PolicyDocument must be an object.

Body:
You forgot Statement:

CloudTrailBucketPolicy:
  # Version : 2012-10-17,
  Type:  AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CloudTrailBucket
      PolicyDocument:
        Statement:
          - Action:
              - "s3:GetBucketAcl"
            Effect:  Allow
            Resource: { "Fn::Join": ["", ["arn:aws:s3:::", !Ref CloudTrailBucket] ] }
            Principal:  "*"
          - Action:
              - "s3:PutObject"
            Effect:  Allow
            Resource: { "Fn::Join": ["", ["arn:aws:s3:::", !Ref CloudTrailBucket, "/*" ] ] }
            Principal:
              Service:  cloudtrail.amazonaws.com


问:
nhibernate collection set mapping to avoid n+1 select and duplicate rows with fetch join
I have a object table and object aliases table.

The aliases is just a set collection of strings:

```<code>object.Aliases
</code>```

If I map the collection like this:

```<code><class name="Object" table="Object" lazy="false">
    ...
    properties...
    ...
    <set name="Aliases" table="Aliases" inverse="true" lazy="false" fetch="join" >
      <key column="ObjectId" />
      <element column="Name" type="String"/>
    </set>
    ...
</class>
</code>```

then

```<code>session.CreateCriteria(typeof (T)).List<T>();
</code>```

from base repository which fetches all objects, returns duplicates for each alias. Why? how can I get rid of the duplicate objects in the list?

Thank you all for your time.

EDIT:
Updated mappings... but that's all the mappings. Aliases doesn't have it's own class as it's just a set of strings that needs to be loaded into ISet<string> Object.Aliases

答:
I was confused by this, too, when I started using NHibernate.  That's how it works.  Because the mapping includes fetch="join", it's using an SQL JOIN between the parent table and the child table, so the parent data is repeated for each child.  But then rather than filter out the extra instances of the parent, you get back a collection with one object per row in the query.  You need to indicate you want distinct objects.  Using ICriteria syntax, you can add Transformers.DistinctRootEntity to your query.

See Get Distinct result set from NHibernate using Criteria API?, and the link it mentions within.

Body:
I have a object table and object aliases table.

The aliases is just a set collection of strings:

object.Aliases

If I map the collection like this:

<class name="Object" table="Object" lazy="false">
    ...
    properties...
    ...
    <set name="Aliases" table="Aliases" inverse="true" lazy="false" fetch="join" >
      <key column="ObjectId" />
      <element column="Name" type="String"/>
    </set>
    ...
</class>

then

session.CreateCriteria(typeof (T)).List<T>();

from base repository which fetches all objects, returns duplicates for each alias. Why? how can I get rid of the duplicate objects in the list?

Thank you all for your time.

EDIT:
Updated mappings... but that's all the mappings. Aliases doesn't have it's own class as it's just a set of strings that needs to be loaded into ISet<string> Object.Aliases


问:
How to access popover element with repeated name inside the component?
I am trying to trigger the toggle function of a popover inside an Angular Material Table.

If a cell in the table has tabbed focus, i would like the popover to open when the user hits the 'Enter' key. This would mimic the behaviour of when the user click's on the table cell.

My problem is that the popover component is given the name #valuePopover which is the same name for all cells in the table.

```<code><ng-container matColumnDef="value">
  <th mat-header-cell *matHeaderCellDef> Value </th>
  <td mat-cell *matCellDef="let entry;" tabindex="0"
    [satPopoverAnchorFor]="valuePopover" (click)="valuePopover.toggle()"
    (keypress)="openPopover($event)">
    <span>{{entry.value}}</span>
    <sat-popover #valuePopover hasBackdrop xAlign="start" yAlign="start" (closed)="updateField(entry, $event)">Hello!
    </sat-popover>
  </td>
</ng-container>
</code>```

For the (click) event it works fine as it can just call the 'valuePopover.toggle()' function. However, with the keypress event I need to check if it is the enter key that has been pressed, and I need to do this in the component.

```<code>@ViewChild('valuePopover') popover;

openPopover(event: KeyboardEvent) {
  if(event.keyCode == 13) popover.toggle();
}
</code>```

The openPopover function always opens the popover of the first cell popover but not the one with the tabbed focus on it!

Does anybody know how I can implement this either in the html or the component?

I am using the 'sat-popover' component which you can find here: https://github.com/ncstate-sat/popover

答:
I solved this with the help of the user Diodeus - James McFarlane, by preventing the default event, and calling the click method of the event.target like so:</p>

```<code>openPopover(event) {
  if(event.keyCode == 13) {
    event.preventDefault();
    var element:HTMLElement = event.target;
    element.click();
  }
}
</code>```

Body:
I am trying to trigger the toggle function of a popover inside an Angular Material Table.

If a cell in the table has tabbed focus, i would like the popover to open when the user hits the 'Enter' key. This would mimic the behaviour of when the user click's on the table cell.

My problem is that the popover component is given the name #valuePopover which is the same name for all cells in the table.

<ng-container matColumnDef="value">
   Value

    {{entry.value}}
    <sat-popover #valuePopover hasBackdrop xAlign="start" yAlign="start" (closed)="updateField(entry, $event)">Hello!
    </sat-popover>

</ng-container>

For the (click) event it works fine as it can just call the 'valuePopover.toggle()' function. However, with the keypress event I need to check if it is the enter key that has been pressed, and I need to do this in the component.

@ViewChild('valuePopover') popover;

openPopover(event: KeyboardEvent) {
  if(event.keyCode == 13) popover.toggle();
}

The openPopover function always opens the popover of the first cell popover but not the one with the tabbed focus on it!

Does anybody know how I can implement this either in the html or the component?

I am using the 'sat-popover' component which you can find here: https://github.com/ncstate-sat/popover

Body:
I solved this with the help of the user Diodeus - James McFarlane, by preventing the default event, and calling the click method of the event.target like so:

openPopover(event) {
  if(event.keyCode == 13) {
    event.preventDefault();
    var element:HTMLElement = event.target;
    element.click();
  }
}


问:
Python Loop, Need to / Can't Retain Value from Original Dataframe
I'm attempting to loop through groups of phrases to match and score them among all the members in each group. Even if some of the phrases are the same, they may have different Codes which is what I'm trimming from the loop inputs - but need to retain in the final df2. I have to make the comparison in the loop without the code but the issue is tying it back to the original df that contains the code so I can identify which rows need to be flagged.

The code below works but I need to add the original DESCR to df2. Appending a and b only contains the trim.

I've tried df.at[] but have mixed, incorrect results. Thank you.

```<code>import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'Oneab'],[1,'Onebc'],[1,'Twode'],[2,'Threegh'],[2,'Threehi'],[2,'Fourjk'],[3,'Fivekl'],[3,'Fivelm'],[3,'Fiveyz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

n_list = []
a_list = []
b_list = []
pr_list = []
tsr_list = []

groups = df.groupby('Ids')
for n,g in groups:
    for a, b in itertools.product(g['DESCR'].str[:-2],g['DESCR'].str[:-2]):
        if str(a) < str(b):
            try:
                n_list.append(n)
                a_list.append(a)
                b_list.append(b)
                pr_list.append(fz.partial_ratio(a,b))
                tsr_list.append(fz.token_set_ratio(a,b))
            except:
                pass
df2 = pd.DataFrame({'Group': n_list, 'First Comparator': a_list, 'Second Comparator': b_list, 'Partial Ratio': pr_list, 'Token Set Ratio': tsr_list})
</code>```

Instead of:

```<code>ab bc 50 50
ab de 0 0
bc de 0 0
gh hi 50 50
gh jk 0 0
hi jk 50 50
...
</code>```

I'd like to see:

```<code>Oneab Onebc 50 50
Oneab Twode 0 0
Onebc Twode 0 0
Threegh Threehi 50 50
Threegh Fourjk 0 0
Threehi Fourjk 50 50
...
</code>```

答:
In case anyone else runs into a similar issue - figured it out - instead of filtering the inputs at the beginning of the second level loop, I'm bringing the full value into the second loop and stripping it there:

```<code>a2 = a[6:]
b2 = b[6:]
</code>```

So:

```<code>import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'Oneab'],[1,'Onebc'],[1,'Twode'],[2,'Threegh'],[2,'Threehi'],[2,'Fourjk'],[3,'Fivekl'],[3,'Fivelm'],[3,'Fiveyz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

n_list = []
a_list = []
b_list = []
pr_list = []
tsr_list = []

groups = df.groupby('Ids')
for n,g in groups:
    for a, b in itertools.product(g['DESCR'],g['DESCR']):
        if str(a) < str(b):
            try:
                a2 = a[:-2]
                b2 = b[:-2]
                n_list.append(n)
                a_list.append(a)
                b_list.append(b)
                pr_list.append(fz.partial_ratio(a2,b2))
                tsr_list.append(fz.token_set_ratio(a2,b2))
            except:
                pass
df2 = pd.DataFrame({'Group': n_list, 'First Comparator': a_list, 'Second Comparator': b_list, 'Partial Ratio': pr_list, 'Token Set Ratio': tsr_list})
</code>```

Body:
I'm attempting to loop through groups of phrases to match and score them among all the members in each group. Even if some of the phrases are the same, they may have different Codes which is what I'm trimming from the loop inputs - but need to retain in the final df2. I have to make the comparison in the loop without the code but the issue is tying it back to the original df that contains the code so I can identify which rows need to be flagged.

The code below works but I need to add the original DESCR to df2. Appending a and b only contains the trim.

I've tried df.at[] but have mixed, incorrect results. Thank you.

import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'Oneab'],[1,'Onebc'],[1,'Twode'],[2,'Threegh'],[2,'Threehi'],[2,'Fourjk'],[3,'Fivekl'],[3,'Fivelm'],[3,'Fiveyz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

n_list = []
a_list = []
b_list = []
pr_list = []
tsr_list = []

groups = df.groupby('Ids')
for n,g in groups:
    for a, b in itertools.product(g['DESCR'].str[:-2],g['DESCR'].str[:-2]):
        if str(a) < str(b):
            try:
                n_list.append(n)
                a_list.append(a)
                b_list.append(b)
                pr_list.append(fz.partial_ratio(a,b))
                tsr_list.append(fz.token_set_ratio(a,b))
            except:
                pass
df2 = pd.DataFrame({'Group': n_list, 'First Comparator': a_list, 'Second Comparator': b_list, 'Partial Ratio': pr_list, 'Token Set Ratio': tsr_list})

Instead of:

ab bc 50 50
ab de 0 0
bc de 0 0
gh hi 50 50
gh jk 0 0
hi jk 50 50
...

I'd like to see:

Oneab Onebc 50 50
Oneab Twode 0 0
Onebc Twode 0 0
Threegh Threehi 50 50
Threegh Fourjk 0 0
Threehi Fourjk 50 50
...

Body:
In case anyone else runs into a similar issue - figured it out - instead of filtering the inputs at the beginning of the second level loop, I'm bringing the full value into the second loop and stripping it there:

a2 = a[6:]
b2 = b[6:]

So:

import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'Oneab'],[1,'Onebc'],[1,'Twode'],[2,'Threegh'],[2,'Threehi'],[2,'Fourjk'],[3,'Fivekl'],[3,'Fivelm'],[3,'Fiveyz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

n_list = []
a_list = []
b_list = []
pr_list = []
tsr_list = []

groups = df.groupby('Ids')
for n,g in groups:
    for a, b in itertools.product(g['DESCR'],g['DESCR']):
        if str(a) < str(b):
            try:
                a2 = a[:-2]
                b2 = b[:-2]
                n_list.append(n)
                a_list.append(a)
                b_list.append(b)
                pr_list.append(fz.partial_ratio(a2,b2))
                tsr_list.append(fz.token_set_ratio(a2,b2))
            except:
                pass
df2 = pd.DataFrame({'Group': n_list, 'First Comparator': a_list, 'Second Comparator': b_list, 'Partial Ratio': pr_list, 'Token Set Ratio': tsr_list})


问:
Combining words (tomato,carrot) and display count of locales over time in Big Query [en,en-uk,en-sv,en-au as EN]
I am currently picking up SQL and have come across a problem.

This question pertains to many use cases for me. I have locales in en-uk, en-au, es-latam, es-spain that I want to combine simply as EN or ES for reporting over time.

Below are examples on asking how to count number of tomato page views, and number of carrot page views.

I am hoping once I figure out how to do this, I can apply this to language locales.

The intended output can be seen in this spreadsheet here in column H:L: https://docs.google.com/spreadsheets/d/1CNE__ikiHEQHedH0UiSPmRI1s47e7qEH_aJJVtYSSzU/edit?usp=sharing

Unfamiliar with CASE as I am beginning to start out on this journey, but I need to aggregate/summarize the data already lying in the table even more so that I may build a chart.

Can anyone point out any optimization areas? In addition, a side request:
    AND url.website like '%tomato%' or '%carrot%' (How do I make this an OR?)

Lastly, can anyone help me figure out how to use a NOT CONTAIN in
    AND url.website does not contain any of these words case insensitive (?i)
    potato,Mushroom,Celery

I am coming from a Spreadsheets background and am an advanced user, but seems as if I am having difficulty transferring this knowledge over to SQL.

Many thanks! And please let me know if you have any questions,

After many forum scourings, I understand I will need to insert a Subquery in here in order to get the intended table. I aim to plot the count of these website page visits in a graph over time.

[Most Recent EDIT]

Shows URL with Count number on the right hand side

```<code>SELECT
url.website
report.timestamp
count(url.website) as count
FROM
datatable.report
WHERE url.website like '%carrot%' OR url.website like '%tomato%'
Group by url.website
</code>```

Error code: report.timestamp is not found in Group By - but if I add it, I get microseconds in one column, and the count of appearances of these microseconds.

The main gist is to add the report.timestamp in the select, so that I could plot by aggregated month, but once I do this, the count values are not summed.

[Past Edit 2]

```<code>  SELECT
  url.website
  COUNT(url.website) as Count
  (CASE WHEN report.web.url like '%carrot%' then 'carrot website'
  WHEN report.web.url like '%tomato%' then 'tomato website'
  ELSE 'other website'
  END)

  FROM datatable.report
  WHERE (product.tag = 12345)
  AND url.website NOT IN ('Potato','Mushroom','Celery')
  AND url.website like '%tomato%'
  GROUP BY url.website
</code>```

[Past Edit 3]

```<code> SELECT
 (CASE WHEN url.website like '%carrot%' THEN 'carrot'
 WHEN url.website like '%tomato%' THEN 'tomato'
 ELSE 'other'
 END)
 url.website
 COUNT(carrot) as carrotwebsite
 COUNT(fundamental) As tomatowebsite

*thinking that maybe I needed to case/group them first, then show the
 count
 displays.
</code>```

Please see column H:L in the public spreadsheet: https://docs.google.com/spreadsheets/d/1CNE__ikiHEQHedH0UiSPmRI1s47e7qEH_aJJVtYSSzU/edit?usp=sharing

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  COUNTIF(url LIKE '%tomato%') tomato_views,
  COUNTIF(url LIKE '%carrot%') carrot_views,
  COUNTIF(NOT url LIKE '%tomato%' AND NOT url LIKE '%carrot%') other_views
FROM `project.dataset.table`
GROUP BY month_year
</code>```

You can test, play with above using sample/dummy data as in below example

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT '1/1/2019' dt, 'www.websiteurl.com/tomato/page1' url UNION ALL
  SELECT '1/10/2019', 'www.websiteurl.com/tomato/page2' UNION ALL
  SELECT '1/3/2019', 'www.websiteurl.com/tomato/page3' UNION ALL
  SELECT '2/4/2019', 'www.websiteurl.com/tomato/page4' UNION ALL
  SELECT '2/21/2019', 'www.websiteurl.com/tomato/page5' UNION ALL
  SELECT '2/7/2019', 'www.websiteurl.com/tomato/page6' UNION ALL
  SELECT '3/7/2019', 'www.websiteurl.com/tomato/page7' UNION ALL
  SELECT '3/15/2019', 'www.websiteurl.com/tomato/page8' UNION ALL
  SELECT '3/29/2019', 'www.websiteurl.com/tomato/page9' UNION ALL
  SELECT '3/16/2019', 'www.websiteurl.com/tomato/page10' UNION ALL
  SELECT '1/11/2019', 'www.websiteurl.com/carrot/page1' UNION ALL
  SELECT '1/12/2019', 'www.websiteurl.com/carrot/page2' UNION ALL
  SELECT '4/10/2019', 'www.websiteurl.com/carrot/page3' UNION ALL
  SELECT '4/10/2019', 'www.websiteurl.com/carrot/page4' UNION ALL
  SELECT '4/18/2019', 'www.websiteurl.com/carrot/page5' UNION ALL
  SELECT '1/16/2019', 'www.websiteurl.com/carrot/page6' UNION ALL
  SELECT '1/17/2019', 'www.websiteurl.com/carrot/page7' UNION ALL
  SELECT '1/18/2019', 'www.websiteurl.com/turnip/home' UNION ALL
  SELECT '1/19/2019', 'www.websiteurl.com/turnip/resources'
)
SELECT FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  COUNTIF(url LIKE '%tomato%') tomato_views,
  COUNTIF(url LIKE '%carrot%') carrot_views,
  COUNTIF(NOT url LIKE '%tomato%' AND NOT url LIKE '%carrot%') other_views
FROM `project.dataset.table`
GROUP BY month_year
</code>```

with result

```<code>Row month_year  tomato_views    carrot_views    other_views
1   Jan 2019    3               4               2
2   Feb 2019    3               0               0
3   Mar 2019    4               0               0
4   Apr 2019    0               3               0
</code>```

Body:
I am currently picking up SQL and have come across a problem.

This question pertains to many use cases for me. I have locales in en-uk, en-au, es-latam, es-spain that I want to combine simply as EN or ES for reporting over time.

Below are examples on asking how to count number of tomato page views, and number of carrot page views.

I am hoping once I figure out how to do this, I can apply this to language locales.

The intended output can be seen in this spreadsheet here in column H:L: https://docs.google.com/spreadsheets/d/1CNE__ikiHEQHedH0UiSPmRI1s47e7qEH_aJJVtYSSzU/edit?usp=sharing

Unfamiliar with CASE as I am beginning to start out on this journey, but I need to aggregate/summarize the data already lying in the table even more so that I may build a chart.

Can anyone point out any optimization areas? In addition, a side request:
    AND url.website like '%tomato%' or '%carrot%' (How do I make this an OR?)

Lastly, can anyone help me figure out how to use a NOT CONTAIN in
    AND url.website does not contain any of these words case insensitive (?i)
    potato,Mushroom,Celery

I am coming from a Spreadsheets background and am an advanced user, but seems as if I am having difficulty transferring this knowledge over to SQL.

Many thanks! And please let me know if you have any questions,

After many forum scourings, I understand I will need to insert a Subquery in here in order to get the intended table. I aim to plot the count of these website page visits in a graph over time.

[Most Recent EDIT]

Shows URL with Count number on the right hand side

SELECT
url.website
report.timestamp
count(url.website) as count
FROM
datatable.report
WHERE url.website like '%carrot%' OR url.website like '%tomato%'
Group by url.website

Error code: report.timestamp is not found in Group By - but if I add it, I get microseconds in one column, and the count of appearances of these microseconds.

The main gist is to add the report.timestamp in the select, so that I could plot by aggregated month, but once I do this, the count values are not summed.

[Past Edit 2]

  SELECT
  url.website
  COUNT(url.website) as Count
  (CASE WHEN report.web.url like '%carrot%' then 'carrot website'
  WHEN report.web.url like '%tomato%' then 'tomato website'
  ELSE 'other website'
  END)

  FROM datatable.report
  WHERE (product.tag = 12345)
  AND url.website NOT IN ('Potato','Mushroom','Celery')
  AND url.website like '%tomato%'
  GROUP BY url.website

[Past Edit 3]

 SELECT
 (CASE WHEN url.website like '%carrot%' THEN 'carrot'
 WHEN url.website like '%tomato%' THEN 'tomato'
 ELSE 'other'
 END)
 url.website
 COUNT(carrot) as carrotwebsite
 COUNT(fundamental) As tomatowebsite

*thinking that maybe I needed to case/group them first, then show the
 count
 displays.

Please see column H:L in the public spreadsheet: https://docs.google.com/spreadsheets/d/1CNE__ikiHEQHedH0UiSPmRI1s47e7qEH_aJJVtYSSzU/edit?usp=sharing

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  COUNTIF(url LIKE '%tomato%') tomato_views,
  COUNTIF(url LIKE '%carrot%') carrot_views,
  COUNTIF(NOT url LIKE '%tomato%' AND NOT url LIKE '%carrot%') other_views
FROM `project.dataset.table`
GROUP BY month_year

You can test, play with above using sample/dummy data as in below example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '1/1/2019' dt, 'www.websiteurl.com/tomato/page1' url UNION ALL
  SELECT '1/10/2019', 'www.websiteurl.com/tomato/page2' UNION ALL
  SELECT '1/3/2019', 'www.websiteurl.com/tomato/page3' UNION ALL
  SELECT '2/4/2019', 'www.websiteurl.com/tomato/page4' UNION ALL
  SELECT '2/21/2019', 'www.websiteurl.com/tomato/page5' UNION ALL
  SELECT '2/7/2019', 'www.websiteurl.com/tomato/page6' UNION ALL
  SELECT '3/7/2019', 'www.websiteurl.com/tomato/page7' UNION ALL
  SELECT '3/15/2019', 'www.websiteurl.com/tomato/page8' UNION ALL
  SELECT '3/29/2019', 'www.websiteurl.com/tomato/page9' UNION ALL
  SELECT '3/16/2019', 'www.websiteurl.com/tomato/page10' UNION ALL
  SELECT '1/11/2019', 'www.websiteurl.com/carrot/page1' UNION ALL
  SELECT '1/12/2019', 'www.websiteurl.com/carrot/page2' UNION ALL
  SELECT '4/10/2019', 'www.websiteurl.com/carrot/page3' UNION ALL
  SELECT '4/10/2019', 'www.websiteurl.com/carrot/page4' UNION ALL
  SELECT '4/18/2019', 'www.websiteurl.com/carrot/page5' UNION ALL
  SELECT '1/16/2019', 'www.websiteurl.com/carrot/page6' UNION ALL
  SELECT '1/17/2019', 'www.websiteurl.com/carrot/page7' UNION ALL
  SELECT '1/18/2019', 'www.websiteurl.com/turnip/home' UNION ALL
  SELECT '1/19/2019', 'www.websiteurl.com/turnip/resources'
)
SELECT FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  COUNTIF(url LIKE '%tomato%') tomato_views,
  COUNTIF(url LIKE '%carrot%') carrot_views,
  COUNTIF(NOT url LIKE '%tomato%' AND NOT url LIKE '%carrot%') other_views
FROM `project.dataset.table`
GROUP BY month_year

with result

Row month_year  tomato_views    carrot_views    other_views
1   Jan 2019    3               4               2
2   Feb 2019    3               0               0
3   Mar 2019    4               0               0
4   Apr 2019    0               3               0


问:
How can I read tar.gz file using pandas read_csv with gzip compression option?
I have a very simple csv, with the following data, compressed inside the tar.gz file. I need to read that in dataframe using pandas.read_csv.

```<code>   A  B
0  1  4
1  2  5
2  3  6

import pandas as pd
pd.read_csv("sample.tar.gz",compression='gzip')
</code>```

However, I am getting error:

```<code>CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2
</code>```

Following are the set of read_csv commands and the different errors I get with them:

```<code>pd.read_csv("sample.tar.gz",compression='gzip',  engine='python')
Error: line contains NULL byte

pd.read_csv("sample.tar.gz",compression='gzip', header=0)
CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2

pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ")
CParserError: Error tokenizing data. C error: Expected 2 fields in line 94, saw 14

pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ", engine='python')
Error: line contains NULL byte
</code>```

What's going wrong here? How can I fix this?

答:
You can use the tarfile module to read a particular file from the tar.gz archive (as discussed in this resolved issue).
If there is only one file in the archive, then you can do this:

```<code>import tarfile
import pandas as pd
with tarfile.open("sample.tar.gz", "r:*") as tar:
    csv_path = tar.getnames()[0]
    df = pd.read_csv(tar.extractfile(csv_path), header=0, sep=" ")
</code>```

The read mode r:* handles the gz extension (or other kinds of compression) appropriately.  If there are multiple files in the zipped tar file, then you could do something like csv_path = list(n for n in tar.getnames() if n.endswith('.csv'))[-1] line to get the last csv file in the archived folder.

Body:
I have a very simple csv, with the following data, compressed inside the tar.gz file. I need to read that in dataframe using pandas.read_csv.

   A  B
0  1  4
1  2  5
2  3  6

import pandas as pd
pd.read_csv("sample.tar.gz",compression='gzip')

However, I am getting error:

CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2

Following are the set of read_csv commands and the different errors I get with them:

pd.read_csv("sample.tar.gz",compression='gzip',  engine='python')
Error: line contains NULL byte

pd.read_csv("sample.tar.gz",compression='gzip', header=0)
CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2

pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ")
CParserError: Error tokenizing data. C error: Expected 2 fields in line 94, saw 14

pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ", engine='python')
Error: line contains NULL byte

What's going wrong here? How can I fix this?

Body:
You can use the tarfile module to read a particular file from the tar.gz archive (as discussed in this resolved issue).
If there is only one file in the archive, then you can do this:

import tarfile
import pandas as pd
with tarfile.open("sample.tar.gz", "r:*") as tar:
    csv_path = tar.getnames()[0]
    df = pd.read_csv(tar.extractfile(csv_path), header=0, sep=" ")

The read mode r:* handles the gz extension (or other kinds of compression) appropriately.  If there are multiple files in the zipped tar file, then you could do something like csv_path = list(n for n in tar.getnames() if n.endswith('.csv'))[-1] line to get the last csv file in the archived folder.


答:
NodeJS is not just regular javascript, it is a javascript runtime that sits on top of a C++ engine called V8, provided by Google. Node executes outside the browser, whereas React / Vue / Angular / etc are in-browser javascript frameworks.

React is a whole separate animal; it is a framework that renders its own DOM in the browser.   It is a javascript engine that is configured to optimize DOM manipulation.

While the development pattern of frontend and backend appear similar, they are doing different things. React is handling component lifecycles, applying dynamic style rules, processing in-browser data, and making API calls. Node is handling requests from the browser, coordinating access to the server's file system, managing network I-O, performing cryptographic evaluation, etc. Because of these different responsibilities, Node makes use of different dependencies (read: node modules) than a frontend framework.

Ultimately, Node and React communicate through HTTP calls (or, less frequently, through a WebSocket or SOAP protocol).

It would behoove you to read about how node works under the hood.

Title: ReactJS vs NodeJS - Why do I need to create both?

Body:
I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.

For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.

I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.

How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.


问:
Save first n prime numbers in an array without overwriting it
I'm trying to save first 20 prime numbers that are greater or equal than entered number.
Right now the output is 20 times 997 because values overwrite previous ones. I can't figure out what to do to limit them. When the array is full stop the loop or something so the overwriting won't happen?

bool is_prime(int num) {
    if (num < 2) {
        return false;
    }

    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

void fillArr(int arr[20], int num) {
    for (int index = num; index <= 1000; index++) { //don't know how to set up
    //2nd condition, depends on entered number
        if (is_prime(index)) {
            //save first 20 prime numbers that are >= num into an array
            //Code fills the array with every prime it finds, setting it for all
            //values and overwriting any previous primes it has found. Right now
            //output would be the same 20 prime numbers closest to index 1000,
            //based on second condition
            for (int i = 0; i < 20; i++) {
                arr[i] = index;
            }
        }
    }
    //print test
    for (int i = 0; i < 20; i++) {
        std::cout << arr[i] << "\t";
    }
}
```

<pre class="lang-c prettyprint-override"><code>int main() {
        int arr[20];
    int num;

    std::cout << "Enter number: ";
    std::cin >> num;

    fillArr(arr, num);

    return 0;
}
</code>```

答:
In your code, initialize i to 0 at the beginning. Each time you encounter a prime, add it to your array and increment i. Break when i >= 20.

```<code>void fillArr(int arr[20], int num) {
    int i = 0;
    for (int index = num; index <= 1000 && i < 20; index++) {
        if (is_prime(index)) {
            arr[i++] = index;
        }
    }
    //print test
    for (int i = 0; i < 20; i++) {
        std::cout << arr[i] << "\t";
    }
}
</code>```

Also note that this is not the most optimal way to find primes. For finding whether a given number is prime, you only need to check for whether it is divisible by primes uptil square root of the number (and not till n/2). You may also want to read about the Seive of Eratosthenes.

As also specified in the comments, it's better to use std::vector or std::array rather than raw arrays. In that case, you'd simply want to push_back(index) and break when vector's size >= 20.

Body:
I'm trying to save first 20 prime numbers that are greater or equal than entered number.
Right now the output is 20 times 997 because values overwrite previous ones. I can't figure out what to do to limit them. When the array is full stop the loop or something so the overwriting won't happen?

bool is_prime(int num) {
    if (num < 2) {
        return false;
    }

    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

void fillArr(int arr[20], int num) {
    for (int index = num; index <= 1000; index++) { //don't know how to set up
    //2nd condition, depends on entered number
        if (is_prime(index)) {
            //save first 20 prime numbers that are >= num into an array
            //Code fills the array with every prime it finds, setting it for all
            //values and overwriting any previous primes it has found. Right now
            //output would be the same 20 prime numbers closest to index 1000,
            //based on second condition
            for (int i = 0; i < 20; i++) {
                arr[i] = index;
            }
        }
    }
    //print test
    for (int i = 0; i < 20; i++) {
        std::cout << arr[i] << "\t";
    }
}

int main() {
        int arr[20];
    int num;

    std::cout << "Enter number: ";
    std::cin >> num;

    fillArr(arr, num);

    return 0;
}

Body:
In your code, initialize i to 0 at the beginning. Each time you encounter a prime, add it to your array and increment i. Break when i >= 20.

void fillArr(int arr[20], int num) {
    int i = 0;
    for (int index = num; index <= 1000 && i < 20; index++) {
        if (is_prime(index)) {
            arr[i++] = index;
        }
    }
    //print test
    for (int i = 0; i < 20; i++) {
        std::cout << arr[i] << "\t";
    }
}

Also note that this is not the most optimal way to find primes. For finding whether a given number is prime, you only need to check for whether it is divisible by primes uptil square root of the number (and not till n/2). You may also want to read about the Seive of Eratosthenes.

As also specified in the comments, it's better to use std::vector or std::array rather than raw arrays. In that case, you'd simply want to push_back(index) and break when vector's size >= 20.


答: NodeJS will serve as your backend, whereas ReactJS will create the interface/UI where you can actually manipulate your server (nodeJS). So first you'll write your NodeJS server or API. You don't need to use ReactJS to create a frontend that would interact with your node server, like you said you can use NodeJS to create your views as well through a different library. ReactJS is just one choice of many for the front end of your NodeJS app.


问:
Error in PowerShell due to copying the content of an S3 bucket
I copy the content of an S3 bucket to a local directory, however I get an error output from the powershell.

Copy-S3Object : The requested range is not satisfiable

It is pointing to this command:

```<code>Copy-S3Object -BucketName $bucket -Key $object.Key -LocalFile $localFilePath -Region $region
</code>```

Why do I get this error ? Note that the desired files that are needed to be copied do indeed get copied locally.

答:
this seems to occur with folders that do not contain files since copy wants to copy files.
i accepted this error and trapped it.</p>

```<code>catch  [Amazon.S3.AmazonS3Exception]
{

  # get error record
  [Management.Automation.ErrorRecord]$e = $_

  # retrieve information about runtime error
  $info = [PSCustomObject]@{
    Exception = $e.Exception.Message
    Reason    = $e.CategoryInfo.Reason
    Target    = $e.CategoryInfo.TargetName
    Script    = $e.InvocationInfo.ScriptName
    Line      = $e.InvocationInfo.ScriptLineNumber
    Column    = $e.InvocationInfo.OffsetInLine
    ErrorCode = $e.Exception.ErrorCode
  }
  if ($info.ErrorCode="InvalidRange") { #do nothing
  } Else {
  # output information. Post-process collected info, and log info (optional)
  write-host $info -ForegroundColor Red}
}

  }
</code>```

Body:
I copy the content of an S3 bucket to a local directory, however I get an error output from the powershell.

Copy-S3Object : The requested range is not satisfiable

It is pointing to this command:

Copy-S3Object -BucketName $bucket -Key $object.Key -LocalFile $localFilePath -Region $region

Why do I get this error ? Note that the desired files that are needed to be copied do indeed get copied locally.

Body:
this seems to occur with folders that do not contain files since copy wants to copy files.
i accepted this error and trapped it.

catch  [Amazon.S3.AmazonS3Exception]
{

  # get error record
  [Management.Automation.ErrorRecord]$e = $_

  # retrieve information about runtime error
  $info = [PSCustomObject]@{
    Exception = $e.Exception.Message
    Reason    = $e.CategoryInfo.Reason
    Target    = $e.CategoryInfo.TargetName
    Script    = $e.InvocationInfo.ScriptName
    Line      = $e.InvocationInfo.ScriptLineNumber
    Column    = $e.InvocationInfo.OffsetInLine
    ErrorCode = $e.Exception.ErrorCode
  }
  if ($info.ErrorCode="InvalidRange") { #do nothing
  } Else {
  # output information. Post-process collected info, and log info (optional)
  write-host $info -ForegroundColor Red}
}

  }