问:
Slick for-comprehensions: How to handle an enumerator that can be None or Some-thing?
I have a use-case maybe not specific to Slick but to for-comprehensions. The high level pattern is like this but it leads to a compiler error in enum3:

```<code>(for {
   enum1 <- // ...
   enum2 <- // ...
   enum3 <- optionArg.fold(empty result).map { ... }
 } yield ())
</code>```

Then I end up doing the following that compiles but has code duplication namely of enum1 and enum2:

```<code>optionArg match {
  case (Some(arg)) => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
        enum3 <- // do something with arg
      } yield ())
    }
    case None => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
      } yield ())
    }
  }
}
</code>```

In concrete I have that this repetitive variant compiles:

```<code>/**
 * Returns the inserted `oauth2Info` instance including the params. We first
 * look up the `LoginInfo` by the relevant search criteria, fetching its `userId`
 * which is then used to persist a `OAuth2Info` and multiple `OAuth2InfoParam`.
 *
 * @param extLoginInfo The login info for which the auth info should be added.
 * @param extOAuth2Info The TOTP info to add containing the params.
 * @return the inserted `oauth2Info` instance including the params.
 */
def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
        } yield ())
      }
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}
</code>```

and this succinct desired variant doesn't:

```<code>def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = (for {
      userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
      _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
      _ <- extOAuth2Info.params.fold(DBIOAction.seq()) { params =>
        DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
      }
    } yield ()).transactionally
    db.run(insertion).map(_ => extOAuth2Info)
}
</code>```

Gives compiles error:

```<code>[play-silhouette-seed] $ compile
[info] Formatting 1 Scala source ProjectRef(uri("file:/home/skywalker/code/play-silhouette-seed/"), "root")(compile) ...
[info] Compiling 1 Scala source to /home/skywalker/code/play-silhouette-seed/target/scala-2.12/classes ...
[error] /home/skywalker/code/play-silhouette-seed/app/models/daos/OAuth2InfoDaoImpl.scala:58:28: type mismatch;
[error]  found   : slick.dbio.DBIOAction[scala.collection.immutable.Iterable[Int],slick.dbio.NoStream,slick.dbio.Effect.Write]
[error]  required: slick.dbio.DBIOAction[Unit,slick.dbio.NoStream,slick.dbio.Effect]
[error]         DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
[error]                            ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed May 28, 2019 10:42:00 AM
</code>```

答:
This is a problem with fold when the compiler cannot type-infer the proper generic types for the expression. It does not properly widen the type returned from the first expression to the type of the second one. You need to help the compiler a bit.

It also happens in situations like this

```<code> Some(123).fold(None)(_ => Some("123"))
 // type mismatch; found: Some[String] required: None.type
</code>```

You can change fold to map().getOrElse() (then the "good type" comes first and get be inferred).

Or you can add type annotations somewhere, such as

```<code> private val noAction: slick.dbio.DBIOAction[Iterable[Int],NoStream,Effect.Write]
   = DBIOAction.sequence()

 theOption.fold(noAction)(params => .... )
</code>```

Also, if you find yourself duplicating code, this can be mitigated by moving the common expression out. With functional (side-effect-free) code like Slick, this kind of refactoring is quite safe. You can just build a couple of val or def with the Slick actions you need to run and compose them later.

```<code>def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val getUserId = LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
    val insertOAuth = for {
        userId <- getUserId
        _ = (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
    } yield userId

    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- insertOAuth
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None =>
         insertOAuth
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}
</code>```

Body:
I have a use-case maybe not specific to Slick but to for-comprehensions. The high level pattern is like this but it leads to a compiler error in enum3:

(for {
   enum1 <- // ...
   enum2 <- // ...
   enum3 <- optionArg.fold(empty result).map { ... }
 } yield ())

Then I end up doing the following that compiles but has code duplication namely of enum1 and enum2:

optionArg match {
  case (Some(arg)) => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
        enum3 <- // do something with arg
      } yield ())
    }
    case None => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
      } yield ())
    }
  }
}

In concrete I have that this repetitive variant compiles:

/**
 * Returns the inserted `oauth2Info` instance including the params. We first
 * look up the `LoginInfo` by the relevant search criteria, fetching its `userId`
 * which is then used to persist a `OAuth2Info` and multiple `OAuth2InfoParam`.
 *
 * @param extLoginInfo The login info for which the auth info should be added.
 * @param extOAuth2Info The TOTP info to add containing the params.
 * @return the inserted `oauth2Info` instance including the params.
 */
def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
        } yield ())
      }
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}

and this succinct desired variant doesn't:

def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = (for {
      userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
      _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
      _ <- extOAuth2Info.params.fold(DBIOAction.seq()) { params =>
        DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
      }
    } yield ()).transactionally
    db.run(insertion).map(_ => extOAuth2Info)
}

Gives compiles error:

[play-silhouette-seed] $ compile
[info] Formatting 1 Scala source ProjectRef(uri("file:/home/skywalker/code/play-silhouette-seed/"), "root")(compile) ...
[info] Compiling 1 Scala source to /home/skywalker/code/play-silhouette-seed/target/scala-2.12/classes ...
[error] /home/skywalker/code/play-silhouette-seed/app/models/daos/OAuth2InfoDaoImpl.scala:58:28: type mismatch;
[error]  found   : slick.dbio.DBIOAction[scala.collection.immutable.Iterable[Int],slick.dbio.NoStream,slick.dbio.Effect.Write]
[error]  required: slick.dbio.DBIOAction[Unit,slick.dbio.NoStream,slick.dbio.Effect]
[error]         DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
[error]                            ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed May 28, 2019 10:42:00 AM

Body:
This is a problem with fold when the compiler cannot type-infer the proper generic types for the expression. It does not properly widen the type returned from the first expression to the type of the second one. You need to help the compiler a bit.

It also happens in situations like this

 Some(123).fold(None)(_ => Some("123"))
 // type mismatch; found: Some[String] required: None.type

You can change fold to map().getOrElse() (then the "good type" comes first and get be inferred).

Or you can add type annotations somewhere, such as

 private val noAction: slick.dbio.DBIOAction[Iterable[Int],NoStream,Effect.Write]
   = DBIOAction.sequence()

 theOption.fold(noAction)(params => .... )

Also, if you find yourself duplicating code, this can be mitigated by moving the common expression out. With functional (side-effect-free) code like Slick, this kind of refactoring is quite safe. You can just build a couple of val or def with the Slick actions you need to run and compose them later.

def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val getUserId = LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
    val insertOAuth = for {
        userId <- getUserId
        _ = (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
    } yield userId

    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- insertOAuth
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None =>
         insertOAuth
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}


来源: stackexchange

问:
Regular Expression in Java for Password Pattern
The regex not working for "At least one Alphabets,At least one Digits and At least one Special Characters" and "At least one Digits and At least one Special Characters"

For example :

```<code>String passwordpattern="A9009"; //Not working for  pattern3
</code>```

Note:It should check atleast one Alphabets, Digits and Special Characters

and

```<code>String passwordpattern="A3566523"; //Not working for  pattern4
</code>```

Note:It should check at least one Special character and at least Digit

```<code>    //Alphabets, Digits and Special Characters
            String pattern3 = "[^\\\\w\\\\d]*(([0-9]+.*[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*)|[A-Za-z]+.*[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*[0-9]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*[A-Za-z]+.*|[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*|[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*)";

   //Digits and Special Characters
  String pattern4 = "([^\\\\w\\\\d]*(([!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*)|[0-9]+.*([!#%&'()*+,-:;<=>?@]+.*)))";
</code>```

答:
This regex pattern will do what you want - match only if there is at least one alphabetic letter, one digit and one special character in a given string input:

^(?=.)[a-zA-Z]+[0-9]+[^\w]+[^\s]+

ContentLicense: CC BY-SA 4.0

Body:
The regex not working for "At least one Alphabets,At least one Digits and At least one Special Characters" and "At least one Digits and At least one Special Characters"

For example :

String passwordpattern="A9009"; //Not working for  pattern3

Note:It should check atleast one Alphabets, Digits and Special Characters

and

String passwordpattern="A3566523"; //Not working for  pattern4

Note:It should check at least one Special character and at least Digit

    //Alphabets, Digits and Special Characters
            String pattern3 = "[^\\\\w\\\\d]*(([0-9]+.*[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*)|[A-Za-z]+.*[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*[0-9]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*[A-Za-z]+.*|[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*|[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*)";

   //Digits and Special Characters
  String pattern4 = "([^\\\\w\\\\d]*(([!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*)|[0-9]+.*([!#%&'()*+,-:;<=>?@]+.*)))";


问:
Angular, ng-ckeditor, and the editor-destroy-iframe bug
This posting is regards ng2-ckeditor@1.1.13 loaded with ckeditor@4.8.0.

Although there are a couple of articles on SO with this question I believe this is still an open question.  Please do not mark this posting as a duplicate.

To replicate problem:  1) instantiate a DOM element with the ckeditor directive.  2) navigate away from the view in such a way that the Angular Component that is hosting the ckeditor is destroyed.  You get this in the Javascript console:

```<code>ckeditor.js:19 [CKEDITOR] Error code: editor-destroy-iframe.
</code>```

There is a closed bug on github over this with no apparent or acceptable solution, unless I missed it.  If there is a solution there we should document it on this post because it is incomplete or obscure.

The problem is apparently that Angular framework destroys the iframe element before the ckeditor itself is destroyed. This causes the diagnostic message.

One proposed solution involves the use of a plugin called divarea.  From what I understand this replaces the iframe with a div element.  The reason this is problematic is that the CSS elements from the hosting page will be mixed in with the CSS that CKEDITOR uses.

Another proposed solution involves the following snippet of code:

```<code>for (name in CKEDITOR.instances) {
    CKEDITOR.instances[name].destroy(true);
}
</code>```

This SO posting mentions this and asks for where this code can be inserted.  There is no Angular lifecycle event that seems to work.  Even if it did this would not be an acceptable fix because it destroys all CKEDITOR instances and in my application there might be more than one on the page that might survive a router event.

Along those lines I discovered that I can find "my" CKEDITOR instance in my Angular Component with these steps.  In the template:

```<code>  <ckeditor id="content"
            #editor
            [(ngModel)]="editorContent"
            [config]="{}"
            debounce="500"
            name="content"
  ></ckeditor>
</code>```

Which is standard except for the #editor directive which establishes a local variable.  Then in the component you can build a method like this:

```<code>declare const CKEDITOR: any;

@Component() ....

  @ViewChild('editor') ckeditor: CKEditorComponent;

  destroyEditor() {
     var name = this.ckeditor.instance.name;
     CKEDITOR.instances[name].destroy(true);
  }
</code>```

So the question is: where to call the destroyEditor function?  (Other question is whether the destroy(true) method is the right one to call.)

Calling it from ngOnDestroy does not work.   Catching an event from the router hasn't worked either.   Any other suggestions?

答:
If modifying JS-files under node_module is not desired, as in my case, call the following function from ngOnDestroy():

public destroyEditor(): void {
  const editor = window['CKEDITOR'];
  if (editor.instances) {
      for (const editorInstance in editor.instances) {
          if (editor.instances.hasOwnProperty(editorInstance) &&
              editor.instances[editorInstance]) {
              editor.instances[editorInstance].destroy();
              editor.instances[editorInstance] = {
                  destroy: () => true,
              };
          }
      }
}```
</div>
</div>
</p>

<p>Note, that after destroying, a dummy object is assigned to the collection item to prevent a JS error, when the component is to be destroyed from the native function.
The component must implement OnDestroy interface and the destroyEditor() function called like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class RichTextEditorComponent implements OnDestroy {
    public ngOnDestroy(): void {
        this.destroyEditor();
    }
}</code>```

ContentLicense: CC BY-SA 3.0

Body:
This posting is regards ng2-ckeditor@1.1.13 loaded with ckeditor@4.8.0.

Although there are a couple of articles on SO with this question I believe this is still an open question.  Please do not mark this posting as a duplicate.

To replicate problem:  1) instantiate a DOM element with the ckeditor directive.  2) navigate away from the view in such a way that the Angular Component that is hosting the ckeditor is destroyed.  You get this in the Javascript console:

ckeditor.js:19 [CKEDITOR] Error code: editor-destroy-iframe.

There is a closed bug on github over this with no apparent or acceptable solution, unless I missed it.  If there is a solution there we should document it on this post because it is incomplete or obscure.

The problem is apparently that Angular framework destroys the iframe element before the ckeditor itself is destroyed. This causes the diagnostic message.

One proposed solution involves the use of a plugin called divarea.  From what I understand this replaces the iframe with a div element.  The reason this is problematic is that the CSS elements from the hosting page will be mixed in with the CSS that CKEDITOR uses.

Another proposed solution involves the following snippet of code:

for (name in CKEDITOR.instances) {
    CKEDITOR.instances[name].destroy(true);
}

This SO posting mentions this and asks for where this code can be inserted.  There is no Angular lifecycle event that seems to work.  Even if it did this would not be an acceptable fix because it destroys all CKEDITOR instances and in my application there might be more than one on the page that might survive a router event.

Along those lines I discovered that I can find "my" CKEDITOR instance in my Angular Component with these steps.  In the template:

  <ckeditor id="content"
            #editor
            [(ngModel)]="editorContent"
            [config]="{}"
            debounce="500"
            name="content"
  ></ckeditor>

Which is standard except for the #editor directive which establishes a local variable.  Then in the component you can build a method like this:

declare const CKEDITOR: any;

@Component() ....

  @ViewChild('editor') ckeditor: CKEditorComponent;

  destroyEditor() {
     var name = this.ckeditor.instance.name;
     CKEDITOR.instances[name].destroy(true);
  }

So the question is: where to call the destroyEditor function?  (Other question is whether the destroy(true) method is the right one to call.)

Calling it from ngOnDestroy does not work.   Catching an event from the router hasn't worked either.   Any other suggestions?

Body:
If modifying JS-files under node_module is not desired, as in my case, call the following function from ngOnDestroy():

public destroyEditor(): void {
  const editor = window['CKEDITOR'];
  if (editor.instances) {
      for (const editorInstance in editor.instances) {
          if (editor.instances.hasOwnProperty(editorInstance) &&
              editor.instances[editorInstance]) {
              editor.instances[editorInstance].destroy();
              editor.instances[editorInstance] = {
                  destroy: () => true,
              };
          }
      }
}

Note, that after destroying, a dummy object is assigned to the collection item to prevent a JS error, when the component is to be destroyed from the native function.
The component must implement OnDestroy interface and the destroyEditor() function called like this:

export class RichTextEditorComponent implements OnDestroy {
    public ngOnDestroy(): void {
        this.destroyEditor();
    }
}


问:
Find elemtnt*s* return array with same element
I've been up on this for 2 days.

Trying to get all Text(s) from span(s), which appear in many div(s).

All the div(s) looks pretty much the same :

```<code><div class="_3_7SH _3DFk6 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">TEXT TO COPY IS ME</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>

</code>```

This is how tried to find ALL "message-in" elements :

in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

I got back the length of the array: 11

Then, tried to get all text from span(s):

```<code>for index in in_mesg_arr:
   last_msg = last_msg + str(index.find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)
</code>```

HOWEVER, i get back the same text (same element over and over!).

print(last_msg) = bla bla bla bla bla bla bla bla bla bla bla

Will be glad to get some directions.

FULL HTML:

答:
```<code>for index in last_msg:
   last_msg = last_msg + str(in_mesg_arr[index].find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)
</code>```

This code will always returns the 1st element because it will search span element any where in the DOM.

The XPath expression in the loop has to start with a dot to be context-specific.Use any of the following code.

```<code> in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")
    for item in in_mesg_arr:
        spanele=item.find_element_by_xpath(".//span[contains(@class,'selectable-text invisible-space copyable-text')]")
        print(spanele.text)
</code>```

OR

```<code>in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

for item in range(len(in_mesg_arr)):
    spanele=in_mesg_arr[item].find_element_by_xpath(".//span[contains(@class,'selectable-text invisible-space copyable-text')]")
    print(spanele.text)
</code>```

Let me know how it goes.

Body:
I've been up on this for 2 days.

Trying to get all Text(s) from span(s), which appear in many div(s).

All the div(s) looks pretty much the same :

TEXT TO COPY IS ME

10:26 AM

This is how tried to find ALL "message-in" elements :

in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

I got back the length of the array: 11

Then, tried to get all text from span(s):

for index in in_mesg_arr:
   last_msg = last_msg + str(index.find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)

HOWEVER, i get back the same text (same element over and over!).

print(last_msg) = bla bla bla bla bla bla bla bla bla bla bla

Will be glad to get some directions.

FULL HTML:

Body:
for index in last_msg:
   last_msg = last_msg + str(in_mesg_arr[index].find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)

This code will always returns the 1st element because it will search span element any where in the DOM.

The XPath expression in the loop has to start with a dot to be context-specific.Use any of the following code.

 in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")
    for item in in_mesg_arr:
        spanele=item.find_element_by_xpath(".//span[contains(@class,'selectable-text invisible-space copyable-text')]")
        print(spanele.text)

OR

in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

for item in range(len(in_mesg_arr)):
    spanele=in_mesg_arr[item].find_element_by_xpath(".//span[contains(@class,'selectable-text invisible-space copyable-text')]")
    print(spanele.text)

Let me know how it goes.


问:
Eclipse BIRT Designer
I am attempting to create a table with the format of information below in the reporting tool, BIRT Designer. I have labeled the images with the wanted and unwanted outputs. Currently I am running into the issue with Unwanted Output. I want to list the count of each fruit by name. The count is currently adding all of the fruit regardless of the subject.

I have a group in the table and it is grouping based on name currently.

Unwanted Output

Wanted Output

答:
Once you group the table, say on Region and you need aggregation of sales column:
When you are aggregating the column, make sure you select Aggregation On Group and not on Table

Hope this works!

Title: Eclipse BIRT Designer


问:
FCM Push Notification with Action Button Not Working
I develop an Android application, where the user can receive an earthquake information. If user's device has location close to the earthquake location, the notification will have 2 buttons to confirm if they're being safe or evacuated from that happening earthquake. I'm stuck in a process while the user press 1 of the 2 buttons in notification (SAFE or EVACUATED).

Here is my code :

MyFirebaseInstanceService.java

```<code>private void showNotification(String title, String body) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "com.example.yohan.notifgempafcm";

    Intent amanIntent = setIntent(body, "SAFE");
    Intent evakuasiIntent = setIntent(body, "EVACUATED");

    PendingIntent pendingIntentAman = PendingIntent.getBroadcast(this, 0, amanIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pendingIntentEvakuasi = PendingIntent.getActivity(this, 1, evakuasiIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.enableLights(true);
        notificationChannel.setDescription("Info Gempa");
        notificationChannel.setLightColor(Color.BLUE);
        if (title.contains("WASPADA GEMPA")) {
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        }
        notificationManager.createNotificationChannel(notificationChannel);
    }

    NotificationCompat.Action actAman = new NotificationCompat.Action.Builder(android.R.drawable.ic_secure, "AMAN", pendingIntentAman).build();
    NotificationCompat.Action actEvakuasi = new NotificationCompat.Action.Builder(android.R.drawable.ic_partial_secure, "EVAKUASI", pendingIntentEvakuasi).build();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    notificationBuilder.setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(body)
            .setContentInfo("Info");
    if (title.contains("WASPADA GEMPA")) {
        notificationBuilder.addAction(actAman);
        notificationBuilder.addAction(actEvakuasi);
    }
    final Notification notification = notificationBuilder.build();
    notificationManager.notify(11111, notification);
}

public Intent setIntent(String body, String status){
    Intent intent = new Intent(this, NotificationActionReceiver.class);
    intent.putExtra("tanggal", (body.split(" ")[2] + " " + body.split(" ")[3]));
    intent.putExtra("token", token);
    intent.putExtra("status", status);
    return intent;
}
</code>```

NotificationActionReceiver.java

```<code>public class NotificationActionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String tanggal = intent.getStringExtra("tanggal");
        String token = intent.getStringExtra("token");
        String status = intent.getStringExtra("status");
        konfirmasi(context, tanggal, token, status);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(11111);
    }

    public void konfirmasi(final Context context, String tanggal, String token, String status){
        HashMap<String, String> data = pushData(tanggal, token, status);
        PostResponseAsyncTask konfirm = new PostResponseAsyncTask(context, data, new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                if (s.equals("UPDATED")){
                    Toast.makeText(context, "Konfirmasi berhasil disimpan", Toast.LENGTH_SHORT).show();
                }
            }
        });
        konfirm.execute(LoginActivity.URL + "notifikasi/changeStatus");
    }

    public HashMap<String, String> pushData(String tanggal, String token, String status){
        HashMap<String, String> data = new HashMap<>();
        data.put("datetime", tanggal);
        data.put("token", token);
        data.put("konfirmasi", status);
        return data;
    }
}
</code>```

I expect (example) if user press SAFE button in notification, it will safe the confirmation status from the user from NOTIFIED (default) to SAFE in database server, and so on. But it returns an error :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.yohan.notifgempafcm, PID: 3821
    java.lang.RuntimeException: Unable to start receiver com.example.yohan.notifgempafcm.NotificationActionReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2621)
        at android.app.ActivityThread.access$1700(ActivityThread.java:153)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5293)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:569)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
        at android.app.Dialog.show(Dialog.java:298)
        at com.kosalgeek.genasync12.PostResponseAsyncTask.onPreExecute(PostResponseAsyncTask.java:151)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
        at android.os.AsyncTask.execute(AsyncTask.java:539)
        at com.example.yohan.notifgempafcm.NotificationActionReceiver.konfirmasi(NotificationActionReceiver.java:36)
        at com.example.yohan.notifgempafcm.NotificationActionReceiver.onReceive(NotificationActionReceiver.java:21)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2614)
        at android.app.ActivityThread.access$1700(ActivityThread.java:153)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5293)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

Any solution?

答:
In this case error prone code is

```<code>  Toast.makeText(context, "Konfirmasi berhasil disimpan", Toast.LENGTH_SHORT).show();
</code>```

BroadcastReceiver are allowed to run for up to 10 seconds . If you access the context after it it will be invalid(This is your case). Also if this is the only stuff in Process at that time then this Process will be killed and it won't care your API is being called or not . So you should not directly do long running operation inside #onReceive().
 Documentation

To resolve this with your code you can use goAsync(). This will keep the broadcast active after returning from that function . Before using this please read the documentation of #goAsync().

Here is an example of goAsync().

To do this more elegant way You can start an IntentService which handle the API call in background thread automatically .

Body:
I develop an Android application, where the user can receive an earthquake information. If user's device has location close to the earthquake location, the notification will have 2 buttons to confirm if they're being safe or evacuated from that happening earthquake. I'm stuck in a process while the user press 1 of the 2 buttons in notification (SAFE or EVACUATED).

Here is my code :

MyFirebaseInstanceService.java

private void showNotification(String title, String body) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "com.example.yohan.notifgempafcm";

    Intent amanIntent = setIntent(body, "SAFE");
    Intent evakuasiIntent = setIntent(body, "EVACUATED");

    PendingIntent pendingIntentAman = PendingIntent.getBroadcast(this, 0, amanIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pendingIntentEvakuasi = PendingIntent.getActivity(this, 1, evakuasiIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.enableLights(true);
        notificationChannel.setDescription("Info Gempa");
        notificationChannel.setLightColor(Color.BLUE);
        if (title.contains("WASPADA GEMPA")) {
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        }
        notificationManager.createNotificationChannel(notificationChannel);
    }

    NotificationCompat.Action actAman = new NotificationCompat.Action.Builder(android.R.drawable.ic_secure, "AMAN", pendingIntentAman).build();
    NotificationCompat.Action actEvakuasi = new NotificationCompat.Action.Builder(android.R.drawable.ic_partial_secure, "EVAKUASI", pendingIntentEvakuasi).build();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    notificationBuilder.setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(body)
            .setContentInfo("Info");
    if (title.contains("WASPADA GEMPA")) {
        notificationBuilder.addAction(actAman);
        notificationBuilder.addAction(actEvakuasi);
    }
    final Notification notification = notificationBuilder.build();
    notificationManager.notify(11111, notification);
}

public Intent setIntent(String body, String status){
    Intent intent = new Intent(this, NotificationActionReceiver.class);
    intent.putExtra("tanggal", (body.split(" ")[2] + " " + body.split(" ")[3]));
    intent.putExtra("token", token);
    intent.putExtra("status", status);
    return intent;
}

NotificationActionReceiver.java

public class NotificationActionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String tanggal = intent.getStringExtra("tanggal");
        String token = intent.getStringExtra("token");
        String status = intent.getStringExtra("status");
        konfirmasi(context, tanggal, token, status);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(11111);
    }

    public void konfirmasi(final Context context, String tanggal, String token, String status){
        HashMap<String, String> data = pushData(tanggal, token, status);
        PostResponseAsyncTask konfirm = new PostResponseAsyncTask(context, data, new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                if (s.equals("UPDATED")){
                    Toast.makeText(context, "Konfirmasi berhasil disimpan", Toast.LENGTH_SHORT).show();
                }
            }
        });
        konfirm.execute(LoginActivity.URL + "notifikasi/changeStatus");
    }

    public HashMap<String, String> pushData(String tanggal, String token, String status){
        HashMap<String, String> data = new HashMap<>();
        data.put("datetime", tanggal);
        data.put("token", token);
        data.put("konfirmasi", status);
        return data;
    }
}

I expect (example) if user press SAFE button in notification, it will safe the confirmation status from the user from NOTIFIED (default) to SAFE in database server, and so on. But it returns an error :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.yohan.notifgempafcm, PID: 3821
    java.lang.RuntimeException: Unable to start receiver com.example.yohan.notifgempafcm.NotificationActionReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2621)
        at android.app.ActivityThread.access$1700(ActivityThread.java:153)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5293)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:569)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
        at android.app.Dialog.show(Dialog.java:298)
        at com.kosalgeek.genasync12.PostResponseAsyncTask.onPreExecute(PostResponseAsyncTask.java:151)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
        at android.os.AsyncTask.execute(AsyncTask.java:539)
        at com.example.yohan.notifgempafcm.NotificationActionReceiver.konfirmasi(NotificationActionReceiver.java:36)
        at com.example.yohan.notifgempafcm.NotificationActionReceiver.onReceive(NotificationActionReceiver.java:21)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2614)
        at android.app.ActivityThread.access$1700(ActivityThread.java:153)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5293)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Any solution?

Body:
In this case error prone code is

  Toast.makeText(context, "Konfirmasi berhasil disimpan", Toast.LENGTH_SHORT).show();

BroadcastReceiver are allowed to run for up to 10 seconds . If you access the context after it it will be invalid(This is your case). Also if this is the only stuff in Process at that time then this Process will be killed and it won't care your API is being called or not . So you should not directly do long running operation inside #onReceive().
 Documentation

To resolve this with your code you can use goAsync(). This will keep the broadcast active after returning from that function . Before using this please read the documentation of #goAsync().

Here is an example of goAsync().

To do this more elegant way You can start an IntentService which handle the API call in background thread automatically .


问:
pySerial serial.open() works in interactive shell but raises exception as a script
EDIT: It seems like the issue might have to do with Python 3. I tried executing the script in a Anaconda Environment of Python 2.7.15 and was able to get it to work. Thinking it might be just Anaconda, I tried running it in a Anaconda Environment of Python 3.6.5 and ran into the same error. To remove the variable of Anaconda, I tried running Python 2.7.15 from a fresh install without Anaconda and was again able to get the script running properly. Note that my original problem came up when running through a non-Anaconda Python3 environment. I do not think this really answers the question but is somewhat of a solution for anyone running into the same issue.

Windows 10. Python 3.6.5

I am trying to establish/open a connection with a connected COM port through pyserial. I am able to do this just fine through a Python shell started in cmd, but receive an exception when running it through a script. The exception chain is this:

```<code>File "C:\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 62, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM8': OSError(22, 'Element not found.', None, 1168)
</code>```

The script is this:

```<code>import serial.tools.list_ports
import time
import sys

SERIAL_CONNECTION_ATTEMPTS = 3

ports = list(serial.tools.list_ports.comports())
bluetoothPorts = []

for p in ports:
    if 'Bluetooth' in p.description:
        bluetoothPorts.append(p)
        print("Found: ", p)

selectedPort = bluetoothPorts[0]
print("selected port: ", selectedPort.device)

ser = serial.Serial()
ser.baudrate = 9600
ser.timeout = 120
ser.port = selectedPort.device

for i in range(0, SERIAL_CONNECTION_ATTEMPTS):
    try:
        ser.open()
        time.sleep(5)
        if ser.is_open():
            break
    except:
        print(sys.exc_info())
        if i == SERIAL_CONNECTION_ATTEMPTS-1:
            print("Failed to connect. Will stop trying now.")
            exit()
        print("Failed to connect. Retrying...")
        ser.close()
        time.sleep(5)

print(ser.read(32))
print("Closing out now..")
ser.close()
</code>```

Successful connections using the interactive shell follow the script exactly, excluding the use of the try-except block.

One thing I have noticed is that the target device seems to recognize a connection attempt for a very brief moment. I am able to make this guess because the target device has an LED to indicate an established serial connection. When the script runs to the ser.open(), this LED flashes for a moment before quickly turning off. On the other hand, when ser.open() is attempted in the interactive shell, the shell blocks until the connection is made and the LED stays lit.

Please let me know if any additional information would help.

答:
well you know Bluetooth, it doesn't work from the first attempt, just give it a try, one and two and three ... </p>

```<code>def getSerialOrNone(port, conn_att):
connec_attempts = 0
ser = None
while ser is None:
    try:
        connec_attempts+=1
        print('connect attempts to %s num %d' % (port , (connec_attempts)))
        ser = serial.Serial(port, 9600,timeout=1.5, parity=serial.PARITY_NONE,
                                stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
        if connec_attempts == conn_att:
                print('Serial connection error',
                                       'Failed to commect to port  ', self.port  )
                return None
#time.sleep(2)
    except Exception as e:
            print('Serial connection error',
                                   'Error sending message "%s" to controller:\n%s' %
                               (port, e))
return ser
</code>```

Body:
EDIT: It seems like the issue might have to do with Python 3. I tried executing the script in a Anaconda Environment of Python 2.7.15 and was able to get it to work. Thinking it might be just Anaconda, I tried running it in a Anaconda Environment of Python 3.6.5 and ran into the same error. To remove the variable of Anaconda, I tried running Python 2.7.15 from a fresh install without Anaconda and was again able to get the script running properly. Note that my original problem came up when running through a non-Anaconda Python3 environment. I do not think this really answers the question but is somewhat of a solution for anyone running into the same issue.

Windows 10. Python 3.6.5

I am trying to establish/open a connection with a connected COM port through pyserial. I am able to do this just fine through a Python shell started in cmd, but receive an exception when running it through a script. The exception chain is this:

File "C:\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 62, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM8': OSError(22, 'Element not found.', None, 1168)

The script is this:

import serial.tools.list_ports
import time
import sys

SERIAL_CONNECTION_ATTEMPTS = 3

ports = list(serial.tools.list_ports.comports())
bluetoothPorts = []

for p in ports:
    if 'Bluetooth' in p.description:
        bluetoothPorts.append(p)
        print("Found: ", p)

selectedPort = bluetoothPorts[0]
print("selected port: ", selectedPort.device)

ser = serial.Serial()
ser.baudrate = 9600
ser.timeout = 120
ser.port = selectedPort.device

for i in range(0, SERIAL_CONNECTION_ATTEMPTS):
    try:
        ser.open()
        time.sleep(5)
        if ser.is_open():
            break
    except:
        print(sys.exc_info())
        if i == SERIAL_CONNECTION_ATTEMPTS-1:
            print("Failed to connect. Will stop trying now.")
            exit()
        print("Failed to connect. Retrying...")
        ser.close()
        time.sleep(5)

print(ser.read(32))
print("Closing out now..")
ser.close()

Successful connections using the interactive shell follow the script exactly, excluding the use of the try-except block.

One thing I have noticed is that the target device seems to recognize a connection attempt for a very brief moment. I am able to make this guess because the target device has an LED to indicate an established serial connection. When the script runs to the ser.open(), this LED flashes for a moment before quickly turning off. On the other hand, when ser.open() is attempted in the interactive shell, the shell blocks until the connection is made and the LED stays lit.

Please let me know if any additional information would help.

Body:
well you know Bluetooth, it doesn't work from the first attempt, just give it a try, one and two and three ...

def getSerialOrNone(port, conn_att):
connec_attempts = 0
ser = None
while ser is None:
    try:
        connec_attempts+=1
        print('connect attempts to %s num %d' % (port , (connec_attempts)))
        ser = serial.Serial(port, 9600,timeout=1.5, parity=serial.PARITY_NONE,
                                stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
        if connec_attempts == conn_att:
                print('Serial connection error',
                                       'Failed to commect to port  ', self.port  )
                return None
#time.sleep(2)
    except Exception as e:
            print('Serial connection error',
                                   'Error sending message "%s" to controller:\n%s' %
                               (port, e))
return ser


问:
How to write the init for the child class of this class?
I'm trying to write a sub class from this class:

```<code>class InsertCreateAlter(object):

def __init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs):
    if connection is not None:
        self.engine = connection
    elif engine is not None:
        self.engine = engine
    elif session is not None:
        self.engine = session
    else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)
</code>```

This was my attempt so far:

```<code>class InsertCreateAlterEAV(InsertCreateAlter):

def __init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs):
    InsertCreateAlter.__init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs)
    if connection is not None:
        self.engine = connection
    elif engine is not None:
        self.engine = engine
    elif session is not None:
        self.engine = session
    else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)
</code>```

When I call the function as:

```<code>InsertCreateAlterEAV(session=session)
</code>```

I got the error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-ee54fec26f76>", line 2, in <module>
    InsertCreateAlterEAV(session=session)
  File "/Users/asportelli/Documents/gitRepos/etl/etl/eav/InsertCreateAlterEAV.py", line 18, in __init__
    **kwargs)
  File "/Users/asportelli/Documents/gitRepos/etl/etl/insert/InsertCreateAlter.py", line 27, in __init__
    self.engine = sqlalchemy.create_engine(url, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 425, in create_engine
    return strategy.create(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 52, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
</code>```

答:
You should not duplicate the code of the parent class. Do it like this:

```<code>class InsertCreateAlterEAV(InsertCreateAlter):
    def __init__(self, url=None, engine=None, connection=None, session=None,
                 **kwargs):
        # Do you have code you want to run before running the parent's __init__?
        # Maybe adding default arguments or changing one of them?
        # Then add that code here.

        # init the parent
        super().__init__(url=url,
                         engine=engine,
                         connection=connection,
                         session=session,
                         **kwargs)

        # Here you can add code after the parent's init code. Maybe for
        # initializing subclass-specific attributes.
</code>```

In case you are still using Python 2, use InsertCreateAlter.__init__(self, ...

Now let's see what the problem was. You call your subclass as follows:

```<code>InsertCreateAlterEAV(session=session)
</code>```

then your subclass calls the parent class' __init__ method, but with session=None. Therefore, the parent class takes this branch:

```<code>else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)
</code>```

and because kwargs is empty, only url (which is None) is passed to create_engine(). This method does not know how to deal with url==None.

Thus, you get an exception.

Body:
I'm trying to write a sub class from this class:

class InsertCreateAlter(object):

def __init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs):
    if connection is not None:
        self.engine = connection
    elif engine is not None:
        self.engine = engine
    elif session is not None:
        self.engine = session
    else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)

This was my attempt so far:

class InsertCreateAlterEAV(InsertCreateAlter):

def __init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs):
    InsertCreateAlter.__init__(self, url=None, engine=None, connection=None, session=None,
             **kwargs)
    if connection is not None:
        self.engine = connection
    elif engine is not None:
        self.engine = engine
    elif session is not None:
        self.engine = session
    else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)

When I call the function as:

InsertCreateAlterEAV(session=session)

I got the error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-ee54fec26f76>", line 2, in <module>
    InsertCreateAlterEAV(session=session)
  File "/Users/asportelli/Documents/gitRepos/etl/etl/eav/InsertCreateAlterEAV.py", line 18, in __init__
    **kwargs)
  File "/Users/asportelli/Documents/gitRepos/etl/etl/insert/InsertCreateAlter.py", line 27, in __init__
    self.engine = sqlalchemy.create_engine(url, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 425, in create_engine
    return strategy.create(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 52, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'

Body:
You should not duplicate the code of the parent class. Do it like this:

class InsertCreateAlterEAV(InsertCreateAlter):
    def __init__(self, url=None, engine=None, connection=None, session=None,
                 **kwargs):
        # Do you have code you want to run before running the parent's __init__?
        # Maybe adding default arguments or changing one of them?
        # Then add that code here.

        # init the parent
        super().__init__(url=url,
                         engine=engine,
                         connection=connection,
                         session=session,
                         **kwargs)

        # Here you can add code after the parent's init code. Maybe for
        # initializing subclass-specific attributes.

In case you are still using Python 2, use InsertCreateAlter.__init__(self, ...

Now let's see what the problem was. You call your subclass as follows:

InsertCreateAlterEAV(session=session)

then your subclass calls the parent class' __init__ method, but with session=None. Therefore, the parent class takes this branch:

else:
        self.engine = sqlalchemy.create_engine(url, **kwargs)

and because kwargs is empty, only url (which is None) is passed to create_engine(). This method does not know how to deal with url==None.

Thus, you get an exception.


问:
Deploy EventGrid using powershell
I have an EventGrid for analyzing the device active and inactive status which means Azure IOT collect the information from sensors and publish the event to EventGrid and subscribe to Azure Queue. It is working fine. Now, I want to deploy this EventGrid functionality to cloud using PowerShell. I have checked a lot of EventGrid document deployment using Azure PowerShell. We can deploy the EventGrid with Queue subscription. But could not find any input from IoT. How will we set input from IoT hub?</p>

答:
There might be a way to subscribe to and filter all of the events of a resource group. Provided that your IoT hub is part of a resource group, perhaps you can receive all events from it?

I imagine you've tried that though.https://learn.microsoft.com/en-us/powershell/azure/get-started-azureps?view=azps-1.8.0

If the above link doesn't help you. I would request you to let me know, –

Title: Deploy EventGrid using powershell


问:
How to save input values on server using puppeteer?
How to save input fields value on server ? i want to save form value after i submit the values disappears  when i reopen the form . </p>

```<code> await page.$$eval("input[data-bind='value: SyringeOut']",el=>{
            for(i=0; i<el.length; i++){
                el[i].value=3;
            }
        });
</code>```

答:
all i have to first double click on input element then type figure/value in it. the final code look like this </p>

```<code>await page.$$("input[data-bind='value: SyringeOut']").then(async(ee)=>{
        for(var i=0; i<ee.length; i++){
            await ee[i].click({clickCount:2});
            await ee[i].type('3');
            }

    });
</code>```

Body:
How to save input fields value on server ? i want to save form value after i submit the values disappears  when i reopen the form .

 await page.$$eval("input[data-bind='value: SyringeOut']",el=>{
            for(i=0; i<el.length; i++){
                el[i].value=3;
            }
        });

Body:
all i have to first double click on input element then type figure/value in it. the final code look like this

await page.$$("input[data-bind='value: SyringeOut']").then(async(ee)=>{
        for(var i=0; i<ee.length; i++){
            await ee[i].click({clickCount:2});
            await ee[i].type('3');
            }

    });


问:
Rails console tips, tricks and customizations
There's this great post on irb tricks, but what about further customizing Rails console behavior and output?

Awesome print and Hirb are great.

SQL logging  is a must for me. In your ~/.irbrc paste:

```<code>require 'logger'
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(Rails)
</code>```

What's your tip/trick/gem of choice?

答: I've recently written a rails specific console tweaks blog post: https://rbjl.janlelis.com/49-railsrc-rails-console-snippets (as gist)</p>

ContentLicense: CC BY-SA 2.5

Body:
There's this great post on irb tricks, but what about further customizing Rails console behavior and output?

Awesome print and Hirb are great.

SQL logging  is a must for me. In your ~/.irbrc paste:

require 'logger'
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(Rails)

What's your tip/trick/gem of choice?


问:
Unable to fetch referral code after install android app from app store
In my application have a referral program.I want when a customer share app link, that link redirect to playstore and after install app referral code retrieve from playstore. I already do that link but I don't understand how can i receive that referral code after install.</p>

```<code>public static void shareMyApp(Context context) {

    String link = "https://play.google.com/store/apps/details?id="+context.getPackageName();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("text/*");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
    context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));
}
</code>```

答:
Create a link with referral code and send to others friends and users...

String link = http://yourdomain.com/testrefer.php?refercode=ABCD // http or https

```<code>Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));
</code>```

and in testrefer file to create app store link and append refercode and then redirect to play store using below link and then you can get referral code.

https://play.google.com/store/apps/details?id="+context.getPackageName()+"&referrer=ABCD

in Manifest file in your launching screen to write below code

```<code><activity
    android:name=".activity.SplActivity"
    android:screenOrientation="portrait"
    android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="yourdomain.com"
                android:pathPrefix="/testrefer.php"
                android:scheme="https" />  <!-- https or http -->
      </intent-filter>
</activity>
</code>```

InstallRefererReciever is a file name that you have created BroadcastReceiver

```<code><receiver
    android:name=".common.InstallRefererReciever"
    android:exported="true"
    android:permission="android.permission.INSTALL_PACKAGES">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>
</code>```

Create BroascatReceiver and write below code :

```<code>public class InstallRefererReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
          Bundle extras = intent.getExtras();
          if (extras != null) {
             String referral = extras.getString("referrer");
             Logger.e("ReferCode --> ", referral);
             if (referral != null) {
                 if (!referral.equals("utm_source=google-play&utm_medium=organic")) {
                     if (!referral.equals("com.android.chrome")) {
                       String referralCode = referral; // Store in sharedpreferences
                    }
                }
             }
          }
       }
   }

}
</code>```

Body:
In my application have a referral program.I want when a customer share app link, that link redirect to playstore and after install app referral code retrieve from playstore. I already do that link but I don't understand how can i receive that referral code after install.

public static void shareMyApp(Context context) {

    String link = "https://play.google.com/store/apps/details?id="+context.getPackageName();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("text/*");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
    context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));
}

Body:
Create a link with referral code and send to others friends and users...

String link = http://yourdomain.com/testrefer.php?refercode=ABCD // http or https

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));

and in testrefer file to create app store link and append refercode and then redirect to play store using below link and then you can get referral code.

https://play.google.com/store/apps/details?id="+context.getPackageName()+"&referrer=ABCD

in Manifest file in your launching screen to write below code

<activity
    android:name=".activity.SplActivity"
    android:screenOrientation="portrait"
    android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="yourdomain.com"
                android:pathPrefix="/testrefer.php"
                android:scheme="https" />  <!-- https or http -->
      </intent-filter>
</activity>

InstallRefererReciever is a file name that you have created BroadcastReceiver

<receiver
    android:name=".common.InstallRefererReciever"
    android:exported="true"
    android:permission="android.permission.INSTALL_PACKAGES">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

Create BroascatReceiver and write below code :

public class InstallRefererReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
          Bundle extras = intent.getExtras();
          if (extras != null) {
             String referral = extras.getString("referrer");
             Logger.e("ReferCode --> ", referral);
             if (referral != null) {
                 if (!referral.equals("utm_source=google-play&utm_medium=organic")) {
                     if (!referral.equals("com.android.chrome")) {
                       String referralCode = referral; // Store in sharedpreferences
                    }
                }
             }
          }
       }
   }

}


问:
Method Produces --> Extension method must be defined in a non-generic static class
Whenever i put in this method

```<code>  private Stream createstream(this System.Drawing.Image image, ImageFormat format)
        {
            var stream = new System.IO.MemoryStream();
            image.Save(stream, format);
            stream.Position = 0;
            return stream;
        }
</code>```

I keep getting

Extension method must be defined in a non-generic static class

As far as  i know i'm not extending anything.Please advice

答:
The compiler thinks you're trying to write an extension method. Extension methods:

Are static methods

The first parameter has this at the start of it

Are defined in a non-generic static class

The compiler saw the this in your this System.Drawing.Image image, thought you were trying to write an extension method, and complained that you weren't meeting point 3.

If you don't intend to write an extension method, then remove the this from this System.Drawing.Image image.

Body:
Whenever i put in this method

  private Stream createstream(this System.Drawing.Image image, ImageFormat format)
        {
            var stream = new System.IO.MemoryStream();
            image.Save(stream, format);
            stream.Position = 0;
            return stream;
        }

I keep getting

Extension method must be defined in a non-generic static class

As far as  i know i'm not extending anything.Please advice


问:
gpflow: Is it possible to use data that doesn't fit in memory?
I'm trying to train a gpflow model with a huge amount of data that doesn't fit in memory.

I was thinking of using SVGP with minibatch option, but it seems to require a numpy array of the full data, and I don't want to load everything all at once.

Is it possible to do training with data that doesn't fit in memory using gpflow?
Is there an example that does this?

Thanks for your help.

答:
You can pass tf.data.Dataset iterators instead of numpy data. Here is an example:

```<code>buffer_size = 10000
batch_size = 128

# x_shape is a feature shape, e.g. for CIFAR it will be [32, 32, 3]
xy_shapes = ([], [])
xy_dtypes = (tf.float32, tf.float32)

# Read data from disk
def read_data():
    # Do something, read from disk or anything else...
    yield x, y

# Make dataset, do batching and shuffling
ds = tf.data.Dataset.from_generator(read_data, xy_dtypes, xy_shapes)
ds = ds.prefetch(buffer_size)
ds = ds.repeat()
ds = ds.shuffle()
ds = ds.batch(batch_size)

# Get data iterators
x_iter, y_iter = ds.make_one_shot_iterator().get_next()
</code>```

Now you can create a model with TensorFlow iterators. The only difference from standard approach is that you have to pass num_data argument to compute scaling factor correctly.

```<code>kernel = ...
likelihood = ...
feature = ...

num_data = ... # size of your dataset
model = gpflow.models.SVGP(x_iter, y_iter, kernel, likelihood, feature, num_data=num_data)
</code>```

More information on how to work with tf.data you can find here.

Body:
You can pass tf.data.Dataset iterators instead of numpy data. Here is an example:

buffer_size = 10000
batch_size = 128

# x_shape is a feature shape, e.g. for CIFAR it will be [32, 32, 3]
xy_shapes = ([], [])
xy_dtypes = (tf.float32, tf.float32)

# Read data from disk
def read_data():
    # Do something, read from disk or anything else...
    yield x, y

# Make dataset, do batching and shuffling
ds = tf.data.Dataset.from_generator(read_data, xy_dtypes, xy_shapes)
ds = ds.prefetch(buffer_size)
ds = ds.repeat()
ds = ds.shuffle()
ds = ds.batch(batch_size)

# Get data iterators
x_iter, y_iter = ds.make_one_shot_iterator().get_next()

Now you can create a model with TensorFlow iterators. The only difference from standard approach is that you have to pass num_data argument to compute scaling factor correctly.

kernel = ...
likelihood = ...
feature = ...

num_data = ... # size of your dataset
model = gpflow.models.SVGP(x_iter, y_iter, kernel, likelihood, feature, num_data=num_data)

More information on how to work with tf.data you can find here.


问:
CGAL: efficiently finding all triangles in a volume (bounding box or ball query)
I want to efficiently find all triangles (e.g. facets of a polyhedral mesh) that are contained in or intersected by a volume (e.g. AABB or sphere query). I want to do this, if possible and reasonable, with CGALs built-in features.

My current solution is simple brute force: for all facets in mesh, check if distance of facet to ball center is smaller than the ball radius. I used a fuzzy sphere query of the KD-tree on the vertices before, but it was not accurate enough for my application. I need full sphere-triangle intersections.

The CGAL AABB tree (https://doc.cgal.org/latest/AABB_tree/index.html) seems like the best datastructure but I need the 3D linear Kernel which has no intersection test for triangles and any kind of volume (https://doc.cgal.org/latest/Kernel_23/group__intersection__linear__grp.html).
The CGAL KD tree doesn't work because it can only contain points.

My ideas are:

Add a custom do_intersect() for Triangle_3 and Sphere_3 that the AABB tree can use. Is that even possible? This will probably require a custom squared_distance() as well.

Convert the volume query into two area queries by projecting the triangles on e.g. the XY and YZ planes. Can the AABB tree even handle 2D search? There is no intersection for circle and 2D triangle but I could use the intersection of Iso_rectangle_2 and Triangle_2 as good first guess.

Somehow traverse the internals of the AABB tree and stop before I find a node that doesn't contain my query anymore.

Modify the closest_point_and_primitive() method, give an optional max_distance parameter and return all primitives within that distance. This would require me to mess with the CGAL code.

Write my own datastructure. This will take some time to get it right.

Did I miss anything? Which solution would be the least effort?

答:
Using some ideas from sloriot's answer, I was able to solve my problem.

Since the documentation of do_intersect() doesn't show an overload for Sphere_3 and Triangle_3, it's not surprising that the AABB tree doesn't support queries with Sphere_3.

However, the AABB tree supports queries with BBox_3, which is not mentioned in the do_intersect() docu.

Calling all_intersected_primitives() with the Bbox_3 returns all primitives of the AABB tree that are contained or intersection by the Bbox_3. This is a first good guess to get the actual intersections with the sphere.

With this optimization, I could reduce the query time from 20 ms (simple brute force) to 3 ms on a mesh with 100k faces where one query returns roughly 10 faces.

Here is the relevant code:

```<code>double r = CGAL::sqrt(patch_radius_squared);
CGAL::Bbox_3 query(
    sphere_center.x() - r,
    sphere_center.y() - r,
    sphere_center.z() - r,
    sphere_center.x() + r,
    sphere_center.y() + r,
    sphere_center.z() + r);

std::list<Tree::Primitive_id> primitives;
tree.all_intersected_primitives(query, std::back_inserter(primitives));

std::vector<Triangle_3> intersected_facets;
for (const Tree::Primitive_id& p : primitives)
{
    // intersection with bb gives only a good first guess -> check actual intersection
    if (CGAL::squared_distance(*p, sphere_center) <= patch_radius_squared)
    {
        intersected_facets.push_back(*p);
    }
}
</code>```

Body:
Using some ideas from sloriot's answer, I was able to solve my problem.

Since the documentation of do_intersect() doesn't show an overload for Sphere_3 and Triangle_3, it's not surprising that the AABB tree doesn't support queries with Sphere_3.

However, the AABB tree supports queries with BBox_3, which is not mentioned in the do_intersect() docu.

Calling all_intersected_primitives() with the Bbox_3 returns all primitives of the AABB tree that are contained or intersection by the Bbox_3. This is a first good guess to get the actual intersections with the sphere.

With this optimization, I could reduce the query time from 20 ms (simple brute force) to 3 ms on a mesh with 100k faces where one query returns roughly 10 faces.

Here is the relevant code:

double r = CGAL::sqrt(patch_radius_squared);
CGAL::Bbox_3 query(
    sphere_center.x() - r,
    sphere_center.y() - r,
    sphere_center.z() - r,
    sphere_center.x() + r,
    sphere_center.y() + r,
    sphere_center.z() + r);

std::list<Tree::Primitive_id> primitives;
tree.all_intersected_primitives(query, std::back_inserter(primitives));

std::vector<Triangle_3> intersected_facets;
for (const Tree::Primitive_id& p : primitives)
{
    // intersection with bb gives only a good first guess -> check actual intersection
    if (CGAL::squared_distance(*p, sphere_center) <= patch_radius_squared)
    {
        intersected_facets.push_back(*p);
    }
}


问:
How to Insert New Rows (with a condition) in Excel using Python / Pandas
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

```<code>Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3
</code>```

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

Body:
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

Body:
df = pd.DataFrame(
    data={
        'A': ['AA', 'CC', 'DD'],
        'B': [111, 222, 333],
        'C':[2, 8, 3],
        'D':[2, 12, 3],
        'E':[None, None, None],
    }
)

new_df = pd.DataFrame(
    data={
        'A': [],
        'B': [],
        'C': [],
        'D': [],
        'E': [],
    },
    dtype=np.int64
)

for idx, row in df.iterrows():
    if row['C'] == row['D']:
        new_df = new_df.append(
            pd.DataFrame(
                data={
                    'A': [row['A']],
                    'B': [int(row['B'])],
                    'C': [int(row['C'])],
                    'D': [int(row['D'])],
                    'E': [str(row['B']) + '-' + str(row['D'])],
                }
            )
        )
    elif int(row['D']) > int(row['C']):
        tmp_c = int(row['C'])
        tmp_d = int(row['D'])
        while tmp_d >= tmp_c:
            new_df = new_df.append(
                pd.DataFrame(
                    data={
                        'A': [row['A']],
                        'B': [int(row['B'])],
                        'C': [int(row['C'])],
                        'D': [tmp_c],
                        'E': [str(row['B']) + '-' + str(tmp_c)],
                    }
                )
            )
            tmp_c += 1

print(new_df)


问:
how to sync multiple UIKit accordions
I'm rendering UIKit accordions dynamically inside table rows and each one contains just one child (li) element. how can I sync these accordions so that when one of them is open, other ones get collapsed? just like the option multiple: false. it's a Vue app (in case you can provide a more specific answer).

答:
This answer is much better and more performant

i is index of the loop.

prevAccordionIndex is defined in Vue instance data and initially set to null. It is used to hold the index of previous (last) opened accordion so there's no need to loop through $refs to find the open accordion like previous answer.

All accordions are initially collapsed (closed).

methods: {
    handleAccordionShow(index) {
        if (this.prevAccordionIndex !== null) {
            this.$uikit.accordion(this.$refs.categoryAccordion[this.prevAccordionIndex]).toggle(0, false)
            this.prevAccordionIndex = index
        } else {
            this.prevAccordionIndex = index
        }
    },
    handleAccordionHide(index) {
        this.prevAccordionIndex = this.prevAccordionIndex === index ? null : index
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul ref="categoryAccordion" @beforeshow="handleAccordionShow(i)" @beforehide="handleAccordionHide(i)" uk-accordion>
  <li>...</li>
</ul></code>```

Title: how to sync multiple UIKit accordions

Body:
This answer is much better and more performant

i is index of the loop.

prevAccordionIndex is defined in Vue instance data and initially set to null. It is used to hold the index of previous (last) opened accordion so there's no need to loop through $refs to find the open accordion like previous answer.

All accordions are initially collapsed (closed).

methods: {
    handleAccordionShow(index) {
        if (this.prevAccordionIndex !== null) {
            this.$uikit.accordion(this.$refs.categoryAccordion[this.prevAccordionIndex]).toggle(0, false)
            this.prevAccordionIndex = index
        } else {
            this.prevAccordionIndex = index
        }
    },
    handleAccordionHide(index) {
        this.prevAccordionIndex = this.prevAccordionIndex === index ? null : index
    }
}

<ul ref="categoryAccordion" @beforeshow="handleAccordionShow(i)" @beforehide="handleAccordionHide(i)" uk-accordion>
  <li>...</li>
</ul>


问:
Find the smallest positive integer that does not occur in a given sequence
I was trying to solve this problem:

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

```<code>Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.
</code>```

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

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

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

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

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

```

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

答:
I achieved 100% on this by the below solution in Python:-</p>

```<code>def solution(A):
   a=frozenset(sorted(A))
   m=max(a)
   if m>0:
       for i in range(1,m):
           if i not in a:
              return i
       else:
          return m+1
   else:
       return 1
</code>```

Body:
I was trying to solve this problem:

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

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

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

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

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

Body:
I achieved 100% on this by the below solution in Python:-

def solution(A):
   a=frozenset(sorted(A))
   m=max(a)
   if m>0:
       for i in range(1,m):
           if i not in a:
              return i
       else:
          return m+1
   else:
       return 1


问:
Clipping / cropping lines and fills in matplotlib on seaborn distplot kde-function
Let's say I use seaborn to plot a distribution, it's median and standard deviation like this:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

# Plot
sns.distplot(data)
plt.axvline(median, c='r')
plt.axvline(low, c='k')
plt.axvline(hi, c='k')
```

How would I go about "cropping" or "clipping" the lines, so they only appear below the kde-function of the distplot? The result should be something like this (quickly done with gimp):

Bonus question: How would I do the same with a plt.fill_between(), so that only the area under the curve is filled? I think I'm missing something easy here. I've already clipped fill_between calls to other elements before, but I don't know how to get coordinates of the function and how to do it with lines.

Is there an easy and concise way to do what I want?

答:
You can do it by accessing the smooth distribution line plotted by the distplot. As to the bonus part, I would recommend asking a new question and not mix two problems in the same question.

The trick here is to get the x-value closest to low, median and high and then use plt.ylines instead of plt.axvline to plot a vertical line from y=0 to the desired y-value.

```<code># Plot
ax = sns.distplot(data)
x, y = ax.get_lines()[0].get_data()
plt.vlines(median, 0, y[np.argmin(abs(x-median))], color='r')
plt.vlines(low, 0, y[np.argmin(abs(x-low))], color='k')
plt.vlines(hi, 0, y[np.argmin(abs(x-hi))], color='k')
plt.show()
</code>```

Body:
Let's say I use seaborn to plot a distribution, it's median and standard deviation like this:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

# Plot
sns.distplot(data)
plt.axvline(median, c='r')
plt.axvline(low, c='k')
plt.axvline(hi, c='k')

How would I go about "cropping" or "clipping" the lines, so they only appear below the kde-function of the distplot? The result should be something like this (quickly done with gimp):

Bonus question: How would I do the same with a plt.fill_between(), so that only the area under the curve is filled? I think I'm missing something easy here. I've already clipped fill_between calls to other elements before, but I don't know how to get coordinates of the function and how to do it with lines.

Is there an easy and concise way to do what I want?

Body:
You can do it by accessing the smooth distribution line plotted by the distplot. As to the bonus part, I would recommend asking a new question and not mix two problems in the same question.

The trick here is to get the x-value closest to low, median and high and then use plt.ylines instead of plt.axvline to plot a vertical line from y=0 to the desired y-value.

# Plot
ax = sns.distplot(data)
x, y = ax.get_lines()[0].get_data()
plt.vlines(median, 0, y[np.argmin(abs(x-median))], color='r')
plt.vlines(low, 0, y[np.argmin(abs(x-low))], color='k')
plt.vlines(hi, 0, y[np.argmin(abs(x-hi))], color='k')
plt.show()


问:
Last repeating character in a string
I am searching for a solution to find the last repeating character in a string which says "how are you doing today", which supposed to give y as the answer. I have tried using Linked Hash Map to get the ordered insertions, but I am getting d as the last repeated one.

```<code>String testString  =  "how are you doing today";

    char[] testStringArray = testString.toCharArray();
    Map<Character,Integer> map = new LinkedHashMap<>();

    for( char i : testStringArray) {
     if (!(i==' ')) {
    if(map.containsKey(i) ) {
        map.put(i, map.get(i)+1);
    } else {
        map.put(i, 1);
    }
     }
    }

    System.out.println(map);

    List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
    ListIterator<Entry<Character, Integer>> it = list.listIterator(list.size());

    while(it.hasPrevious()) {
        if(it.previous().getValue() > 1)
            System.out.println(it.previous().getKey());

    }
}
</code>```

Help is appreciated.

答:
```<code>    String str="how are you doing today";

    char charArr[]=str.toCharArray();

    HashMap<Character,Integer> hMap=new HashMap();

    for(int i=0;i<charArr.length;i++)
    {
        if(hMap.containsKey(charArr[i]))
        {
            int count=hMap.get(charArr[i]);
            hMap.put(charArr[i],count+1);
        }else
        {
            hMap.put(charArr[i], 1);
        }
    }
    System.out.println(hMap);
    for(int i=charArr.length-1;i>=0;i--)
    {
        if(hMap.get(charArr[i])>1)
        {
            System.out.println("The Last Repeated Character is :"+charArr[i]);
            break;
        }
    }
</code>```

<p>Output: </p>

```<code>    { =4, a=2, d=2, e=1, g=1, h=1, i=1, n=1, o=4, r=1, t=1, u=1, w=1, y=2}

    The Last Repeated Character is : y
</code>```

Title: Last repeating character in a string

Body:
I am searching for a solution to find the last repeating character in a string which says "how are you doing today", which supposed to give y as the answer. I have tried using Linked Hash Map to get the ordered insertions, but I am getting d as the last repeated one.

String testString  =  "how are you doing today";

    char[] testStringArray = testString.toCharArray();
    Map<Character,Integer> map = new LinkedHashMap<>();

    for( char i : testStringArray) {
     if (!(i==' ')) {
    if(map.containsKey(i) ) {
        map.put(i, map.get(i)+1);
    } else {
        map.put(i, 1);
    }
     }
    }

    System.out.println(map);

    List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
    ListIterator<Entry<Character, Integer>> it = list.listIterator(list.size());

    while(it.hasPrevious()) {
        if(it.previous().getValue() > 1)
            System.out.println(it.previous().getKey());

    }
}

Help is appreciated.

Body:
    String str="how are you doing today";

    char charArr[]=str.toCharArray();

    HashMap<Character,Integer> hMap=new HashMap();

    for(int i=0;i<charArr.length;i++)
    {
        if(hMap.containsKey(charArr[i]))
        {
            int count=hMap.get(charArr[i]);
            hMap.put(charArr[i],count+1);
        }else
        {
            hMap.put(charArr[i], 1);
        }
    }
    System.out.println(hMap);
    for(int i=charArr.length-1;i>=0;i--)
    {
        if(hMap.get(charArr[i])>1)
        {
            System.out.println("The Last Repeated Character is :"+charArr[i]);
            break;
        }
    }

Output:

    { =4, a=2, d=2, e=1, g=1, h=1, i=1, n=1, o=4, r=1, t=1, u=1, w=1, y=2}

    The Last Repeated Character is : y


问:
Checking Sucsessfull Validation of Form
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

```<code>    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>
</code>```

A nudge in the right direction would be appreciated.

Title: Checking Sucsessfull Validation of Form

Body:
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>

A nudge in the right direction would be appreciated.

Body:
Use this:

if($("form").valid()){
    ....
}


问:
Adding percentage to number in SQL
I would like to add a percentage sign after a number in SQL.

This is the query I have

```<code>select cast(vetted as float)/cast(account_create as float)*100 from numbers
</code>```

I have tried using the format function to change the integer to a string and concatenate the percentage sign, but this doesn't seem to work

答: You can also use the function concat_ws to place a delimiter between a concat of number and delimeter number</p>

Title: Adding percentage to number in SQL

Body:
I would like to add a percentage sign after a number in SQL.

This is the query I have

select cast(vetted as float)/cast(account_create as float)*100 from numbers

I have tried using the format function to change the integer to a string and concatenate the percentage sign, but this doesn't seem to work


问:
create icon for multiple file upload
I would like to create an icon for multi file upload using bootstrap-4.
I have referred this below code for  single file upload >
but, how to create an icon for multi file upload

```<code>     <!DOCTYPE html>
        <html>
         <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/
          3.3.7/css/bootstrap.min.css">
          <script
   src="https://ajax.googleapis.com/ajax/libs/
     jquery/3.2.1/jquery.min.js">
       </script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/
    3.3.7/js/bootstrap.min.js"></script>
      </head>
      <body>
        <div class="container">
           <h2>Upload Glyph</h2>
  <p>Upload icon: <span class="glyphicon glyphicon-upload"></span></p>
  <p>Upload icon as a link:
    <a href="#">
      <span class="glyphicon glyphicon-upload"></span>
    </a>
  </p>
  <p>Upload icon on a button:
    <button type="button" class="btn btn-default btn-sm">
      <span class="glyphicon glyphicon-upload"></span> Upload
    </button>
  </p>
  <p>Upload icon on a styled link button:
    <a href="#" class="btn btn-info btn-lg">
      <span class="glyphicon glyphicon-upload"></span> Upload
    </a>
  </p>
  <p>Unicode:
    <span class="glyphicon"></span>
  </p>
</div>
</code>```

 this is the icon, it produced, but how can I make it as multifileupload ?
   SINGLE-file-upload-icon

答:
Bootstrap 4 doesn't include an icon font like it did in version 3. This leaves people free to choose whichever icon font they want to use.

From your code it looks like you're using Bootstrap 3 though. All of the available icons are listed in their documentation. Just replace the glyphicon-upload class with the class for the icon you want to use (for instance, glyphicon-open).

<button type="button" class="btn btn-default btn-sm">
     Multi upload
</button>
```

<p>Alternatively, rather than trying to create a new icon yourself, you can use two and change their positioning to give the appearance of a single icon:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn .glyphicon + .glyphicon {
    margin-left: -5px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button type="button" class="btn btn-default btn-sm">
     Multi upload
</button>```

Title: create icon for multiple file upload

Body:
I would like to create an icon for multi file upload using bootstrap-4.
I have referred this below code for  single file upload >
but, how to create an icon for multi file upload

     <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/
          3.3.7/css/bootstrap.min.css">

Upload Glyph

Upload icon:

Upload icon as a link:

Upload icon on a button:
    <button type="button" class="btn btn-default btn-sm">
       Upload
    </button>

Upload icon on a styled link button:

       Upload

Unicode:
    

 this is the icon, it produced, but how can I make it as multifileupload ?
   SINGLE-file-upload-icon

Body:
Bootstrap 4 doesn't include an icon font like it did in version 3. This leaves people free to choose whichever icon font they want to use.

From your code it looks like you're using Bootstrap 3 though. All of the available icons are listed in their documentation. Just replace the glyphicon-upload class with the class for the icon you want to use (for instance, glyphicon-open).

<button type="button" class="btn btn-default btn-sm">
    <span class="glyphicon glyphicon-open"></span> Multi upload
</button>

Alternatively, rather than trying to create a new icon yourself, you can use two and change their positioning to give the appearance of a single icon:

.btn .glyphicon + .glyphicon {
    margin-left: -5px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button type="button" class="btn btn-default btn-sm">
    <span class="glyphicon glyphicon-arrow-up"></span><span class="glyphicon glyphicon-arrow-up"></span> Multi upload
</button>