问:
How to query derived object's properties type-safely in typescript?
I'd like to query a Typescript object to see if it has a property. Code like this:

class Base {
    x: number = 1
}

class DerivedA extends Base {
    y: number = 2
}
class DerivedB extends Base {
    y: number = 3
}
// and many more derived classes...

function f(obj: Base) {
    console.log('x', obj.x)
    if ('y' in obj) {
        console.log('y', obj.y) // ERROR: property 'y' does not exist on type 'never'
    }
}

f(new Base())
f(new DerivedA())
```

(see playground)

In f I'd like to avoid many instanceof DerivedA || instanceof DerivedB because there may be many, and I'd forget to add new ones. I'd like to just duck-type it and check for the y property. Can I do that in typescript and avoid the error? Do I have to do (obj as any).y?

It seems like a bigger question: how can I duck-type an object as a generic derived type of a known base class?

(I'm clearly still learning typescript in case it's not obvious)

答:
Typescript is structurally typed so that signature function f(obj: Base) is the same as function f(obj: {x: number}). i.e. you can call f({x: 10}) no problem, it doesn't need to actually be an instance of Base. Hopefully this helps motivate at least one reason why we can't expect typescript to narrow the type.

Typescript can narrow unions very well and this is the appropriate approach to the problem. We do need to capture "all" the possible argument shapes in the signature but that is easier than a long (and potentially increasing) list like DerivedA | DerivedB. Instead we can write the shape like Base & {y?: number} or if you prefer, Base | Base & {y: number}. Don't treat classes like you would in other OO languages like Java or C#, they behave much differently in the type system here.

Base & {y?: number} says the object will have a x: number and possibly a y: number too. Then when narrowing with 'y' in obj, typescript knows obj has the field y and the only option is that 'y' has type number, so in the if typescript treats obj as Base & {y: number}. You want to write a signature that covers just what you need in the function body.

Body:
I'd like to query a Typescript object to see if it has a property. Code like this:

class Base {
    x: number = 1
}

class DerivedA extends Base {
    y: number = 2
}
class DerivedB extends Base {
    y: number = 3
}
// and many more derived classes...

function f(obj: Base) {
    console.log('x', obj.x)
    if ('y' in obj) {
        console.log('y', obj.y) // ERROR: property 'y' does not exist on type 'never'
    }
}

f(new Base())
f(new DerivedA())

(see playground)

In f I'd like to avoid many instanceof DerivedA || instanceof DerivedB because there may be many, and I'd forget to add new ones. I'd like to just duck-type it and check for the y property. Can I do that in typescript and avoid the error? Do I have to do (obj as any).y?

It seems like a bigger question: how can I duck-type an object as a generic derived type of a known base class?

(I'm clearly still learning typescript in case it's not obvious)


来源: stackexchange

问:
Hover over text and overlay transformation
I have overlaid two layers of text, and I try to animate with :hover the overlaid text to fade out and simultaneously the underlaid text to fade in.

http://prntscr.com/nw3tc4

The problem seems that the hover command only recognizes the upper text, but I try with one hover to activate both layers.

I made a grid of each letter independently, so when I hover over one letter it disappears and the one beneath it appears. But I can successfully only animate the over text and not the underneath one.

Is it possible only with CSS? Any info is appreciated!

M

O

L

I

V

I

.

D

E

S

I

G

N

.

```

<pre class="lang-css prettyprint-override"><code>
.letters{
  list-style: none;
  display:grid;
  grid-template-columns: 4fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 4fr;
  grid-column-gap: 5px;
  font-size: 150px;
  margin: 5rem;
}
.design{
/* visibility: hidden; */
/* visibility or opacity, I'm not sure which one*/
opacity: 0;
}
.molivi{
  color: red;
}

.molivi:hover {opacity:0}

.design:hover{
/* visibility: visible; */
opacity:1;
}

/*WORD "MOLIVI" */

li:nth-child(1){
  grid-column: 2/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}
li:nth-child(2){
  grid-column: 3/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}
li:nth-child(3){
  grid-column: 4/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(4){
  grid-column: 5/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(5){
  grid-column: 6/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(6){
  grid-column: 7/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
  text-align: center;
}
li:nth-child(7){
  grid-column: 8/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}

/*WORD DESIGN*/
li:nth-child(8){
  grid-column: 2/ span 1;
  grid-row:  1/ span 1;
  /* text-align: center; */

}
li:nth-child(9){
  grid-column: 3/ span 1;
  grid-row:  1/ span 1;
  /* text-align: center; */
}
li:nth-child(10){
  grid-column: 4/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(11){
  grid-column: 5/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(12){
  grid-column: 6/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(13){
  grid-column: 7/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(14){
  grid-column: 8/ span 1;
  grid-row:  1/ span 1;
}
</code>```

答:
Put the change on hover of the container, changing the opacity value accordingly:

```<code>.letters:hover .design {
  opacity: 1;
}
.letters:hover .molivi {
  opacity: 0;
}
</code>```

Add a transition property to the items in the list. This is applying to all of them the same:

```<code>.letters li {
  transition: all 0.5s ease;
}
</code>```

Add a transition-delay to each item. You can control the speed of the animation by adjusting this value, as well as control the direction the fade is happening based on which value you put on which item in the sequence:

```<code>transition-delay: 0.1s;
</code>```

.letters {
  list-style: none;
  display: grid;
  grid-template-columns: 4fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 4fr;
  grid-column-gap: 5px;
  font-size: 150px;
  margin: 5rem;
}

.letters li {
  transition: all 0.5s ease;
}

.design {
  opacity: 0;
}

.molivi {
  color: red;
  opacity: 1;
}

.letters:hover .design {
  opacity: 1;
}
.letters:hover .molivi {
  opacity: 0;
}

/*WORD "MOLIVI" */

li:nth-child(1) {
  grid-column: 2/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0s;
}

li:nth-child(2) {
  grid-column: 3/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.1s;
}

li:nth-child(3) {
  grid-column: 4/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.2s;
}

li:nth-child(4) {
  grid-column: 5/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.3s;
}

li:nth-child(5) {
  grid-column: 6/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.4s;
}

li:nth-child(6) {
  grid-column: 7/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  text-align: center;
  transition-delay: 0.5s;
}

li:nth-child(7) {
  grid-column: 8/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.6s;
}

/*WORD DESIGN*/

li:nth-child(8) {
  grid-column: 2/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.7s;
}

li:nth-child(9) {
  grid-column: 3/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.8s;
}

li:nth-child(10) {
  grid-column: 4/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.9s;
}

li:nth-child(11) {
  grid-column: 5/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1s;
}

li:nth-child(12) {
  grid-column: 6/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.1s;
}

li:nth-child(13) {
  grid-column: 7/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.2s;
}

li:nth-child(14) {
  grid-column: 8/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.3s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <ul class="letters">
    <li class="molivi">M</li>
    <li class="molivi">O</li>
    <li class="molivi">L</li>
    <li class="molivi">I</li>
    <li class="molivi">V</li>
    <li class="molivi">I</li>
    <li class="molivi">.</li>
    <li class="design">D</li>
    <li class="design">E</li>
    <li class="design">S</li>
    <li class="design">I</li>
    <li class="design">G</li>
    <li class="design">N</li>
    <li class="design">.</li>
  </ul>
</section></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have overlaid two layers of text, and I try to animate with :hover the overlaid text to fade out and simultaneously the underlaid text to fade in.

http://prntscr.com/nw3tc4

The problem seems that the hover command only recognizes the upper text, but I try with one hover to activate both layers.

I made a grid of each letter independently, so when I hover over one letter it disappears and the one beneath it appears. But I can successfully only animate the over text and not the underneath one.

Is it possible only with CSS? Any info is appreciated!

M

O

L

I

V

I

.

D

E

S

I

G

N

.

.letters{
  list-style: none;
  display:grid;
  grid-template-columns: 4fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 4fr;
  grid-column-gap: 5px;
  font-size: 150px;
  margin: 5rem;
}
.design{
/* visibility: hidden; */
/* visibility or opacity, I'm not sure which one*/
opacity: 0;
}
.molivi{
  color: red;
}

.molivi:hover {opacity:0}

.design:hover{
/* visibility: visible; */
opacity:1;
}

/*WORD "MOLIVI" */

li:nth-child(1){
  grid-column: 2/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}
li:nth-child(2){
  grid-column: 3/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}
li:nth-child(3){
  grid-column: 4/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(4){
  grid-column: 5/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(5){
  grid-column: 6/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;

}
li:nth-child(6){
  grid-column: 7/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
  text-align: center;
}
li:nth-child(7){
  grid-column: 8/ span 1;
  grid-row:  1/ span 1;
  z-index: 2;
}

/*WORD DESIGN*/
li:nth-child(8){
  grid-column: 2/ span 1;
  grid-row:  1/ span 1;
  /* text-align: center; */

}
li:nth-child(9){
  grid-column: 3/ span 1;
  grid-row:  1/ span 1;
  /* text-align: center; */
}
li:nth-child(10){
  grid-column: 4/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(11){
  grid-column: 5/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(12){
  grid-column: 6/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(13){
  grid-column: 7/ span 1;
  grid-row:  1/ span 1;
}
li:nth-child(14){
  grid-column: 8/ span 1;
  grid-row:  1/ span 1;
}

Body:
Put the change on hover of the container, changing the opacity value accordingly:

.letters:hover .design {
  opacity: 1;
}
.letters:hover .molivi {
  opacity: 0;
}

Add a transition property to the items in the list. This is applying to all of them the same:

.letters li {
  transition: all 0.5s ease;
}

Add a transition-delay to each item. You can control the speed of the animation by adjusting this value, as well as control the direction the fade is happening based on which value you put on which item in the sequence:

transition-delay: 0.1s;

.letters {
  list-style: none;
  display: grid;
  grid-template-columns: 4fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 4fr;
  grid-column-gap: 5px;
  font-size: 150px;
  margin: 5rem;
}

.letters li {
  transition: all 0.5s ease;
}

.design {
  opacity: 0;
}

.molivi {
  color: red;
  opacity: 1;
}

.letters:hover .design {
  opacity: 1;
}
.letters:hover .molivi {
  opacity: 0;
}

/*WORD "MOLIVI" */

li:nth-child(1) {
  grid-column: 2/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0s;
}

li:nth-child(2) {
  grid-column: 3/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.1s;
}

li:nth-child(3) {
  grid-column: 4/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.2s;
}

li:nth-child(4) {
  grid-column: 5/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.3s;
}

li:nth-child(5) {
  grid-column: 6/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.4s;
}

li:nth-child(6) {
  grid-column: 7/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  text-align: center;
  transition-delay: 0.5s;
}

li:nth-child(7) {
  grid-column: 8/ span 1;
  grid-row: 1/ span 1;
  z-index: 2;
  transition-delay: 0.6s;
}

/*WORD DESIGN*/

li:nth-child(8) {
  grid-column: 2/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.7s;
}

li:nth-child(9) {
  grid-column: 3/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.8s;
}

li:nth-child(10) {
  grid-column: 4/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 0.9s;
}

li:nth-child(11) {
  grid-column: 5/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1s;
}

li:nth-child(12) {
  grid-column: 6/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.1s;
}

li:nth-child(13) {
  grid-column: 7/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.2s;
}

li:nth-child(14) {
  grid-column: 8/ span 1;
  grid-row: 1/ span 1;
  transition-delay: 1.3s;
}

<section>
  <ul class="letters">
    <li class="molivi">M</li>
    <li class="molivi">O</li>
    <li class="molivi">L</li>
    <li class="molivi">I</li>
    <li class="molivi">V</li>
    <li class="molivi">I</li>
    <li class="molivi">.</li>
    <li class="design">D</li>
    <li class="design">E</li>
    <li class="design">S</li>
    <li class="design">I</li>
    <li class="design">G</li>
    <li class="design">N</li>
    <li class="design">.</li>
  </ul>
</section>


问:
Representing set-theoretical notions in terms of lists in Haskell
I'm trying to define a new type in Haskell (i.e. sets) and to operate with it in terms of functions that input and output unordered lists without duplicates.

Am I on the right path over here? Any suggestion is welcomed, even the most minor quibble. I'd want my code to be as elegant as possible.

```<code>-- generalized membership

type Set a = [a]

member :: Eq a => a -> [a] -> Bool
member x []                 = False
member x (y:ys) | x == y    = True
                | otherwise = member x ys

-- elimination of duplicates

noReps :: Set Integer -> Set Integer
noReps []                   = []
noReps (x:xs) | member x xs = noReps xs
              | otherwise   = x : noReps xs

inclusion :: Set Integer -> Set Integer -> Bool
inclusion x y = length [i | i <- x, not (member i y)] == 0

identical :: Set Integer -> Set Integer -> Bool
identical x y = inclusion x y && inclusion y x

-- membership for sets of sets

setmember :: Set Integer -> Set (Set Integer) -> Bool
setmember [] _                      = True
setmember _ []                      = False
setmember x (y:ys)  | identical x y = True
                    | otherwise     = setmember x ys

addsets :: Set Integer -> Set (Set Integer) -> Set (Set Integer)
addsets x y | setmember x y = y
            | otherwise = x:y

-- adding an integer to every member of a sets of sets of integers

addelem :: Integer -> Set (Set Integer) -> Set (Set Integer)
addelem x y = [noReps (x : i) | i <- y]

-- powerset of the set {1,...,n}

powerset :: Integer -> Set (Set Integer)
powerset 1 = [[], [1]]
powerset x = powerset (x-1) ++ addelem x (powerset (x-1))
</code>```

答:
Looks good to me (for an "exercise in futility", as you put it); one thing: None of your signatures require specializing as Integer, anything that supports equality (Eq) will work, with powerset additionally requiring a numeric value (again, not necessarily an Integer):

noReps :: Eq a => Set a -> Set a
inclusion :: Eq a => Set a -> Set a -> Bool
identical :: Eq a => Set a -> Set a -> Bool
setmember :: Eq a => Set a -> Set (Set a) -> Bool
addsets :: Eq a => Set a -> Set (Set a) -> Set (Set a)
addelem :: Eq a => a -> Set (Set a) -> Set (Set a)
powerset :: (Eq a, Num a) => a -> Set (Set a)
```

All these signatures will work, without changing absolutely anything in the functions themselves.

(EDIT: it is usually a good idea to make your signatures as generic and polymorphic as possible - not only will allow reusing the code, but, by restricting what your functions can do with their arguments - in this case, the signature allows you ONLY applying the == operator - you reduce the risk of bugs / unintended effects).

Of course, using lists will make the code simple yet slow - for real-life code, you'd use balanced trees to represent the sets - more complex, but fast; in fact, that's how Haskell's own Set type is implemented.

Body:
I'm trying to define a new type in Haskell (i.e. sets) and to operate with it in terms of functions that input and output unordered lists without duplicates.

Am I on the right path over here? Any suggestion is welcomed, even the most minor quibble. I'd want my code to be as elegant as possible.

-- generalized membership

type Set a = [a]

member :: Eq a => a -> [a] -> Bool
member x []                 = False
member x (y:ys) | x == y    = True
                | otherwise = member x ys

-- elimination of duplicates

noReps :: Set Integer -> Set Integer
noReps []                   = []
noReps (x:xs) | member x xs = noReps xs
              | otherwise   = x : noReps xs

inclusion :: Set Integer -> Set Integer -> Bool
inclusion x y = length [i | i <- x, not (member i y)] == 0

identical :: Set Integer -> Set Integer -> Bool
identical x y = inclusion x y && inclusion y x

-- membership for sets of sets

setmember :: Set Integer -> Set (Set Integer) -> Bool
setmember [] _                      = True
setmember _ []                      = False
setmember x (y:ys)  | identical x y = True
                    | otherwise     = setmember x ys

addsets :: Set Integer -> Set (Set Integer) -> Set (Set Integer)
addsets x y | setmember x y = y
            | otherwise = x:y

-- adding an integer to every member of a sets of sets of integers

addelem :: Integer -> Set (Set Integer) -> Set (Set Integer)
addelem x y = [noReps (x : i) | i <- y]

-- powerset of the set {1,...,n}

powerset :: Integer -> Set (Set Integer)
powerset 1 = [[], [1]]
powerset x = powerset (x-1) ++ addelem x (powerset (x-1))

Body:
Looks good to me (for an "exercise in futility", as you put it); one thing: None of your signatures require specializing as Integer, anything that supports equality (Eq) will work, with powerset additionally requiring a numeric value (again, not necessarily an Integer):

noReps :: Eq a => Set a -> Set a
inclusion :: Eq a => Set a -> Set a -> Bool
identical :: Eq a => Set a -> Set a -> Bool
setmember :: Eq a => Set a -> Set (Set a) -> Bool
addsets :: Eq a => Set a -> Set (Set a) -> Set (Set a)
addelem :: Eq a => a -> Set (Set a) -> Set (Set a)
powerset :: (Eq a, Num a) => a -> Set (Set a)

All these signatures will work, without changing absolutely anything in the functions themselves.

(EDIT: it is usually a good idea to make your signatures as generic and polymorphic as possible - not only will allow reusing the code, but, by restricting what your functions can do with their arguments - in this case, the signature allows you ONLY applying the == operator - you reduce the risk of bugs / unintended effects).

Of course, using lists will make the code simple yet slow - for real-life code, you'd use balanced trees to represent the sets - more complex, but fast; in fact, that's how Haskell's own Set type is implemented.


问:
Cannot connect through tcp remotely
I’m developing an app that connects on port 9050 through the public ip of my server. It works fine on lan but if I’m connected on a different network it fails what can I do to fix this?</p>

答:
first try from Command Prompt this command: telnet ip 9050
if it working means the port 9050 between your pc and the server already opened , otherwise you should check why and where the port is blocked (may be firewall in this case you need to create rule in firewall to pass ).</p>

Title: Cannot connect through tcp remotely


问:
How to schedule an hourly check on a list a bulk 404 URL checker?
I'm trying to set up a Google sheet that checks the response of a list of URLs (around 30) of them. I would like it to be scheduled every hour. It doesn't matter when in the hour the URL responses are checked but it would be preferable it's done every 60 minutes and also works when I'm not accessing the spreadsheet (i.e. offline)

I'm very new to using google sheets script editor so still trying to get to grips with it.
I used the script below. In the script editor I did the following:

Edit > Project Triggers > Add Trigger.

Choose Function > HTTP Response

Even source > Time driven

Select type of time based trigger > hour timer.

```<code>function HTTPResponse( uri )
{
 var response_code ;
try {
 response_code = UrlFetchApp .fetch( uri ) .getResponseCode() .toString() ;
 }
catch( error ) {
 response_code = error .toString() .match( / returned code (\d\d\d)\./ )[1]
;
 }
finally {
 return response_code ;
 }
}
</code>```

I expected the above setup to update the URL checks every hour...but they only seem to update when I manually update the cell.

Any help would be much appreciated.

答:
Try this:

```<code>function checkUrls( ) {
  var ss=SpreadsheetApp.openById('id');//set ss id
  var sh=ss.getSheetByName('Sheet1');//set sheet name
  var urlA=['https:example.com','http://example.com'];//u pick em
  for(var i=0;i<urlA.length;i++) {
    var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "'yyyy/mm/dd HH:mm:ss");//change format if you wish
    var response=UrlFetchApp.fetch(urlA[i]);
    sh.appendRow(ts,urlA[i],response.getResponseCode());
  }
}
</code>```

Setting up the Timer:

```<code>function setupHourlyTimer() {
  if(!isTrigger('checkUrls')) {
    ScriptApp.newTrigger('checkUrls').timeBased().everyHours(1).create();
  }
}

function isTrigger(funcName){
  var r=false;
  if(funcName){
    var allTriggers=ScriptApp.getProjectTriggers();
    for(var i=0;i<allTriggers.length;i++){
      if(funcName==allTriggers[i].getHandlerFunction()){
        r=true;
        break;
      }
    }
  }
  return r;
}
</code>```

Body:
I'm trying to set up a Google sheet that checks the response of a list of URLs (around 30) of them. I would like it to be scheduled every hour. It doesn't matter when in the hour the URL responses are checked but it would be preferable it's done every 60 minutes and also works when I'm not accessing the spreadsheet (i.e. offline)

I'm very new to using google sheets script editor so still trying to get to grips with it.
I used the script below. In the script editor I did the following:

Edit > Project Triggers > Add Trigger.

Choose Function > HTTP Response

Even source > Time driven

Select type of time based trigger > hour timer.

function HTTPResponse( uri )
{
 var response_code ;
try {
 response_code = UrlFetchApp .fetch( uri ) .getResponseCode() .toString() ;
 }
catch( error ) {
 response_code = error .toString() .match( / returned code (\d\d\d)\./ )[1]
;
 }
finally {
 return response_code ;
 }
}

I expected the above setup to update the URL checks every hour...but they only seem to update when I manually update the cell.

Any help would be much appreciated.

Body:
Try this:

function checkUrls( ) {
  var ss=SpreadsheetApp.openById('id');//set ss id
  var sh=ss.getSheetByName('Sheet1');//set sheet name
  var urlA=['https:example.com','http://example.com'];//u pick em
  for(var i=0;i<urlA.length;i++) {
    var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "'yyyy/mm/dd HH:mm:ss");//change format if you wish
    var response=UrlFetchApp.fetch(urlA[i]);
    sh.appendRow(ts,urlA[i],response.getResponseCode());
  }
}

Setting up the Timer:

function setupHourlyTimer() {
  if(!isTrigger('checkUrls')) {
    ScriptApp.newTrigger('checkUrls').timeBased().everyHours(1).create();
  }
}

function isTrigger(funcName){
  var r=false;
  if(funcName){
    var allTriggers=ScriptApp.getProjectTriggers();
    for(var i=0;i<allTriggers.length;i++){
      if(funcName==allTriggers[i].getHandlerFunction()){
        r=true;
        break;
      }
    }
  }
  return r;
}


问:
Selecting data from sql database doesn't work. how do I fix it?
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

```<code><?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>
</code>```

I expect to only see "connected successfully"

答:
Your query is right just write your database name in mysqli constructor.

```<code>$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
</code>```

Visit: https://www.php.net/manual/en/mysqli.construct.php

Body:
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>

I expect to only see "connected successfully"

Body:
Your query is right just write your database name in mysqli constructor.

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

Visit: https://www.php.net/manual/en/mysqli.construct.php


问:
MLKit Firebase android - How to convert FirebaseVisionFace to Image Object (like Bitmap)?
I have integrated MLkit FaceDetection into my android application. I have referred below URL

https://firebase.google.com/docs/ml-kit/android/detect-faces

Code for Face Detection Processor Class is

```<code>import java.io.IOException;
import java.util.List;

/** Face Detector Demo. */
public class FaceDetectionProcessor extends VisionProcessorBase<List<FirebaseVisionFace>> {

  private static final String TAG = "FaceDetectionProcessor";

  private final FirebaseVisionFaceDetector detector;

  public FaceDetectionProcessor() {

    FirebaseVisionFaceDetectorOptions options =
        new FirebaseVisionFaceDetectorOptions.Builder()
            .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
            .setLandmarkType(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .setTrackingEnabled(true)
            .build();

    detector = FirebaseVision.getInstance().getVisionFaceDetector(options);
  }

  @Override
  public void stop() {
    try {
      detector.close();
    } catch (IOException e) {
      Log.e(TAG, "Exception thrown while trying to close Face Detector: " + e);
    }
  }

  @Override
  protected Task<List<FirebaseVisionFace>> detectInImage(FirebaseVisionImage image) {
    return detector.detectInImage(image);
  }

  @Override
  protected void onSuccess(
      @NonNull List<FirebaseVisionFace> faces,
      @NonNull FrameMetadata frameMetadata,
      @NonNull GraphicOverlay graphicOverlay) {
      graphicOverlay.clear();

    for (int i = 0; i < faces.size(); ++i) {
      FirebaseVisionFace face = faces.get(i);
      FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
      graphicOverlay.add(faceGraphic);
      faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
    }

  }

  @Override
  protected void onFailure(@NonNull Exception e) {
    Log.e(TAG, "Face detection failed " + e);
  }
}
</code>```

Here in "onSuccess" listener , we will get array of "FirebaseVisionFace" class objects which will have "Bounding Box" of face.

```<code>@Override
      protected void onSuccess(
          @NonNull List<FirebaseVisionFace> faces,
          @NonNull FrameMetadata frameMetadata,
          @NonNull GraphicOverlay graphicOverlay) {
          graphicOverlay.clear();

        for (int i = 0; i < faces.size(); ++i) {
          FirebaseVisionFace face = faces.get(i);
          FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
          graphicOverlay.add(faceGraphic);
          faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
        }
      }
</code>```

I want to know How to convert this FirebaseVisionFace objects into Bitmap.
I want to extract face image and show it in ImageView. Can anyone please help me . Thanks in advance.

Note : I have downloaded the sample Source code of MLKit android from below URL

https://github.com/firebase/quickstart-android/tree/master/mlkit

答:
Since the accepted answer was not specific enough I will try to explain what I did.

1.- Create an ImageView on LivePreviewActivity like this:

```<code>private ImageView imageViewTest;
</code>```

2.- Create it on the Activity xml and link it to java file. I placed it right before the  the sample code had, so it can be visible on top of the camera feed.

3.-When they create a FaceDetectionProcessor pass an instance of  the imageView to be able to set the source image inside the object.

```<code>FaceDetectionProcessor processor = new FaceDetectionProcessor(imageViewTest);
</code>```

4.-Change the constructor of FaceDetectionProcessor to be able to receive ImageView as a parameter and create a global variable that saves that instance.

```<code>public FaceDetectionProcessor(ImageView imageView) {
    FirebaseVisionFaceDetectorOptions options =
            new FirebaseVisionFaceDetectorOptions.Builder()
                    .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
                    .setTrackingEnabled(true)
                    .build();

    detector = FirebaseVision.getInstance().getVisionFaceDetector(options);
    this.imageView  = imageView;
}
</code>```

5.- I created a crop method that takes a bitmap and a Rect to focus only on the face. So go ahead and do the same.

```<code>    public static Bitmap cropBitmap(Bitmap bitmap, Rect rect) {
    int w = rect.right - rect.left;
    int h = rect.bottom - rect.top;
    Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());
    Canvas canvas = new Canvas(ret);
    canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
    return ret;
}
</code>```

6.- Modify detectInImage method to save an instance of the bitmap  being detected and save it in a global variable.

```<code>    @Override
protected Task<List<FirebaseVisionFace>> detectInImage(FirebaseVisionImage image) {
    imageBitmap = image.getBitmapForDebugging();
    return detector.detectInImage(image);
}
</code>```

7.- Finally, modify OnSuccess method by calling the cropping method and assign result to the imageView.

```<code>    @Override
protected void onSuccess(
        @NonNull List<FirebaseVisionFace> faces,
        @NonNull FrameMetadata frameMetadata,
        @NonNull GraphicOverlay graphicOverlay) {
    graphicOverlay.clear();
    for (int i = 0; i < faces.size(); ++i) {
        FirebaseVisionFace face = faces.get(i);
        FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
        graphicOverlay.add(faceGraphic);
        faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
        croppedImage = cropBitmap(imageBitmap, face.getBoundingBox());
    }
    imageView.setImageBitmap(croppedImage);
}
</code>```

Body:
I have integrated MLkit FaceDetection into my android application. I have referred below URL

https://firebase.google.com/docs/ml-kit/android/detect-faces

Code for Face Detection Processor Class is

import java.io.IOException;
import java.util.List;

/** Face Detector Demo. */
public class FaceDetectionProcessor extends VisionProcessorBase<List<FirebaseVisionFace>> {

  private static final String TAG = "FaceDetectionProcessor";

  private final FirebaseVisionFaceDetector detector;

  public FaceDetectionProcessor() {

    FirebaseVisionFaceDetectorOptions options =
        new FirebaseVisionFaceDetectorOptions.Builder()
            .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
            .setLandmarkType(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .setTrackingEnabled(true)
            .build();

    detector = FirebaseVision.getInstance().getVisionFaceDetector(options);
  }

  @Override
  public void stop() {
    try {
      detector.close();
    } catch (IOException e) {
      Log.e(TAG, "Exception thrown while trying to close Face Detector: " + e);
    }
  }

  @Override
  protected Task<List<FirebaseVisionFace>> detectInImage(FirebaseVisionImage image) {
    return detector.detectInImage(image);
  }

  @Override
  protected void onSuccess(
      @NonNull List<FirebaseVisionFace> faces,
      @NonNull FrameMetadata frameMetadata,
      @NonNull GraphicOverlay graphicOverlay) {
      graphicOverlay.clear();

    for (int i = 0; i < faces.size(); ++i) {
      FirebaseVisionFace face = faces.get(i);
      FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
      graphicOverlay.add(faceGraphic);
      faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
    }

  }

  @Override
  protected void onFailure(@NonNull Exception e) {
    Log.e(TAG, "Face detection failed " + e);
  }
}

Here in "onSuccess" listener , we will get array of "FirebaseVisionFace" class objects which will have "Bounding Box" of face.

@Override
      protected void onSuccess(
          @NonNull List<FirebaseVisionFace> faces,
          @NonNull FrameMetadata frameMetadata,
          @NonNull GraphicOverlay graphicOverlay) {
          graphicOverlay.clear();

        for (int i = 0; i < faces.size(); ++i) {
          FirebaseVisionFace face = faces.get(i);
          FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
          graphicOverlay.add(faceGraphic);
          faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
        }
      }

I want to know How to convert this FirebaseVisionFace objects into Bitmap.
I want to extract face image and show it in ImageView. Can anyone please help me . Thanks in advance.

Note : I have downloaded the sample Source code of MLKit android from below URL

https://github.com/firebase/quickstart-android/tree/master/mlkit

Body:
Since the accepted answer was not specific enough I will try to explain what I did.

1.- Create an ImageView on LivePreviewActivity like this:

private ImageView imageViewTest;

2.- Create it on the Activity xml and link it to java file. I placed it right before the  the sample code had, so it can be visible on top of the camera feed.

3.-When they create a FaceDetectionProcessor pass an instance of  the imageView to be able to set the source image inside the object.

FaceDetectionProcessor processor = new FaceDetectionProcessor(imageViewTest);

4.-Change the constructor of FaceDetectionProcessor to be able to receive ImageView as a parameter and create a global variable that saves that instance.

public FaceDetectionProcessor(ImageView imageView) {
    FirebaseVisionFaceDetectorOptions options =
            new FirebaseVisionFaceDetectorOptions.Builder()
                    .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
                    .setTrackingEnabled(true)
                    .build();

    detector = FirebaseVision.getInstance().getVisionFaceDetector(options);
    this.imageView  = imageView;
}

5.- I created a crop method that takes a bitmap and a Rect to focus only on the face. So go ahead and do the same.

    public static Bitmap cropBitmap(Bitmap bitmap, Rect rect) {
    int w = rect.right - rect.left;
    int h = rect.bottom - rect.top;
    Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());
    Canvas canvas = new Canvas(ret);
    canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
    return ret;
}

6.- Modify detectInImage method to save an instance of the bitmap  being detected and save it in a global variable.

    @Override
protected Task<List<FirebaseVisionFace>> detectInImage(FirebaseVisionImage image) {
    imageBitmap = image.getBitmapForDebugging();
    return detector.detectInImage(image);
}

7.- Finally, modify OnSuccess method by calling the cropping method and assign result to the imageView.

    @Override
protected void onSuccess(
        @NonNull List<FirebaseVisionFace> faces,
        @NonNull FrameMetadata frameMetadata,
        @NonNull GraphicOverlay graphicOverlay) {
    graphicOverlay.clear();
    for (int i = 0; i < faces.size(); ++i) {
        FirebaseVisionFace face = faces.get(i);
        FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay);
        graphicOverlay.add(faceGraphic);
        faceGraphic.updateFace(face, frameMetadata.getCameraFacing());
        croppedImage = cropBitmap(imageBitmap, face.getBoundingBox());
    }
    imageView.setImageBitmap(croppedImage);
}


问:
SQL Server: Return results when not duplicate
I just can't seem to get my mind wrapped around this.  To simplify as much as possible, let's say I have a table:

```<code>Id      cid         Account
1       4010        Bank Co
2       5323        Webazon
3       3513        Internal
4       3513        PhoneCo
5       5597        Internal
</code>```

I'm wanting to return all results except for the lines that are Account = 'Internal' where there's also a customer with the same cid.  So, in this case, we would return lines 1,2,4, and 5.  Line 3 would not be returned, because 'PhoneCo' and 'Internal' share cid 3513.  However, line 5 would be returned because there's not another record that shares cid 5597.

I'm going down the road of doing it with a UNION, where the first part is eliminating all 'Internal' records, and the second part is just those I'm interested in, but I may be going about it the wrong way.

答:
Here is one method:

```<code>select t.*
from t
where t.account <> 'Internal' or
      not exists (select 1
                  from t t2
                  where t2.cid = t.cid and t2.account <> 'Internal'
                 );
</code>```

That is, select everything all non-internal records.  And, select records for internal accounts where there is not a corresponding non-internal account.

Body:
I just can't seem to get my mind wrapped around this.  To simplify as much as possible, let's say I have a table:

Id      cid         Account
1       4010        Bank Co
2       5323        Webazon
3       3513        Internal
4       3513        PhoneCo
5       5597        Internal

I'm wanting to return all results except for the lines that are Account = 'Internal' where there's also a customer with the same cid.  So, in this case, we would return lines 1,2,4, and 5.  Line 3 would not be returned, because 'PhoneCo' and 'Internal' share cid 3513.  However, line 5 would be returned because there's not another record that shares cid 5597.

I'm going down the road of doing it with a UNION, where the first part is eliminating all 'Internal' records, and the second part is just those I'm interested in, but I may be going about it the wrong way.

Body:
Here is one method:

select t.*
from t
where t.account <> 'Internal' or
      not exists (select 1
                  from t t2
                  where t2.cid = t.cid and t2.account <> 'Internal'
                 );

That is, select everything all non-internal records.  And, select records for internal accounts where there is not a corresponding non-internal account.


问:
Using VIM on Windows to access windows server share directory
In Windows Explorer I can navigate to "\\servername\shared_directory". Is there any way I can navigate to the same directory using VIM and NERDTree?

Example:

:NERDTree \\servername\shared_drirectory

答:
I think you might want to report this behavior to the NERDTree developer. I tried it myself and no, it does not work.

You could try pulling the current NERDTree from https://github.com/scrooloose/nerdtree or writing the developer.

ContentLicense: CC BY-SA 3.0


问:
How do I guarantee a certain named constructor in Dart?
Let us say I have the concrete classes Cat, Dog, and Parrot, and the following interface:

```<code>class HasGuid {
  HasGuid.fromId(String id);
}
</code>```

My goal is to guarantee that Cat, Dog, and Parrot all have a fromId named constructor. So, I can make calls like:

```<code>Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido")     =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]
</code>```

fromId is making a call across the network, for this reason I return it as a Future. I basically want a contract that states that any class that mixes/extends/implements/whatever the HasGuid class will have a named constructor of fromId. Where fromId on class T will take an identity string and will return a Future<T>.

答:
The short answer is that you cannot force a subclass to implement a specific named constructor ... all you can do is force the subclass to make sure the named constructor is called by the subclass.

Take for example the following ...

class Animal {
  String name;

  Animal.fromName(this.name);
}

class Dog extends Animal {

  Dog.withName(String name) : super.fromName(name);
}
```

<p>Note the following ...</p>

<ol>
<li><code>Animal</code> has no zero argument constructor.</li>
<li>If you don't call the <code>super.fromName()</code> constructor from <code>Dog</code> you will get a compile error</li>
</ol>

```The superclass 'Animal' doesn't have a zero argument constructor.
```

Although Dog must call the fromName() constructor ... it doesn't have to call its named constructor the same.  In this case notice it is called withName().

Body:
Let us say I have the concrete classes Cat, Dog, and Parrot, and the following interface:

class HasGuid {
  HasGuid.fromId(String id);
}

My goal is to guarantee that Cat, Dog, and Parrot all have a fromId named constructor. So, I can make calls like:

Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido")     =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]

fromId is making a call across the network, for this reason I return it as a Future. I basically want a contract that states that any class that mixes/extends/implements/whatever the HasGuid class will have a named constructor of fromId. Where fromId on class T will take an identity string and will return a Future<T>.

Body:
The short answer is that you cannot force a subclass to implement a specific named constructor ... all you can do is force the subclass to make sure the named constructor is called by the subclass.

Take for example the following ...

class Animal {
  String name;

  Animal.fromName(this.name);
}

class Dog extends Animal {

  Dog.withName(String name) : super.fromName(name);
}

Note the following ...

Animal has no zero argument constructor.

If you don't call the super.fromName() constructor from Dog you will get a compile error

The superclass 'Animal' doesn't have a zero argument constructor.

Although Dog must call the fromName() constructor ... it doesn't have to call its named constructor the same.  In this case notice it is called withName().


问:
Terraform create a Cloudwatch rule with multiple targets
From the Terraform docs - https://www.terraform.io/docs/providers/aws/r/cloudwatch_event_target.html

I don't see an option to map multiple targets to the same Cloudwatch rule. It only takes an arn field which accepts one resource. I'm trying to map 5 Lambdas to the same Cloudwatch rule. Does Terraform support this?

EDIT: How can I attach only 5 lambdas? If I've created 15 lambdas, I want to attach 5 each to 3 cloudwatch rules.

答:
Got it working! I had to divide the count of the rules by 5 when I assigned targets to rules. This is roughly what it looks like:

```<code>resource "aws_cloudwatch_event_rule" "arule" {
  count       = "${ceil(length(var.lambda_arns) / 5.0)}"  // Needs to be 5.0 to force float computation
  name        = "${var.rule_name}${format("-%d", count.index)}"
  is_enabled  = true
}

resource "aws_cloudwatch_event_target" "atarget" {
  depends_on = ["aws_cloudwatch_event_rule.arule"]
  count = "${length(var.lambda_arns)}"
  rule  = "${aws_cloudwatch_event_rule.arule.*.name[count.index / 5]}"
  arn   = "${var.lambda_arns[count.index]}"
}
</code>```

I created the event rules based on the number of lambdas (i.e., if there are 10 lambdas, 2 rules are created).

I created the targets based on number of lambdas (i.e., if there are 10 lambdas, 10 targets are created).

I assigned the targets proportionally among the rules by dividing the count.index by 5 (the same logic used to determine the count of rules).

Body:
Got it working! I had to divide the count of the rules by 5 when I assigned targets to rules. This is roughly what it looks like:

resource "aws_cloudwatch_event_rule" "arule" {
  count       = "${ceil(length(var.lambda_arns) / 5.0)}"  // Needs to be 5.0 to force float computation
  name        = "${var.rule_name}${format("-%d", count.index)}"
  is_enabled  = true
}

resource "aws_cloudwatch_event_target" "atarget" {
  depends_on = ["aws_cloudwatch_event_rule.arule"]
  count = "${length(var.lambda_arns)}"
  rule  = "${aws_cloudwatch_event_rule.arule.*.name[count.index / 5]}"
  arn   = "${var.lambda_arns[count.index]}"
}

I created the event rules based on the number of lambdas (i.e., if there are 10 lambdas, 2 rules are created).

I created the targets based on number of lambdas (i.e., if there are 10 lambdas, 10 targets are created).

I assigned the targets proportionally among the rules by dividing the count.index by 5 (the same logic used to determine the count of rules).


问:
a SVG span inside a link not working in IE
Needed to add  in between  and SVG, so that a javascript can call out the SVG inline from another file. Everything working, but not in IE, is there anything I missed?? (when testing in IE, it didn't even know that is a link, nothing clickable, and I also have a hover effect too, but nothing show up in IE.) putting together a final code example after the javascript loaded the inline SVG together.

.icon svg{
  display: inline-block;
  width: 3rem;
  height: 3rem;
  margin: 0;
  stroke-width: 1.5;
  stroke-linecap: round;
}

.icon-black svg{
 stroke: #1A1A1A;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<span class="icon icon-black" id="icon-arrow">
<svg id="icon-arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke-linejoin="arcs"><path d="M12 19V6M5 12l7-7 7 7"/>
</svg>
</span>
</code>```

答: Just noticed, I missed set the  as display: inline-block;

Body:
Needed to add  in between  and SVG, so that a javascript can call out the SVG inline from another file. Everything working, but not in IE, is there anything I missed?? (when testing in IE, it didn't even know that is a link, nothing clickable, and I also have a hover effect too, but nothing show up in IE.) putting together a final code example after the javascript loaded the inline SVG together.

.icon svg{
  display: inline-block;
  width: 3rem;
  height: 3rem;
  margin: 0;
  stroke-width: 1.5;
  stroke-linecap: round;
}

.icon-black svg{
 stroke: #1A1A1A;
 }

<svg id="icon-arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke-linejoin="arcs"><path d="M12 19V6M5 12l7-7 7 7"/>
</svg>

Body: Just noticed, I missed set the <span> as display: inline-block;


问:
MySQL: a simple regexp not working as expected
In a field of a MySQL table, I have to recognize when content is of the form dd/mm/yyyy, in order to reformat it in proper SQL form like yyyy-mm-dd.

It didn't work so I tried testing in this simple form:

```<code>SELECT "23/01/2002" REGEXP "^\\d{2}/\\d{2}/\\d{4}$"
</code>```

which returns the following:

```<code>"23/01/2002" REGEXP "^\\d{2}/\\d{2}/\\d{4}$" -> 0
</code>```

I'm probably missing something obvious...

答:
Rather than using regex, use STR_TO_DATE using a format string for the date. In your case:

```<code>SELECT STR_TO_DATE(col, "%d/%m/%Y") FROM table
</code>```

If this doesn't parse, it will be NULL

Body:
In a field of a MySQL table, I have to recognize when content is of the form dd/mm/yyyy, in order to reformat it in proper SQL form like yyyy-mm-dd.

It didn't work so I tried testing in this simple form:

SELECT "23/01/2002" REGEXP "^\\d{2}/\\d{2}/\\d{4}$"

which returns the following:

"23/01/2002" REGEXP "^\\d{2}/\\d{2}/\\d{4}$" -> 0

I'm probably missing something obvious...

Body:
Rather than using regex, use STR_TO_DATE using a format string for the date. In your case:

SELECT STR_TO_DATE(col, "%d/%m/%Y") FROM table

If this doesn't parse, it will be NULL


问:
left and right objects are evaluated / resolved during runtime or compile-time?
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();
```

<p>...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...</p>

<pre class="lang-java prettyprint-override"><code>left.invoke (right);
</code>```

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right

答:
A) is the correct answer here.

The following code demonstrates that.

```<code>    public class Main001 {

        public static void main(String[] args) {
            A right = createRightInstance();
            B left = createLeftInstance();

            left.invoke(right);
            System.out.println("Done!!!");
        }

        public static B createLeftInstance() {
            return new B2();
        }

        public static A createRightInstance() {
            return new A2();
        }

    }

    class A{

    }

    class A1 extends A{

    }

    class A2 extends A1{

    }

    class B{
        public void invoke(A x) {
            System.out.println("Invoking method A on B with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B with argument " + x.getClass().getName());
        }
    }

    class B1 extends B{
        public void invoke(A x) {
            System.out.println("Invoking method A on B1 with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B1 with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B1 with argument " + x.getClass().getName());
        }

    }

    class B2 extends B1{
        public void invoke(A x) {
            System.out.println("Invoking method A on B2 with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B2 with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B2 with argument " + x.getClass().getName());
        }
    }
</code>```

This example prints

```<code>Invoking method A on B2 with argument A2
Done!!!
</code>```

which means A) is the correct answer.

Why does it mean that?

Well... because:

1) a method from the B2 class is invoked (as the output says) and B2 is the runtime type of left (the compile time type of left is B).

2) a method with parameter A is invoked (note that A is the compile-time type of right), even though the runtime type of right is A2. Compile time type of right is just the type with which right is declared i.e. A. Runtime type of right is the actual type of the argument i.e. A2 (see the output, it says with argument A2 there).

Body:
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();

...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...

left.invoke (right);

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right

Body:
A) is the correct answer here.

The following code demonstrates that.

    public class Main001 {

        public static void main(String[] args) {
            A right = createRightInstance();
            B left = createLeftInstance();

            left.invoke(right);
            System.out.println("Done!!!");
        }

        public static B createLeftInstance() {
            return new B2();
        }

        public static A createRightInstance() {
            return new A2();
        }

    }

    class A{

    }

    class A1 extends A{

    }

    class A2 extends A1{

    }

    class B{
        public void invoke(A x) {
            System.out.println("Invoking method A on B with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B with argument " + x.getClass().getName());
        }
    }

    class B1 extends B{
        public void invoke(A x) {
            System.out.println("Invoking method A on B1 with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B1 with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B1 with argument " + x.getClass().getName());
        }

    }

    class B2 extends B1{
        public void invoke(A x) {
            System.out.println("Invoking method A on B2 with argument " + x.getClass().getName());
        }
        public void invoke(A1 x) {
            System.out.println("Invoking method A1 on B2 with argument " + x.getClass().getName());
        }
        public void invoke(A2 x) {
            System.out.println("Invoking method A2 on B2 with argument " + x.getClass().getName());
        }
    }

This example prints

Invoking method A on B2 with argument A2
Done!!!

which means A) is the correct answer.

Why does it mean that?

Well... because:

1) a method from the B2 class is invoked (as the output says) and B2 is the runtime type of left (the compile time type of left is B).

2) a method with parameter A is invoked (note that A is the compile-time type of right), even though the runtime type of right is A2. Compile time type of right is just the type with which right is declared i.e. A. Runtime type of right is the actual type of the argument i.e. A2 (see the output, it says with argument A2 there).


问:
Parse 1 column into 3 columns using DB2 SQL
Using DB2 for z/OS 10, I'm have a column (ADDRESS3) in a table that contains city, state, and zipcode all in one column. But, the formatting is somewhat "free-form". (see code below)

I can successfully parse the city by taking everything before the comma. Using only DB2 SQL, how would I parse out the state and zipcode?

```<code>SELECT ADDRESS3,
       TRIM(SUBSTR(ADDRESS3,1,LOCATE(',', ADDRESS3)-1)) AS CITY
  FROM MYTABLE

ADDRESS3                            CITY
----------------------------------  -------------
GRANADA HILLS       ,CA 91344       GRANADA HILLS
SIMI VALLEY         ,CA 93065       SIMI VALLEY
BUENA PARK          ,CA 90621       BUENA PARK
SHERMAN OAKS        ,CA 91423       SHERMAN OAKS
GLENDALE            ,CA 91203-2089  GLENDALE
VENTURA             ,CA 93002       VENTURA
HAWTHORNE           ,CA 90250       HAWTHORNE
PASADENA            ,CA 91185-2594  PASADENA
BEVERLY HILLS       ,CA 90211       BEVERLY HILLS
ARCADIA             ,CA 91007       ARCADIA
WALNUT CREEK        ,CA 94596       WALNUT CREEK
INDEPENDANCE        ,CA 93526       INDEPENDANCE
LOS ANGELES         ,CA 90017       LOS ANGELES
</code>```

Ultimately, I'd like the query results to look like this:

```<code>CITY          STATE ZIP
------------- ----- -----
GRANADA HILLS CA    91344
SIMI VALLEY   CA    93065
BUENA PARK    CA    90621
SHERMAN OAKS  CA    91423
GLENDALE      CA    91203
VENTURA       CA    93002
HAWTHORNE     CA    90250
PASADENA      CA    91185
...
</code>```

Thanks!

答:
I think you need this assuming the format is the same always.

```<code>  SELECT
       TRIM(
         SUBSTR(
           SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1)
           , 1
           , POSITION(' ' , SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1))
         )
       ) AS STATE
    ,  TRIM(
           SUBSTR(
             SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1)
           , POSITION(' ' , SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1))
         )
       ) AS ZIP
  FROM MYTABLE
</code>```

The demo result into these results with these values

Test data

```<code>  VALUES
    ('GRANADA HILLS       ,CA 91344')
  , ('SIMI VALLEY         ,CA 93065')
  , ('GLENDALE            ,CA 91203-2089')
  , ('SIMI VALLEY         ,CA    93065')
  , ('SIMI VALLEY         ,CA    93065')
  , ('GLENDALE            ,CA    91203-2089')
</code>```

Results

```<code>STATE   ZIP
CA      91344
CA      93065
CA      91203-2089
CA      93065
CA      93065
CA      91203-2089
</code>```

see demo

Body:
Using DB2 for z/OS 10, I'm have a column (ADDRESS3) in a table that contains city, state, and zipcode all in one column. But, the formatting is somewhat "free-form". (see code below)

I can successfully parse the city by taking everything before the comma. Using only DB2 SQL, how would I parse out the state and zipcode?

SELECT ADDRESS3,
       TRIM(SUBSTR(ADDRESS3,1,LOCATE(',', ADDRESS3)-1)) AS CITY
  FROM MYTABLE

ADDRESS3                            CITY
----------------------------------  -------------
GRANADA HILLS       ,CA 91344       GRANADA HILLS
SIMI VALLEY         ,CA 93065       SIMI VALLEY
BUENA PARK          ,CA 90621       BUENA PARK
SHERMAN OAKS        ,CA 91423       SHERMAN OAKS
GLENDALE            ,CA 91203-2089  GLENDALE
VENTURA             ,CA 93002       VENTURA
HAWTHORNE           ,CA 90250       HAWTHORNE
PASADENA            ,CA 91185-2594  PASADENA
BEVERLY HILLS       ,CA 90211       BEVERLY HILLS
ARCADIA             ,CA 91007       ARCADIA
WALNUT CREEK        ,CA 94596       WALNUT CREEK
INDEPENDANCE        ,CA 93526       INDEPENDANCE
LOS ANGELES         ,CA 90017       LOS ANGELES

Ultimately, I'd like the query results to look like this:

CITY          STATE ZIP
------------- ----- -----
GRANADA HILLS CA    91344
SIMI VALLEY   CA    93065
BUENA PARK    CA    90621
SHERMAN OAKS  CA    91423
GLENDALE      CA    91203
VENTURA       CA    93002
HAWTHORNE     CA    90250
PASADENA      CA    91185
...

Thanks!

Body:
I think you need this assuming the format is the same always.

  SELECT
       TRIM(
         SUBSTR(
           SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1)
           , 1
           , POSITION(' ' , SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1))
         )
       ) AS STATE
    ,  TRIM(
           SUBSTR(
             SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1)
           , POSITION(' ' , SUBSTR(MYTABLE.A, LOCATE(',', MYTABLE.A) + 1))
         )
       ) AS ZIP
  FROM MYTABLE

The demo result into these results with these values

Test data

  VALUES
    ('GRANADA HILLS       ,CA 91344')
  , ('SIMI VALLEY         ,CA 93065')
  , ('GLENDALE            ,CA 91203-2089')
  , ('SIMI VALLEY         ,CA    93065')
  , ('SIMI VALLEY         ,CA    93065')
  , ('GLENDALE            ,CA    91203-2089')

Results

STATE   ZIP
CA      91344
CA      93065
CA      91203-2089
CA      93065
CA      93065
CA      91203-2089

see demo


问:
How to overload equality operator?
In swift for example, you can overload the equality operator as follows:

Overloading equivalence (==) operator for custom class in Swift

```<code>class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}
</code>```

Is there a way to do this in elixir?

What I want to achieve is this:

```<code>defmodule IP do
  @enforce_keys [:host, :port]
  defstruct [:host, :port, failures: 0, timeouts: 0]

  @type t :: %IP{host: String.t(), port: integer, failures: integer, timeouts: integer}

  # I want the == operator compare host and port but not failures and timeouts..
  def compare(l, r) do
    l.host == r.host && l.port == r.port
  end
end
</code>```

答:
```<code>defmodule IP do
  defstruct [:host, :port, :name]

  def left_ip == right_ip do
    Kernel.==(left_ip.host, right_ip.host) &&
    Kernel.==(left_ip.port, right_ip.port)
  end

end
</code>```

In iex:

```<code>~/elixir_programs$ iex ip.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.8.2) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> left_ip = %IP{host: 10, port: 3, name: "Joe"}
%IP{host: 10, name: "Joe", port: 3}

iex(2)> right_ip = %IP{host: 10, port: 3, name: "Karen"}
%IP{host: 10, name: "Karen", port: 3}

iex(3)> left_ip == right_ip
false

iex(4)> import Kernel, except: [==: 2]
Kernel

iex(5)> left_ip == right_ip
** (CompileError) iex:5: undefined function ==/2

iex(5)> import IP
IP

iex(6)> left_ip == right_ip
true
</code>```

Kernel is automatically imported into iex, so you have to import Kernel again excepting the function Kernel.==().

An import statement has to do with namespacing.  By importing IP, you no longer have to precede a function's name with the module name:

```<code>IP.==(left, right)

v.

left == right
</code>```

I wanted structs to be compared as equals when inserted inside a MapSet

No worky with MapSets:

```<code>iex(24)> left_ip == right_ip
true

iex(27)> ms = MapSet.new()
#MapSet<[]>

iex(28)> ms |> MapSet.put("hello") |> MapSet.put(left_ip) |> MapSet.put("hello") |> MapSet.put(right_ip) |> MapSet.put(left_ip)
#MapSet<[
  %IP{host: 10, name: "Joe", port: 3},
  %IP{host: 10, name: "Karen", port: 3},
  "hello"
]>
</code>```

Mapset.put calls Map.put which calls :maps.put--which is an erlang function.

Title: How to overload equality operator?

Body:
In swift for example, you can overload the equality operator as follows:

Overloading equivalence (==) operator for custom class in Swift

class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}

Is there a way to do this in elixir?

What I want to achieve is this:

defmodule IP do
  @enforce_keys [:host, :port]
  defstruct [:host, :port, failures: 0, timeouts: 0]

  @type t :: %IP{host: String.t(), port: integer, failures: integer, timeouts: integer}

  # I want the == operator compare host and port but not failures and timeouts..
  def compare(l, r) do
    l.host == r.host && l.port == r.port
  end
end

Body:
defmodule IP do
  defstruct [:host, :port, :name]

  def left_ip == right_ip do
    Kernel.==(left_ip.host, right_ip.host) &&
    Kernel.==(left_ip.port, right_ip.port)
  end

end

In iex:

~/elixir_programs$ iex ip.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.8.2) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> left_ip = %IP{host: 10, port: 3, name: "Joe"}
%IP{host: 10, name: "Joe", port: 3}

iex(2)> right_ip = %IP{host: 10, port: 3, name: "Karen"}
%IP{host: 10, name: "Karen", port: 3}

iex(3)> left_ip == right_ip
false

iex(4)> import Kernel, except: [==: 2]
Kernel

iex(5)> left_ip == right_ip
** (CompileError) iex:5: undefined function ==/2

iex(5)> import IP
IP

iex(6)> left_ip == right_ip
true

Kernel is automatically imported into iex, so you have to import Kernel again excepting the function Kernel.==().

An import statement has to do with namespacing.  By importing IP, you no longer have to precede a function's name with the module name:

IP.==(left, right)

v.

left == right

I wanted structs to be compared as equals when inserted inside a MapSet

No worky with MapSets:

iex(24)> left_ip == right_ip
true

iex(27)> ms = MapSet.new()
#MapSet<[]>

iex(28)> ms |> MapSet.put("hello") |> MapSet.put(left_ip) |> MapSet.put("hello") |> MapSet.put(right_ip) |> MapSet.put(left_ip)
#MapSet<[
  %IP{host: 10, name: "Joe", port: 3},
  %IP{host: 10, name: "Karen", port: 3},
  "hello"
]>

Mapset.put calls Map.put which calls :maps.put--which is an erlang function.


问:
Why I can't checked more than checkboxes?
Using Flask I populated a table and tried to create something which made it possible for clicking in any part of row and "checked" the checkbox input. But I can't checked more than one.

Created a var to check if the input is "checked", if no, checked! if yes, make possible unchecked the box at any part of tr.

```<code>  $("table tbody tr").on('click',function(){
    var checked = $("input:checkbox").is(':checked');
    if(checked){
     $("input:checkbox",this).prop('checked', false);
     console.log(checked);
    }else{
     console.log(checked);
     $("input:checkbox",this).prop('checked', true);
    }
</code>```

HTML:

```<code><table class="table table-responsive" id="osTable" width="100%" cellspacing="0" align="center">
        <thead align="center">
            <tr>
             <th>#</th>
             <th>Id</th>
             <th>Name</th>
            </tr>
        </thead>
        <tbody>
         {%for data in data%}
         <tr>
           <td><input type="checkbox" name="{{data[0]}}"></td>
           <td>{{data[0]}}</td>
           <td>{{data[1]}}</td>

         </tr>
         {%endfor%}
        </tbody>
    </table>
</code>```

答:
You can shorten the whole thing to these three lines using with:

```<code>$("table tbody").on('click',"tr",function(){
  with($("input:checkbox",this))
    prop('checked',!is(':checked'));
});
</code>```

Body:
Using Flask I populated a table and tried to create something which made it possible for clicking in any part of row and "checked" the checkbox input. But I can't checked more than one.

Created a var to check if the input is "checked", if no, checked! if yes, make possible unchecked the box at any part of tr.

  $("table tbody tr").on('click',function(){
    var checked = $("input:checkbox").is(':checked');
    if(checked){
     $("input:checkbox",this).prop('checked', false);
     console.log(checked);
    }else{
     console.log(checked);
     $("input:checkbox",this).prop('checked', true);
    }

HTML:

             #
             Id
             Name

         {%for data in data%}

           <input type="checkbox" name="{{data[0]}}">
           {{data[0]}}
           {{data[1]}}

         {%endfor%}

Body:
You can shorten the whole thing to these three lines using with:

$("table tbody").on('click',"tr",function(){
  with($("input:checkbox",this))
    prop('checked',!is(':checked'));
});


问:
How to bind custom style in b-col (bootstrap-vue) element?
I need to add custom style to my  element like below:

```<code><b-container fluid class="bootstrap-container">
    <b-row id="plan-execution">
        <b-col :style="executionProgress" >Hello!</b-col>
    </b-row>
</b-container>
</code>```

In the executionProgress variable it stores my previously calculated styles eg:

```<code>background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat
</code>```

(The style is calculated depending on the data collected from the API)

I tried: :style="", v-bind:style="" but no effect.

In code below binding style works perfect

        Hello!

```

Short question: How I can bind my previously populated style to  element?

答:
Binding :style as string doesn't seem to work on Bootstrap Vue components. You can pass styles to them using an object, with camel-cased CSS properties (i.e. marginTop, backgroundImage, etc...) and string values. In your case:

```<code>executionProgress: {
  background: 'linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
}
</code>```

See it working:

new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    executionProgress: {
      background: 'linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
    }
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  background-color: #eee;
}</code>```

<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

```
</div>
</div>
</p>

<hr>

<p>A quick test shows us string notation on Vue components works, so this is a Bootstrap Vue specific problem:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('testComponent', {
  template: '#testTemplate',
  props: {
    style: {
      type: String | Object,
      default: ''
    }
  }
})
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    stringStyle: 'background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
  })
})</code>```

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>

<script id="appTemplate" type="text/template">
  <test-component :style="stringStyle" />
</script>
<script id="testTemplate" type="text/template">
  <div :style="style">
    <slot>test</slot>
  </div>
</script>
<div id="app"></div></code>```

Edit: Filed it as a Bootstrap Vue bug here.

Body:
I need to add custom style to my  element like below:

        Hello!

In the executionProgress variable it stores my previously calculated styles eg:

background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat

(The style is calculated depending on the data collected from the API)

I tried: :style="", v-bind:style="" but no effect.

In code below binding style works perfect

        Hello!

Short question: How I can bind my previously populated style to  element?

Body:
Binding :style as string doesn't seem to work on Bootstrap Vue components. You can pass styles to them using an object, with camel-cased CSS properties (i.e. marginTop, backgroundImage, etc...) and string values. In your case:

executionProgress: {
  background: 'linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
}

See it working:

new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    executionProgress: {
      background: 'linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
    }
  })
})

.container {
  background-color: #eee;
}

<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CMutationObserver" crossorigin="anonymous"></script>
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<script id="appTemplate" type="text/template">
  <b-container class="bv-example-row">
    <b-row>
      <b-col>1 of 3</b-col>
      <b-col>2 of 3</b-col>
      <b-col :style="executionProgress">3 of 3</b-col>
    </b-row>
  </b-container>
</script>
<div id="app"></div>

A quick test shows us string notation on Vue components works, so this is a Bootstrap Vue specific problem:

Vue.component('testComponent', {
  template: '#testTemplate',
  props: {
    style: {
      type: String | Object,
      default: ''
    }
  }
})
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    stringStyle: 'background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat'
  })
})

body {
  margin: 0;
}

<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>

<script id="appTemplate" type="text/template">
  <test-component :style="stringStyle" />
</script>
<script id="testTemplate" type="text/template">
  <div :style="style">
    <slot>test</slot>
  </div>
</script>
<div id="app"></div>

Edit: Filed it as a Bootstrap Vue bug here.


问:
How to display and filter this array for angular/typescript app?
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic</p>

```<code> {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }
</code>```

答:
You can do something like this, without importing any other library:

```<code> // Build an array of the Pallet IDs
    this.pallets = this.source.Sku.map(item => {
        return item.breakdownPalletID;
    }).filter((item, index, self) => {// Remove duplicate Pallet IDs
        return index === self.indexOf(item);
    });

    // Sort Pallet IDs (optional)
    this.pallets.sort();

    // Create a new array with the items grouped by PalletId
    this.pallets.forEach(pId => {
        this.target.push({
            PalletId: pId,
            Items: this.source.Sku.filter(item => item.breakdownPalletID === pId)
        });
    });
</code>```

Where, "this.source" is your original object. The output is an array of object you can use with an *ngFor.

See demo

Body:
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic

 {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }

Body:
You can do something like this, without importing any other library:

 // Build an array of the Pallet IDs
    this.pallets = this.source.Sku.map(item => {
        return item.breakdownPalletID;
    }).filter((item, index, self) => {// Remove duplicate Pallet IDs
        return index === self.indexOf(item);
    });

    // Sort Pallet IDs (optional)
    this.pallets.sort();

    // Create a new array with the items grouped by PalletId
    this.pallets.forEach(pId => {
        this.target.push({
            PalletId: pId,
            Items: this.source.Sku.filter(item => item.breakdownPalletID === pId)
        });
    });

Where, "this.source" is your original object. The output is an array of object you can use with an *ngFor.

See demo


问:
Swift UIScrollView - Correct Implementation for Only Vertical Scrolling
In advance, I apologize as I would say that I'm a beginner with iOS programming.

I want to use UIScrollView because the content to display exceed the height of the screen.
Therefore, I would like only a vertical scroll and not a horizontal scrolling.

I'm using the Storyboard to draw the views with AutoLayout.

Here's are the screenshot of my UIViewController with the UIScrollView :

Then I change the Label to a big text like that

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    self.label1Label.text = "Seize jours après la chute du président Blaise Compaoré, le Burkina Faso a un nouveau chef d'EtatA l'issue d'ultimes tractions, civils et militaires se sont accordés, lundi 17 novembre, sur le nom du diplomate Michel KafandoSeize jours après la chute du président Blaise Compaoré, le Burkina Faso a un nouveau chef d'EtatA l'issue d'ultimes tractions, civils et militaires se sont accordés, lundi 17 novembre, sur le nom du diplomate Michel Kafando"
    self.label1Label.numberOfLines = 0
    self.label1Label.sizeToFit()
</code>```

My problem is that if I don't set manually a width for my contentView (inside the UIScrollView), the scrolling is horizontal, not vertical. (Look Screenshot below):

I've tried to set contentSize as I've seen in many google post but without success :

```<code>self.scrollView.contentSize = CGSizeMake(400.0, 600.0)
</code>```

If I set a width manually for my contentview (i.e : 320pts), the scrolling will be vertical (GOOD) but then depending on the iphone size, it won't cover the whole width of the screen as shown in the following screenshot :

The question is : what is the correct implementation to use UIScrollView to have a contentView that respect the autolayout constraint (full screen  : 0top - 0bottom - 0left - 0right) and the scrolling to be only vertical.

Thanks a lot for your help!

答:
You can define ScrollView normally and constrain the properties of ScrollView normally

```<code>        let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.backgroundColor = .white
    self.view.addSubview(scrollView)

    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
</code>```

But the trick is in how you define your Label (or other view) that may be wider than the screen.
Instead of using

```<code>myLabel.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -10.0).isActive = true
</code>```

You should use

```<code>myLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10.0).isActive = true
</code>```

This second line will stop that view from causing horizontal scrolling.  Do that with all your subviews and you won't scroll horizontally.  (It will still scroll vertically as planned.)

Also, don't forget to set the bottom constraint on your last subview to make sure your UIScrollview scrolls vertically.

```<code>labelX.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -10.0).isActive = true
</code>```

Body:
In advance, I apologize as I would say that I'm a beginner with iOS programming.

I want to use UIScrollView because the content to display exceed the height of the screen.
Therefore, I would like only a vertical scroll and not a horizontal scrolling.

I'm using the Storyboard to draw the views with AutoLayout.

Here's are the screenshot of my UIViewController with the UIScrollView :

Then I change the Label to a big text like that

override func viewDidLoad() {
    super.viewDidLoad()

    self.label1Label.text = "Seize jours après la chute du président Blaise Compaoré, le Burkina Faso a un nouveau chef d'EtatA l'issue d'ultimes tractions, civils et militaires se sont accordés, lundi 17 novembre, sur le nom du diplomate Michel KafandoSeize jours après la chute du président Blaise Compaoré, le Burkina Faso a un nouveau chef d'EtatA l'issue d'ultimes tractions, civils et militaires se sont accordés, lundi 17 novembre, sur le nom du diplomate Michel Kafando"
    self.label1Label.numberOfLines = 0
    self.label1Label.sizeToFit()

My problem is that if I don't set manually a width for my contentView (inside the UIScrollView), the scrolling is horizontal, not vertical. (Look Screenshot below):

I've tried to set contentSize as I've seen in many google post but without success :

self.scrollView.contentSize = CGSizeMake(400.0, 600.0)

If I set a width manually for my contentview (i.e : 320pts), the scrolling will be vertical (GOOD) but then depending on the iphone size, it won't cover the whole width of the screen as shown in the following screenshot :

The question is : what is the correct implementation to use UIScrollView to have a contentView that respect the autolayout constraint (full screen  : 0top - 0bottom - 0left - 0right) and the scrolling to be only vertical.

Thanks a lot for your help!

Body:
You can define ScrollView normally and constrain the properties of ScrollView normally

        let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.backgroundColor = .white
    self.view.addSubview(scrollView)

    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true

But the trick is in how you define your Label (or other view) that may be wider than the screen.
Instead of using

myLabel.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -10.0).isActive = true

You should use

myLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10.0).isActive = true

This second line will stop that view from causing horizontal scrolling.  Do that with all your subviews and you won't scroll horizontally.  (It will still scroll vertically as planned.)

Also, don't forget to set the bottom constraint on your last subview to make sure your UIScrollview scrolls vertically.

labelX.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -10.0).isActive = true


问:
WPF Recursive call to Automation Peer API is not valid
I am receiving an error message "Recursive call to Automation Peer API is not valid" when loading a datagrid with a datatemplatecolumn containing a combobox column. The error ends up caught in our unhandled exception code. This seems to be an issue on my machine, and google has provided no source of guidance on resolving the issue. The issue appears to only occur when I am populating the comboboxes with data. Populating the comboboxes (if I do not load data) works correctly, and while the error is displayed I am able to see the data properly retrieved in the background.

I am using a WPF datagrid where I'm using a DataGridTemplateColumn for adding a combobox inside the grid. I have the drop down list bound to an enum using an objectdataprovider. In the code behind when initializing my screen I use a Linq2Sql statement to retrieve data and populate the Itemssource of the grid.

```<code><grid:DataGrid.Resources>
 <ObjectDataProvider
  x:Key="ChangeTypeData"
  MethodName="GetValues"
  ObjectType="{x:Type System:Enum}">
  <ObjectDataProvider.MethodParameters>
   <x:Type TypeName="namespace:ChangeType" />
  </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>
    </grid:DataGrid.Resources>

 <grid:DataGrid.Columns>
 <grid:DataGridTextColumn Binding="{Binding DatapointName}" Header="Datapoint Changed" IsReadOnly="True" Width="Auto" />
 <grid:DataGridTemplateColumn Header="Change Type">
  <grid:DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
    <ComboBox
     Text="{Binding Path=ChangeTypeName}"
     ItemsSource="{Binding Source={StaticResource ChangeTypeData}}"
     Name="dgcboChangeType"
SelectionChanged="dgcboChangeType_SelectionChanged"/>
   </DataTemplate>
  </grid:DataGridTemplateColumn.CellTemplate>
</code>```

Any and all guidance on solving this issue is appreciated.

答:
I was able to fix this issue by replacing both the DataGrid and the ComboBox in the WPF XAML file with the following two derived classes which both override the OnCreateAutomationPeer() method.</p>

```<code>public class SafeDataGrid : DataGrid
{
    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return null;
    }
}

public class SafeComboBox : ComboBox
{
    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return null;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am receiving an error message "Recursive call to Automation Peer API is not valid" when loading a datagrid with a datatemplatecolumn containing a combobox column. The error ends up caught in our unhandled exception code. This seems to be an issue on my machine, and google has provided no source of guidance on resolving the issue. The issue appears to only occur when I am populating the comboboxes with data. Populating the comboboxes (if I do not load data) works correctly, and while the error is displayed I am able to see the data properly retrieved in the background.

I am using a WPF datagrid where I'm using a DataGridTemplateColumn for adding a combobox inside the grid. I have the drop down list bound to an enum using an objectdataprovider. In the code behind when initializing my screen I use a Linq2Sql statement to retrieve data and populate the Itemssource of the grid.

<grid:DataGrid.Resources>
 <ObjectDataProvider
  x:Key="ChangeTypeData"
  MethodName="GetValues"
  ObjectType="{x:Type System:Enum}">
  <ObjectDataProvider.MethodParameters>
   <x:Type TypeName="namespace:ChangeType" />
  </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>
    </grid:DataGrid.Resources>

 <grid:DataGrid.Columns>
 <grid:DataGridTextColumn Binding="{Binding DatapointName}" Header="Datapoint Changed" IsReadOnly="True" Width="Auto" />
 <grid:DataGridTemplateColumn Header="Change Type">
  <grid:DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
    <ComboBox
     Text="{Binding Path=ChangeTypeName}"
     ItemsSource="{Binding Source={StaticResource ChangeTypeData}}"
     Name="dgcboChangeType"
SelectionChanged="dgcboChangeType_SelectionChanged"/>
   </DataTemplate>
  </grid:DataGridTemplateColumn.CellTemplate>

Any and all guidance on solving this issue is appreciated.

Body:
I was able to fix this issue by replacing both the DataGrid and the ComboBox in the WPF XAML file with the following two derived classes which both override the OnCreateAutomationPeer() method.

public class SafeDataGrid : DataGrid
{
    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return null;
    }
}

public class SafeComboBox : ComboBox
{
    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return null;
    }
}


问:
Roblox Studio Lua : Clone with local script
I created a template or when someone touches that template, it's destroyed, but it's only for that person. I try to clone the model with a local script, but it does not work.</p>

```<code>local part2 = script.Parent.MarioBrick:Clone()
part2.Parent = game.Workspace.Camera
</code>```

答:
Your code looks fine. I suspect that your problem is that your LocalScript is not in a place that is run by clients. If you want a LocalScript to run, it needs to exist on a Player's model somewhere. An easy way to do this is to add the LocalScript into StarterPlayer > StarterCharacterScripts
This will clone the contents into the character when they spawn. Here's my example that seems to work :

```<code>local testPart = Instance.new("Part")
testPart.BrickColor = BrickColor.Random()
testPart.Position = Vector3.new(math.random(-10, 10), 1, math.random(-10, 10))
testPart.Parent = game.Workspace.Camera
</code>```

When I go into the Test tab, I can start a server with 3 players. Each of those 3 players will see a different color cube somewhere different.

Body:
I created a template or when someone touches that template, it's destroyed, but it's only for that person. I try to clone the model with a local script, but it does not work.

local part2 = script.Parent.MarioBrick:Clone()
part2.Parent = game.Workspace.Camera

Body:
Your code looks fine. I suspect that your problem is that your LocalScript is not in a place that is run by clients. If you want a LocalScript to run, it needs to exist on a Player's model somewhere. An easy way to do this is to add the LocalScript into StarterPlayer > StarterCharacterScripts
This will clone the contents into the character when they spawn. Here's my example that seems to work :

local testPart = Instance.new("Part")
testPart.BrickColor = BrickColor.Random()
testPart.Position = Vector3.new(math.random(-10, 10), 1, math.random(-10, 10))
testPart.Parent = game.Workspace.Camera

When I go into the Test tab, I can start a server with 3 players. Each of those 3 players will see a different color cube somewhere different.


问:
How to convert UTF8 string to byte array?
The .charCodeAt function returns with the unicode code of the caracter. But I would like to get the byte array instead. I know, if the charcode is over 127, then the character is stored in two or more bytes.

```<code>var arr=[];
for(var i=0; i<str.length; i++) {
    arr.push(str.charCodeAt(i))
}
</code>```

答:
I was using Joni's solution and it worked fine, but this one is much shorter.

This was inspired by the atobUTF16() function of Solution #3 of Mozilla's Base64 Unicode discussion

```<code>function convertStringToUTF8ByteArray(str) {
    let binaryArray = new Uint8Array(str.length)
    Array.prototype.forEach.call(binaryArray, function (el, idx, arr) { arr[idx] = str.charCodeAt(idx) })
    return binaryArray
}
</code>```

Body:
The .charCodeAt function returns with the unicode code of the caracter. But I would like to get the byte array instead. I know, if the charcode is over 127, then the character is stored in two or more bytes.

var arr=[];
for(var i=0; i<str.length; i++) {
    arr.push(str.charCodeAt(i))
}

Body:
I was using Joni's solution and it worked fine, but this one is much shorter.

This was inspired by the atobUTF16() function of Solution #3 of Mozilla's Base64 Unicode discussion

function convertStringToUTF8ByteArray(str) {
    let binaryArray = new Uint8Array(str.length)
    Array.prototype.forEach.call(binaryArray, function (el, idx, arr) { arr[idx] = str.charCodeAt(idx) })
    return binaryArray
}


问:
how to display the entire object in console in react native
I recently started doing react native and don't understand as how to debug so as to get my results in console .
Here is the result I get in console .

```<code>Organizations is [object Object]
</code>```

How do i get all the content of organizations .
I did this in my code for console .

```<code>console.log('Organizations is '+organizations);
</code>```

答:
use below code to print object in react-native </p>

```<code><View> {(()=>{ console.log(object) })()} </View>
</code>```

Body:
I recently started doing react native and don't understand as how to debug so as to get my results in console .
Here is the result I get in console .

Organizations is [object Object]

How do i get all the content of organizations .
I did this in my code for console .

console.log('Organizations is '+organizations);

Body:
use below code to print object in react-native

<View> {(()=>{ console.log(object) })()} </View>