问:
Getting an error on incorrect routes
When I run node server I am getting an error and cannot figure out the root cause. I am pasting the error below. I would really appreciate some help as I have spent a lot of time going through stack overflow posts and trying to debug the issue. Thank you.

ERROR:

```<code>C:\Users\desktop\studentSearch\node_modules\express\lib\router\index.js:458
      throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
      ^

TypeError: Router.use() requires middleware function but got a undefined
    at Function.use (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\router\index.js:458:13)
    at Function.<anonymous> (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\application.js:220:21)
    at Array.forEach (native)
    at Function.use (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\application.js:217:7)
    at Object.<anonymous> (C:\Users\Monica\desktop\studentSearch\server.js:46:5)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:535:3
</code>```

CODE

```<code>// ******************************************************************************
// *** Dependencies
// =============================================================
var express = require("express");
var exphbs = require("express-handlebars");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
    jwtExp = require("express-jwt");
    tokenSecret = require("./tokensecret.js");
    cookieParser = require("cookie-parser");
// Sets up the Express App
// =============================================================
var app = express();
var PORT = process.env.PORT || 8080;

//cookie parser
app.use(cookieParser(tokenSecret));

// Set Handlebars as the default templating engine.
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Requiring our models for syncing
var db = require("./models");

// Sets up the Express app to handle data parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));

// Override with POST having ?_method=DELETE
app.use(methodOverride("_method"));

// Routes =============================================================

require("./routes/html-routes.js")(app);
var apiRoutes = require("./routes/api-routes.js")(app);
var authRoutes = require("./routes/auth-routes.js");

// API MIDDLEWARE
// app.use("/api", jwtExp({ secret: tokenSecret }));
app.use("/api", apiRoutes);

// AUTH MIDDLEWARE
app.use("/auth", authRoutes);
app.use("/auth", express.static("./public"));

// USER MIDDLEWARE
app.get("/", jwtExp({
  secret: tokenSecret,
  getToken: function fromCookie(req) {
    if (req.signedCookies) {
      return req.signedCookies.jwtAuthToken;
    }
    return null;
  },
  credentialsRequired: false
}), function(req, res, next) {
  if (req.user) {
    next();
  } else {
    res.redirect("/auth/login");
  }
});

app.use("/", apiRoutes);

app.use(express.static("./public"));

// Syncing our sequelize models and then starting our express app
db.sequelize.sync({}).then(function() {
    app.listen(PORT, function() {
        console.log("App listening on PORT " + PORT);
    });
});
</code>```

答:
The issue was having the (app) in the definition. See below. </p>

```<code>var apiRoutes = require("./routes/api-routes.js")(app);
</code>```

Title: Getting an error on incorrect routes

Body:
When I run node server I am getting an error and cannot figure out the root cause. I am pasting the error below. I would really appreciate some help as I have spent a lot of time going through stack overflow posts and trying to debug the issue. Thank you.

ERROR:

C:\Users\desktop\studentSearch\node_modules\express\lib\router\index.js:458
      throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
      ^

TypeError: Router.use() requires middleware function but got a undefined
    at Function.use (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\router\index.js:458:13)
    at Function.<anonymous> (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\application.js:220:21)
    at Array.forEach (native)
    at Function.use (C:\Users\Monica\desktop\studentSearch\node_modules\express\lib\application.js:217:7)
    at Object.<anonymous> (C:\Users\Monica\desktop\studentSearch\server.js:46:5)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:535:3

CODE

// ******************************************************************************
// *** Dependencies
// =============================================================
var express = require("express");
var exphbs = require("express-handlebars");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
    jwtExp = require("express-jwt");
    tokenSecret = require("./tokensecret.js");
    cookieParser = require("cookie-parser");
// Sets up the Express App
// =============================================================
var app = express();
var PORT = process.env.PORT || 8080;

//cookie parser
app.use(cookieParser(tokenSecret));

// Set Handlebars as the default templating engine.
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Requiring our models for syncing
var db = require("./models");

// Sets up the Express app to handle data parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));

// Override with POST having ?_method=DELETE
app.use(methodOverride("_method"));

// Routes =============================================================

require("./routes/html-routes.js")(app);
var apiRoutes = require("./routes/api-routes.js")(app);
var authRoutes = require("./routes/auth-routes.js");

// API MIDDLEWARE
// app.use("/api", jwtExp({ secret: tokenSecret }));
app.use("/api", apiRoutes);

// AUTH MIDDLEWARE
app.use("/auth", authRoutes);
app.use("/auth", express.static("./public"));

// USER MIDDLEWARE
app.get("/", jwtExp({
  secret: tokenSecret,
  getToken: function fromCookie(req) {
    if (req.signedCookies) {
      return req.signedCookies.jwtAuthToken;
    }
    return null;
  },
  credentialsRequired: false
}), function(req, res, next) {
  if (req.user) {
    next();
  } else {
    res.redirect("/auth/login");
  }
});

app.use("/", apiRoutes);

app.use(express.static("./public"));

// Syncing our sequelize models and then starting our express app
db.sequelize.sync({}).then(function() {
    app.listen(PORT, function() {
        console.log("App listening on PORT " + PORT);
    });
});

Body:
The issue was having the (app) in the definition. See below.

var apiRoutes = require("./routes/api-routes.js")(app);


来源: stackexchange

问:
QuickSort not fully working
A quicksort algorithm that I've adapted from multiple sources isn't working fully and I can't figure out what's wrong with it. I think there is a off-by-one error somewhere but I've been trying this for an hour now with no different outcome.

```<code>public static <T extends Comparable<T>> void serialSort(List<T> list){
    if (list == null || list.size() <= 1) {
        return;
    }
    T pivot = list.get(list.size() / 2 - 1);
    int i = 0;
    int j = list.size() - 1;
    while (i <= j){
        while (list.get(i).compareTo(pivot) == -1){
            i++;
        }
        while (list.get(j).compareTo(pivot) == 1){
            j--;
        }
        if (i <= j) {
            Collections.swap(list, i, j);
            i++;
            j--;
        }
    }
    if (0 < j)
        serialSort(list.subList(0, j));
    if (i < list.size())
        serialSort(list.subList(i, list.size()));
}
</code>```

I'm supposed to adapt this to a multi-threaded version but I'd like to fix the error first.

Example input:

```<code>[2, 9, 4, 1, 7, 2, 1, 1, 6, 6, 3, 8, 4, 7, 6, 7, 8, 6, 3, 3, 3, 1, 4, 1, 1, 2, 9, 7, 7, 2]
</code>```

Output:

```<code>[1, 1, 1, 1, 1, 2, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 3, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 9, 9]
</code>```

答:
I figured out that List.subList(int, int) is this from the java documentation:

```<code>Returns a view of the portion of this list between the specified fromIndex,
inclusive, and toIndex, exclusive.
</code>```

As I suspected it was a off by one error. I wasn't including the last element of the "left" sublist in every recursive call. Doing this fixed it:

```<code>if (0 < j)
        serialSort(list.subList(0, j + 1));
</code>```

ContentLicense: CC BY-SA 3.0

Title: QuickSort not fully working

Body:
A quicksort algorithm that I've adapted from multiple sources isn't working fully and I can't figure out what's wrong with it. I think there is a off-by-one error somewhere but I've been trying this for an hour now with no different outcome.

public static <T extends Comparable<T>> void serialSort(List<T> list){
    if (list == null || list.size() <= 1) {
        return;
    }
    T pivot = list.get(list.size() / 2 - 1);
    int i = 0;
    int j = list.size() - 1;
    while (i <= j){
        while (list.get(i).compareTo(pivot) == -1){
            i++;
        }
        while (list.get(j).compareTo(pivot) == 1){
            j--;
        }
        if (i <= j) {
            Collections.swap(list, i, j);
            i++;
            j--;
        }
    }
    if (0 < j)
        serialSort(list.subList(0, j));
    if (i < list.size())
        serialSort(list.subList(i, list.size()));
}

I'm supposed to adapt this to a multi-threaded version but I'd like to fix the error first.

Example input:

[2, 9, 4, 1, 7, 2, 1, 1, 6, 6, 3, 8, 4, 7, 6, 7, 8, 6, 3, 3, 3, 1, 4, 1, 1, 2, 9, 7, 7, 2]

Output:

[1, 1, 1, 1, 1, 2, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 3, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 9, 9]

Body:
I figured out that List.subList(int, int) is this from the java documentation:

Returns a view of the portion of this list between the specified fromIndex,
inclusive, and toIndex, exclusive.

As I suspected it was a off by one error. I wasn't including the last element of the "left" sublist in every recursive call. Doing this fixed it:

if (0 < j)
        serialSort(list.subList(0, j + 1));


问:
If statements(no returns) in Pharo Smalltalk for flatten list
I'm trying to make a list(30) of lists (30).
I have this:

```<code>#(#(a a a) nil nil #(b) #(c) #(d) nil nil nil #(e e) nil #(f f) nil #(g)
  #(h) nil nil nil #(i  i) nil nil nil #(j) nil nil nil nil nil
  #(k) #(l l l)
</code>```

And I want to do a program that turns that into just a list like this:

```<code> #(a a a b c d e e f f g hi i j k l l l)
</code>```

My code is this:

```<code>ToList: lista
    | retorno y z |
    retorno := Array new: 30.
    y := 1.
    (1 to: lista size)
        do: [ :i |
            z := 0.
            (lista at: i) isNil
            ifFalse:
            (1 to: (lista at: i) size do: [ :j | retorno at: (y + z) put: ((lista at: i) at: j )
                y:= y+1.
                z:= z +1.]
            )].
        ^retorno
</code>```

I think there are some problems with the if-statements, because there's no return. I don't know what to do, because it works without the y:= y+1., but it keeps some nil spaces.

Please, help me!

答:
There are two syntax errors in your code:

The arguments of ifTrue:, ifFalse:, etc., are block and blocks in Smalltalk are expressions enclosed in squared brackets, not parenthesis. In your case you should write

```<code>(lista at: i) isNil
  ifFalse:
    [1 to: (lista at: i               "<- [ not ("
</code>```

and close with

```<code>        z:= z +1.]
    ]].                               "<- ]] not )]."
</code>```

There is a dot missing at the end of the long line:

```<code>.... put: ((lista at: i) at: j)          "<- dot missing"
        y:= y+1.
        z:= z +1.
</code>```

After fixing these two issues you should be able to run the code to see whether it works as expected (or debug it if not.) But that is another story...

ADDENDUM

There is also something suspicious here.

In Smalltalk we use single quotes to delimit literal strings ('Hello world') and the dollar sign in front of literal characters, like in $a.

In addition, we have literal arrays, which are composed of other literals and enclosed between #( and ), as in #('a' $a).

Now, in your code you have written expressions such as #(a a a), which do not conform to the formats we've just seen. So, what does this mean? More precisely, how would the Smalltalk compiler interprete this notation? The answer is that it will assume that you meant:

```<code>#(#a #a #a)
</code>```

i.e., an array of Symbols, and that you didn't want to write so many #s. So, in your exercise, you should think whether you actually wanted characters #($a $a $a), strings #('a' 'a' 'a') or symbols #(#a #a #a).

The same goes for other strings. For example, #(abc de) will get compiled as #(#abc #de)...

... mmm...

But wait a minute. If this is so, why then #(#(a a a) nil) doesn't get compiled as #(#(a a a) #nil)? Well, because the compiler makes an exception with nil, true and false... uff!

Also note that in some dialects of Smalltalk the compiler will interprete #((a a a)) as #(#(a a a)) so you don't have to type that many pound signs...

Summarizing. If you choose to save some pounds in literal arrays, be consistent and write #((a a a)) rather than #(#(a a a)). Otherwise be completeley explicit and write #(#(#a #a #a)).

Body:
I'm trying to make a list(30) of lists (30).
I have this:

#(#(a a a) nil nil #(b) #(c) #(d) nil nil nil #(e e) nil #(f f) nil #(g)
  #(h) nil nil nil #(i  i) nil nil nil #(j) nil nil nil nil nil
  #(k) #(l l l)

And I want to do a program that turns that into just a list like this:

 #(a a a b c d e e f f g hi i j k l l l)

My code is this:

ToList: lista
    | retorno y z |
    retorno := Array new: 30.
    y := 1.
    (1 to: lista size)
        do: [ :i |
            z := 0.
            (lista at: i) isNil
            ifFalse:
            (1 to: (lista at: i) size do: [ :j | retorno at: (y + z) put: ((lista at: i) at: j )
                y:= y+1.
                z:= z +1.]
            )].
        ^retorno

I think there are some problems with the if-statements, because there's no return. I don't know what to do, because it works without the y:= y+1., but it keeps some nil spaces.

Please, help me!

Body:
There are two syntax errors in your code:

The arguments of ifTrue:, ifFalse:, etc., are block and blocks in Smalltalk are expressions enclosed in squared brackets, not parenthesis. In your case you should write

(lista at: i) isNil
  ifFalse:
    [1 to: (lista at: i               "<- [ not ("

and close with

        z:= z +1.]
    ]].                               "<- ]] not )]."

There is a dot missing at the end of the long line:

.... put: ((lista at: i) at: j)          "<- dot missing"
        y:= y+1.
        z:= z +1.

After fixing these two issues you should be able to run the code to see whether it works as expected (or debug it if not.) But that is another story...

ADDENDUM

There is also something suspicious here.

In Smalltalk we use single quotes to delimit literal strings ('Hello world') and the dollar sign in front of literal characters, like in $a.

In addition, we have literal arrays, which are composed of other literals and enclosed between #( and ), as in #('a' $a).

Now, in your code you have written expressions such as #(a a a), which do not conform to the formats we've just seen. So, what does this mean? More precisely, how would the Smalltalk compiler interprete this notation? The answer is that it will assume that you meant:

#(#a #a #a)

i.e., an array of Symbols, and that you didn't want to write so many #s. So, in your exercise, you should think whether you actually wanted characters #($a $a $a), strings #('a' 'a' 'a') or symbols #(#a #a #a).

The same goes for other strings. For example, #(abc de) will get compiled as #(#abc #de)...

... mmm...

But wait a minute. If this is so, why then #(#(a a a) nil) doesn't get compiled as #(#(a a a) #nil)? Well, because the compiler makes an exception with nil, true and false... uff!

Also note that in some dialects of Smalltalk the compiler will interprete #((a a a)) as #(#(a a a)) so you don't have to type that many pound signs...

Summarizing. If you choose to save some pounds in literal arrays, be consistent and write #((a a a)) rather than #(#(a a a)). Otherwise be completeley explicit and write #(#(#a #a #a)).


问:
i need to have a listener for when input gets value in js
I have input in my page and it get or set value from other function in js

now i want know any ways has when my input get or set value it run other

```<code>function and set other input value
 here is my function set value to input1
function showPoint(loc) {
    var docloc = myDiagram.transformDocToView(loc);
    var elt = document.getElementById("P18_LOC");
    elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
  }
</code>```

now i need any event or listener when input get or set value run other function

i tired onchange() and oninput() and some more js event but i cant fix it

now : any way has to do that?

答:
When an element gets its value changed dynamically through code, user events like change and input don't fire off. What you need to do is manually call for those events to fire with the jQuery .trigger() method.

```<code>function showPoint(loc) {
    var docloc = myDiagram.transformDocToView(loc);
    var elt = document.getElementById("P18_LOC");
    elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
    // Trigger the change event of the P18_LOC element
    $(elt).trigger("change");
}
</code>```

Now, you can set up a change event handler for P18_LOC and it will fire whenever showPoint() is called.

Body:
I have input in my page and it get or set value from other function in js

now i want know any ways has when my input get or set value it run other

function and set other input value
 here is my function set value to input1
function showPoint(loc) {
    var docloc = myDiagram.transformDocToView(loc);
    var elt = document.getElementById("P18_LOC");
    elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
  }

now i need any event or listener when input get or set value run other function

i tired onchange() and oninput() and some more js event but i cant fix it

now : any way has to do that?

Body:
When an element gets its value changed dynamically through code, user events like change and input don't fire off. What you need to do is manually call for those events to fire with the jQuery .trigger() method.

function showPoint(loc) {
    var docloc = myDiagram.transformDocToView(loc);
    var elt = document.getElementById("P18_LOC");
    elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
    // Trigger the change event of the P18_LOC element
    $(elt).trigger("change");
}

Now, you can set up a change event handler for P18_LOC and it will fire whenever showPoint() is called.


问:
C++: Array with custom size in class
I want to do this:

```<code>class Graphic
{
    int *array;
    Graphic( int size )
    {
        int temp_array[size];
        array = temp_array;
        glGenTextures( size, array );
    }
}
</code>```

Will this work? And even if it will, is there a better way to do this?

Thanks.

答:
No, the memory for temp_array is allocated on the stack. When the function ends then that memory is deallocated and all you'll be left with is a dangling pointer. If you want to keep the array valid beyond the point that the constructor returns then allocate it dynamically using new. Example:

```<code>array = new int[size]
</code>```

And then remember to delete it. Typically this is done in the destructor like this:

```<code>delete[] array
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++: Array with custom size in class

Body:
I want to do this:

class Graphic
{
    int *array;
    Graphic( int size )
    {
        int temp_array[size];
        array = temp_array;
        glGenTextures( size, array );
    }
}

Will this work? And even if it will, is there a better way to do this?

Thanks.

Body:
No, the memory for temp_array is allocated on the stack. When the function ends then that memory is deallocated and all you'll be left with is a dangling pointer. If you want to keep the array valid beyond the point that the constructor returns then allocate it dynamically using new. Example:

array = new int[size]

And then remember to delete it. Typically this is done in the destructor like this:

delete[] array


答:
As mentioned by @FFritz, use < 0 and > 0 for your compareTo comparisons (this is just good practice in general).

Use j + 1 when building the first subList for the recursion.

This code works:

```<code>public static <T extends Comparable<T>> void serialSort(List<T> list){
    if (list == null || list.size() <= 1) {
        return;
    }
    T pivot = list.get(list.size() / 2 - 1);
    int i = 0;
    int j = list.size() - 1;
    while (i < j){
        while (list.get(i).compareTo(pivot) < 0){
            i++;
        }
        while (list.get(j).compareTo(pivot) > 0 && j > i){
            j--;
        }
        if (i <= j) {
            Collections.swap(list, i, j);
            i++;
            j--;
        }
    }
    if (0 < j)
        serialSort(list.subList(0, j + 1));
    if (i < list.size())
        serialSort(list.subList(i, list.size()));
}
</code>```

Title: QuickSort not fully working

Body:
As mentioned by @FFritz, use < 0 and > 0 for your compareTo comparisons (this is just good practice in general).

Use j + 1 when building the first subList for the recursion.

This code works:

public static <T extends Comparable<T>> void serialSort(List<T> list){
    if (list == null || list.size() <= 1) {
        return;
    }
    T pivot = list.get(list.size() / 2 - 1);
    int i = 0;
    int j = list.size() - 1;
    while (i < j){
        while (list.get(i).compareTo(pivot) < 0){
            i++;
        }
        while (list.get(j).compareTo(pivot) > 0 && j > i){
            j--;
        }
        if (i <= j) {
            Collections.swap(list, i, j);
            i++;
            j--;
        }
    }
    if (0 < j)
        serialSort(list.subList(0, j + 1));
    if (i < list.size())
        serialSort(list.subList(i, list.size()));
}


问:
TypeError: undefined is not an object when unit testing with jasmine
I'm trying to write a unit test for a function and I'm getting an error. I'm also unsure how to test other parts of the function correctly.

```<code>private dictionaryMap (loggedIn, response) {
    const translations = this.convertToArrays(response.data.translations);

    this.configureMomentLocale(language);

    if (!loggedIn) {
        this.cachePublicDictionary(translations);
    }

    // not testing this part
    this.dictionary = new Dictionary({
        translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
    });

    return this.rx.Observable.of(this.dictionary);
}
</code>```

And my unit test so far looks like this:

```<code>describe('dictionaryMap', () => {

    it('calls configureMomentLocale()', () => {
        const foo = {
            'foo':'bar',
        };
        spyOn(service, 'configureMomentLocale');
        service.dictionaryMap({}, false);
        expect(service.configureMomentLocale).toHaveBeenCalled();
    });

});
</code>```

And when I run this test I get this error:

TypeError: undefined is not an object (evaluating 'response.data.translationMap')

Do I need to mock response.data.translations or assign the json structure? (translationMap: {'email': 'email', 'forgotPassword': 'Forgot password?'})

Also, I'm not sure how to properly test the other parts of the function, like the if statement or returning the observable. I am new to unit testing.

答:
Your method dictionaryMap accepts 2 parameters - 1st is loggedIn (presumably boolean) and the 2nd one is response. On the first line of that method (before calling configureMomentLocale) you have a line const translations = this.convertToArrays(response.data.translations); which expects the response variable to have a property named data.

In your test, you have 2 errors on the line service.dictionaryMap({}, false);:

You're setting the arguments in reverse order - you should put the boolean argument first and the object one second

The object doesn't have a property named data

The line should be corrected to be something similar to service.dictionaryMap(false, { data: {} });. You might even need to define translations property for data object - it really depends on what this.convertToArrays function does and how it handles undefined values.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a unit test for a function and I'm getting an error. I'm also unsure how to test other parts of the function correctly.

private dictionaryMap (loggedIn, response) {
    const translations = this.convertToArrays(response.data.translations);

    this.configureMomentLocale(language);

    if (!loggedIn) {
        this.cachePublicDictionary(translations);
    }

    // not testing this part
    this.dictionary = new Dictionary({
        translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
    });

    return this.rx.Observable.of(this.dictionary);
}

And my unit test so far looks like this:

describe('dictionaryMap', () => {

    it('calls configureMomentLocale()', () => {
        const foo = {
            'foo':'bar',
        };
        spyOn(service, 'configureMomentLocale');
        service.dictionaryMap({}, false);
        expect(service.configureMomentLocale).toHaveBeenCalled();
    });

});

And when I run this test I get this error:

TypeError: undefined is not an object (evaluating 'response.data.translationMap')

Do I need to mock response.data.translations or assign the json structure? (translationMap: {'email': 'email', 'forgotPassword': 'Forgot password?'})

Also, I'm not sure how to properly test the other parts of the function, like the if statement or returning the observable. I am new to unit testing.


问:
c - passing argument 1 from incompatible pointer type
I have this code, very simple and it gives me the error on function max(), when I call it from the latest printf:

```<code>#include <stdio.h>

float max(float v[], int n){
  float maxim = v[0];
  for(int i = 0; i < n; i++){
    if(maxim < v[i]){
      maxim = v[i];
    }
  }
  return maxim;
}

void main(){
  int v[10], n;
  float x;

  for(int i = 0; i < 10; i++){
    printf("Introduza %d de 10 números: ", i+1);
    scanf(" %f", &x);
    v[i] = x;
  }

  printf("Indique o número de elementos que pretende avaliar: ");
  scanf(" %d", &n);

  printf("O maior valor introduzido entre os %d primeiros números foi %f", n, max(v,n));
}
</code>```

Text is in Portuguese, but that doesn't matter.
The error:

```<code>warning: passing argument 1 of ‘max’ from incompatible pointer type [-Wincompatible-pointer-types]
</code>```

I saw a few threads but I think this is different. Can somebody help me?

答:
The passed v in max(v,n) is an int array, but max wants a float array.

You also need float v[10] in main, because you are assigning float x to each element.

But I would use double unless there is a very good reason why you must use float.

Aside: please note that main should be

```<code>int main(void)
</code>```

Body:
I have this code, very simple and it gives me the error on function max(), when I call it from the latest printf:

#include <stdio.h>

float max(float v[], int n){
  float maxim = v[0];
  for(int i = 0; i < n; i++){
    if(maxim < v[i]){
      maxim = v[i];
    }
  }
  return maxim;
}

void main(){
  int v[10], n;
  float x;

  for(int i = 0; i < 10; i++){
    printf("Introduza %d de 10 números: ", i+1);
    scanf(" %f", &x);
    v[i] = x;
  }

  printf("Indique o número de elementos que pretende avaliar: ");
  scanf(" %d", &n);

  printf("O maior valor introduzido entre os %d primeiros números foi %f", n, max(v,n));
}

Text is in Portuguese, but that doesn't matter.
The error:

warning: passing argument 1 of ‘max’ from incompatible pointer type [-Wincompatible-pointer-types]

I saw a few threads but I think this is different. Can somebody help me?

Body:
The passed v in max(v,n) is an int array, but max wants a float array.

You also need float v[10] in main, because you are assigning float x to each element.

But I would use double unless there is a very good reason why you must use float.

Aside: please note that main should be

int main(void)


问:
Can not get BLE characteristics to appear for primary service using BLENO on node js
I have a simple app shown below. I have created a primary service and added characteristics to my service using BLENO on node js on Rpi3.

It seems that my app starts and runs ok. I have used two tools to view my BLE service i.e. Nordic nRF application and a simple app I wrote in Android.

Using these apps I can see my BLE app advertising and i can also connect to it. When connected I can see three services which are two generic and one being my "unknown service" which has matching UUID as i have set in my BLE server app.

The problem I am having is when I expend my service, it tells me there are no characteristics set for my service.

I would appreciate if someone could review the code below and check possible reason for no characteristics appearing in my service.

```<code>`var bleno = require("bleno");
var BlenoPrimaryService = bleno.PrimaryService;
var Characteristic = bleno.Characteristic;
var Descriptor = bleno.Descriptor;
//var UserConfigCharecteristic = require('./user-config-characteristic');

bleno.on('stateChange', function (state) {
    console.log('on -> stateChagne: ' + state);
    if (state === 'poweredOn') {
        console.log('ble has been powered on');
        bleno.startAdvertising('rpi-ble-app', ['fffffffffffffffffffffffffffffff0']);
    } else {
        bleno.stopAdvertising();
    }
});

bleno.on('advertisingStart', function () {
console.log('-> advertising start');
bleno.setServices([
    new BlenoPrimaryService(
            {
                uuid: 'fffffffffffffffffffffffffffffff0',
                charecteristics: [
                    new Characteristic({
                        uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
                        properties: ['read', 'write'], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        secure: [], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        value: null, // optional static value, must be of type Buffer - for read only characteristics
                        descriptors: [],
                        onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
                        onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
                        onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
                        onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
                        onNotify: null, // optional notify sent handler, function() { ...}
                        onIndicate: null // optional indicate confirmation received handler, function() { ...}
                    })
                ]
            }
    )], function (error) {
    console.log('setServices: ' + (error ? 'error ' + error : 'success'));
});

});

bleno.on('servicesSet', function () {
    console.log('services set.');
});`
</code>```

Output for my node.js app is

```<code>on -> stateChagne: poweredOn
ble has been powered on
-> advertising start
services set.
setServices: success
</code>```

答:
Seems I have found the problem, I had misspelled Characteristics.

I'm new to nodejs and realise that mis-spelling can be an issue since if you mis-spell you wont override instead you will add a new property.

Body:
I have a simple app shown below. I have created a primary service and added characteristics to my service using BLENO on node js on Rpi3.

It seems that my app starts and runs ok. I have used two tools to view my BLE service i.e. Nordic nRF application and a simple app I wrote in Android.

Using these apps I can see my BLE app advertising and i can also connect to it. When connected I can see three services which are two generic and one being my "unknown service" which has matching UUID as i have set in my BLE server app.

The problem I am having is when I expend my service, it tells me there are no characteristics set for my service.

I would appreciate if someone could review the code below and check possible reason for no characteristics appearing in my service.

`var bleno = require("bleno");
var BlenoPrimaryService = bleno.PrimaryService;
var Characteristic = bleno.Characteristic;
var Descriptor = bleno.Descriptor;
//var UserConfigCharecteristic = require('./user-config-characteristic');

bleno.on('stateChange', function (state) {
    console.log('on -> stateChagne: ' + state);
    if (state === 'poweredOn') {
        console.log('ble has been powered on');
        bleno.startAdvertising('rpi-ble-app', ['fffffffffffffffffffffffffffffff0']);
    } else {
        bleno.stopAdvertising();
    }
});

bleno.on('advertisingStart', function () {
console.log('-> advertising start');
bleno.setServices([
    new BlenoPrimaryService(
            {
                uuid: 'fffffffffffffffffffffffffffffff0',
                charecteristics: [
                    new Characteristic({
                        uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
                        properties: ['read', 'write'], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        secure: [], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        value: null, // optional static value, must be of type Buffer - for read only characteristics
                        descriptors: [],
                        onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
                        onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
                        onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
                        onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
                        onNotify: null, // optional notify sent handler, function() { ...}
                        onIndicate: null // optional indicate confirmation received handler, function() { ...}
                    })
                ]
            }
    )], function (error) {
    console.log('setServices: ' + (error ? 'error ' + error : 'success'));
});

});

bleno.on('servicesSet', function () {
    console.log('services set.');
});`

Output for my node.js app is

on -> stateChagne: poweredOn
ble has been powered on
-> advertising start
services set.
setServices: success


问:
Spark Dataframe/RDD cannot create new column by counting the contents of another column
I have a Spark RDD (or Dataframe - converting to either is not a problem) that has the following columns (example for each structure):

res248: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[1004] at map at <console>:246
org.apache.spark.sql.DataFrame = [id: string, list: array<string>]
```

<p>I want to expand this RDD/DF to have an additional column containing the size of the list array. So the output should be something like this (example):</p>

<pre class="lang-none prettyprint-override"><code>org.apache.spark.sql.DataFrame = [id: string, list: array<string>, length_of_list: int]
</code>```

I tried to do an rdd.map(x=> (x._1,x._2,count(x._2))) but got an error message:

<console>:246: error: overloaded method value count with alternatives:
  (columnName: String)org.apache.spark.sql.TypedColumn[Any,Long] <and>
  (e: org.apache.spark.sql.Column)org.apache.spark.sql.Column
```

Tried adding a new column using DF with the function withColumn("new_column",count($"list")) or any variation thereof. It still doesn't work. I get an error message complaining about aggregation.

Do you know of a way to achieve this without having to collect the RDD?

答:
You can create the new column using a simple UDF to apply to column list as follows:

```<code>val df = Seq(
  ("a", Array("x1", "x2", "x3")),
  ("b", Array("y1", "y2", "y3", "y4"))
).toDF(
  "id", "list"
)
// df: org.apache.spark.sql.DataFrame = [id: string, list: array<string>]

val listSize = (l: Seq[String]) => l.size
// listSize: Seq[String] => Int = <function1>

def listSizeUDF = udf(listSize)
// listSizeUDF: org.apache.spark.sql.expressions.UserDefinedFunction

val df2 = df.withColumn("length_of_list", listSizeUDF($"list"))

df2.show
+---+----------------+--------------+
| id|            list|length_of_list|
+---+----------------+--------------+
|  a|    [x1, x2, x3]|             3|
|  b|[y1, y2, y3, y4]|             4|
+---+----------------+--------------+
</code>```

[UPDATE]

As pointed out by @Ramesh Maharjan, there is a built-in size function in Spark which I somehow forgot about.  I'll leave the old answer as a simple use case for using UDF.

Body:
I have a Spark RDD (or Dataframe - converting to either is not a problem) that has the following columns (example for each structure):

res248: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[1004] at map at <console>:246
org.apache.spark.sql.DataFrame = [id: string, list: array<string>]

I want to expand this RDD/DF to have an additional column containing the size of the list array. So the output should be something like this (example):

org.apache.spark.sql.DataFrame = [id: string, list: array<string>, length_of_list: int]

I tried to do an rdd.map(x=> (x._1,x._2,count(x._2))) but got an error message:

<console>:246: error: overloaded method value count with alternatives:
  (columnName: String)org.apache.spark.sql.TypedColumn[Any,Long] <and>
  (e: org.apache.spark.sql.Column)org.apache.spark.sql.Column

Tried adding a new column using DF with the function withColumn("new_column",count($"list")) or any variation thereof. It still doesn't work. I get an error message complaining about aggregation.

Do you know of a way to achieve this without having to collect the RDD?

Body:
You can create the new column using a simple UDF to apply to column list as follows:

val df = Seq(
  ("a", Array("x1", "x2", "x3")),
  ("b", Array("y1", "y2", "y3", "y4"))
).toDF(
  "id", "list"
)
// df: org.apache.spark.sql.DataFrame = [id: string, list: array<string>]

val listSize = (l: Seq[String]) => l.size
// listSize: Seq[String] => Int = <function1>

def listSizeUDF = udf(listSize)
// listSizeUDF: org.apache.spark.sql.expressions.UserDefinedFunction

val df2 = df.withColumn("length_of_list", listSizeUDF($"list"))

df2.show
+---+----------------+--------------+
| id|            list|length_of_list|
+---+----------------+--------------+
|  a|    [x1, x2, x3]|             3|
|  b|[y1, y2, y3, y4]|             4|
+---+----------------+--------------+

[UPDATE]

As pointed out by @Ramesh Maharjan, there is a built-in size function in Spark which I somehow forgot about.  I'll leave the old answer as a simple use case for using UDF.


问:
Very simple RogueLike in F#, making it more "functional"
I have some existing C# code for a very, very simple RogueLike engine. It is deliberately naive in that I was trying to do the minimum amount as simply as possible. All it does is move an @ symbol around a hardcoded map using the arrow keys and System.Console:

```<code>//define the map
var map = new List<string>{
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "    ###############################     ",
  "    #                             #     ",
  "    #         ######              #     ",
  "    #         #    #              #     ",
  "    #### #### #    #              #     ",
  "       # #  # #    #              #     ",
  "       # #  # #    #              #     ",
  "    #### #### ######              #     ",
  "    #              =              #     ",
  "    #              =              #     ",
  "    ###############################     ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        "
};

//set initial player position on the map
var playerX = 8;
var playerY = 6;

//clear the console
Console.Clear();

//send each row of the map to the Console
map.ForEach( Console.WriteLine );

//create an empty ConsoleKeyInfo for storing the last key pressed
var keyInfo = new ConsoleKeyInfo( );

//keep processing key presses until the player wants to quit
while ( keyInfo.Key != ConsoleKey.Q ) {
  //store the player's current location
  var oldX = playerX;
  var oldY = playerY;

  //change the player's location if they pressed an arrow key
  switch ( keyInfo.Key ) {
    case ConsoleKey.UpArrow:
      playerY--;
      break;
    case ConsoleKey.DownArrow:
      playerY++;
      break;
    case ConsoleKey.LeftArrow:
      playerX--;
      break;
    case ConsoleKey.RightArrow:
      playerX++;
      break;
  }

  //check if the square that the player is trying to move to is empty
  if( map[ playerY ][ playerX ] == ' ' ) {
    //ok it was empty, clear the square they were standing on before
    Console.SetCursorPosition( oldX, oldY );
    Console.Write( ' ' );
    //now draw them at the new square
    Console.SetCursorPosition( playerX, playerY );
    Console.Write( '@' );
  } else {
    //they can't move there, change their location back to the old location
    playerX = oldX;
    playerY = oldY;
  }

  //wait for them to press a key and store it in keyInfo
  keyInfo = Console.ReadKey( true );
}
</code>```

I was playing around with doing it in F#, initially I was trying to write it using functional concepts, but turned out I was a bit over my head, so I did pretty much a straight port - it's not really an F# program (though it compiles and runs) it's a procedural program written in F# syntax:

```<code>open System

//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//set initial player position on the map
let mutable playerX = 8
let mutable playerY = 6

//clear the console
Console.Clear()

//send each row of the map to the Console
map |> Seq.iter (printfn "%s")

//create an empty ConsoleKeyInfo for storing the last key pressed
let mutable keyInfo = ConsoleKeyInfo()

//keep processing key presses until the player wants to quit
while not ( keyInfo.Key = ConsoleKey.Q ) do
    //store the player's current location
    let mutable oldX = playerX
    let mutable oldY = playerY

    //change the player's location if they pressed an arrow key
    if keyInfo.Key = ConsoleKey.UpArrow then
        playerY <- playerY - 1
    else if keyInfo.Key = ConsoleKey.DownArrow then
        playerY <- playerY + 1
    else if keyInfo.Key = ConsoleKey.LeftArrow then
        playerX <- playerX - 1
    else if keyInfo.Key = ConsoleKey.RightArrow then
        playerX <- playerX + 1

    //check if the square that the player is trying to move to is empty
    if map.Item( playerY ).Chars( playerX ) = ' ' then
        //ok it was empty, clear the square they were standing on
        Console.SetCursorPosition( oldX, oldY )
        Console.Write( ' ' )
        //now draw them at the new square
        Console.SetCursorPosition( playerX, playerY )
        Console.Write( '@' )
    else
        //they can't move there, change their location back to the old location
        playerX <- oldX
        playerY <- oldY

    //wait for them to press a key and store it in keyInfo
    keyInfo <- Console.ReadKey( true )
</code>```

So my question is, what do I need to learn in order to rewrite this more functionally, can you give me some hints, a vague overview, that kind of thing.

I'd prefer a shove in the right direction rather than just seeing some code, but if that's the easiest way for you to explain it to me then fine, but in that case can you please also explain the "why" rather the "how" of it?

答:
I'll try and avoid being overly specific - if I end up going too far in the other direction and this is too vague, let me know and I'll try improve it a little.

When making a functional program that has some sort of state, the basic mechanism you want to implement is something like:

```<code>(currentState, input) => newState
</code>```

Then you can write a small wrapper around that to handle fetching input and drawing output.

Body:
I have some existing C# code for a very, very simple RogueLike engine. It is deliberately naive in that I was trying to do the minimum amount as simply as possible. All it does is move an @ symbol around a hardcoded map using the arrow keys and System.Console:

//define the map
var map = new List<string>{
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "    ###############################     ",
  "    #                             #     ",
  "    #         ######              #     ",
  "    #         #    #              #     ",
  "    #### #### #    #              #     ",
  "       # #  # #    #              #     ",
  "       # #  # #    #              #     ",
  "    #### #### ######              #     ",
  "    #              =              #     ",
  "    #              =              #     ",
  "    ###############################     ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        "
};

//set initial player position on the map
var playerX = 8;
var playerY = 6;

//clear the console
Console.Clear();

//send each row of the map to the Console
map.ForEach( Console.WriteLine );

//create an empty ConsoleKeyInfo for storing the last key pressed
var keyInfo = new ConsoleKeyInfo( );

//keep processing key presses until the player wants to quit
while ( keyInfo.Key != ConsoleKey.Q ) {
  //store the player's current location
  var oldX = playerX;
  var oldY = playerY;

  //change the player's location if they pressed an arrow key
  switch ( keyInfo.Key ) {
    case ConsoleKey.UpArrow:
      playerY--;
      break;
    case ConsoleKey.DownArrow:
      playerY++;
      break;
    case ConsoleKey.LeftArrow:
      playerX--;
      break;
    case ConsoleKey.RightArrow:
      playerX++;
      break;
  }

  //check if the square that the player is trying to move to is empty
  if( map[ playerY ][ playerX ] == ' ' ) {
    //ok it was empty, clear the square they were standing on before
    Console.SetCursorPosition( oldX, oldY );
    Console.Write( ' ' );
    //now draw them at the new square
    Console.SetCursorPosition( playerX, playerY );
    Console.Write( '@' );
  } else {
    //they can't move there, change their location back to the old location
    playerX = oldX;
    playerY = oldY;
  }

  //wait for them to press a key and store it in keyInfo
  keyInfo = Console.ReadKey( true );
}

I was playing around with doing it in F#, initially I was trying to write it using functional concepts, but turned out I was a bit over my head, so I did pretty much a straight port - it's not really an F# program (though it compiles and runs) it's a procedural program written in F# syntax:

open System

//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//set initial player position on the map
let mutable playerX = 8
let mutable playerY = 6

//clear the console
Console.Clear()

//send each row of the map to the Console
map |> Seq.iter (printfn "%s")

//create an empty ConsoleKeyInfo for storing the last key pressed
let mutable keyInfo = ConsoleKeyInfo()

//keep processing key presses until the player wants to quit
while not ( keyInfo.Key = ConsoleKey.Q ) do
    //store the player's current location
    let mutable oldX = playerX
    let mutable oldY = playerY

    //change the player's location if they pressed an arrow key
    if keyInfo.Key = ConsoleKey.UpArrow then
        playerY <- playerY - 1
    else if keyInfo.Key = ConsoleKey.DownArrow then
        playerY <- playerY + 1
    else if keyInfo.Key = ConsoleKey.LeftArrow then
        playerX <- playerX - 1
    else if keyInfo.Key = ConsoleKey.RightArrow then
        playerX <- playerX + 1

    //check if the square that the player is trying to move to is empty
    if map.Item( playerY ).Chars( playerX ) = ' ' then
        //ok it was empty, clear the square they were standing on
        Console.SetCursorPosition( oldX, oldY )
        Console.Write( ' ' )
        //now draw them at the new square
        Console.SetCursorPosition( playerX, playerY )
        Console.Write( '@' )
    else
        //they can't move there, change their location back to the old location
        playerX <- oldX
        playerY <- oldY

    //wait for them to press a key and store it in keyInfo
    keyInfo <- Console.ReadKey( true )

So my question is, what do I need to learn in order to rewrite this more functionally, can you give me some hints, a vague overview, that kind of thing.

I'd prefer a shove in the right direction rather than just seeing some code, but if that's the easiest way for you to explain it to me then fine, but in that case can you please also explain the "why" rather the "how" of it?

Body:
I'll try and avoid being overly specific - if I end up going too far in the other direction and this is too vague, let me know and I'll try improve it a little.

When making a functional program that has some sort of state, the basic mechanism you want to implement is something like:

(currentState, input) => newState

Then you can write a small wrapper around that to handle fetching input and drawing output.


问:
I'd like to create CloudFormation stack with resources in multiple regions. Is this possible?
Is it possible to create a single Amazon CloudFormation stack template that instantiates an AWS::EC2::Instance in ap-southeast-1 and another AWS::EC2::Instance in us-west-2 for example?

I suspect not, but I've not yet found a definitive yes/no saying that stacks can't have resources spanning multiple regions.

答:
You can create a lambda function invoking to create a resource in another region, and even making your lambda function to invoke another stack in the other region.

To make your life easy, in this case you can use the lambda cli2cloudformation (https://github.com/lucioveloso/cli2cloudformation).

Using it, you can execute CLI commands inside your lambda, and by this way, you specific the --region in the command.

It's also interesting, because you will be able to set a command when your stack is created, updated and deleted.

```<code>  "myCustomResource": {
    "Type": "Custom::LocationConstraint",
    "Properties": {
      "ServiceToken": "arn:aws:lambda:eu-west-1:432811670411:function:cli2cfn_proxy2",
      "CliCommandCreate": "s3api get-bucket-location --bucket my-test-bucket --region eu-west-1",
      "CliCommandUpdate": "",
      "CliCommandDelete": ""
    }
  },
</code>```

Body:
You can create a lambda function invoking to create a resource in another region, and even making your lambda function to invoke another stack in the other region.

To make your life easy, in this case you can use the lambda cli2cloudformation (https://github.com/lucioveloso/cli2cloudformation).

Using it, you can execute CLI commands inside your lambda, and by this way, you specific the --region in the command.

It's also interesting, because you will be able to set a command when your stack is created, updated and deleted.

  "myCustomResource": {
    "Type": "Custom::LocationConstraint",
    "Properties": {
      "ServiceToken": "arn:aws:lambda:eu-west-1:432811670411:function:cli2cfn_proxy2",
      "CliCommandCreate": "s3api get-bucket-location --bucket my-test-bucket --region eu-west-1",
      "CliCommandUpdate": "",
      "CliCommandDelete": ""
    }
  },


问:
Replace values in a subset of a data.table
Let's suppose I have this:

```<code>dt <- data.table(mtcars)[1:3, ]
dt[wt == 2.620, "am"] <- 4
dt[wt == 2.620,]
</code>```

My output is:

```<code>    mpg cyl disp  hp drat   wt  qsec vs am gear carb
1:  21   6  160 110  3.9 2.62 16.46  0  4    4    4
</code>```

I want to replace the value 4 by 0 only in the columns gear and carb.

The final data would look like this:

```<code>    mpg cyl disp  hp drat    wt  qsec vs am gear carb
1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
</code>```

答:
In your small example, the method proposed by @HenryRice is sufficient (with maybe a further subset where wt == 2.62).

If you were doing it on more rows or columns, using data.table's for / set loop would be useful in this scenario

```<code>for(j in c("gear", "carb"))
    set(dt, i = which(dt[[j]] == 4 & dt[["wt"]] == 2.620), j = j, value = 0)

dt
#     mpg cyl disp  hp drat    wt  qsec vs am gear carb
# 1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
# 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
</code>```

Body:
Let's suppose I have this:

dt <- data.table(mtcars)[1:3, ]
dt[wt == 2.620, "am"] <- 4
dt[wt == 2.620,]

My output is:

    mpg cyl disp  hp drat   wt  qsec vs am gear carb
1:  21   6  160 110  3.9 2.62 16.46  0  4    4    4

I want to replace the value 4 by 0 only in the columns gear and carb.

The final data would look like this:

    mpg cyl disp  hp drat    wt  qsec vs am gear carb
1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Body:
In your small example, the method proposed by @HenryRice is sufficient (with maybe a further subset where wt == 2.62).

If you were doing it on more rows or columns, using data.table's for / set loop would be useful in this scenario

for(j in c("gear", "carb"))
    set(dt, i = which(dt[[j]] == 4 & dt[["wt"]] == 2.620), j = j, value = 0)

dt
#     mpg cyl disp  hp drat    wt  qsec vs am gear carb
# 1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
# 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1


问:
Trouble Exporting JSON in Firebase Read-only & Non-realtime Mode
It seems like when the amount of data gets too large, Firebase goes into a "Read-only & Non-realtime Mode" which they didn't warn about. In this mode, the Export JSON does not work. I can go into each and every node to extract the JSON, but that will mean that I have to do for tens of nodes. How do I get the node (that is currently too large) to become real time again, or how do I export the JSON when it is non-realtime? Also, is Firebase still writable when it is in non-realtime?</p>

答: Yes, the console will stop reflecting updates to data in real time when your data set becomes too large.  If you need to download parts of your database outside the console, you can still use the REST API to download any or all of your database.</p>


问:
Sort error - dates in Unity
Here's an interesting one. I am sorting a list by date using the iComparable interface. I was testing it again today, when I noticed something. I had entered 11/1/2016 as a date. When the data was sent to the screen, that date was first even though the other dates in the list were before it. I realize that the system would think that 11 might need to be at the top of the list, but how can I fix this?

```<code>public class SortbyDate :IComparer<OilChange> {
  public int Compare(OilChange x, OilChange y) {
    return x.ServiceDate.CompareTo (y.ServiceDate);
  }
}
</code>```

Thanks!

答:
If you sort it as a string, 11 is going to come before, for example, 2, making November come before February. If the value that it represents is a date, you should probably store and manipulate it as a date.

Here are the functions I'm using for date swapping

```<code>public string SwitchDate(string date)
{
    Debug.Log ("Date IN: Switch " + date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}", inputSections[2], inputSections[0], inputSections[1]);
    Debug.Log ("Date OUT: Switch " + ServiceDate);

    return ServiceDate;
}

string SwitchbackDate(string date)
{
    Debug.Log ("Switchback In: " +date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}",inputSections[1], inputSections[2], inputSections[0]);
    Debug.Log ("Switchback Out: " + ServiceDate);

    return ServiceDate;
}
</code>```

Title: Sort error - dates in Unity

Body:
Here's an interesting one. I am sorting a list by date using the iComparable interface. I was testing it again today, when I noticed something. I had entered 11/1/2016 as a date. When the data was sent to the screen, that date was first even though the other dates in the list were before it. I realize that the system would think that 11 might need to be at the top of the list, but how can I fix this?

public class SortbyDate :IComparer<OilChange> {
  public int Compare(OilChange x, OilChange y) {
    return x.ServiceDate.CompareTo (y.ServiceDate);
  }
}

Thanks!

Body:
If you sort it as a string, 11 is going to come before, for example, 2, making November come before February. If the value that it represents is a date, you should probably store and manipulate it as a date.

Here are the functions I'm using for date swapping

public string SwitchDate(string date)
{
    Debug.Log ("Date IN: Switch " + date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}", inputSections[2], inputSections[0], inputSections[1]);
    Debug.Log ("Date OUT: Switch " + ServiceDate);

    return ServiceDate;
}

string SwitchbackDate(string date)
{
    Debug.Log ("Switchback In: " +date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}",inputSections[1], inputSections[2], inputSections[0]);
    Debug.Log ("Switchback Out: " + ServiceDate);

    return ServiceDate;
}


问:
MMORPG protocol encryption
Anyone know what the trend is with MMORPG developers encryption their client/server protocols these days?

The pro's and con's are as follows.

Encrypting protocol:

protects trade secrets regarding client/server protocol to a degree?

Botting isn't stopped, it is only changed because people will create bots which read screen states and trigger mouse+keyboard events will then be developed, merely mitigating the development of bots as opposed to stopping them in anyway. Still though bot development is less in supply somewhat, but the demand is still there, they merely get higher bids on rentacoder.com

Regular plain text:

more advanced bots since the developers are able to inject their own datagrams into the client/server protocol. (ie: running through walls, teleporting... which the server side has to now check, which in turn leads to a development contest between out patching exploits via injection (time consuming)

答:
Adding encryption to your packets will only slow a person writing a bot by oh, a few seconds. Your client would need to know how to encrypt to send data to the server and how to decrypt data from the server, and so would the bot.

With regards to preventing warping through walls, you should be doing these checks always. Never trust the user's input, even if you've written the client yourself.

As fastcall mentioned, you should still implement encryption of some data. Specifically the ones containing sensitive data, like logins and chat.

OwnerDisplayName: Zombies

Title: MMORPG protocol encryption

OwnerDisplayName: Samuel


答: Being a game, and using the Console, there is state and side-effects here which are inherent. But the key thing you'll want to do is eliminate those mutables. Using a recursive loop instead of a while loop will help you do that since then you can pass your state as arguments to each recursive call.  Other than that, the main thing I can see to take advantage of F# features here is using pattern matching instead of if/then statements and switches, though that would be a mainly aesthetic improvement.</p>

Title: Very simple RogueLike in F#, making it more "functional"


问:
pandas.read_sql read array columns directly into native structures?
Is there any way to get pandas to read a table with array-typed columns directly into native structures? By default, a int[] column ends up as an object column containing python list of python ints. There are ways to convert this into a column of Series, or better, a column with a multi-index, but this are very slow (~10 seconds) for 500M rows. Would be much faster if the data was originally loaded into a dataframe. I don't what to unroll the array in sql because I have very many array columns.

```<code>url = "postgresql://u:p@host:5432/dname"
engine = sqlalchemy.create_engine(url)

df = pd.read_sql_query("select 1.0 as a, 2.2 as b, array[1,2,3] as c;", engine)
print df
print type(df.loc[0,'c'])  # list
print type(df.loc[0,'c'][0])  # int
</code>```

答: Does it help if you use read_sql_table instead of read_sql_query ? Also, type detection can fail due to missing values. Maybe this is the cause.

Body:
Is there any way to get pandas to read a table with array-typed columns directly into native structures? By default, a int[] column ends up as an object column containing python list of python ints. There are ways to convert this into a column of Series, or better, a column with a multi-index, but this are very slow (~10 seconds) for 500M rows. Would be much faster if the data was originally loaded into a dataframe. I don't what to unroll the array in sql because I have very many array columns.

url = "postgresql://u:p@host:5432/dname"
engine = sqlalchemy.create_engine(url)

df = pd.read_sql_query("select 1.0 as a, 2.2 as b, array[1,2,3] as c;", engine)
print df
print type(df.loc[0,'c'])  # list
print type(df.loc[0,'c'][0])  # int


问:
Showing newest mysql rows in front end search
Can someone help me show the newest row ids when searching the database. Here is my code, limited to showing 100 results, but it shows the oldest rows first. I would like to show the newest rows. Keep in mind i do not have a time stamp.</p>

```<code>$query_str = "SELECT * FROM puppy_data
              WHERE (`breed` LIKE '%".$query."%')
              OR (`sex` LIKE '%".$query."%')
              LIMIT 100 " ;
</code>```

答:
Use the ORDER BY <column(s)> DESC clause to sort by one or more columns in descending order.  This works if you have an auto incrementing ID column, or a DateTime created_at column.  Remember that ideally the column you are ordering by should be an indexed one.

```<code>SELECT * FROM puppy_data
WHERE (breed LIKE '%".$query."%')
OR (sex LIKE '%".$query."%')
ORDER BY id DESC
LIMIT 100
</code>```

https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html

Body:
Can someone help me show the newest row ids when searching the database. Here is my code, limited to showing 100 results, but it shows the oldest rows first. I would like to show the newest rows. Keep in mind i do not have a time stamp.

$query_str = "SELECT * FROM puppy_data
              WHERE (`breed` LIKE '%".$query."%')
              OR (`sex` LIKE '%".$query."%')
              LIMIT 100 " ;

Body:
Use the ORDER BY <column(s)> DESC clause to sort by one or more columns in descending order.  This works if you have an auto incrementing ID column, or a DateTime created_at column.  Remember that ideally the column you are ordering by should be an indexed one.

SELECT * FROM puppy_data
WHERE (breed LIKE '%".$query."%')
OR (sex LIKE '%".$query."%')
ORDER BY id DESC
LIMIT 100

https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html


答:
Like this:</p>

```<code>dt$carb[dt$carb==4] <- 0
dt$gear[dt$gear==4] <- 0
</code>```

Title: Replace values in a subset of a data.table

Body:
Like this:

dt$carb[dt$carb==4] <- 0
dt$gear[dt$gear==4] <- 0


问:
Solve a transaction with mongodb (waterline.js) and node.js (sails.js)
Given is this situation:

-UserA publishs a Campaign with a given amount of photo uploads.

-other Users can upload Photos

-UserA can accept the uploaded Photos

-the owner of the photos get for each accepted photo 1 Coin

-for each accepted photo the amount of possible photos in the campaign decrease.

I solved the "accept photos" function like this (pseudocode):

```<code>accept: function (req, res, next) {

        var photos = req.param('photos'); // [1, 2, 5]
        var campaign_id = req.param('campaign_id'); //1

        Photo.update(photos, {status:'accepted'}).exec(function afterwards(err, updatedPhotos)
            {
                     //get the users Ids from the updatedPhotos
                      // also know how many photos of each user were accepted

                      User.update(users){
                         //increase the amount of coins of this user
                       }

                      Campaign.update(amountOfAcceptedPhotos){
                         //decrease the amount of selectable photos.
                       }

            })

}
</code>```

Everything worked well first, til I noticed when you send quickly the same request with the same photoID's, the Users will get for the same photo multiple coins! How can I prevent this?

Here is a Link for the whole Code, if you want to see the exact function:
https://jsfiddle.net/zsmuoh0x/

答:
In your particular case, I guess you are storing the user selected photos somewhere at campaigns collection for example:

```<code>{Id:999, Name: mycampaign, photos:[1,7] }
</code>```

So, the update query should select the document by id AND by photo id. If you want to add picture 3:

```<code>db.campaigns.update({id:999, photos:3},. {$addToSet:{photos:3}})
</code>```

If result of that is 1 documents updated, then increment the user coins.

PS: I am answering via a mobile phone

Body:
Given is this situation:

-UserA publishs a Campaign with a given amount of photo uploads.

-other Users can upload Photos

-UserA can accept the uploaded Photos

-the owner of the photos get for each accepted photo 1 Coin

-for each accepted photo the amount of possible photos in the campaign decrease.

I solved the "accept photos" function like this (pseudocode):

accept: function (req, res, next) {

        var photos = req.param('photos'); // [1, 2, 5]
        var campaign_id = req.param('campaign_id'); //1

        Photo.update(photos, {status:'accepted'}).exec(function afterwards(err, updatedPhotos)
            {
                     //get the users Ids from the updatedPhotos
                      // also know how many photos of each user were accepted

                      User.update(users){
                         //increase the amount of coins of this user
                       }

                      Campaign.update(amountOfAcceptedPhotos){
                         //decrease the amount of selectable photos.
                       }

            })

}

Everything worked well first, til I noticed when you send quickly the same request with the same photoID's, the Users will get for the same photo multiple coins! How can I prevent this?

Here is a Link for the whole Code, if you want to see the exact function:
https://jsfiddle.net/zsmuoh0x/

Body:
In your particular case, I guess you are storing the user selected photos somewhere at campaigns collection for example:

{Id:999, Name: mycampaign, photos:[1,7] }

So, the update query should select the document by id AND by photo id. If you want to add picture 3:

db.campaigns.update({id:999, photos:3},. {$addToSet:{photos:3}})

If result of that is 1 documents updated, then increment the user coins.

PS: I am answering via a mobile phone


问:
Xcode "Build and Archive" button disabled for Mac app. Why?
I am building a Mac app, but the "Build and Archive" menu item is disabled. I am running Xcode  3.2.4 and OS X 10.6.5. Any suggestions?</p>

答:
Download and install the "Application Tools" package fixed it for me.

Links to the Application Tools download can be found on the index page for the Mac developer program.


问:
EF 6.1.3 how to seed on-to-many relationship
I am trying to seed my EF code first database in the Configuration file of the migrations folder, but somehow I have no idea how as I do not want to add a new entry to the related database.

I have the following database structure.

```<code>public class ClassSchedule
    {
        public int Id { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }

        public virtual Class Classes { get; set; }
        public virtual Classroom Classrooms { get; set; }
    }

public class Class
    {
        public Class()
        {
            this.Students = new HashSet<Student>();
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public int LevelId { get; set; }

        [StringLength(50)]
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Level Levels { get; set; }
        public ICollection<Student> Students { get; set; }
        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

  public class Classroom
    {
        public Classroom()
        {
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public string ClassRoomName { get; set; }
        public int MaxStudents { get; set; }

        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }
</code>```

And have got the following Code in my migration configuration file:

```<code>// all classrooms
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Cherry", MaxStudents = 20 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Pear", MaxStudents = 12 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Apple", MaxStudents = 12 });

  // classes
  context.Classes.Add(new Class() { ClassName = "YR1", MaxStudents = 12, LevelId = 1 });
  context.Classes.Add(new Class() { ClassName = "YB1", MaxStudents = 6, LevelId = 3 });
  context.Classes.Add(new Class() { ClassName = "IELTS L1", MaxStudents = 40, LevelId = 14 });
</code>```

Now what i want to do is something like this:

```<code>// ClassRoom schedules, links the class and classroom on a certain time
            context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = 1, Classrooms = 1 });
</code>```

Another thing I tried was:

```<code>   context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = { Id = 1 }, Classrooms = { Id = 2 } });
</code>```

However that does't work, also note that I cannot use new Classes() { Id = 1 }  as this will create a new entity.

Any help will be appreciated, Cheers!

答:
You can add classrooms and classes to the collections in ClassSchedule:

```<code>var classRoom1 = new Classroom { ClassRoomName = "Cherry", MaxStudents = 20 };
var class1 = new Class { ClassName = "YR1", MaxStudents = 12, LevelId = 1 };
var classSchedule1 = new ClassSchedule { StartTime = ... };

classSchedule1.Classrooms.Add(classRoom1);
classSchedule1.Classess.Add(class1);

context.ClassSchedules.Add(classSchedule1);
</code>```

etc.

That's the gist of it. Add classes and classrooms that belong to a schedule to the ClassSchedules collections and add the schedule to the context. Add classes and classrooms that don't belong to a schedule (yet) to the DbSets of the context.

Body:
I am trying to seed my EF code first database in the Configuration file of the migrations folder, but somehow I have no idea how as I do not want to add a new entry to the related database.

I have the following database structure.

public class ClassSchedule
    {
        public int Id { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }

        public virtual Class Classes { get; set; }
        public virtual Classroom Classrooms { get; set; }
    }

public class Class
    {
        public Class()
        {
            this.Students = new HashSet<Student>();
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public int LevelId { get; set; }

        [StringLength(50)]
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Level Levels { get; set; }
        public ICollection<Student> Students { get; set; }
        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

  public class Classroom
    {
        public Classroom()
        {
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public string ClassRoomName { get; set; }
        public int MaxStudents { get; set; }

        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

And have got the following Code in my migration configuration file:

// all classrooms
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Cherry", MaxStudents = 20 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Pear", MaxStudents = 12 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Apple", MaxStudents = 12 });

  // classes
  context.Classes.Add(new Class() { ClassName = "YR1", MaxStudents = 12, LevelId = 1 });
  context.Classes.Add(new Class() { ClassName = "YB1", MaxStudents = 6, LevelId = 3 });
  context.Classes.Add(new Class() { ClassName = "IELTS L1", MaxStudents = 40, LevelId = 14 });

Now what i want to do is something like this:

// ClassRoom schedules, links the class and classroom on a certain time
            context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = 1, Classrooms = 1 });

Another thing I tried was:

   context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = { Id = 1 }, Classrooms = { Id = 2 } });

However that does't work, also note that I cannot use new Classes() { Id = 1 }  as this will create a new entity.

Any help will be appreciated, Cheers!

Body:
You can add classrooms and classes to the collections in ClassSchedule:

var classRoom1 = new Classroom { ClassRoomName = "Cherry", MaxStudents = 20 };
var class1 = new Class { ClassName = "YR1", MaxStudents = 12, LevelId = 1 };
var classSchedule1 = new ClassSchedule { StartTime = ... };

classSchedule1.Classrooms.Add(classRoom1);
classSchedule1.Classess.Add(class1);

context.ClassSchedules.Add(classSchedule1);

etc.

That's the gist of it. Add classes and classrooms that belong to a schedule to the ClassSchedules collections and add the schedule to the context. Add classes and classrooms that don't belong to a schedule (yet) to the DbSets of the context.


问:
Force focus on input-field on click with angularjs
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

```<code><div data-ng-init="editMode = false">
    <p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
    <span data-ng-show="editMode">
       <input data-ng-blur="editMode = false" data-ng-model="color">
    </span>
  </div>
</code>```

Thanks in advance for your help!

答:
reference: Input autofocus attribute

angular.module('ng').directive('autoFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.autoFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.autoFocusLost ) ) {
                    scope.$apply( attrs.autoFocusLost );

                }
            });
        }
    };
});```

Body:
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

{{color}}

       <input data-ng-blur="editMode = false" data-ng-model="color">

Thanks in advance for your help!


问:
Trying to optimize my background changes, and trying to make them fade in
Just about finished my Weather Forecast page for my FCC challenge. I don't like how the code for swapping my bg works however. Feels wrong, but for the life of me I can't work out how to fix it. At the same time, it means I can't find a good way to make the bg fade in instead of flicking into existence. Any ideas?

https://codepen.io/EpicTriffid/pen/xrjxVE

$(document).ready(function() {

  var curUnit = "F";

  //Backgrounds

  var clearday = "url('https://static.pexels.com/photos/125457/pexels-photo-125457.jpeg')";
  var clearnight = "url('https://static.pexels.com/photos/355465/pexels-photo-355465.jpeg')";
  var rain = "url('https://static.pexels.com/photos/125510/pexels-photo-125510.jpeg')";
  var snow = "url('https://static.pexels.com/photos/41088/pexels-photo-41088.jpeg')";
  var sleet = "url('https://static.pexels.com/photos/27629/pexels-photo-27629.jpg')";
  var wind = "url('https://static.pexels.com/photos/6041/nature-grain-moving-cereal.jpg')";
  var fog = "url('https://static.pexels.com/photos/109037/pexels-photo-109037.jpeg')";
  var cloudy = "url('https://static.pexels.com/photos/158163/clouds-cloudporn-weather-lookup-158163.jpeg')";
  var partlycloudyday = "url('https://static.pexels.com/photos/152536/pexels-photo-152536.jpeg')";
  var partlycloudynight = "url('https://static.pexels.com/photos/23985/pexels-photo-23985.jpg')";

  //location API

  var darksky = 'https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/';

  var apikey = "15f8bf5641489ec32f66662221933c14";

  $("#myweather").load("window",function() {
      $.ajax({
        url: "https://geoip-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function(loc) {
          $("#location").load("window", function() {
              $("#location").html(loc.city).fadeIn(1000);
          });

          //Weather Summary

          $("#result").load("window", function() {
              $.getJSON(darksky + apikey + "/" + loc.latitude + "," + loc.longitude, function(forecast){
                $("#result").html(forecast.currently.summary).fadeIn(2000);

                //Skycon

                function addSkycon() {
                  var skycons = new Skycons({color: 'white'});
                  var skyconCanvas = document.getElementById("skycon");
                  skycons.add(skyconCanvas, forecast.currently.icon);
                  var iconsum = forecast.currently.icon
                  skycons.play();
                  $("#skycon").fadeIn(2000);
                  if(iconsum == "clear-day") {
                    document.body.style.backgroundImage = clearday;
                  }
                  else if(iconsum == "clear-night") {
                    document.body.style.backgroundImage = clearnight;
                  }
                  else if(iconsum == "rain") {
                    document.body.style.backgroundImage = rain;
                  }
                  else if(iconsum == "snow") {
                    document.body.style.backgroundImage = snow;
                  }
                  else if(iconsum == "sleet") {
                    document.body.style.backgroundImage = sleet;
                  }
                  else if(iconsum == "wind") {
                    document.body.style.backgroundImage = wind;
                  }
                  else if(iconsum == "fog") {
                    document.body.style.backgroundImage = fog;
                  }
                  else if(iconsum == "cloudy") {
                    document.body.style.backgroundImage = cloudy;
                  }
                  else if(iconsum == "partly-cloudy-day") {
                    document.body.style.backgroundImage = partlycloudyday;
                  }
                  else if(iconsum == "partly-cloudy-night") {
                    document.body.style.backgroundImage = partlycloudynight;
                  }
                } addSkycon();

                //Temperature

                $("#corf").load("window", function() {
                  $("#corf").fadeIn(2000);
                });

                var ftemp = Math.round(forecast.currently.temperature);
                var ctemp = Math.round((forecast.currently.temperature - 32) *
                                       (5 / 9))
                $("#temp").html(ftemp).fadeIn(2000);
                $("#corf").on("click", function() {
                  $("#temp").fadeOut(function() {
                    if (curUnit == "F") {
                      $("#temp").html(Math.round(ctemp));
                      $("#degreeswitch").html("&degc");
                      curUnit = "C";
                    }
                    else {
                      $("#temp").html(Math.round(ftemp));
                      $("#degreeswitch").html("&degf");
                      curUnit = "F";
                    }
                    $("#temp").fadeIn();
                  });
                });
              });
          });
        }
      });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#spacer {
  margin:0;
  padding:0;
  height:50px;
}
body {
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: auto;
  position: fixed;
  top: 0;
  left: 0;
  background-color:black;
  background-image:
}
.text {
  color:white;
  font-family:"raleway";
}
#myweather {
  margin-left:30px;
  margin-top:30px;
  font-size:5em;
}
#header {
  float:left;
  margin-left:20px;
}
#location {
  font-style: italic;
  color:white;
  margin-left:-200px;
  display:none;
}
#skycon {
  padding:30px;
  display:none;
}
#result {
  position:relative;
  padding-top:20px;
  padding-left:60px;
  display:none;
}
#temp {
  padding-left:60px;
  font-size:150px;
  display:none;
}
#corf {
  color:white;
  font-weight:bold;
  display:none;
  margin-left:-45px;
  margin-top:-30px;
}
#degreeswitch {
  font-family:"raleway";
}
#degreecon {
  margin-top:2%;
  margin-left:-2%;
}
#mark {
  text-align: center;
  font-family:"raleway";
  font-size: 20px;
  position: fixed;
  bottom: 0;
  width:100%;
  color: white;
}</code>```

  <link href="https://fonts.googleapis.com/css?family=Josefin+Slab" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Crimson+Text" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/climacons-fork/1.0.0/climacons.min.css" rel="stylesheet">

myWeather.

Weather for :

      <canvas id="skycon" width="300" height="300">
          </canvas>

      <svg id="corf">
        <text id="degreeswitch" x="31" y="67" fill="white" font-size="50px">&degf</text>
        <circle cx="50" cy="50" r="30" stroke="white" stroke-width="3" fill="transparent"/>
      </svg>

By Epic Triffid and powered by Darksky and GeoIP
```

Sorry, I also cant seem to get links to work :/

答:
I've solved it for you. Here is an updated CodePen: https://codepen.io/anon/pen/jwvELj

Basically, I've created a new element

 and made it fixed covering full-screen. I set the z-index of it to 0 and wrapped the rest of the content inside

 and set that z-index to 1. I've changed your if statements and instead of directly modifying the  tag's CSS with a background-image, I'm now setting a variable to the URL of the image.

Now is when the magic is happening. Here's the snippet

```<code>var bg = new Image();
bg.onload = function(){
   $('#background').css({'background-image': 'url('+imgUrl+')'});
   $('#background').addClass('visible');
}
bg.src = imgUrl;
</code>```

We're creating a new object of Image in JS and defining a function to be run when the image is loaded. The function sets the background image of #background and also adds a class visible to it. I've made the background invisible by default and set the class visible to give it opacity: 1;. This with a 1.5s transition makes up for a nice fade in effect. Hope this is what you're looking for.

Body:
Just about finished my Weather Forecast page for my FCC challenge. I don't like how the code for swapping my bg works however. Feels wrong, but for the life of me I can't work out how to fix it. At the same time, it means I can't find a good way to make the bg fade in instead of flicking into existence. Any ideas?

https://codepen.io/EpicTriffid/pen/xrjxVE

$(document).ready(function() {

  var curUnit = "F";

  //Backgrounds

  var clearday = "url('https://static.pexels.com/photos/125457/pexels-photo-125457.jpeg')";
  var clearnight = "url('https://static.pexels.com/photos/355465/pexels-photo-355465.jpeg')";
  var rain = "url('https://static.pexels.com/photos/125510/pexels-photo-125510.jpeg')";
  var snow = "url('https://static.pexels.com/photos/41088/pexels-photo-41088.jpeg')";
  var sleet = "url('https://static.pexels.com/photos/27629/pexels-photo-27629.jpg')";
  var wind = "url('https://static.pexels.com/photos/6041/nature-grain-moving-cereal.jpg')";
  var fog = "url('https://static.pexels.com/photos/109037/pexels-photo-109037.jpeg')";
  var cloudy = "url('https://static.pexels.com/photos/158163/clouds-cloudporn-weather-lookup-158163.jpeg')";
  var partlycloudyday = "url('https://static.pexels.com/photos/152536/pexels-photo-152536.jpeg')";
  var partlycloudynight = "url('https://static.pexels.com/photos/23985/pexels-photo-23985.jpg')";

  //location API

  var darksky = 'https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/';

  var apikey = "15f8bf5641489ec32f66662221933c14";

  $("#myweather").load("window",function() {
      $.ajax({
        url: "https://geoip-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function(loc) {
          $("#location").load("window", function() {
              $("#location").html(loc.city).fadeIn(1000);
          });

          //Weather Summary

          $("#result").load("window", function() {
              $.getJSON(darksky + apikey + "/" + loc.latitude + "," + loc.longitude, function(forecast){
                $("#result").html(forecast.currently.summary).fadeIn(2000);

                //Skycon

                function addSkycon() {
                  var skycons = new Skycons({color: 'white'});
                  var skyconCanvas = document.getElementById("skycon");
                  skycons.add(skyconCanvas, forecast.currently.icon);
                  var iconsum = forecast.currently.icon
                  skycons.play();
                  $("#skycon").fadeIn(2000);
                  if(iconsum == "clear-day") {
                    document.body.style.backgroundImage = clearday;
                  }
                  else if(iconsum == "clear-night") {
                    document.body.style.backgroundImage = clearnight;
                  }
                  else if(iconsum == "rain") {
                    document.body.style.backgroundImage = rain;
                  }
                  else if(iconsum == "snow") {
                    document.body.style.backgroundImage = snow;
                  }
                  else if(iconsum == "sleet") {
                    document.body.style.backgroundImage = sleet;
                  }
                  else if(iconsum == "wind") {
                    document.body.style.backgroundImage = wind;
                  }
                  else if(iconsum == "fog") {
                    document.body.style.backgroundImage = fog;
                  }
                  else if(iconsum == "cloudy") {
                    document.body.style.backgroundImage = cloudy;
                  }
                  else if(iconsum == "partly-cloudy-day") {
                    document.body.style.backgroundImage = partlycloudyday;
                  }
                  else if(iconsum == "partly-cloudy-night") {
                    document.body.style.backgroundImage = partlycloudynight;
                  }
                } addSkycon();

                //Temperature

                $("#corf").load("window", function() {
                  $("#corf").fadeIn(2000);
                });

                var ftemp = Math.round(forecast.currently.temperature);
                var ctemp = Math.round((forecast.currently.temperature - 32) *
                                       (5 / 9))
                $("#temp").html(ftemp).fadeIn(2000);
                $("#corf").on("click", function() {
                  $("#temp").fadeOut(function() {
                    if (curUnit == "F") {
                      $("#temp").html(Math.round(ctemp));
                      $("#degreeswitch").html("&degc");
                      curUnit = "C";
                    }
                    else {
                      $("#temp").html(Math.round(ftemp));
                      $("#degreeswitch").html("&degf");
                      curUnit = "F";
                    }
                    $("#temp").fadeIn();
                  });
                });
              });
          });
        }
      });
  });
});

#spacer {
  margin:0;
  padding:0;
  height:50px;
}
body {
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: auto;
  position: fixed;
  top: 0;
  left: 0;
  background-color:black;
  background-image:
}
.text {
  color:white;
  font-family:"raleway";
}
#myweather {
  margin-left:30px;
  margin-top:30px;
  font-size:5em;
}
#header {
  float:left;
  margin-left:20px;
}
#location {
  font-style: italic;
  color:white;
  margin-left:-200px;
  display:none;
}
#skycon {
  padding:30px;
  display:none;
}
#result {
  position:relative;
  padding-top:20px;
  padding-left:60px;
  display:none;
}
#temp {
  padding-left:60px;
  font-size:150px;
  display:none;
}
#corf {
  color:white;
  font-weight:bold;
  display:none;
  margin-left:-45px;
  margin-top:-30px;
}
#degreeswitch {
  font-family:"raleway";
}
#degreecon {
  margin-top:2%;
  margin-left:-2%;
}
#mark {
  text-align: center;
  font-family:"raleway";
  font-size: 20px;
  position: fixed;
  bottom: 0;
  width:100%;
  color: white;
}

  <link href="https://fonts.googleapis.com/css?family=Josefin+Slab" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Crimson+Text" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/climacons-fork/1.0.0/climacons.min.css" rel="stylesheet">

myWeather.

Weather for :

      <canvas id="skycon" width="300" height="300">
          </canvas>

      <svg id="corf">
        <text id="degreeswitch" x="31" y="67" fill="white" font-size="50px">&degf</text>
        <circle cx="50" cy="50" r="30" stroke="white" stroke-width="3" fill="transparent"/>
      </svg>

By Epic Triffid and powered by Darksky and GeoIP

Sorry, I also cant seem to get links to work :/

Body:
I've solved it for you. Here is an updated CodePen: https://codepen.io/anon/pen/jwvELj

Basically, I've created a new element <div id="background"></div> and made it fixed covering full-screen. I set the z-index of it to 0 and wrapped the rest of the content inside <div id="wrapper"></div> and set that z-index to 1. I've changed your if statements and instead of directly modifying the <body> tag's CSS with a background-image, I'm now setting a variable to the URL of the image.

Now is when the magic is happening. Here's the snippet

var bg = new Image();
bg.onload = function(){
   $('#background').css({'background-image': 'url('+imgUrl+')'});
   $('#background').addClass('visible');
}
bg.src = imgUrl;

We're creating a new object of Image in JS and defining a function to be run when the image is loaded. The function sets the background image of #background and also adds a class visible to it. I've made the background invisible by default and set the class visible to give it opacity: 1;. This with a 1.5s transition makes up for a nice fade in effect. Hope this is what you're looking for.


问:
How to stop .+ at the first instance of a character and not the last with regular expressions in perl?
I want to replace:

```<code>'''<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>'''
</code>```

With:

```<code>='''<font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now my existing code is:

```<code>$html =~ s/\n(.+)<font size=\".+?\">(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm
</code>```

However this ends up with this as the result:

```<code>=''' SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?

答:
Write .+? in all places to make each match non-greedy.

```
$html =~ s/\n(.+?)<font size=\".+?\">(.+?)<\/font>(.+?)\n/\n=$1$2$3=\n/gm
                ^                ^      ^            ^
```

Also try to avoid using regular expressions to parse HTML. Use an HTML parser if possible.

Body:
I want to replace:

''' SUMMER/WINTER CONFIGURATION FILES'''

With:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now my existing code is:

$html =~ s/\n(.+)(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm

However this ends up with this as the result:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?

Body:
Write .+? in all places to make each match non-greedy.

$html =~ s/\n(.+?)<font size=\".+?\">(.+?)<\/font>(.+?)\n/\n=$1$2$3=\n/gm
                ^                ^      ^            ^

Also try to avoid using regular expressions to parse HTML. Use an HTML parser if possible.