问:
detecting a click inside a hexagon drawn using canvas?
I'm working on a certain layout where I need to draw a hexagon which needs to be clickable. I'm using the Path2D construct and isPointInPath function. I'm constructing an animation where a number of hexagons is created and then each moved to a certain position. After the movement is done, I am attaching onclick event handlers to certain hexagons. However there is weird behaviour.

Some initialized variables

```<code>const COLOR_DARK = "#73b6c6";
const COLOR_LIGHT = "#c3dadd";
const COLOR_PRIMARY = "#39a4c9";

const TYPE_PRIMARY = 'primary';

let hexagons = [];
</code>```

Below is the function which draws the hexagons.

```<code>function drawHex(ctx, x, y, hexProps, stroke, color) {

    let myPath = new Path2D();

    myPath.moveTo(x + hexProps.width*0.5, y);
    myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
    myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
    myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
    myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
    myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
    myPath.lineTo(x + hexProps.width*0.5, y);
    myPath.closePath();

    if (stroke){
        ctx.strokeStyle = color;
        ctx.stroke(myPath);
    } else {
        ctx.fillStyle = color;
        ctx.fill(myPath);
    }

    return myPath;
}
</code>```

This function populates the hexagon array

```<code>function populateLeftHex(canvasWidth, canvasHeight, hexProps) {

const startX = canvasWidth / 2;
const startY = canvasHeight / 2;
const baseLeft = canvasWidth * 0.05;

for(let i = 0; i < 5; i++){
    let hexNumber = (i % 4 == 0)? 2: 1;

    for(let j = 0; j < hexNumber; j++){
        hexagons.push({
            startX: startX,
            startY: startY,
            endX: baseLeft + (2 * j) + ((i % 2 == 0)? (hexProps.width * j) : (hexProps.width/2)),
            endY: ((i + 1) * hexProps.height) - ((i) * hexProps.height * hexProps.facShort)  + (i* 2),
            stroke: true,
            color: ( i % 2 == 0 && j % 2 == 0)? COLOR_DARK : COLOR_LIGHT,
            type: TYPE_PRIMARY
        });
    }
}
</code>```

}

And here is where Im calling the isPointInPath function.

```<code>   window.onload = function (){
const c = document.getElementById('canvas');

const canvasWidth = c.width = window.innerWidth,
    canvasHeight = c.height = window.innerHeight,
    ctx = c.getContext('2d');

window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

console.log(canvasWidth);

let hexProps = {
  width: canvasWidth * 0.075,
    get height () {
      return this.width/Math.sqrt(3) + (1.5)*(this.width/Math.sqrt(2)/2);
    } ,
    facShort: 0.225,
    get facLong () {
      return 1 - this.facShort;
    }
};

populateLeftHex(canvasWidth, canvasHeight, hexProps);

let pct = 0;
const fps = 200;

animate();

function animate () {

    setTimeout(function () {
    // increment pct towards 100%
    pct += .03;

    // if we're not done, request another animation frame
    if (pct < 1.00) {
        requestAnimFrame(animate);
    } else { //if pct is no longer less than 1.00, then the movement animation is over.
        hexagons.forEach(function (hex) {
            if(hex.type === TYPE_PRIMARY) {

                console.info(hex.path);

                c.onclick = function(e) {

                    let x = e.clientX - c.offsetLeft,
                        y = e.clientY - c.offsetTop;
                    console.info(ctx.isPointInPath(hex.path, (e.clientX - c.offsetLeft), (e.clientY - c.offsetTop) ));
                };
            }
        })
    }

    ctx.clearRect(0, 0, c.width, c.height);

        // draw all hexagons
        for ( let i = 0; i < hexagons.length; i++) {

            // get reference to next shape
            let hex = hexagons[i];

            // note: dx/dy are fixed values
            // they could be put in the shape object for efficiency
            let dx = hex.endX - hex.startX;
            let dy = hex.endY - hex.startY;
            let nextX = hex.startX + dx * pct;
            let nextY = hex.startY + dy * pct;
            hex = hexagons[i];
            ctx.fillStyle = hex.color;
            hex.path = drawHex(ctx, nextX, nextY, hexProps, hex.stroke, hex.color);

        }

    }, 1000 / fps);
}
</code>```

Can you help me figure out what I'm doing wrong? Maybe I misunderstood how Path2D works? Thanks in advance.

答:
Had to do a bit of work to build a test page as your example is incomplete, but this is working for me - though my hexagon is concave...

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");

var hexProps = {width:100, height:100, facShort:-2, facLong:10};

var hexagons = [];

 function drawHex(ctx, x, y, hexProps, stroke, color) {

     let myPath = new Path2D();

     myPath.moveTo(x + hexProps.width*0.5, y);
     myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
     myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
     myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
     myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
     myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
     myPath.lineTo(x + hexProps.width*0.5, y);
     myPath.closePath();

     if (stroke){
         ctx.strokeStyle = color;
         ctx.stroke(myPath);
     } else {
         ctx.fillStyle = color;
         ctx.fill(myPath);
     }

     return myPath;
 }

hexagons.push({type:0, path:drawHex(ctx,100,100,hexProps,false,"#0f0")});

   hexagons.forEach(function (hex) {
            if(hex.type === 0) {

                console.info(hex.path);

                myCanvas.onclick = function(e) {

                    let x = e.clientX - myCanvas.offsetLeft,
                        y = e.clientY - myCanvas.offsetTop;
                    console.info(x,y);
                    console.info(ctx.isPointInPath(hex.path, (e.clientX -
 myCanvas.offsetLeft), (e.clientY - myCanvas.offsetTop) ));

                };
            }
        })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width=500 height=500 id=myCanvas style='border:1px solid red'></canvas></code>```

Test clicks give true and false where expected:

```<code>test.htm:48 165 168
test.htm:49 true
test.htm:48 151 336
test.htm:49 false
test.htm:48 124 314
test.htm:49 true
test.htm:48 87 311
test.htm:49 false
</code>```

Body:
I'm working on a certain layout where I need to draw a hexagon which needs to be clickable. I'm using the Path2D construct and isPointInPath function. I'm constructing an animation where a number of hexagons is created and then each moved to a certain position. After the movement is done, I am attaching onclick event handlers to certain hexagons. However there is weird behaviour.

Some initialized variables

const COLOR_DARK = "#73b6c6";
const COLOR_LIGHT = "#c3dadd";
const COLOR_PRIMARY = "#39a4c9";

const TYPE_PRIMARY = 'primary';

let hexagons = [];

Below is the function which draws the hexagons.

function drawHex(ctx, x, y, hexProps, stroke, color) {

    let myPath = new Path2D();

    myPath.moveTo(x + hexProps.width*0.5, y);
    myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
    myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
    myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
    myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
    myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
    myPath.lineTo(x + hexProps.width*0.5, y);
    myPath.closePath();

    if (stroke){
        ctx.strokeStyle = color;
        ctx.stroke(myPath);
    } else {
        ctx.fillStyle = color;
        ctx.fill(myPath);
    }

    return myPath;
}

This function populates the hexagon array

function populateLeftHex(canvasWidth, canvasHeight, hexProps) {

const startX = canvasWidth / 2;
const startY = canvasHeight / 2;
const baseLeft = canvasWidth * 0.05;

for(let i = 0; i < 5; i++){
    let hexNumber = (i % 4 == 0)? 2: 1;

    for(let j = 0; j < hexNumber; j++){
        hexagons.push({
            startX: startX,
            startY: startY,
            endX: baseLeft + (2 * j) + ((i % 2 == 0)? (hexProps.width * j) : (hexProps.width/2)),
            endY: ((i + 1) * hexProps.height) - ((i) * hexProps.height * hexProps.facShort)  + (i* 2),
            stroke: true,
            color: ( i % 2 == 0 && j % 2 == 0)? COLOR_DARK : COLOR_LIGHT,
            type: TYPE_PRIMARY
        });
    }
}

}

And here is where Im calling the isPointInPath function.

   window.onload = function (){
const c = document.getElementById('canvas');

const canvasWidth = c.width = window.innerWidth,
    canvasHeight = c.height = window.innerHeight,
    ctx = c.getContext('2d');

window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

console.log(canvasWidth);

let hexProps = {
  width: canvasWidth * 0.075,
    get height () {
      return this.width/Math.sqrt(3) + (1.5)*(this.width/Math.sqrt(2)/2);
    } ,
    facShort: 0.225,
    get facLong () {
      return 1 - this.facShort;
    }
};

populateLeftHex(canvasWidth, canvasHeight, hexProps);

let pct = 0;
const fps = 200;

animate();

function animate () {

    setTimeout(function () {
    // increment pct towards 100%
    pct += .03;

    // if we're not done, request another animation frame
    if (pct < 1.00) {
        requestAnimFrame(animate);
    } else { //if pct is no longer less than 1.00, then the movement animation is over.
        hexagons.forEach(function (hex) {
            if(hex.type === TYPE_PRIMARY) {

                console.info(hex.path);

                c.onclick = function(e) {

                    let x = e.clientX - c.offsetLeft,
                        y = e.clientY - c.offsetTop;
                    console.info(ctx.isPointInPath(hex.path, (e.clientX - c.offsetLeft), (e.clientY - c.offsetTop) ));
                };
            }
        })
    }

    ctx.clearRect(0, 0, c.width, c.height);

        // draw all hexagons
        for ( let i = 0; i < hexagons.length; i++) {

            // get reference to next shape
            let hex = hexagons[i];

            // note: dx/dy are fixed values
            // they could be put in the shape object for efficiency
            let dx = hex.endX - hex.startX;
            let dy = hex.endY - hex.startY;
            let nextX = hex.startX + dx * pct;
            let nextY = hex.startY + dy * pct;
            hex = hexagons[i];
            ctx.fillStyle = hex.color;
            hex.path = drawHex(ctx, nextX, nextY, hexProps, hex.stroke, hex.color);

        }

    }, 1000 / fps);
}

Can you help me figure out what I'm doing wrong? Maybe I misunderstood how Path2D works? Thanks in advance.

Body:
Had to do a bit of work to build a test page as your example is incomplete, but this is working for me - though my hexagon is concave...

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");

var hexProps = {width:100, height:100, facShort:-2, facLong:10};

var hexagons = [];

 function drawHex(ctx, x, y, hexProps, stroke, color) {

     let myPath = new Path2D();

     myPath.moveTo(x + hexProps.width*0.5, y);
     myPath.lineTo(x, y + hexProps.height*hexProps.facShort);
     myPath.lineTo(x, y + hexProps.height*hexProps.facLong);
     myPath.lineTo(x + hexProps.width*0.5, y + hexProps.height);
     myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facLong);
     myPath.lineTo(x + hexProps.width, y + hexProps.height*hexProps.facShort);
     myPath.lineTo(x + hexProps.width*0.5, y);
     myPath.closePath();

     if (stroke){
         ctx.strokeStyle = color;
         ctx.stroke(myPath);
     } else {
         ctx.fillStyle = color;
         ctx.fill(myPath);
     }

     return myPath;
 }

hexagons.push({type:0, path:drawHex(ctx,100,100,hexProps,false,"#0f0")});

   hexagons.forEach(function (hex) {
            if(hex.type === 0) {

                console.info(hex.path);

                myCanvas.onclick = function(e) {

                    let x = e.clientX - myCanvas.offsetLeft,
                        y = e.clientY - myCanvas.offsetTop;
                    console.info(x,y);
                    console.info(ctx.isPointInPath(hex.path, (e.clientX -
 myCanvas.offsetLeft), (e.clientY - myCanvas.offsetTop) ));

                };
            }
        })

<canvas width=500 height=500 id=myCanvas style='border:1px solid red'></canvas>

Test clicks give true and false where expected:

test.htm:48 165 168
test.htm:49 true
test.htm:48 151 336
test.htm:49 false
test.htm:48 124 314
test.htm:49 true
test.htm:48 87 311
test.htm:49 false


来源: stackexchange

问:
Class instance of two variables
I'm very new to Haskell and created this class

```<code>class Printable a where
    toString :: a -> String
</code>```

And two of its instances

```<code>instance Printable Bool where
    toString x | x == True = "true"
               | x == False  = "false"

instance Printable () where
    toString x = "unit type"
</code>```

They work just fine, and now I want to create an instance that would take two parameters, but I'm having troubles. What I created so far is

```<code>instance (Printable a, Printable b) => Printable (a, b) where
    toString x | fst x == True = "(true,unit type)"
</code>```

But now I get the error

Couldn't match expected type ‘a’ with actual type ‘Bool’

which is reasonable, but when I replace a with Bool I also get an error. How can I make it work in the first place, and can I restrict the types for a and b - for example, what if I want a to always be Bool and b to always be ()?

答:
Just because a has a Printable instance doesn't mean you can assume a ~ Bool, so x == True fails.

You should be using pattern matching instead of equality, though, which would sidestep the issue.

```<code>class Printable a where
    toString :: a -> String

instance Printable Bool where
    toString True = "true"
    toString False = "false"

instance Printable () where
    toString () = "unit type"
</code>```

Your tuple instance should then make use of the fact that a and b are both Printable. You only need to pattern-match on the constructor, not the individual components.

```<code>instance (Printable a, Printable b) => Printable (a, b) where
    toString (x, y)  = "(" ++ toString x ++ "," ++ toString y ++ ")"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Class instance of two variables

Body:
I'm very new to Haskell and created this class

class Printable a where
    toString :: a -> String

And two of its instances

instance Printable Bool where
    toString x | x == True = "true"
               | x == False  = "false"

instance Printable () where
    toString x = "unit type"

They work just fine, and now I want to create an instance that would take two parameters, but I'm having troubles. What I created so far is

instance (Printable a, Printable b) => Printable (a, b) where
    toString x | fst x == True = "(true,unit type)"

But now I get the error

Couldn't match expected type ‘a’ with actual type ‘Bool’

which is reasonable, but when I replace a with Bool I also get an error. How can I make it work in the first place, and can I restrict the types for a and b - for example, what if I want a to always be Bool and b to always be ()?

Body:
Just because a has a Printable instance doesn't mean you can assume a ~ Bool, so x == True fails.

You should be using pattern matching instead of equality, though, which would sidestep the issue.

class Printable a where
    toString :: a -> String

instance Printable Bool where
    toString True = "true"
    toString False = "false"

instance Printable () where
    toString () = "unit type"

Your tuple instance should then make use of the fact that a and b are both Printable. You only need to pattern-match on the constructor, not the individual components.

instance (Printable a, Printable b) => Printable (a, b) where
    toString (x, y)  = "(" ++ toString x ++ "," ++ toString y ++ ")"


问:
Where should i put my Admin control panel?
I'm building a community site using PHP/MySQL, I was thinking of just letting admins login where normal users log in, and then present them with a "Admin Control Panel" link. So that the control panel platform is hosted on the same site. Is this secure? Should there be a different "gateway" for admins instead i.e. http://admin.example.com? Or should i host the Control Panel on an entirely different domain?

Thanks for your time.

答:
Having admins and normal users log in using the same form is not necessarily less secure, depending your other security measures. Some CMS systems, such as Drupal, use that model.

You're better off focusing energy on other security concerns, rather than security through obscurity. Do you limit admin logins to certain IP addresses? Do you block users after a number of unsuccessful login attempts? Do you encourage/force strong passwords? Etc.

ContentLicense: CC BY-SA 2.5


问:
broadcast error : optimal transport library
I'm doing a Barycenter clustering. but why this error? Looks like something bad happened when doing matrix multiplications.

```<code>import numpy as np
import pandas as pd
import ot

def initialize_clusters(points, k):
    return points[np.random.randint(points.shape[0], size=k)]

def get_distances(centroid, points):
    return np.linalg.norm(points - centroid, axis=1)

if __name__ == "__main__":
    X = pd.read_csv('./csv/inst_clust2.csv',encoding='utf-8')[['lat','lng']]
    M = ot.dist(X,metric='euclidean')
    X = X.as_matrix()
    k = 3
    maxiter = 50
    centroids = initialize_clusters(X,k)
    classes = np.zeros(X.shape[0],dtype=np.float64)
    distances = np.zeros([X.shape[0],k],dtype=np.float64)
    for i in range(maxiter):
        for i, c in enumerate(centroids):
            distances[:,i] = get_distances(c, X)
        classes = np.argmin(distances,axis=1)
        for c in range(k):
            print(X)
            print(X[classes==c])
            centroids[c]=ot.barycenter(X[classes==c],M,1e-3)
</code>```

gives error

```<code>/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ot/bregman.py:801: RuntimeWarning: invalid value encountered in log
  return np.exp(np.mean(np.log(alldistribT), axis=1))
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/bc.py", line 25, in <module>
    centroids[c]=ot.bregman.barycenter(X[classes==c],M,1e-3)
ValueError: could not broadcast input array from shape (605) into shape (2)
</code>```

答:
That message is caused by an attempt to assign something to the wrong shaped array.

```<code>>>> f = np.zeros((2,2))
>>> f[0] = np.zeros((605,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (605) into shape (2)
</code>```

My reading of the documentation for ot.barycenter is that it will return an array of shape matching its first parameter. That means X[classes==c] has a length of more than 2. Have you tried ot.barycenter(X[classes==c][0],M,1e-3)?

Here are the relevant docs:

```<code>barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=0.0001, verbose=False, log=False)
    Compute the entropic regularized wasserstein barycenter of distributions A

    ... snip ...

    Parameters
    ----------
    A : np.ndarray (d,n)
        n training distributions of size d

    ... snip ...

    Returns
    -------
    a : (d,) ndarray
</code>```

Body:
I'm doing a Barycenter clustering. but why this error? Looks like something bad happened when doing matrix multiplications.

import numpy as np
import pandas as pd
import ot

def initialize_clusters(points, k):
    return points[np.random.randint(points.shape[0], size=k)]

def get_distances(centroid, points):
    return np.linalg.norm(points - centroid, axis=1)

if __name__ == "__main__":
    X = pd.read_csv('./csv/inst_clust2.csv',encoding='utf-8')[['lat','lng']]
    M = ot.dist(X,metric='euclidean')
    X = X.as_matrix()
    k = 3
    maxiter = 50
    centroids = initialize_clusters(X,k)
    classes = np.zeros(X.shape[0],dtype=np.float64)
    distances = np.zeros([X.shape[0],k],dtype=np.float64)
    for i in range(maxiter):
        for i, c in enumerate(centroids):
            distances[:,i] = get_distances(c, X)
        classes = np.argmin(distances,axis=1)
        for c in range(k):
            print(X)
            print(X[classes==c])
            centroids[c]=ot.barycenter(X[classes==c],M,1e-3)

gives error

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ot/bregman.py:801: RuntimeWarning: invalid value encountered in log
  return np.exp(np.mean(np.log(alldistribT), axis=1))
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/bc.py", line 25, in <module>
    centroids[c]=ot.bregman.barycenter(X[classes==c],M,1e-3)
ValueError: could not broadcast input array from shape (605) into shape (2)

Body:
That message is caused by an attempt to assign something to the wrong shaped array.

>>> f = np.zeros((2,2))
>>> f[0] = np.zeros((605,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (605) into shape (2)

My reading of the documentation for ot.barycenter is that it will return an array of shape matching its first parameter. That means X[classes==c] has a length of more than 2. Have you tried ot.barycenter(X[classes==c][0],M,1e-3)?

Here are the relevant docs:

barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=0.0001, verbose=False, log=False)
    Compute the entropic regularized wasserstein barycenter of distributions A

    ... snip ...

    Parameters
    ----------
    A : np.ndarray (d,n)
        n training distributions of size d

    ... snip ...

    Returns
    -------
    a : (d,) ndarray


问:
Sentiment analysis for tidytext in R
I am trying to perform sentiment analysis in R.
I want to use either afinn or bing lexicon, but the problem is i cant tokenize the words.

Here are the words for which i need the sentiments for :

So there are 6 words for whom i want sentiments for :
Pass
Fail
Not Ready
Out of Business
Pass w/conditions
No entry

How do i use any of the lexicons to assign sentiments to these words

Here is my code :

```<code>d<- as.data.frame(data$Results)
d<- as.data.frame(d[1:2000,])

colnames(d) <- "text"

#Making preprocessed file for raw data
preprocess<-data.frame(text=sapply(tweet_corpus_clean, identity),
                       stringsAsFactors=F)

# tokenize
tokens <- data_frame(text = preprocess$text) %>% unnest_tokens(word, text)
</code>```

When run this i get :

Because for lexicons to assign sentiments it has to be one token per row

So i had to merge those words together.
Now when i use afinn its not able to understand what outofbusiness is obvioulsy

```<code>tokens <- data_frame(text = preprocess$text) %>% unnest_tokens(word, text)

contributions = tokens %>%ungroup()%>%
  inner_join(get_sentiments("afinn"), by = "word") %>%
  group_by(word) %>%
  summarize(score = as.numeric(sum(score * n) / sum(n))) %>%
  arrange(desc(sentiment))
</code>```

how do i do sentiment analysis for those 6 tpes of words?

答:
Hmmmm, this doesn't sounds like a sentiment analysis problem to me. You have six words/phrases that you know about exactly, and you know what they mean in your context. This sounds like you just want to assign these words/phrases scores, or even just levels of a factor.

You could do something like what I show here, where you as the analyst decide what score each of your phrases should have. Here, scores is the dataframe that you as the analyst construct with sensibly chosen scores for each text options, and df is the data you are analyzing.

library(dplyr)

scores <- data_frame(text = c("pass",
                              "fail",
                              "not ready",
                              "out of business",
                              "pass w/conditions",
                              "no entry"),
                     score = c(3, -1, 0, 0, 2, 1))

scores
#> # A tibble: 6 x 2
#>   text              score
#>   <chr>             <dbl>
#> 1 pass               3.00
#> 2 fail              -1.00
#> 3 not ready          0
#> 4 out of business    0
#> 5 pass w/conditions  2.00
#> 6 no entry           1.00

df <- data_frame(text = c("pass",
                          "pass",
                          "fail",
                          "not ready",
                          "out of business",
                          "no entry",
                          "fail",
                          "pass w/conditions",
                          "fail",
                          "no entry",
                          "pass w/conditions"))

df %>%
  left_join(scores)
#> Joining, by = "text"
#> # A tibble: 11 x 2
#>    text              score
#>    <chr>             <dbl>
#>  1 pass               3.00
#>  2 pass               3.00
#>  3 fail              -1.00
#>  4 not ready          0
#>  5 out of business    0
#>  6 no entry           1.00
#>  7 fail              -1.00
#>  8 pass w/conditions  2.00
#>  9 fail              -1.00
#> 10 no entry           1.00
#> 11 pass w/conditions  2.00
```

Sentiment analysis is most appropriate where you have large amounts of unstructured text that you need to extract insight from. Here you have only six text elements, and you can use what you know about your domain and context to assign scores.

Title: Sentiment analysis for tidytext in R

Body:
I am trying to perform sentiment analysis in R.
I want to use either afinn or bing lexicon, but the problem is i cant tokenize the words.

Here are the words for which i need the sentiments for :

So there are 6 words for whom i want sentiments for :
Pass
Fail
Not Ready
Out of Business
Pass w/conditions
No entry

How do i use any of the lexicons to assign sentiments to these words

Here is my code :

d<- as.data.frame(data$Results)
d<- as.data.frame(d[1:2000,])

colnames(d) <- "text"

#Making preprocessed file for raw data
preprocess<-data.frame(text=sapply(tweet_corpus_clean, identity),
                       stringsAsFactors=F)

# tokenize
tokens <- data_frame(text = preprocess$text) %>% unnest_tokens(word, text)

When run this i get :

Because for lexicons to assign sentiments it has to be one token per row

So i had to merge those words together.
Now when i use afinn its not able to understand what outofbusiness is obvioulsy

tokens <- data_frame(text = preprocess$text) %>% unnest_tokens(word, text)

contributions = tokens %>%ungroup()%>%
  inner_join(get_sentiments("afinn"), by = "word") %>%
  group_by(word) %>%
  summarize(score = as.numeric(sum(score * n) / sum(n))) %>%
  arrange(desc(sentiment))

how do i do sentiment analysis for those 6 tpes of words?

Body:
Hmmmm, this doesn't sounds like a sentiment analysis problem to me. You have six words/phrases that you know about exactly, and you know what they mean in your context. This sounds like you just want to assign these words/phrases scores, or even just levels of a factor.

You could do something like what I show here, where you as the analyst decide what score each of your phrases should have. Here, scores is the dataframe that you as the analyst construct with sensibly chosen scores for each text options, and df is the data you are analyzing.

library(dplyr)

scores <- data_frame(text = c("pass",
                              "fail",
                              "not ready",
                              "out of business",
                              "pass w/conditions",
                              "no entry"),
                     score = c(3, -1, 0, 0, 2, 1))

scores
#> # A tibble: 6 x 2
#>   text              score
#>   <chr>             <dbl>
#> 1 pass               3.00
#> 2 fail              -1.00
#> 3 not ready          0
#> 4 out of business    0
#> 5 pass w/conditions  2.00
#> 6 no entry           1.00

df <- data_frame(text = c("pass",
                          "pass",
                          "fail",
                          "not ready",
                          "out of business",
                          "no entry",
                          "fail",
                          "pass w/conditions",
                          "fail",
                          "no entry",
                          "pass w/conditions"))

df %>%
  left_join(scores)
#> Joining, by = "text"
#> # A tibble: 11 x 2
#>    text              score
#>    <chr>             <dbl>
#>  1 pass               3.00
#>  2 pass               3.00
#>  3 fail              -1.00
#>  4 not ready          0
#>  5 out of business    0
#>  6 no entry           1.00
#>  7 fail              -1.00
#>  8 pass w/conditions  2.00
#>  9 fail              -1.00
#> 10 no entry           1.00
#> 11 pass w/conditions  2.00

Sentiment analysis is most appropriate where you have large amounts of unstructured text that you need to extract insight from. Here you have only six text elements, and you can use what you know about your domain and context to assign scores.


问:
Get keys from Flow object type in code
Is it possible to get the keys from a Flow object type definition in the app code (in other words, are Flow type definition reified in runtime code in any way)?

Use case:

```<code>type Props = {
  userID: string,
  size: number | PhotoSize,
  subscribePresence: Function,
  unsubscribePresence: Function,
  presenceStatus: ?PresenceStatus,
  photoURL: ?string,
  userName: ?string,
};

class Photo extends Component<Props> {
  // ...
  render() {
    const { userID, size, presenceStatus } = this.props;
    // Other props used elsewhere in the component
    const restProps = _.omit(this.props, ???)
  }
}
</code>```

The spread destructure (const { /* etc */ ... rest} = this.props) wouldn't work because there are other props that don't get used in render. However, I'd like to pick up other props that might've been specified (className, id, etc).

Can ??? be derived from something analogous to Object.keys(Props)? As far as I can tell, the type definitions are compiled away, so attempting to reference Props in runtime code throws a RuntimeError: Props is not defined.

答:
Flow provides static type analysis and all Flow code is stripped before runtime (flow annotations are not valid Javascript code).

To achieve what you want, you need to have the information about your expected Props available after you strip Flow code. You could do that by setting defaultProps for all props in your component and then you could write:

```<code>const restProps = _.omit(this.props, Photo.defaultProps)
</code>```

Setting defaultProps is usually a good idea anyway.

Title: Get keys from Flow object type in code

Body:
Is it possible to get the keys from a Flow object type definition in the app code (in other words, are Flow type definition reified in runtime code in any way)?

Use case:

type Props = {
  userID: string,
  size: number | PhotoSize,
  subscribePresence: Function,
  unsubscribePresence: Function,
  presenceStatus: ?PresenceStatus,
  photoURL: ?string,
  userName: ?string,
};

class Photo extends Component<Props> {
  // ...
  render() {
    const { userID, size, presenceStatus } = this.props;
    // Other props used elsewhere in the component
    const restProps = _.omit(this.props, ???)
  }
}

The spread destructure (const { /* etc */ ... rest} = this.props) wouldn't work because there are other props that don't get used in render. However, I'd like to pick up other props that might've been specified (className, id, etc).

Can ??? be derived from something analogous to Object.keys(Props)? As far as I can tell, the type definitions are compiled away, so attempting to reference Props in runtime code throws a RuntimeError: Props is not defined.

Body:
Flow provides static type analysis and all Flow code is stripped before runtime (flow annotations are not valid Javascript code).

To achieve what you want, you need to have the information about your expected Props available after you strip Flow code. You could do that by setting defaultProps for all props in your component and then you could write:

const restProps = _.omit(this.props, Photo.defaultProps)

Setting defaultProps is usually a good idea anyway.


问:
Swift Status bar height change
Using Xcode 8 and Swift 2.3.

In my app when I get WhatsApp call or enable hotspot,

Status bar height changes and alignment gets altered.

How do I refresh the screen when status bar height changes,

So screen gets adjusted.

I came across these two delegate methods but no idea how to use this for my requirement.

```<code>func application(application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect)
{
    print("Frame Change old")
}

func application(application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect)
{
    print("Frame Change new")

}
</code>```

答:
Those delegates must be added to the AppDelegate.swift, if I'm not mistaken.

Then you need to resize the Window putting this code inside the new status bar delegate

```<code>if let window = self.window {
    window.clipsToBounds = true
    window.frame = CGRect(x: 0, y: newStatusBarFrame.size.height, width: window.frame.size.width, height: window.frame.size.height);
    window.bounds = CGRect(x: 0, y: 0, width: window.frame.size.width, height: window.frame.size.height);
}
</code>```

Haven't tested the code so I hope it works

Title: Swift Status bar height change

Body:
Using Xcode 8 and Swift 2.3.

In my app when I get WhatsApp call or enable hotspot,

Status bar height changes and alignment gets altered.

How do I refresh the screen when status bar height changes,

So screen gets adjusted.

I came across these two delegate methods but no idea how to use this for my requirement.

func application(application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect)
{
    print("Frame Change old")
}

func application(application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect)
{
    print("Frame Change new")

}

Body:
Those delegates must be added to the AppDelegate.swift, if I'm not mistaken.

Then you need to resize the Window putting this code inside the new status bar delegate

if let window = self.window {
    window.clipsToBounds = true
    window.frame = CGRect(x: 0, y: newStatusBarFrame.size.height, width: window.frame.size.width, height: window.frame.size.height);
    window.bounds = CGRect(x: 0, y: 0, width: window.frame.size.width, height: window.frame.size.height);
}

Haven't tested the code so I hope it works


问:
frames question
I am working on a site that has a bar on the side, and then using jquery load function I'm loading content in the main div, without navigating out of the page.

Since the stuff loaded on the main div does not require the header, menus, etc, I have files around that I don't know how to hide from the outside world. For example, I am loading to my main div with code like this: $(document).ready(function() {
        $('#see_bio').click(function() {
        $("#main").load("show.php?=bio");
        return false;
    });
    });

I want to avoid the user from going to mydomain.com/show.php by himself... How can I do so?

答:
You can select which elements of the resulting content are added to the div by using CSS selectors. For example you can replace:

```<code>$("#main").load("show.php?=bio");
</code>```

with:

```<code>$("#main").load("show.php?=bio div#content");
</code>```

this will pick from the returned data only the div with id="content" inside the #main element. So headers and menus are just discarded.

Title: frames question

Body:
You can select which elements of the resulting content are added to the div by using CSS selectors. For example you can replace:

$("#main").load("show.php?=bio");

with:

$("#main").load("show.php?=bio div#content");

this will pick from the returned data only the div with id="content" inside the #main element. So headers and menus are just discarded.


问:
Special color for "master" git branch name in bash prompt
I have the following in my ~/.bashrc which make my prompt display (branch_name) $ in green when I am in a directory using Git.

Example:

```<code>yoshi@x1carbon:~ $ cd /path/to/git/project
yoshi@x1carbon:/path/to/git/project (master) $
#                                   ^^^^^^^^ this part only in green
</code>```

What I want is to display the branch name in yellow instead of green only if I am on master.

This is what I currently have:

```<code>git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo "\[\033[33m\]\${branch}\[\033[00m\]" # yellow
  elif [ "$branch" = "" ]; then
     echo "\[\033[31m\] (no git)\[\033[00m\]" # red
  else
     echo "\[\033[32m\]\${branch}\[\033[00m\]" # green
  fi
}
export PS1="\u@\h:\w$(git_branch) \$ "
</code>```

The problem is it always display (no git), even if __git_ps1 in the directory returns the proper current branch name. It seems that $branch is always equal to an empty string, whether I am in a dir using git or not.

The following works but applies the same color for all branch names:

```<code>git_branch_simple() {
  echo "\[\033[33m\]\$(__git_ps1 2> /dev/null)\[\033[00m\]"
}
export PS1="\u@\h:\w$(git_branch_simple) \$ "
</code>```

What am I missing here? How can I store the result of __git_ps1 in a local variable and then test it?

Edit: Thanks to @ElpieKay, I identified the different problems I had in my script:

I should not escape the $ sign in the echo instruction:

```<code>echo "\[\033[33m\]\${branch}\[\033[00m\]"
#                 ^ removed that backslash
</code>```

echo must use the option -e to be able to print colors

```<code>echo -e "\[\033[33m\]${branch}\[\033[00m\]"
#    ^^ added this option
</code>```

答:
Try this snippet</p>

```<code>git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo -e "\033[33m${branch}\033[00m" # yellow
  elif [ "$branch" = "" ]; then
     echo -e "\033[31m (no git)\033[00m" # red
  else
     echo -e "\033[32m${branch}\033[00m" # green
  fi
}
PS1='\u@\h:\w`git_branch` \$ '
</code>```

Body:
I have the following in my ~/.bashrc which make my prompt display (branch_name) $ in green when I am in a directory using Git.

Example:

yoshi@x1carbon:~ $ cd /path/to/git/project
yoshi@x1carbon:/path/to/git/project (master) $
#                                   ^^^^^^^^ this part only in green

What I want is to display the branch name in yellow instead of green only if I am on master.

This is what I currently have:

git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo "\[\033[33m\]\${branch}\[\033[00m\]" # yellow
  elif [ "$branch" = "" ]; then
     echo "\[\033[31m\] (no git)\[\033[00m\]" # red
  else
     echo "\[\033[32m\]\${branch}\[\033[00m\]" # green
  fi
}
export PS1="\u@\h:\w$(git_branch) \$ "

The problem is it always display (no git), even if __git_ps1 in the directory returns the proper current branch name. It seems that $branch is always equal to an empty string, whether I am in a dir using git or not.

The following works but applies the same color for all branch names:

git_branch_simple() {
  echo "\[\033[33m\]\$(__git_ps1 2> /dev/null)\[\033[00m\]"
}
export PS1="\u@\h:\w$(git_branch_simple) \$ "

What am I missing here? How can I store the result of __git_ps1 in a local variable and then test it?

Edit: Thanks to @ElpieKay, I identified the different problems I had in my script:

I should not escape the $ sign in the echo instruction:

echo "\[\033[33m\]\${branch}\[\033[00m\]"
#                 ^ removed that backslash

echo must use the option -e to be able to print colors

echo -e "\[\033[33m\]${branch}\[\033[00m\]"
#    ^^ added this option

Body:
Try this snippet

git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo -e "\033[33m${branch}\033[00m" # yellow
  elif [ "$branch" = "" ]; then
     echo -e "\033[31m (no git)\033[00m" # red
  else
     echo -e "\033[32m${branch}\033[00m" # green
  fi
}
PS1='\u@\h:\w`git_branch` \$ '


问:
Error while trying to assign user to app
As the title indicates, I'm getting an error while trying to assign a user to an AAD application.
Here is the request and the error I'm getting

Obviously it's related to the version of the API but I can't get it to work even with changing the api-version parameter.

Update :
When I modify the request url to https://graph.microsoft.com/v1.0/..., I get the following error : Unsupported segment type. ODataQuery: users/{userid}/appRoleAssignments

Update 2 :
Even with beta version, this seems not to be working :

Update 3 :
Is this still available in beta version of MS Graph? otherwise is there any alternatives (other than powershell and graph api) to achieve what I want programatically
    https://graph.microsoft.com/beta/users/{userId}/appRoleAssignments/{appRoleId}

Still getting Unsupported segment type error

答:
The URL you're using here isn't a valid Microsoft Graph call.

AS a REST API, each segment of the URL is effectively an API namespace or method (depending if it's the final URI segment). To illustrate, let's break down a URI for retrieving a user:

```<code>GET https://graph.microsoft.com/v1.0/users/{userid}
</code>```

Breaking this into it's components we get:

GET is the "HTTP verb" that defines the action we're taking. This follow the standard CRUD model:

POST = Create an entity or record

GET = Read an entity or record

PATCH = Update an entity or record

DELETE = Delete an entity or record

https://graph.microsoft.com is the address for the Microsoft Graph itself .

/v1.0 is the version of the API you want to call (currently either /v1.0 or /beta).

/users tells Graph you're looking to access the user collection

/{userid} tells Graph you're which specific user you're looking for within the /users collection

Since /{userid} is the final segment specified by the URL, it will return a JSON representation of that individual User record from Azure Active Directory.

You can find a good detailed explanation of how Microsoft Graph is organized in the article Traverse Microsoft Graph in the Microsoft Graph Documentation.

In your question you described two different calls:

```<code>POST https://graph.microsoft.com/{GUID}
POST https://graph.microsoft.com/v1.0/{GUID}
</code>```

The reason you're getting an error is that there is no namespace or method for the {GUID} you're sending it. It literally has no idea what you're asking for it to do. And since Microsoft Graph handles a slew of different services (SharePoint, Azure AD, Exchange, Planner, Teams, Groups, etc.) it couldn't even begin to guess at which service you're targeting.

Based on the additional comment you made, it sounds like you're trying to work with the appRoleAssignment. This endpoint is still in preview so it is only available in the /beta version. It also only supports GET, UPDATE and DELETE methods (UPDATE adds a user to the appRoleAssignment, DELETE removes a user from the appRoleAssignment).

You're call should therefore look something like this:

```<code>https://graph.microsoft.com/beta/users/{userId}/appRoleAssignments/{appRoleId}
</code>```

You can find the full documentation for this call at Update approleassignment.

Body:
The URL you're using here isn't a valid Microsoft Graph call.

AS a REST API, each segment of the URL is effectively an API namespace or method (depending if it's the final URI segment). To illustrate, let's break down a URI for retrieving a user:

GET https://graph.microsoft.com/v1.0/users/{userid}

Breaking this into it's components we get:

GET is the "HTTP verb" that defines the action we're taking. This follow the standard CRUD model:

POST = Create an entity or record

GET = Read an entity or record

PATCH = Update an entity or record

DELETE = Delete an entity or record

https://graph.microsoft.com is the address for the Microsoft Graph itself .

/v1.0 is the version of the API you want to call (currently either /v1.0 or /beta).

/users tells Graph you're looking to access the user collection

/{userid} tells Graph you're which specific user you're looking for within the /users collection

Since /{userid} is the final segment specified by the URL, it will return a JSON representation of that individual User record from Azure Active Directory.

You can find a good detailed explanation of how Microsoft Graph is organized in the article Traverse Microsoft Graph in the Microsoft Graph Documentation.

In your question you described two different calls:

POST https://graph.microsoft.com/{GUID}
POST https://graph.microsoft.com/v1.0/{GUID}

The reason you're getting an error is that there is no namespace or method for the {GUID} you're sending it. It literally has no idea what you're asking for it to do. And since Microsoft Graph handles a slew of different services (SharePoint, Azure AD, Exchange, Planner, Teams, Groups, etc.) it couldn't even begin to guess at which service you're targeting.

Based on the additional comment you made, it sounds like you're trying to work with the appRoleAssignment. This endpoint is still in preview so it is only available in the /beta version. It also only supports GET, UPDATE and DELETE methods (UPDATE adds a user to the appRoleAssignment, DELETE removes a user from the appRoleAssignment).

You're call should therefore look something like this:

https://graph.microsoft.com/beta/users/{userId}/appRoleAssignments/{appRoleId}

You can find the full documentation for this call at Update approleassignment.


问:
Oracle Apex 5.1: Interactive Grid Target Specific Cell
I'm working on interactive grid in Oracle Apex 5.1. My problem is: How can I target a specific cell of their grid (not the column), using JQuery, in order to change some properties like readonly or other?</p>

答:
I found some (maybe weired) kind of workaround:
In PageDesigner add every Column a unique class.
Use javascript to get the record(the row) you want to change. form the record get the unique RecordID.
Then combine both in a jquery selector to get the cell

```<code> $("[data-id='AAE6TDAAFAAPTP1AAd'] .GRUND_INFRA").addClass("is-readonly")
</code>```

with "AAE6TDAAFAAPTP1AAd" as the RecordID and "GRUND_INFRA" as the ClassId of the Column

Body:
I found some (maybe weired) kind of workaround:
In PageDesigner add every Column a unique class.
Use javascript to get the record(the row) you want to change. form the record get the unique RecordID.
Then combine both in a jquery selector to get the cell

 $("[data-id='AAE6TDAAFAAPTP1AAd'] .GRUND_INFRA").addClass("is-readonly")

with "AAE6TDAAFAAPTP1AAd" as the RecordID and "GRUND_INFRA" as the ClassId of the Column


问:
How to send SQS message to FIFO type Queue
I can easily send and receive messages to AWS SQS message queue (standard type) but when I create a FIFO queue and try to send a message I receive an exception which is saying I have to set a non-empty Message group Id.

I found example of this in java at AWS documentation :

```<code>**// Send a message

SendMessageRequest sendMessageRequest = new SendMessageRequest(myQueueUrl, "This is my message text.");
*// You must provide a non-empty MessageGroupId when sending messages to a FIFO queue
sendMessageRequest.setMessageGroupId("messageGroup1");*
</code>```

But when I use the AWS.SQS package in c# I cannot find any properties or method which I can set the Message group Id.

this is the code

```<code>SendMessageRequest sendMessageRequest = new SendMessageRequest();
sendMessageRequest.QueueUrl = myQueueUrl; //URL from initial queue creation
sendMessageRequest.MessageBody = "This is my message text.";
sqs.SendMessage(sendMessageRequest);
</code>```

答: Well Actually there is a MessageGroupId property in SendMessageRequest. I could not find it because I was searching for it in the live example of the Awssdk.SQS and i thought they have the latest version but their example is not using the latest version so I could not found it. I installed the last version and then it start to work. </p>

Body:
I can easily send and receive messages to AWS SQS message queue (standard type) but when I create a FIFO queue and try to send a message I receive an exception which is saying I have to set a non-empty Message group Id.

I found example of this in java at AWS documentation :

**// Send a message

SendMessageRequest sendMessageRequest = new SendMessageRequest(myQueueUrl, "This is my message text.");
*// You must provide a non-empty MessageGroupId when sending messages to a FIFO queue
sendMessageRequest.setMessageGroupId("messageGroup1");*

But when I use the AWS.SQS package in c# I cannot find any properties or method which I can set the Message group Id.

this is the code

SendMessageRequest sendMessageRequest = new SendMessageRequest();
sendMessageRequest.QueueUrl = myQueueUrl; //URL from initial queue creation
sendMessageRequest.MessageBody = "This is my message text.";
sqs.SendMessage(sendMessageRequest);


问:
What are some good Code Formats?
Firstly, I am aware of this question:
Are there standard formats for comments within code?

But it didn't answer mine. Whenever I write code, I always try to form a habit of ensuring that the comments are all consistent, but that is where I am sometimes indecisive about my code format convention. Especially since I want my code to be 80 or so lines wide.

Needless to say, a code format convention should be:

Easy to read

Easy to modify

And there may be different comment formats in different parts of your code, so it's important to ensure they remain consistent and readable.

Here are some examples:

Single Line

```<code>// simple comment in lowercase
do_something();

// longer comment in lowercase. but now it doesn't seem like a proper sentence.
do_something();

// Longer comment in sentence case. But should we use sentence case for short comments too?
do_something();
// Like this one?
do_something_else(); // Or even this one.
</code>```

Multi-line

```<code>// This code is very detailed and so I must continue further.
// Every time you start a new line you need to ensure you add //.
// If you finish your comment and forget to add something, you're screwed.
// You'll have to add your something and then make sure all the lines are 80 characters or less,
// and if they aren't you need to restructure all the lines below it.

/*  This is better but you need to make sure it's properly indented each line.
    Although you have to worry about those comment delimiters getting in the way.
    At least it's compact. */

/*  This comment seems better.
    No need to worry about that last delimiter being inside your comment block.
*/

/*
    Or maybe this is better?
    At least it looks clean.
*/

/*  GOOD FOR FUNCTION DEFINITIONS
    Or maybe this is even better?
    Who knows?
*/
</code>```

答:
Answer 1 - don't, any time wasted argueing about braces is a waste of time.

Answer 2 - if you must, just pick one eg. http://www.possibility.com/Cpp/CppCodingStandard.html

Title: What are some good Code Formats?

Body:
Firstly, I am aware of this question:
Are there standard formats for comments within code?

But it didn't answer mine. Whenever I write code, I always try to form a habit of ensuring that the comments are all consistent, but that is where I am sometimes indecisive about my code format convention. Especially since I want my code to be 80 or so lines wide.

Needless to say, a code format convention should be:

Easy to read

Easy to modify

And there may be different comment formats in different parts of your code, so it's important to ensure they remain consistent and readable.

Here are some examples:

Single Line

// simple comment in lowercase
do_something();

// longer comment in lowercase. but now it doesn't seem like a proper sentence.
do_something();

// Longer comment in sentence case. But should we use sentence case for short comments too?
do_something();
// Like this one?
do_something_else(); // Or even this one.

Multi-line

// This code is very detailed and so I must continue further.
// Every time you start a new line you need to ensure you add //.
// If you finish your comment and forget to add something, you're screwed.
// You'll have to add your something and then make sure all the lines are 80 characters or less,
// and if they aren't you need to restructure all the lines below it.

/*  This is better but you need to make sure it's properly indented each line.
    Although you have to worry about those comment delimiters getting in the way.
    At least it's compact. */

/*  This comment seems better.
    No need to worry about that last delimiter being inside your comment block.
*/

/*
    Or maybe this is better?
    At least it looks clean.
*/

/*  GOOD FOR FUNCTION DEFINITIONS
    Or maybe this is even better?
    Who knows?
*/


问:
Create both jQuery and vanilla Javascript plugin that supports UMD?
Is it possible to create a plugin that can be initialized both using jQuery and vanilla Javascript like for example:

```<code>// jQuery
$("#selector").plugin({
    option1: "val1",
    option2: "val2"
});

// Javascript
var plugin = plugin("#selector", {
    option1: "val1",
    option2: "val2"
});
</code>```

But also making sure it can be used via ES6 or CommonJS modules with import plugin from 'plugin.js' or var plugin = require('plugin.js')

答:
I think this is a wider topic, but I recently implemented somehting similar, by using WebPack to instantiate some content using ES6 (If i'm correct Webpack is based on CommonJS if no specific override is set)

To allow, let's say, a plugin to be instanciated with jQuery, I assume a simple wrapper could do the trick.

Body:
Is it possible to create a plugin that can be initialized both using jQuery and vanilla Javascript like for example:

// jQuery
$("#selector").plugin({
    option1: "val1",
    option2: "val2"
});

// Javascript
var plugin = plugin("#selector", {
    option1: "val1",
    option2: "val2"
});

But also making sure it can be used via ES6 or CommonJS modules with import plugin from 'plugin.js' or var plugin = require('plugin.js')


问:
Evaluate rolling mean by group when groups have insufficient observations
I am trying to calculate a bunch of rolling means for a dataset -

```<code>     date name px_last
2012-12-04   A  6.81
2012-12-05   A  4.28
2012-12-06   A  4.32
2012-12-04   A  6.89
2012-12-05   A  7.24
2012-12-04   B  6.81
2012-12-05   B  9.38
2012-12-06   B  3.62
2012-12-04   C  3.85
2012-12-05   C  4.23
2012-12-06   C  7.32
2012-12-04   C  2.84
2012-12-05   C  8.38
</code>```

The is the code I am using -

```<code>vec = c(2, 3, 4, 5)
for(i in c(1:length(vec))){
  varname = paste0("ma", vec[i])
  df = df %>% group_by(name) %>% mutate(!!varname := rollapplyr(px_last, vec[i], mean, na.rm = TRUE, fill = "NA"))
}
</code>```

The error I get from the third iteration is -

```<code>Error in mutate_impl(.data, dots) :
Evaluation error: wrong sign in 'by' argument.
</code>```

From this post - Clueless about this error: wrong sign in 'by' argument - I understand that is because some groups have insufficient rows; in this example, group with name = B

How do I got about calculating the means without deleting the groups with insufficient observations? I would like NAs preferably in places where the mean cannot be calculated due to insufficient observations.

答:
@phil_t So the issue is that the rollapply is attempting to apply the mean in a right-aligned fashion. When this is attempted on a window of size 4 on group B, which only has 3 values it correctly fails.

So you will need to "regularize" the DF to have the required number of rows for each group.

```<code>library(plyr)
> df <- ddply(df, 'name', function(x) {
                 rbind.fill(x, data.frame(name = rep(unique(x$name), each = max(vec) - nrow(x))))
              })

> df
  date name px_last
  2012-12-04    A    6.81
  2012-12-05    A    4.28
  2012-12-06    A    4.32
  2012-12-04    A    6.89
  2012-12-05    A    7.24
  2012-12-04    B    6.81
  2012-12-05    B    9.38
  2012-12-06    B    3.62
  <NA>    B      NA
  <NA>    B      NA
  2012-12-04    C    3.85
  2012-12-05    C    4.23
  2012-12-06    C    7.32
  2012-12-04    C    2.84
  2012-12-05    C    8.38

> for(i in c(1:length(vec))){
    varname = paste0("ma", vec[i])
    df = df %>% group_by(name) %>% mutate(!!varname := rollapplyr(px_last, vec[i], mean, na.rm = TRUE, fill = "NA"))
  }
</code>```

That should help.

Body:
I am trying to calculate a bunch of rolling means for a dataset -

     date name px_last
2012-12-04   A  6.81
2012-12-05   A  4.28
2012-12-06   A  4.32
2012-12-04   A  6.89
2012-12-05   A  7.24
2012-12-04   B  6.81
2012-12-05   B  9.38
2012-12-06   B  3.62
2012-12-04   C  3.85
2012-12-05   C  4.23
2012-12-06   C  7.32
2012-12-04   C  2.84
2012-12-05   C  8.38

The is the code I am using -

vec = c(2, 3, 4, 5)
for(i in c(1:length(vec))){
  varname = paste0("ma", vec[i])
  df = df %>% group_by(name) %>% mutate(!!varname := rollapplyr(px_last, vec[i], mean, na.rm = TRUE, fill = "NA"))
}

The error I get from the third iteration is -

Error in mutate_impl(.data, dots) :
Evaluation error: wrong sign in 'by' argument.

From this post - Clueless about this error: wrong sign in 'by' argument - I understand that is because some groups have insufficient rows; in this example, group with name = B

How do I got about calculating the means without deleting the groups with insufficient observations? I would like NAs preferably in places where the mean cannot be calculated due to insufficient observations.

Body:
@phil_t So the issue is that the rollapply is attempting to apply the mean in a right-aligned fashion. When this is attempted on a window of size 4 on group B, which only has 3 values it correctly fails.

So you will need to "regularize" the DF to have the required number of rows for each group.

library(plyr)
> df <- ddply(df, 'name', function(x) {
                 rbind.fill(x, data.frame(name = rep(unique(x$name), each = max(vec) - nrow(x))))
              })

> df
  date name px_last
  2012-12-04    A    6.81
  2012-12-05    A    4.28
  2012-12-06    A    4.32
  2012-12-04    A    6.89
  2012-12-05    A    7.24
  2012-12-04    B    6.81
  2012-12-05    B    9.38
  2012-12-06    B    3.62
  <NA>    B      NA
  <NA>    B      NA
  2012-12-04    C    3.85
  2012-12-05    C    4.23
  2012-12-06    C    7.32
  2012-12-04    C    2.84
  2012-12-05    C    8.38

> for(i in c(1:length(vec))){
    varname = paste0("ma", vec[i])
    df = df %>% group_by(name) %>% mutate(!!varname := rollapplyr(px_last, vec[i], mean, na.rm = TRUE, fill = "NA"))
  }

That should help.


问:
How to check if class overides parent methods in ES6
I want to create something like interface in ES6 and I want to force overide methods in base class.

```<code>class DatabaseAPI {
  login() {
     throw new Error('Unimplemented method: login');
  }
}

class UserService extends DatabaseAPI {
  constructor() {
    super();
  }
}
</code>```

Is there any way to force above error during creating UserService class?

答:
I wrote this package you can try it out
es6-interface</p>

Body:
I want to create something like interface in ES6 and I want to force overide methods in base class.

class DatabaseAPI {
  login() {
     throw new Error('Unimplemented method: login');
  }
}

class UserService extends DatabaseAPI {
  constructor() {
    super();
  }
}

Is there any way to force above error during creating UserService class?


问:
HashTables in Cocoa
HashTables/HashMaps are one of the most (if not the most) useful of data-structures in existence.  As such, one of the first things I investigated when starting to learn programming in Cocoa was how to create, populate, and read data from a hashtable.

To my surprise: all the documentation I've been reading on Cocoa/Objective-C programming doesn't seem to explain this much at all.  As a Java developer that uses "java.util" as if it were a bodily function: I am utterly baffled by this.

So, if someone could provide me with a primer for creating, populating, and reading the contents of a hashtable: I would greatly appreciate it.

答: In addition to NSDictionary, also check out NSSet for when you need a collection with no order and no duplicates.</p>

OwnerDisplayName: Ryan Delucchi

Title: HashTables in Cocoa

LastEditorDisplayName: Ryan Delucchi

OwnerDisplayName: Chris Hanson


问:
Problems with converting a C# code to VB.net
I have problems to convert the following piece of code into vb.net because I am not so experienced with lambda expressions. Especially the last line is my problem. Teleric Code Converter doesn't help me because of the last line. Could somebody help me? </p>

```<code>int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
</code>```

答:
Conversion with Telerik works if you store the output of the last line in a new variable. Then you get this:</p>

```<code>Private numbers As Integer() = {1, 3, 4, 9, 2, 4}
Private numToRemove As Integer = 4
Private numIndex As Integer = Array.IndexOf(numbers, numToRemove)
Private result = numbers.Where(Function(val, idx) idx <> numIndex)
</code>```

Body:
I have problems to convert the following piece of code into vb.net because I am not so experienced with lambda expressions. Especially the last line is my problem. Teleric Code Converter doesn't help me because of the last line. Could somebody help me?

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();

Body:
Conversion with Telerik works if you store the output of the last line in a new variable. Then you get this:

Private numbers As Integer() = {1, 3, 4, 9, 2, 4}
Private numToRemove As Integer = 4
Private numIndex As Integer = Array.IndexOf(numbers, numToRemove)
Private result = numbers.Where(Function(val, idx) idx <> numIndex)


问:
Insert column if it doesn't exist
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

```<code>ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0
</code>```

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

答:
You can try this.</p>

```<code>IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'HasAccess24_7' AND TABLE_NAME = 'tSafeUnit')
   AND EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tSafeUnit')
BEGIN
    ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 TINYINT NOT NULL DEFAULT 0
END
</code>```

ContentLicense: CC BY-SA 4.0

Title: Insert column if it doesn't exist

Body:
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

Body:
You can try this.

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'HasAccess24_7' AND TABLE_NAME = 'tSafeUnit')
   AND EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tSafeUnit')
BEGIN
    ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 TINYINT NOT NULL DEFAULT 0
END


问:
Microsoft Word File getting corrupted when it has images in it, send through sendmail library of unix
I am using sendmail library of unix to send mail. I am sending a mail with an attachment which is a (Microsoft word) .docx file. This word file has images in it. The issue is, receiver is not able to open a mail attachment which is word (.docx file) with images inside it. Opening a Microsoft word file gives error "file is corrupted".

Receiver is able to open a word file if it has only text in it. Problem comes only when the word file has images in it, and that word file is being send as a attachment of a mail.

Here is the file content looks like. This is a sh file, and use sendmail api of linux to execute this sh file for sending mail..

```<code>echo -e MIME-Version: 1.0;
echo -e 'Content-Type: multipart/mixed; boundary="CONTENT_BOUNDARY"';
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/html; charset=utf-8';
echo ;
echo -e "  ";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/plain; charset=utf-8';
echo ;
echo -e "Hello World!";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/html; charset=utf-8';
echo ;
echo -e "<b>Hello</b> <i>World</i>!";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document; name=Editor-issue-6-30-2016.docx';
echo -e 'Content-Transfer-Encoding: base64';
echo ;
echo -e PK
</code>```

When the attached word file is opened in the microsoft word, this is how it image looks like (not same as the original image)

When I try to send the same attachment using other mail sending api like nodemailer in node.js, this attachment get properly opened by the receiver.

Any help highly appreciated.

Thanks.

答:
From this: Using sendmail for HTML body and binary attachment

Try to change

```<code>'Content-Transfer-Encoding: base64';
</code>```

to

```<code>'Content-Transfer-Encoding: uuencode';
</code>```

and add

```<code>uuencode 'Editor-issue-6-30-2016.docx' $(basename 'Editor-issue-6-30-2016.docx')
</code>```

Body:
I am using sendmail library of unix to send mail. I am sending a mail with an attachment which is a (Microsoft word) .docx file. This word file has images in it. The issue is, receiver is not able to open a mail attachment which is word (.docx file) with images inside it. Opening a Microsoft word file gives error "file is corrupted".

Receiver is able to open a word file if it has only text in it. Problem comes only when the word file has images in it, and that word file is being send as a attachment of a mail.

Here is the file content looks like. This is a sh file, and use sendmail api of linux to execute this sh file for sending mail..

echo -e MIME-Version: 1.0;
echo -e 'Content-Type: multipart/mixed; boundary="CONTENT_BOUNDARY"';
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/html; charset=utf-8';
echo ;
echo -e "  ";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/plain; charset=utf-8';
echo ;
echo -e "Hello World!";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: text/html; charset=utf-8';
echo ;
echo -e "Hello World!";
echo ;
echo -e --CONTENT_BOUNDARY;
echo -e 'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document; name=Editor-issue-6-30-2016.docx';
echo -e 'Content-Transfer-Encoding: base64';
echo ;
echo -e PK

When the attached word file is opened in the microsoft word, this is how it image looks like (not same as the original image)

When I try to send the same attachment using other mail sending api like nodemailer in node.js, this attachment get properly opened by the receiver.

Any help highly appreciated.

Thanks.

Body:
From this: Using sendmail for HTML body and binary attachment

Try to change

'Content-Transfer-Encoding: base64';

to

'Content-Transfer-Encoding: uuencode';

and add

uuencode 'Editor-issue-6-30-2016.docx' $(basename 'Editor-issue-6-30-2016.docx')


问:
CSS Transparent Gold Background
I've been struggling for days on how to achieve this transparent gold at the right side of the image below.

That is what exactly look like in the PSD but when saving it as .PNG it seems to look like a very different color as it kinda turns to yellow. Maybe because it doesn't use the web standard colors. So I'm trying some CSS solution on this code sample below, but I don't know how to do it right or what should be the color combination should I use.

.bg-gold { position: relative; }
.bg-gold-1, .bg-gold-2 {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 5;
}
.bg-gold-1 {
  background: #b38600;
  opacity: .5;
}
.bg-gold-2 {
  background: #b36b00;
  opacity: .2;
}

img {
  position: relative;
  z-index: 1;
  width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bg-gold">
  <img src="http://wilsin.com.sg/wp-content/uploads/2017/08/index-banner-1-black-and-white.jpg" alt="">
  <div class="bg-gold bg-gold-1"></div>
  <div class="bg-gold bg-gold-2"></div>
</div></code>```

答:
Using an appropriate value of mix-blend-mode on your overlay should do the trick; you can read more about all the values here.

Based on playing around a bit, I think mix-blend-mode: multiply; should work well, but you'll need to play around a bit to get the desired effect.

Keep in mind browser support is varied

Title: CSS Transparent Gold Background


问:
Target specific div Using Jquery
I Want to target a div using jQuery and change its color of innerHtml to red having INACTIVE Status (It is basically a select2 box)

This is the jQuery code  I have so far to target that div:

```<code>$("div#select2-drop ul > li > div:contains(INACTIVE)").css('color','red');
</code>```

答:
Look at the :contains() Selector example at: https://api.jquery.com/contains-selector/#entry-examples

$( "div:contains('John')" ).css( "text-decoration", "underline" );

Your div:contains(INACTIVE) should be div:contains('INACTIVE') to find all divs containing "INACTIVE"

Title: Target specific div Using Jquery

Body:
I Want to target a div using jQuery and change its color of innerHtml to red having INACTIVE Status (It is basically a select2 box)

This is the jQuery code  I have so far to target that div:

$("div#select2-drop ul > li > div:contains(INACTIVE)").css('color','red');


问:
Is there any reliable way of accessing specific elements of Gmail from inside a userscript?
I'd like to make a script that replaces either the Notes box in the contact page, or the sidebar of a conversation thread, with content pulled from my server, very similar to the way Rapportive (http://rapportive.com/) works. I'd even like to be able to grab the email address of the person being looked at or emailed with, the way they do.

But Rapportive uses a browser extension. Is there any way this can be done via a greasemonkey script?

Is this something I should use a gadget for? Can I get the email address of the current 'context' from inside a gadget?

答:
Short answer: No.

Long answer: Still no, but I needed enough length to submit.


问:
How to remove these vertical white lines in PhpStorm 2017.3
How to remove these vertical white lines in PhpStorm 2017.3?

答:
You might want to remove foreground on these guides instead of completly disable this feature, since something (either PhpStorm 2017.3 itself or Material Theme plugin) introduced this bug in the latest update.

Go to the Settings -> Editor -> Color Scheme -> General and look for the Guides section. Uncheck the Foreground option on Visual Guides or change its color from EEEEEE to 32424A. Hit Apply & Ok.

Now these guides should look the same as in 2017.2.


问:
Zlib: Node.js can't extract compressed data from python

I use python to compress string data and store the data in sqlite3. For my project I need also to use node.js to extract the data. The problem is, when i try to do that. I get a error from node.js:

{ Error: incorrect header check
    at Gunzip.zlibOnError (zlib.js:153:15) errno: -3, code: 'Z_DATA_ERROR' }

I tried to encode the string in Python with Base64 and utf8. Both doesn't make a difference.

In JavaScript i tried to skip some bits of the encode data, so that I may overcome the head check problem. That's also in vain.

Here is the compress code in python

```<code>import zlib, base64
import time
text = 'STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW '
textToBytes = text.encode('utf-8')
code =  zlib.compress(textToBytes)

code = base64.b64encode(code)
print('code in base64:', code)

timestamp = time.time()
#Store in database
conn = sqlite3.connect('testsDummy.db')
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS tests (id INTEGER PRIMARY KEY, timestamp REAL, code TEXT)")
conn.commit()
c.execute("INSERT INTO  tests (code ,timestamp) VALUES (?,?)",(code ,timestamp))
conn.commit()
conn.close()
</code>```

Now this is code in node.js

```<code>function toArrayBuffer(buffer) {
  var arrayBuffer = new ArrayBuffer(buffer.length);
  var view = new Uint8Array(arrayBuffer);
  for (var i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return arrayBuffer;
}

app.get('/download/logfile/:timestamp', (req, res) => {
  var zlib = require('zlib');

  var db = new sqlite3.Database(path.join(__dirname, 'dependencies', 'testsDummy.db'));
  db.serialize(() => {
    db.all('SELECT code FROM tests WHERE timestamp=' + req.params.timestamp, (error, tests) => {
      db.close();

      if (tests[0].code== '' || tests[0].code== null) {
        res.send('No qdxm data collected.');
      }
      else {
        console.log(tests[0].code)
        var arrayBuffer = toArrayBuffer(Buffer.from(tests[0].code, 'base64'));
        zlib.gunzip(Buffer.from(arrayBuffer, 4), function (err, uncompressedMessage) {
          if (err) {
            console.log(err)
            res.send();
          }
          else {
            res.json({ uncompressedMessage: uncompressedMessage.toString() })
            console.log(uncompressedMessage.toString())
          }
        });
      }
    });
  });
});
</code>```

答: zlib.compress in Python (without a wbits parameter) will generate the zlib format, whereas zlib.gunzip in Node.js is expecting the gzip format. Either use zlib.compress with wbits equal to 31 to get the gzip format, or use zlib.inflate in Node.js to decompress the zlib format.

Body:
I use python to compress string data and store the data in sqlite3. For my project I need also to use node.js to extract the data. The problem is, when i try to do that. I get a error from node.js:

{ Error: incorrect header check
    at Gunzip.zlibOnError (zlib.js:153:15) errno: -3, code: 'Z_DATA_ERROR' }

I tried to encode the string in Python with Base64 and utf8. Both doesn't make a difference.

In JavaScript i tried to skip some bits of the encode data, so that I may overcome the head check problem. That's also in vain.

Here is the compress code in python

import zlib, base64
import time
text = 'STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW '
textToBytes = text.encode('utf-8')
code =  zlib.compress(textToBytes)

code = base64.b64encode(code)
print('code in base64:', code)

timestamp = time.time()
#Store in database
conn = sqlite3.connect('testsDummy.db')
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS tests (id INTEGER PRIMARY KEY, timestamp REAL, code TEXT)")
conn.commit()
c.execute("INSERT INTO  tests (code ,timestamp) VALUES (?,?)",(code ,timestamp))
conn.commit()
conn.close()

Now this is code in node.js

function toArrayBuffer(buffer) {
  var arrayBuffer = new ArrayBuffer(buffer.length);
  var view = new Uint8Array(arrayBuffer);
  for (var i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return arrayBuffer;
}

app.get('/download/logfile/:timestamp', (req, res) => {
  var zlib = require('zlib');

  var db = new sqlite3.Database(path.join(__dirname, 'dependencies', 'testsDummy.db'));
  db.serialize(() => {
    db.all('SELECT code FROM tests WHERE timestamp=' + req.params.timestamp, (error, tests) => {
      db.close();

      if (tests[0].code== '' || tests[0].code== null) {
        res.send('No qdxm data collected.');
      }
      else {
        console.log(tests[0].code)
        var arrayBuffer = toArrayBuffer(Buffer.from(tests[0].code, 'base64'));
        zlib.gunzip(Buffer.from(arrayBuffer, 4), function (err, uncompressedMessage) {
          if (err) {
            console.log(err)
            res.send();
          }
          else {
            res.json({ uncompressedMessage: uncompressedMessage.toString() })
            console.log(uncompressedMessage.toString())
          }
        });
      }
    });
  });
});


问:
Efficient way to copy or merge two ArrayList containing same objects
I have an Object like below

```<code>Product {

String name;

boolean isFiltered;

}
</code>```

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}
</code>```

Approach 2

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}
</code>```

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

答:
What about using a third list. Using a third list prevent contains to include the added elements in the search.

```<code>List<Object> listA;
List<Object> listB;

List<Object> listMerged = new List<>(); // init listMerged
listMerged.addAll(listA);
for(Object elt: listB){
    if (!listA.contains(elt))
        listMerged.add(elt);
}
</code>```

Body:
I have an Object like below

Product {

String name;

boolean isFiltered;

}

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}

Approach 2

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

Body:
What about using a third list. Using a third list prevent contains to include the added elements in the search.

List<Object> listA;
List<Object> listB;

List<Object> listMerged = new List<>(); // init listMerged
listMerged.addAll(listA);
for(Object elt: listB){
    if (!listA.contains(elt))
        listMerged.add(elt);
}


问:
Output black when I decode h264 720p with ffmpeg

First, sorry for my english. When I decode h264 720p in ardrone2.0 my output is black and I cant see anything.

I have try to change the value of pCodecCtx->pix_fmt = AV_PIX_FMT_BGR24; to pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P; and the value of pCodecCtxH264->pix_fmt = AV_PIX_FMT_BGR24; to pCodecCtxH264->pix_fmt = AV_PIX_FMT_YUV420P; but my program crash. What am I doing wrong?. Thank you, see part of my code:

```<code>av_register_all();
avcodec_register_all();
avformat_network_init();

// 1.2. Open video file
if(avformat_open_input(&pFormatCtx, drone_addr, NULL, NULL) != 0) {
  mexPrintf("No conecct with Drone");
  EndVideo();
  return;
}

pCodec    = avcodec_find_decoder(AV_CODEC_ID_H264);

pCodecCtx = avcodec_alloc_context3(pCodec);
pCodecCtx->pix_fmt = AV_PIX_FMT_BGR24;
pCodecCtx->skip_frame = AVDISCARD_DEFAULT;
pCodecCtx->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
pCodecCtx->err_recognition = AV_EF_CAREFUL;
pCodecCtx->skip_loop_filter = AVDISCARD_DEFAULT;
pCodecCtx->workaround_bugs = FF_BUG_AUTODETECT;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->codec_id = AV_CODEC_ID_H264;
pCodecCtx->skip_idct = AVDISCARD_DEFAULT;
pCodecCtx->width = 1280;
pCodecCtx->height = 720;

pCodecH264 = avcodec_find_decoder(AV_CODEC_ID_H264);
pCodecCtxH264 = avcodec_alloc_context3(pCodecH264);

pCodecCtxH264->pix_fmt = AV_PIX_FMT_BGR24;
pCodecCtxH264->skip_frame = AVDISCARD_DEFAULT;
pCodecCtxH264->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
pCodecCtxH264->err_recognition = AV_EF_CAREFUL;
pCodecCtxH264->skip_loop_filter = AVDISCARD_DEFAULT;
pCodecCtxH264->workaround_bugs = FF_BUG_AUTODETECT;
pCodecCtxH264->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtxH264->codec_id = AV_CODEC_ID_H264;
pCodecCtxH264->skip_idct = AVDISCARD_DEFAULT;

if(avcodec_open2(pCodecCtxH264, pCodecH264, &optionsDict) < 0)
{
   mexPrintf("Error opening H264 codec");
   return ;
}

pFrame_BGR24 = av_frame_alloc();

if(pFrame_BGR24 == NULL) {
   mexPrintf("Could not allocate pFrame_BGR24\n");
   return ;
}

// Determine required buffer size and allocate buffer

buffer_BGR24 =
(uint8_t *)av_mallocz(av_image_get_buffer_size(AV_PIX_FMT_BGR24,
pCodecCtx->width, ((pCodecCtx->height == 720) ? 720 : pCodecCtx->height) *
sizeof(uint8_t)*3,1));

// Assign buffer to image planes

av_image_fill_arrays(pFrame_BGR24->data, pFrame_BGR24->linesize,
buffer_BGR24,AV_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height,1);

// format conversion context
pConvertCtx_BGR24 = sws_getContext(pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,  AV_PIX_FMT_BGR24,
                                 SWS_BILINEAR | SWS_ACCURATE_RND, 0, 0, 0);

// 1.6. get video frames
pFrame = av_frame_alloc();

av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
}

//Captura un frame
void video::capture(mxArray *plhs[]) {

  if(av_read_frame(pFormatCtx, &packet) < 0){
      mexPrintf("Error al leer frame");
      return;
  }
   do {
       do {
          rest = avcodec_send_packet(pCodecCtxH264, &packet);
       } while(rest == AVERROR(EAGAIN));

       if(rest == AVERROR_EOF || rest == AVERROR(EINVAL)) {
                printf("AVERROR(EAGAIN): %d, AVERROR_EOF: %d,
                AVERROR(EINVAL): %d\n", AVERROR(EAGAIN), AVERROR_EOF,
                AVERROR(EINVAL));
            printf("fe_read_frame: Frame getting error (%d)!\n", rest);
            return;
       }

       rest = avcodec_receive_frame(pCodecCtxH264, pFrame);
   } while(rest == AVERROR(EAGAIN));

   if(rest == AVERROR_EOF || rest == AVERROR(EINVAL)) {

    // An error or EOF occured,index break out and return what
    // we have so far.
      printf("AVERROR(EAGAIN): %d, AVERROR_EOF: %d, AVERROR(EINVAL): %d\n",
      AVERROR(EAGAIN), AVERROR_EOF, AVERROR(EINVAL));
        printf("fe_read_frame: EOF or some othere decoding error (%d)!\n",
        rest);
        return;
   }

   // 2.1.1. convert frame to GRAYSCALE [or BGR] for OpenCV
   sws_scale(pConvertCtx_BGR24,   (const uint8_t* const*)pFrame->data,
       pFrame->linesize, 0,pCodecCtx->height,   pFrame_BGR24->data,
             pFrame_BGR24->linesize);
//}
   av_packet_unref(&packet);
   av_init_packet(&packet);
   mwSize dims[] = {(pCodecCtx->width)*((pCodecCtx->height == 720) ? 720 :
   pCodecCtx->height)*sizeof(uint8_t)*3};
   plhs[0] = mxCreateNumericArray(1,dims,mxUINT8_CLASS, mxREAL);
    //plhs[0]=mxCreateDoubleMatrix(pCodecCtx->height,pCodecCtx-
    >width,mxREAL);
   point=mxGetPr(plhs[0]);
   memcpy(point, pFrame_BGR24->data[0],(pCodecCtx->width)*(pCodecCtx-
    >height)*sizeof(uint8_t)*3);
}
</code>```

答: Go to debugger and see your memcpy. I am not sure if it works for all dimensions that you want. Also, there may be more memory problems. For example, try to see what is the value of buffer_BGR24 and pFrame. I bet that sometimes, they do not return right values. Check them out in the code.</p>

Body:
First, sorry for my english. When I decode h264 720p in ardrone2.0 my output is black and I cant see anything.

I have try to change the value of pCodecCtx->pix_fmt = AV_PIX_FMT_BGR24; to pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P; and the value of pCodecCtxH264->pix_fmt = AV_PIX_FMT_BGR24; to pCodecCtxH264->pix_fmt = AV_PIX_FMT_YUV420P; but my program crash. What am I doing wrong?. Thank you, see part of my code:

av_register_all();
avcodec_register_all();
avformat_network_init();

// 1.2. Open video file
if(avformat_open_input(&pFormatCtx, drone_addr, NULL, NULL) != 0) {
  mexPrintf("No conecct with Drone");
  EndVideo();
  return;
}

pCodec    = avcodec_find_decoder(AV_CODEC_ID_H264);

pCodecCtx = avcodec_alloc_context3(pCodec);
pCodecCtx->pix_fmt = AV_PIX_FMT_BGR24;
pCodecCtx->skip_frame = AVDISCARD_DEFAULT;
pCodecCtx->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
pCodecCtx->err_recognition = AV_EF_CAREFUL;
pCodecCtx->skip_loop_filter = AVDISCARD_DEFAULT;
pCodecCtx->workaround_bugs = FF_BUG_AUTODETECT;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->codec_id = AV_CODEC_ID_H264;
pCodecCtx->skip_idct = AVDISCARD_DEFAULT;
pCodecCtx->width = 1280;
pCodecCtx->height = 720;

pCodecH264 = avcodec_find_decoder(AV_CODEC_ID_H264);
pCodecCtxH264 = avcodec_alloc_context3(pCodecH264);

pCodecCtxH264->pix_fmt = AV_PIX_FMT_BGR24;
pCodecCtxH264->skip_frame = AVDISCARD_DEFAULT;
pCodecCtxH264->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
pCodecCtxH264->err_recognition = AV_EF_CAREFUL;
pCodecCtxH264->skip_loop_filter = AVDISCARD_DEFAULT;
pCodecCtxH264->workaround_bugs = FF_BUG_AUTODETECT;
pCodecCtxH264->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtxH264->codec_id = AV_CODEC_ID_H264;
pCodecCtxH264->skip_idct = AVDISCARD_DEFAULT;

if(avcodec_open2(pCodecCtxH264, pCodecH264, &optionsDict) < 0)
{
   mexPrintf("Error opening H264 codec");
   return ;
}

pFrame_BGR24 = av_frame_alloc();

if(pFrame_BGR24 == NULL) {
   mexPrintf("Could not allocate pFrame_BGR24\n");
   return ;
}

// Determine required buffer size and allocate buffer

buffer_BGR24 =
(uint8_t *)av_mallocz(av_image_get_buffer_size(AV_PIX_FMT_BGR24,
pCodecCtx->width, ((pCodecCtx->height == 720) ? 720 : pCodecCtx->height) *
sizeof(uint8_t)*3,1));

// Assign buffer to image planes

av_image_fill_arrays(pFrame_BGR24->data, pFrame_BGR24->linesize,
buffer_BGR24,AV_PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height,1);

// format conversion context
pConvertCtx_BGR24 = sws_getContext(pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,  AV_PIX_FMT_BGR24,
                                 SWS_BILINEAR | SWS_ACCURATE_RND, 0, 0, 0);

// 1.6. get video frames
pFrame = av_frame_alloc();

av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
}

//Captura un frame
void video::capture(mxArray *plhs[]) {

  if(av_read_frame(pFormatCtx, &packet) < 0){
      mexPrintf("Error al leer frame");
      return;
  }
   do {
       do {
          rest = avcodec_send_packet(pCodecCtxH264, &packet);
       } while(rest == AVERROR(EAGAIN));

       if(rest == AVERROR_EOF || rest == AVERROR(EINVAL)) {
                printf("AVERROR(EAGAIN): %d, AVERROR_EOF: %d,
                AVERROR(EINVAL): %d\n", AVERROR(EAGAIN), AVERROR_EOF,
                AVERROR(EINVAL));
            printf("fe_read_frame: Frame getting error (%d)!\n", rest);
            return;
       }

       rest = avcodec_receive_frame(pCodecCtxH264, pFrame);
   } while(rest == AVERROR(EAGAIN));

   if(rest == AVERROR_EOF || rest == AVERROR(EINVAL)) {

    // An error or EOF occured,index break out and return what
    // we have so far.
      printf("AVERROR(EAGAIN): %d, AVERROR_EOF: %d, AVERROR(EINVAL): %d\n",
      AVERROR(EAGAIN), AVERROR_EOF, AVERROR(EINVAL));
        printf("fe_read_frame: EOF or some othere decoding error (%d)!\n",
        rest);
        return;
   }

   // 2.1.1. convert frame to GRAYSCALE [or BGR] for OpenCV
   sws_scale(pConvertCtx_BGR24,   (const uint8_t* const*)pFrame->data,
       pFrame->linesize, 0,pCodecCtx->height,   pFrame_BGR24->data,
             pFrame_BGR24->linesize);
//}
   av_packet_unref(&packet);
   av_init_packet(&packet);
   mwSize dims[] = {(pCodecCtx->width)*((pCodecCtx->height == 720) ? 720 :
   pCodecCtx->height)*sizeof(uint8_t)*3};
   plhs[0] = mxCreateNumericArray(1,dims,mxUINT8_CLASS, mxREAL);
    //plhs[0]=mxCreateDoubleMatrix(pCodecCtx->height,pCodecCtx-
    >width,mxREAL);
   point=mxGetPr(plhs[0]);
   memcpy(point, pFrame_BGR24->data[0],(pCodecCtx->width)*(pCodecCtx-
    >height)*sizeof(uint8_t)*3);
}


问:
MobaXterm opens a black (cmd) window moxt2.exe at every new opened tab
MobaXterm opens a black (cmd) window moxt2.exe at every new opening tab. If I close the additional moxt2.exe window, it also closes the associated tab from MobaXTerm.

The program runs fine for a few weeks, but yesterday began to keep open that annoying window.

It also opened an XWin.exe window but that I have managed to keep it closed by disable X server, from Settings->Configuration->X11.

How can I make MobaXterm run as it should, without open a new moxt2.exe window at every new ssh session?

答: I was able to correct the problem by running the MobaXterm_Professional_7.3.exe program in Windows 7 compatibility mode. After that, no more extra empty windows appears in the background.


问:
Java Split file lines into two lists
I'm currently writing an app that takes the data from the file. I need to sort the data in different ways. The problem is that the file is in format:

```<code>NAME1(tab)A(tab)B
NAME2(tab)C(tab)D
</code>```

I want to split data into two ArrayLists, one will gather NAME1, NAME2 etc, so the first element of line, the second list will gather the rest.

Here's my code:

```<code>Scanner scan = new Scanner(new File(fname));

while(scan.hasNext()){

}
scan.close();

System.out.println("Lang: ");
for(String item : lang)
    System.out.print(item + " ");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

I tried to play with scanner methods, but there are no results and I have no idea what to do.

答:
Here is my attempt:</p>

```<code>List<String> list1 = new ArrayList<>();
List<String> list2 = Files.lines(Paths.get(fname)).flatMap(s -> {
    String[] line = s.split("\\t");
    if (line.length > 0) {
        list1.add(line[0]);
    }
    return Arrays.stream(line).skip(1);
}).collect(Collectors.toList());
</code>```

Title: Java Split file lines into two lists

Body:
I'm currently writing an app that takes the data from the file. I need to sort the data in different ways. The problem is that the file is in format:

NAME1(tab)A(tab)B
NAME2(tab)C(tab)D

I want to split data into two ArrayLists, one will gather NAME1, NAME2 etc, so the first element of line, the second list will gather the rest.

Here's my code:

Scanner scan = new Scanner(new File(fname));

while(scan.hasNext()){

}
scan.close();

System.out.println("Lang: ");
for(String item : lang)
    System.out.print(item + " ");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

I tried to play with scanner methods, but there are no results and I have no idea what to do.

Body:
Here is my attempt:

List<String> list1 = new ArrayList<>();
List<String> list2 = Files.lines(Paths.get(fname)).flatMap(s -> {
    String[] line = s.split("\\t");
    if (line.length > 0) {
        list1.add(line[0]);
    }
    return Arrays.stream(line).skip(1);
}).collect(Collectors.toList());


问:
Getting files by creation date in .NET
I have a folder which contains many files. Is there any easy way to get the file names in the directory sorted by their creation date/time?

If I use Directory.GetFiles(), it returns the files sorted by their file name.

答:
You can use Linq</p>

```<code>var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);
</code>```

Title: Getting files by creation date in .NET

Body:
You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);


问:
Pandas Python: Slice / Transform URL to get item and item counts
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

```<code>http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1
</code>```

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

答:
Here's another approach with re module:

```<code>import re
df['item'] = df['URL'].apply(lambda x: (re.findall('\?(.*)=', x)[0]).replace('+', ' '))
df['count'] = df['URL'].apply(lambda x: int((re.findall('=(.*)', x)[0])))
</code>```

Body:
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

Body:
Here's another approach with re module:

import re
df['item'] = df['URL'].apply(lambda x: (re.findall('\?(.*)=', x)[0]).replace('+', ' '))
df['count'] = df['URL'].apply(lambda x: int((re.findall('=(.*)', x)[0])))