问:
Socket.io 404 Not Found
For some reason I keep getting "http://127.0.0.1:3000/socket.io/socket.io.js" 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.

Server:

```<code>var express = require('express'),
    session = require('express-session');

var app = express();

var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);

var sessionMiddleware = session({
    resave: false,
    saveUninitialized: false,
    secret: 'secret',
    store: new MongoStore({url: "mongodb://localhost:27017/database"})
});

app.use(sessionMiddleware);

io.use(sessionMiddleware, function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);
});

io.sockets.on('connection', function (socket) {
    console.log("Socket connected");
});

app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
   res.render('index');
});

app.listen(3000);
console.log('listening');
</code>```

Pug File:

```<code>html
    head
        script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
        script(type='text/javascript', src='../javascripts/chat.js')
    body
</code>```

Client javascript:

```<code>try {
    var socket = io.connect('http://127.0.0.1:3000');

} catch(e) {
    console.log(e);
}
</code>```

答:
Change this:

```<code>app.listen(3000);
</code>```

to:

```<code>server.listen(3000);
</code>```

app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.

See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:

websockets, express.js and can’t establish a connection to the server

Note, you could use app.listen(), but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:

```<code>var app = express();
var server = app.listen(3000);
var io = require('socket.io')(server);
</code>```

Which is not quite how your code is structured (but you could rearrange things to do it this way).

Title: Socket.io 404 Not Found

Body:
For some reason I keep getting "http://127.0.0.1:3000/socket.io/socket.io.js" 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.

Server:

var express = require('express'),
    session = require('express-session');

var app = express();

var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);

var sessionMiddleware = session({
    resave: false,
    saveUninitialized: false,
    secret: 'secret',
    store: new MongoStore({url: "mongodb://localhost:27017/database"})
});

app.use(sessionMiddleware);

io.use(sessionMiddleware, function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);
});

io.sockets.on('connection', function (socket) {
    console.log("Socket connected");
});

app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
   res.render('index');
});

app.listen(3000);
console.log('listening');

Pug File:

html
    head
        script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
        script(type='text/javascript', src='../javascripts/chat.js')
    body

Client javascript:

try {
    var socket = io.connect('http://127.0.0.1:3000');

} catch(e) {
    console.log(e);
}

Body:
Change this:

app.listen(3000);

to:

server.listen(3000);

app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.

See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:

websockets, express.js and can’t establish a connection to the server

Note, you could use app.listen(), but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:

var app = express();
var server = app.listen(3000);
var io = require('socket.io')(server);

Which is not quite how your code is structured (but you could rearrange things to do it this way).


来源: stackexchange

问:
HTML Search element styling
I´m trying to build a search element together with a button, something like:

Except that I need to change the background color of the search icon (blue, gray, whatever...).

Here is my code so far and the result:

.searchWrap {
  position: absolute;
  border: thin solid #f2f2f2;
  border-radius: 5px;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 20px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 5px;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className="searchWrap">
  <input type="text" className="searchTerm" placeholder="Search..." />
  <button type="submit" className="searchButton">
          <Icon name='search' />
       </button>
</div></code>```

I'm using React. Here is my result so far:

The external border is rounded, ok, that's what I need, but the separation between the searchTerm and the searchButton is also rounded, and I need a plain separator here, something like:

答:
Try this for the search button css instead of border-radius

```<code>.searchButton {
    ...
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: HTML Search element styling

Body:
I´m trying to build a search element together with a button, something like:

Except that I need to change the background color of the search icon (blue, gray, whatever...).

Here is my code so far and the result:

.searchWrap {
  position: absolute;
  border: thin solid #f2f2f2;
  border-radius: 5px;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 20px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 5px;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
}

  <input type="text" className="searchTerm" placeholder="Search..." />
  <button type="submit" className="searchButton">
          <Icon name='search' />
       </button>

I'm using React. Here is my result so far:

The external border is rounded, ok, that's what I need, but the separation between the searchTerm and the searchButton is also rounded, and I need a plain separator here, something like:

Body:
Try this for the search button css instead of border-radius

.searchButton {
    ...
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    ...
}

ContentLicense: CC BY-SA 3.0


问:
When I deploy my R shiny app to shinyapps.io, I get 'Error: oauth_listener() needs an interactive environment'. How can I fix this?
The app is designed to scrap twitter for word frequencies for a given search term, and then create a word cloud based on the frequencies. It works when I run it on my local machine. The following is the source code:</p>

```<code>library(shiny)

library(twitteR)

library(wordcloud)

library(tm)

twitter_key<-"XXX"

twitter_secret<-"XXX"

oauth<-setup_twitter_oauth(twitter_key, twitter_secret)

ui = shinyUI(fluidPage(

titlePanel("Twitter Wordcloud"),

textInput("text", label = h3("Search term:"), value = "president"),

actionButton("goButton", "Search"),

hr(),

mainPanel(

plotOutput("distPlot")

)

))

server = function(input, output) {

output$distPlot <- renderPlot({

input$goButton

isolate({

mach_tweets = searchTwitter(input$text, n=200, lang="en")

mach_text = sapply(mach_tweets, function(x) x$getText())

mach_text = sapply(mach_text,function(row) iconv(row, "latin1", "ASCII",          sub=""))

mach_text = gsub(" https.*","",mach_text)

mach_corpus = Corpus(VectorSource(mach_text))

tdm = TermDocumentMatrix(mach_corpus,

control = list(removePunctuation = TRUE,

stopwords = c(input$text, stopwords("english")),

removeNumbers = TRUE, tolower = TRUE))

m = as.matrix(tdm)

word_freqs = sort(rowSums(m), decreasing=TRUE)

dm = data.frame(word=names(word_freqs), freq=word_freqs)

wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2"))

})

})

}

shinyApp(ui, server)
</code>```

答:
I had the same issue

Run the next line of code in the Console, but first make sure that the .httr-oauth file that setup_twitter_oauthcreates is in the same directory that ui.R and server.R are.

```<code>    rsconnect::deployApp(appDir = getwd(),appFiles = NULL)
</code>```

What it does is that its deploy all files in the working Directory, including the .httr-oauth file that is the key here.

Body:
The app is designed to scrap twitter for word frequencies for a given search term, and then create a word cloud based on the frequencies. It works when I run it on my local machine. The following is the source code:

library(shiny)

library(twitteR)

library(wordcloud)

library(tm)

twitter_key<-"XXX"

twitter_secret<-"XXX"

oauth<-setup_twitter_oauth(twitter_key, twitter_secret)

ui = shinyUI(fluidPage(

titlePanel("Twitter Wordcloud"),

textInput("text", label = h3("Search term:"), value = "president"),

actionButton("goButton", "Search"),

hr(),

mainPanel(

plotOutput("distPlot")

)

))

server = function(input, output) {

output$distPlot <- renderPlot({

input$goButton

isolate({

mach_tweets = searchTwitter(input$text, n=200, lang="en")

mach_text = sapply(mach_tweets, function(x) x$getText())

mach_text = sapply(mach_text,function(row) iconv(row, "latin1", "ASCII",          sub=""))

mach_text = gsub(" https.*","",mach_text)

mach_corpus = Corpus(VectorSource(mach_text))

tdm = TermDocumentMatrix(mach_corpus,

control = list(removePunctuation = TRUE,

stopwords = c(input$text, stopwords("english")),

removeNumbers = TRUE, tolower = TRUE))

m = as.matrix(tdm)

word_freqs = sort(rowSums(m), decreasing=TRUE)

dm = data.frame(word=names(word_freqs), freq=word_freqs)

wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2"))

})

})

}

shinyApp(ui, server)

Body:
I had the same issue

Run the next line of code in the Console, but first make sure that the .httr-oauth file that setup_twitter_oauthcreates is in the same directory that ui.R and server.R are.

    rsconnect::deployApp(appDir = getwd(),appFiles = NULL)

What it does is that its deploy all files in the working Directory, including the .httr-oauth file that is the key here.


问:
Facebook Stream.GetComments is empty
I am using Facebook Toolkit (the old REST API LIB).
I have 2 users with comments in FB.
both have the right permissions for my application.
When I launch Stream.Getcomments I get empty result in one user, and in the other one I get good result.

I tried using the FQL and it still returns empty. When using Facebook FQL test console they offer on their site - it is working ok.

What can it be?

Thanks

答: The Facebook Toolkit is pretty much dead and has a number of bugs. I would suggest switching to the newer Facebook C# SDK. You can find info about that here: http://facebooksdk.codeplex.com/ and here: http://microsoft.com/facebook</p>

ContentLicense: CC BY-SA 2.5

Title: Facebook Stream.GetComments is empty


答:
I'm using font awesome here, so the code isn't spaced like your screenshot, but looks like you have your own library you're using with react for that icon and your spacing is fine.

All you need to do is use border-radius: 0 5px 5px 0 to keep the left side borders from rounding, and assign a border-left on the .searchButton to draw the vertical line. I changed the border color so it's more prominent, but you can use whatever color you want.

*{margin:0;padding:0;}
.searchWrap {
  position: absolute;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
  margin-left: 3px;
  border: thin solid #ddd;
  border-width: thin 0 thin thin;
  border-radius: 5px 0 0 5px;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 32px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 0 5px 5px 0;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
  border: thin solid #ddd;
}

.searchTerm:focus, .searchTerm:focus + .searchButton {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="searchWrap">
    <input type="text" class="searchTerm" placeholder="Search..." />
    <button type="submit" class="searchButton">
      <i class="fa fa-search"></i>
   </button>
 </div></code>```

Title: HTML Search element styling

Body:
I'm using font awesome here, so the code isn't spaced like your screenshot, but looks like you have your own library you're using with react for that icon and your spacing is fine.

All you need to do is use border-radius: 0 5px 5px 0 to keep the left side borders from rounding, and assign a border-left on the .searchButton to draw the vertical line. I changed the border color so it's more prominent, but you can use whatever color you want.

*{margin:0;padding:0;}
.searchWrap {
  position: absolute;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
  margin-left: 3px;
  border: thin solid #ddd;
  border-width: thin 0 thin thin;
  border-radius: 5px 0 0 5px;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 32px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 0 5px 5px 0;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
  border: thin solid #ddd;
}

.searchTerm:focus, .searchTerm:focus + .searchButton {
  border-color: red;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="searchWrap">
    <input type="text" class="searchTerm" placeholder="Search..." />
    <button type="submit" class="searchButton">
      <i class="fa fa-search"></i>
   </button>
 </div>


问:
Multiple Submit Form Without Reload
I was just wondering if its possible to have a loop of submit forms and then submit from any of these submit forms without refreshing/reloading the entire page.

The reason why I wanna know is because, I am currently working on a website and what I wanna do is for users to be able to press like if they like a picture/message (like a tweet on twitter och an image on instagram) but as of right now, when you press the like button, it refreshes the entire page if I do a simple @using (html.beginform("","")) but if I use jquery, then it only works on the last form (the one at the top)

```<code>$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $('#submit-buttons').val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="submit"></button>
</code>```

submit-buttons is the like buttons, and what it does is, it takes the value (an id) and passes it to a controller and then inserts it to a database. but there are several of these buttons but only 1 works (the one that was looped last). what have I done wrong? :/

Please help.
Thanks!

答:
Try using a class for the buttons as the id's must be unique</p>

```<code>$(document).ready(function () {
    $(".submit-buttons").on('click', function () {
        var id = $(this).val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-button1" class="submit-buttons" name="id" value="@item.Id" type="submit"></button>
</code>```

Title: Multiple Submit Form Without Reload

Body:
I was just wondering if its possible to have a loop of submit forms and then submit from any of these submit forms without refreshing/reloading the entire page.

The reason why I wanna know is because, I am currently working on a website and what I wanna do is for users to be able to press like if they like a picture/message (like a tweet on twitter och an image on instagram) but as of right now, when you press the like button, it refreshes the entire page if I do a simple @using (html.beginform("","")) but if I use jquery, then it only works on the last form (the one at the top)

$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $('#submit-buttons').val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="submit"></button>

submit-buttons is the like buttons, and what it does is, it takes the value (an id) and passes it to a controller and then inserts it to a database. but there are several of these buttons but only 1 works (the one that was looped last). what have I done wrong? :/

Please help.
Thanks!

Body:
Try using a class for the buttons as the id's must be unique

$(document).ready(function () {
    $(".submit-buttons").on('click', function () {
        var id = $(this).val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-button1" class="submit-buttons" name="id" value="@item.Id" type="submit"></button>


问:
Pointer arithmetic using cast to "wrong" type
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

```<code>#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}
</code>```

Here's a test driver:

```<code>#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}
</code>```

Both approaches produce the expected results:

```<code>0 0 0 0
1 1 1 1
2 2 2 2
</code>```

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

```<code>vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax
</code>```

答:
vertex_b is completely fine. You only maybe need to refine return offset / sizeof(xyz); since you're dividing std::ptrdiff_t with std::size_t and implicitly casting the result into int.
By book, this behavior is implementation defined. std::ptrdiff_t is signed and std::size_t unsigned and result of division might be larger than INT_MAX (very unlikely) with huge array size on some platforms/compilers.

To cast away your worries, you can put assert()s and/or #errors which check PTRDIFF_MIN, PTRDIFF_MAX, SIZE_MAX, INT_MIN and INT_MAX, but I personally would not bother so much.

Body:
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}

Here's a test driver:

#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}

Both approaches produce the expected results:

0 0 0 0
1 1 1 1
2 2 2 2

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax


问:
Mobile Device Managed Single App Devices
I like to have single android app in our managed devices, we want only that app to be used on the device with necessary restriction, such that,

Single use - Device will have only one app, user can't use other apps, like browsing, youtube or anything,

the initial setting like notification sound, GPS always on, notification and ring sound maximum level can't be modified.

user can not power off the device.

this setting can only be changed by our servers.

i think i have 2 option,

1) Using samsung knox sdk on samsung devices,
 Here's MDM proving feature of Samsung Knox Standard!

2) General Android way, Set up Single-Purpose Devices, COSU solution
Android Developer's site.

Wanted to know your's view on this, may be if you guys have done any of the two or any other ways, i could use some of the guidelines or a path.

Thanks for reading, and please comment if i was unable to articulate the subject or it needs editing.

答:
I have broad experience of using Samsung Kiosk Mode from Knox Standard SDK which is free and Pro-Kiosk mode from Knox Customization SDK (which has more functions but is not free).

So I can tell you for sure that all 4 points that you have mentioned can be achieved by using Knox Standard SDK.

Singe Purpose: https://seap.samsung.com/api-references/android-standard/reference/android/app/enterprise/kioskmode/KioskMode.html

LocationPolicy (you can turn on GPS and restrict changing): https://seap.samsung.com/api-references/android-standard/reference/android/app/enterprise/LocationPolicy.html

Yes. It is possible but I forgot the exact implementation.

Yes, as well.

Only downside of using this SDK is:

You are tied to Samsung (which I personally okay with, since Samsung has such market penetration and you could get service almost anywhere in the world and in enterprise world it is critical)

About Android native functionality: never tried it

Update March 7, 2019: Now I am playing around Device Owner, we use it for Kiosk mode, works well and works on android Device with Nougat and earlier.


问:
Why is class constraint not detected for generic class using an inherited type?
Phrasing the question was hard, I hope the following code snippet makes things clear:

```<code>public class DemoClass<TBase> where TBase : class
{
    public void DemoMethod<T>(T target) where T : TBase
    {
        //The following line causes a design-time error: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T'.
        WeakReference<T> demoRef = new WeakReference<T>(target);
    }
}
</code>```

The WeakReference requires a type, T, that satisfies a class constraint. So far, so good, but...

Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

答:
Let’s check the documentation on what T : class actually means:

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

Unfortunately, this is already satisfied if T is for example an interface. So you can construct a simple example where you can see that applying T : class transitively will not work:

```<code>public interface ITest { }
public struct Test : ITest { }
</code>```

If you now create a DemoClass<ITest>, you are satisfying the type constraint since ITest is a “class” here. But when you call the method DemoMethod<Test>, then you do not have a reference type for T although Test does inherit ITest.

In general, those special generic type constraints do not follow the rules of inheritance. That is why they are defined separately and are not already established by the type system. They are there as a special syntax because the type system is not able to express the constaints otherwise.

Body:
Phrasing the question was hard, I hope the following code snippet makes things clear:

public class DemoClass<TBase> where TBase : class
{
    public void DemoMethod<T>(T target) where T : TBase
    {
        //The following line causes a design-time error: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T'.
        WeakReference<T> demoRef = new WeakReference<T>(target);
    }
}

The WeakReference requires a type, T, that satisfies a class constraint. So far, so good, but...

Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

Body:
Let’s check the documentation on what T : class actually means:

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

Unfortunately, this is already satisfied if T is for example an interface. So you can construct a simple example where you can see that applying T : class transitively will not work:

public interface ITest { }
public struct Test : ITest { }

If you now create a DemoClass<ITest>, you are satisfying the type constraint since ITest is a “class” here. But when you call the method DemoMethod<Test>, then you do not have a reference type for T although Test does inherit ITest.

In general, those special generic type constraints do not follow the rules of inheritance. That is why they are defined separately and are not already established by the type system. They are there as a special syntax because the type system is not able to express the constaints otherwise.


答:
Bootstrap is strongly recommended for this. See http://getbootstrap.com/components/#input-groups.  Coupled with FontAwesome, you could do something like this:</p>

```<code><div class="input-group">
  <input type="text" class="form-control" placeholder="Search for...">
  <span class="input-group-btn">
    <button class="btn btn-default" type="button">
      <span class="fa fa-search"></span>
      <span class="sr-only">Search</span>
    </button>
  </span>
</div>
</code>```

Title: HTML Search element styling

Body:
Bootstrap is strongly recommended for this. See http://getbootstrap.com/components/#input-groups.  Coupled with FontAwesome, you could do something like this:

<div class="input-group">
  <input type="text" class="form-control" placeholder="Search for...">
  <span class="input-group-btn">
    <button class="btn btn-default" type="button">
      <span class="fa fa-search"></span>
      <span class="sr-only">Search</span>
    </button>
  </span>
</div>


问:
GET Requests vs JavaScript
Alright, I have a JavaScript doing HTTP Requests to a PHP file onto the same directory. Then it's returning it's output.

Let's say there are over 50+ people doing this request simultaneously ... will it slow down anything? Yes, this may seem like a dumb question - but sorry. :|

Thank you.

答: Depends on several factors. Are you caching your pages? this would speed up page rendering. how fast is the actual riddle.php script, is the DB interaction that could get bogged down? what is the capacity/memory of the server you files are hosted on, what is the connection speed to that server? how much data are you rendering back? all these things figure into your answer. The best thing to do is actually write something to simulate your expected load and check your results.</p>

Title: GET Requests vs JavaScript


问:
Android - Switching between Activities and Screens with same xml file
I'm building an app for educational purposes, with a lot of questions and challenges to the user to solve. But, it would be a HUGE amount of screens if I create a lot of questions and one xml file and activity for each one, as I want to have different kinds of questions, where the user should be able to write the code, select a block of code or select the correct answer about theory and stuff. Is there a way to use the same model of screen(xml file) for one specific kind of question? Like, using one model to all the screens and questions where the user should select the correct answer, and another model to another kind of question..

p.s: Yes, i'm kind newbie in Android

Thanks! :)

答: You can define all kinds of questions, such as checkboxes, radioButtons, Edittexts and etc. in a xml file and, if necessary, visible or hide them.</p>


问:
Is malloc'd data zeroed in objective c?
I was wondering about this because it's a potential security hole if process A can malloc 50 megs of data that is not zero'd out and that chunk of memory turns out to include what had been physical pages from process B and still contain process B's data.</p>

答:
Is malloc'd data zeroed in objective c?

Mostly Yes. There's a zero-page writer that is part of the memory manager which provides a process with zero'd pages. The memory manager will call memory_object_data_unavailable to tell the kernel to supply zero-filled memory for the region.

If the process calls free and then mallocs again, the page is not re-zero'd. Zeroization only occurs when a new page is demanded. In fact, the page is probably not returned to the system upon free. The process retains the page for its own use due to the runtime. Related, see Will malloc implementations return free-ed memory back to the system?

If a page is returned to the system under a low-memory condition, the the page will be re-zero'd even if the process formerly held the page. The memory manager does not account for last owner of a page. It just assumes a new page needs to be zero'd to avoid an information leak across processes.

Note Microsoft calls it the zero-page writer. Darwin has the same component, but I don't recall seeing it named. Also see Mac OS X Internals: A Systems Approach by Singh. Its a bit dated, but it provides a lot of system information. Chapter 8, Memory, is the chapter of interest.

Singh's book goes into other details, like cases where a page is demanded but does not need to be zeroized. In this case, there was some shared data among processes, and a new page was allocated to the process under a Copy-on-Write (COW) scheme. Effectively, the new page was populated from existing data rather than zero's. The function of interest is memory_object_data_request.

Linux has an interesting discussion of the zero page at Some ado about zero. Its interesting reading about a topic that seems mundane on the surface.

Title: Is malloc'd data zeroed in objective c?


问:
Format number in typescript map
I am new in typescript and my question is how to format data in map?
Output is map of numbers like 24150, 12012, 36012, 300124 and I want to show it like 24 150, 12 012, 36 012, 300 124. I need to separate thousand.</p>

```<code> let koopMap = coefsCopy.map(innerMap =>
    innerMap.map(value => value * area)
  );
</code>```

答:
You want to transform 24150 to  24 150. Assuming the original is a number you would:

```<code>let foo = 24150;
let bar =  foo.toString().substring(0, foo.toString().length - 3) + ' ' + foo.toString().substr(-3); // '24 150'
</code>```

For mapping in an array use map : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Title: Format number in typescript map

Body:
I am new in typescript and my question is how to format data in map?
Output is map of numbers like 24150, 12012, 36012, 300124 and I want to show it like 24 150, 12 012, 36 012, 300 124. I need to separate thousand.

 let koopMap = coefsCopy.map(innerMap =>
    innerMap.map(value => value * area)
  );

Body:
You want to transform 24150 to  24 150. Assuming the original is a number you would:

let foo = 24150;
let bar =  foo.toString().substring(0, foo.toString().length - 3) + ' ' + foo.toString().substr(-3); // '24 150'

For mapping in an array use map : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map


问:
Make mxgraph open an xml automatically
I am trying to make this app open with an xml file (empty one if no file exists) and when I close it, it saves it automatically to that same location.

I have the source code and I have been trying to figure it out but without any luck. For example EditorUi.js, line 3029 is where it opens files, but doesn't help me much. It might be important to say I have never worked in such a project and I'm pretty much new to javascript programming.

Source Code: http://jgraph.github.io/mxgraph/javascript/

答:
Take a look at my anser for this question:
Opening local files in MxGraph via urlParam

If it doesn't guide you the way feel free to ask a more precise question!

Title: Make mxgraph open an xml automatically


问:
How can I grant access to array of admins on Firebase database rules
I am stuck trying to allow an an array of admins access to their data.
I have a database structure like this:

```<code>{
    "Respondents": {
        "Acme Corp": {
            "admins": ["mMK7eTrRL4UgVDh284HntNRETmx1", ""mx1TERNmMK7eTrRL4UgVDh284Hnt"],
            "data": {data goes here...}
        },
        "Another Inc": {
            "admins": ["Dh284HmMK7eTrRL4UgVDh284HntN", ""x1TERNmx1TERNmMK7eTrRL4UgVDh"],
            "data": {their data goes here...}
        }
    }
}
</code>```

And then I tried to set my rules like this

```<code>{
  "rules": {
    "Respondents": {
      "$organisation" : {
        ".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)",
        ".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)"
      }
    }
  }
}
</code>```

..but that won't parse in the Firebase Database Rules editor
I get "Error saving rules - Line 7: No such method/property 'includes'", but I need something to match the user id with the array of admins.
Any experience or suggestions?

答:
As you've found, there is no includes() operation in Firebase's security rules. This is because Firebase doesn't actually store the data as an array. If you look in the Firebase Database console or read this blog post you will see that Firebase stores it as a regular object:

```<code>"admins": {
  "0": "mMK7eTrRL4UgVDh284HntNRETmx1",
  "1": "mx1TERNmMK7eTrRL4UgVDh284Hnt"
}
</code>```

And since that is a regular JavaScript object, there is no contains() method on it.

In general creating arrays are an anti-pattern in the Firebase Database. They're often the wrong data structure and when used are regularly the main cause of scalability problems.

In this case: you're not really looking to store a sequence of UIDs. In fact: the order of the UIDs doesn't matter, and each UID can be meaningfully present in the collection at most once. So instead of an array, you're looking to store set of uids.

To implement a set in Firebase, you use this structure:

```<code>"admins": {
  "mMK7eTrRL4UgVDh284HntNRETmx1": true,
  "mx1TERNmMK7eTrRL4UgVDh284Hnt": true
}
</code>```

The value doesn't matter much. But since you must have a value to store a key, it is idiomatic to use true.

Now you can test whether a key with the relevant UID exists under admins (instead of checking whether it contains a value):

```<code>"root.child('Respondents').child($organisation).child('admins').child(auth.uid).exists()",
</code>```

Body:
I am stuck trying to allow an an array of admins access to their data.
I have a database structure like this:

{
    "Respondents": {
        "Acme Corp": {
            "admins": ["mMK7eTrRL4UgVDh284HntNRETmx1", ""mx1TERNmMK7eTrRL4UgVDh284Hnt"],
            "data": {data goes here...}
        },
        "Another Inc": {
            "admins": ["Dh284HmMK7eTrRL4UgVDh284HntN", ""x1TERNmx1TERNmMK7eTrRL4UgVDh"],
            "data": {their data goes here...}
        }
    }
}

And then I tried to set my rules like this

{
  "rules": {
    "Respondents": {
      "$organisation" : {
        ".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)",
        ".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)"
      }
    }
  }
}

..but that won't parse in the Firebase Database Rules editor
I get "Error saving rules - Line 7: No such method/property 'includes'", but I need something to match the user id with the array of admins.
Any experience or suggestions?

Body:
As you've found, there is no includes() operation in Firebase's security rules. This is because Firebase doesn't actually store the data as an array. If you look in the Firebase Database console or read this blog post you will see that Firebase stores it as a regular object:

"admins": {
  "0": "mMK7eTrRL4UgVDh284HntNRETmx1",
  "1": "mx1TERNmMK7eTrRL4UgVDh284Hnt"
}

And since that is a regular JavaScript object, there is no contains() method on it.

In general creating arrays are an anti-pattern in the Firebase Database. They're often the wrong data structure and when used are regularly the main cause of scalability problems.

In this case: you're not really looking to store a sequence of UIDs. In fact: the order of the UIDs doesn't matter, and each UID can be meaningfully present in the collection at most once. So instead of an array, you're looking to store set of uids.

To implement a set in Firebase, you use this structure:

"admins": {
  "mMK7eTrRL4UgVDh284HntNRETmx1": true,
  "mx1TERNmMK7eTrRL4UgVDh284Hnt": true
}

The value doesn't matter much. But since you must have a value to store a key, it is idiomatic to use true.

Now you can test whether a key with the relevant UID exists under admins (instead of checking whether it contains a value):

"root.child('Respondents').child($organisation).child('admins').child(auth.uid).exists()",


问:
issue with FILE
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

```<code>FILE          *fp[] = {stdout, dump_f};
</code>```

is this acceptable? what is the proper way to achive this?

答:
Classically, most Unix systems used to define stdout as something like (&_iob[1]), which reduced to a valid constant expression; Solaris, for instance, still does.

A few years ago, now, the GNU C Library changed its definition of stdout to something that was not a constant, so old code which used to initialize FILE * variables to any of the standard file pointers ceased to compile.  This is sanctioned by the C standard, so there is no virtue in complaining.  You simply have to accept that you cannot initialize static file pointers to one of the standard I/O channels and recode to get around the problem.  (But it is still a nuisance.)

OwnerDisplayName: Thi

Title: issue with FILE

Body:
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

FILE          *fp[] = {stdout, dump_f};

is this acceptable? what is the proper way to achive this?

LastEditorDisplayName: strager

OwnerDisplayName: Jonathan Leffler


问:
Memory Usuage Between Data Types in Python
I'm trying to figure out why an int8 uses more memory than a float data type. Shouldn't it less since it should only be using 1 byte of memory. </p>

```<code>import numpy as np
import sys

In [32]: sys.getsizeof(np.int8(29.200))
Out[32]: 25

In [33]: sys.getsizeof(np.int16(29.200))
Out[33]: 26

In [34]: sys.getsizeof(np.int32(29.200))
Out[34]: 28

In [35]: sys.getsizeof(np.float(29.200))
Out[35]: 24

In [36]: sys.getsizeof(np.float32(29.200))
Out[36]: 28

In [37]: sys.getsizeof(np.float64(29.200))
Out[37]: 32
</code>```

答:
Using getsizeof on isolated np.types like this isn't very informative.

np.int8(...) is an object that includes not just the data byte, but various numpy attributes.  It's similar to a np.array(123, dtype=int8).  In other words the array overhead is larger than the data storage itself.

It's more useful to look at the size of np.ones((1000,), dtype=np.int8) etc.  That getsize will have show the 1000 data bytes, plus an array 'overhead'.

```<code>In [31]: sys.getsizeof(np.int8(123))
Out[31]: 13
In [32]: sys.getsizeof(np.int16(123))   # 1 more byte
Out[32]: 14
In [33]: sys.getsizeof(np.int32(123))   # 2 more bytes
Out[33]: 16
In [34]: sys.getsizeof(np.int64(123))   # 4 more bytes
Out[34]: 24
In [35]: sys.getsizeof(123)
Out[35]: 14
</code>```

For these arrays there's a 48 bytes overhead, and then 1000 elements:

```<code>In [36]: sys.getsizeof(np.ones(1000, np.int8))  # 1 byte each
Out[36]: 1048
In [37]: sys.getsizeof(np.ones(1000, np.int16))  # 2 bytes each
Out[37]: 2048

In [38]: np.ones(1000, np.int8).itemsize  # np.int8(123).itemsize
Out[38]: 1
In [39]: np.ones(1000, np.int16).itemsize
Out[39]: 2
</code>```

Body:
I'm trying to figure out why an int8 uses more memory than a float data type. Shouldn't it less since it should only be using 1 byte of memory.

import numpy as np
import sys

In [32]: sys.getsizeof(np.int8(29.200))
Out[32]: 25

In [33]: sys.getsizeof(np.int16(29.200))
Out[33]: 26

In [34]: sys.getsizeof(np.int32(29.200))
Out[34]: 28

In [35]: sys.getsizeof(np.float(29.200))
Out[35]: 24

In [36]: sys.getsizeof(np.float32(29.200))
Out[36]: 28

In [37]: sys.getsizeof(np.float64(29.200))
Out[37]: 32

Body:
Using getsizeof on isolated np.types like this isn't very informative.

np.int8(...) is an object that includes not just the data byte, but various numpy attributes.  It's similar to a np.array(123, dtype=int8).  In other words the array overhead is larger than the data storage itself.

It's more useful to look at the size of np.ones((1000,), dtype=np.int8) etc.  That getsize will have show the 1000 data bytes, plus an array 'overhead'.

In [31]: sys.getsizeof(np.int8(123))
Out[31]: 13
In [32]: sys.getsizeof(np.int16(123))   # 1 more byte
Out[32]: 14
In [33]: sys.getsizeof(np.int32(123))   # 2 more bytes
Out[33]: 16
In [34]: sys.getsizeof(np.int64(123))   # 4 more bytes
Out[34]: 24
In [35]: sys.getsizeof(123)
Out[35]: 14

For these arrays there's a 48 bytes overhead, and then 1000 elements:

In [36]: sys.getsizeof(np.ones(1000, np.int8))  # 1 byte each
Out[36]: 1048
In [37]: sys.getsizeof(np.ones(1000, np.int16))  # 2 bytes each
Out[37]: 2048

In [38]: np.ones(1000, np.int8).itemsize  # np.int8(123).itemsize
Out[38]: 1
In [39]: np.ones(1000, np.int16).itemsize
Out[39]: 2


问:
Check if app is installed from webpage
I have an iOS and Android app and I'm building a corresponding website. I would like that the webpage, if opened using a mobile device, opens the app or its corresponding app store page (without using Facebook app links).
On the app side everything is working, including the url schema.

Does someone know how to implement this procedure, without external services, using HTML and JS?

Thanks in advance for your help.

答:
To be honest, this is kind of a pain to implement on your own. There is no easy way to handle everything without a ton of nasty edge cases, most notably the 'Cannot Open Page" error users will see if they don't have your app installed. Until iOS 9, a reasonable basic implementation was putting a JavaScript redirect like this into a dedicated redirect page on your site:

```<code>setTimeout(function() {
  window.location = "https://yourdomain.com";
}, 25);

// If "yourapp://" is registered, the user will see a dialog
// asking if they want to open your app. If they agree, your
// app will launch immediately and the timer won't fire.
// If not installed, you'll get an ugly "Cannot Open Page"
// dialogue and your fallback page will open when the timer expires.

window.location = "yourapp://";
</code>```

Unfortunately this would still show a 'Cannot Open Page' error, but until recently it was possible to get around this in a reasonably user-friendly way by using a more nuanced version of this script. Sadly, Apple intentionally broke that with the iOS 9.2 update, so custom URL schemes are actually pretty much useless for deep linking now, unless you are certain the app is already installed on that device.

Apple is obviously trying to push the newer Universal Links standard as much as possible. Universal Links lets you use a normal http:// URL to a page on your website (the page could be a simple redirection to your desired fallback webpage without the custom URL trigger that causes the 'Cannot Open Page' error), which is intercepted by your phone and sent directly into your app if installed.

This is quite a lot to handle, so the best option might be a free service like Branch.io (full disclosure: I work with the team) to take care of all the technical aspects. You can find examples of apps using the Branch service here.

Title: Check if app is installed from webpage

Body:
To be honest, this is kind of a pain to implement on your own. There is no easy way to handle everything without a ton of nasty edge cases, most notably the 'Cannot Open Page" error users will see if they don't have your app installed. Until iOS 9, a reasonable basic implementation was putting a JavaScript redirect like this into a dedicated redirect page on your site:

setTimeout(function() {
  window.location = "https://yourdomain.com";
}, 25);

// If "yourapp://" is registered, the user will see a dialog
// asking if they want to open your app. If they agree, your
// app will launch immediately and the timer won't fire.
// If not installed, you'll get an ugly "Cannot Open Page"
// dialogue and your fallback page will open when the timer expires.

window.location = "yourapp://";

Unfortunately this would still show a 'Cannot Open Page' error, but until recently it was possible to get around this in a reasonably user-friendly way by using a more nuanced version of this script. Sadly, Apple intentionally broke that with the iOS 9.2 update, so custom URL schemes are actually pretty much useless for deep linking now, unless you are certain the app is already installed on that device.

Apple is obviously trying to push the newer Universal Links standard as much as possible. Universal Links lets you use a normal http:// URL to a page on your website (the page could be a simple redirection to your desired fallback webpage without the custom URL trigger that causes the 'Cannot Open Page' error), which is intercepted by your phone and sent directly into your app if installed.

This is quite a lot to handle, so the best option might be a free service like Branch.io (full disclosure: I work with the team) to take care of all the technical aspects. You can find examples of apps using the Branch service here.


问:
how to make input disabled in react using bootstrap?
I have 2 inputs on the form. I am using React.js and Twitter Bootstrap.

The intended behavior is:

When an input is typed in on either of the form input fields, another input field should not accept any input (or be disabled).

I am using FormControl from Bootstrap.

How should I achieve this in this React.js/Bootstrap setting?

答:
You have to use disabled property. You can do something like this:

```<code>class MyForm extends React.Component{
  constructor(){
    super();
    this.state = {
      focused: undefined,
    }
  }
  onFocus(id){
    this.setState({
      focused: id
    });
  }
  onBlur(){
    this.setState({
      focused: undefined,
    });
  }
  render(){
    const { focused } = this.state;
    return (
        <div>
          <FormGroup>
            <FormControl type="text" onFocus={() => this.onFocus(1)} onBlur={this.onBlur} disabled={focused && focused !== 1}/>
            <FormControl type="text" onFocus={() => this.onSecondFocus(2)} onBlur={this.onBlur} disabled={focused && focused !== 2}/>
          </FormGroup>
        </div>
    );
  }
}

export default MyForm;
</code>```

https://codesandbox.io/s/yPBvrOvKg

Body:
You have to use disabled property. You can do something like this:

class MyForm extends React.Component{
  constructor(){
    super();
    this.state = {
      focused: undefined,
    }
  }
  onFocus(id){
    this.setState({
      focused: id
    });
  }
  onBlur(){
    this.setState({
      focused: undefined,
    });
  }
  render(){
    const { focused } = this.state;
    return (
        <div>
          <FormGroup>
            <FormControl type="text" onFocus={() => this.onFocus(1)} onBlur={this.onBlur} disabled={focused && focused !== 1}/>
            <FormControl type="text" onFocus={() => this.onSecondFocus(2)} onBlur={this.onBlur} disabled={focused && focused !== 2}/>
          </FormGroup>
        </div>
    );
  }
}

export default MyForm;

https://codesandbox.io/s/yPBvrOvKg


问:
What will the most correct microdata schema be for a store listing brands?
I have a store page listing what fashion brands they are selling. But I'm not sure what microdata schema to use. I'm using the schema from schema.org.

Basically the list looks like this:

```<code><span itemscope itemtype="http://schema.org/Store">
 // Store info here

 <ul id="brandList">
  <li id="7750">
    <div class="brandInfo">
      <a href="http://...">Celine Engelstad</a>
    </div>
    <div class="logo">
      <img title="Celine Engelstad" src="http://..." class="logo">
    </div>
  </li>
  // More items here
 </ul>
</span>
</code>```

Would this be the correct schematic to use?

```<code><span itemscope itemtype="http://schema.org/Store">
 // Store info here

 <span itemscope itemtype="http://schema.org/Product">
   <ul id="brandList">
    <li itemprop="productID" id="7750">
      <div itemprop="manufacturer" class="brandInfo">
        <a itemprop="url" href="http://...">Celine Engelstad</a>
      </div>
      <div itemprop="logo" class="logo">
        <img itemprop="logo" title="Celine Engelstad" src="http://..." class="logo">
      </div>
    </li>
    // More items here
  </ul>
</span>
</code>```

1) Since it's not a list of products, rather a list of brands, is it correct to use http://schema.org/Product

2) Brand name is both a name and link. Can I use nested itemprop as I have done?

3) Is there any point in using itemprop="productID" as this is not an item for purchase, buth the ID of the brand on my site?

Update 17.07.2013

I've implemented the following structure to stores listing brands after some outside help:

```<code><ul class="brand-list>
  <li id="426">
    <span itemtype="http://schema.org/Organization" itemscope="">
      <div class="brandInfo floatLef" itemprop="name">
        <a href="#" class="" itemprop="url">American Retro</a>
      </div>
    </span>
  </li>
</ul>
</code>```

Would this be correct to use e.g. on the front page for a section called most popular brands as well?

答: It really depends on the kind of stores you intend to list;  for brick & mortar locations, use the store microdata schema; if, on the other hand, what you are listing are brands you sell on your own store, you'd probably be better off with the brand schema instead.</p>

Body:
I have a store page listing what fashion brands they are selling. But I'm not sure what microdata schema to use. I'm using the schema from schema.org.

Basically the list looks like this:

 // Store info here

      Celine Engelstad

  // More items here

Would this be the correct schematic to use?

 // Store info here

        Celine Engelstad

    // More items here

1) Since it's not a list of products, rather a list of brands, is it correct to use http://schema.org/Product

2) Brand name is both a name and link. Can I use nested itemprop as I have done?

3) Is there any point in using itemprop="productID" as this is not an item for purchase, buth the ID of the brand on my site?

Update 17.07.2013

I've implemented the following structure to stores listing brands after some outside help:

        American Retro

Would this be correct to use e.g. on the front page for a section called most popular brands as well?


问:
Storing user input in variables
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.</p>

```<code> static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}
</code>```

答: As every type of data is a string, you should not bother With list<>. Just do Array, which is more of a basic stuff. But storing these into class is much better idea if you can do So. I'm on my phone right now and writing some code Shaft May be hard. Make a class person with void presenting all the data and simply call it on the end of Main(). But as I said before, if you don't feel comfortable with classes yet, try an Array.</p>

Title: Storing user input in variables

Body:
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.

 static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}


问:
How can I make a TextView look like a Button?
I have a ListActivity in Android. Each row is just an item that starts another activity with some resource. By default this is of course a TextView.

I'd like (and by "I'd like", I mean "the client insists") that TextView to look like a button. If I actually make them Buttons, the default list click handler doesn't work anymore - even if they're non-focusable - so I have to write code to manually inflate the view containing the button and set a click handler.

Is there some way instead I can just make the TextView look like a Button without any of a Button's behaviors?

答:
In XML textview set: </p>

```<code>android:clickable="true"
</code>```

<p>and in java file set: </p>

```<code>TextView youtTextView=(TextView)findViewById(R.id.yourTxt);

youtTextView.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
       //code your button click action/event
    }
});
</code>```

Body:
In XML textview set:

android:clickable="true"

and in java file set:

TextView youtTextView=(TextView)findViewById(R.id.yourTxt);

youtTextView.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
       //code your button click action/event
    }
});


问:
Base64 encode png buffer using node-gd
I'm trying to do some basic PNG manipulation using the node-gd GD wrapper.

I'd like to:

Open a png image

Merge this png with an overlay png

Encode the merged result buffer as a base64 string

My test code:

```<code>gd.openPng('./my_image.png', function(err, img) {
    img.saveAlpha(1);
    gd.openPng('./my_overlay.png', function(err, overlay) {
        overlay.copy(img, 0, 0, 0, 0, overlay.width, overlay.height);

        let buff = gd.createFromPngPtr(new Buffer(img.pngPtr())); /* this returns null? */
        console.log(buff); /* prints null as per previous line */

        let b64 = buff.toString('base64'); /* error: Cannot read property 'toString' of null */
        console.log(b64);
    });
});
</code>```

Why am I getting a null return on the gd.createFromPngPtr call?

答:
Solved like so:</p>

```<code>gd.openPng('./di.png', function(err, img) {
    img.saveAlpha(1);
    gd.openPng('./flaming.png', function(err, overlay) {
        overlay.copy(img, 0, 0, 0, 0, overlay.width, overlay.height);
        var buff = Buffer.from(img.pngPtr(), 'binary');//, 'latin1');
        var b64 = buff.toString('base64');
        console.log(b64);
    });
});
</code>```

Title: Base64 encode png buffer using node-gd

Body:
I'm trying to do some basic PNG manipulation using the node-gd GD wrapper.

I'd like to:

Open a png image

Merge this png with an overlay png

Encode the merged result buffer as a base64 string

My test code:

gd.openPng('./my_image.png', function(err, img) {
    img.saveAlpha(1);
    gd.openPng('./my_overlay.png', function(err, overlay) {
        overlay.copy(img, 0, 0, 0, 0, overlay.width, overlay.height);

        let buff = gd.createFromPngPtr(new Buffer(img.pngPtr())); /* this returns null? */
        console.log(buff); /* prints null as per previous line */

        let b64 = buff.toString('base64'); /* error: Cannot read property 'toString' of null */
        console.log(b64);
    });
});

Why am I getting a null return on the gd.createFromPngPtr call?

Body:
Solved like so:

gd.openPng('./di.png', function(err, img) {
    img.saveAlpha(1);
    gd.openPng('./flaming.png', function(err, overlay) {
        overlay.copy(img, 0, 0, 0, 0, overlay.width, overlay.height);
        var buff = Buffer.from(img.pngPtr(), 'binary');//, 'latin1');
        var b64 = buff.toString('base64');
        console.log(b64);
    });
});


问:
Java: how to make an efficient chance method
Hi there im making a rewards code and im trying to make a good chance code
i have this method for now,

```<code> public int getRandom(int lower, int upper) {
        Random random = new Random();
        return random.nextInt((upper - lower) + 1) + lower;
    }

int chance = getRandom(0, 100);
if(chance < 10){
reward(player)
}
</code>```

Is there a better method can make this code more efficient? sometimes it get random chance within 0 and 10 which gives the best reward.

答:
You can use ThreadLocalRandom which is faster than Random.  However, your code is already O(1), so it can't really be any more efficient.

You also might want to refrain from creating a new object every time the method is called.

Body:
Hi there im making a rewards code and im trying to make a good chance code
i have this method for now,

 public int getRandom(int lower, int upper) {
        Random random = new Random();
        return random.nextInt((upper - lower) + 1) + lower;
    }

int chance = getRandom(0, 100);
if(chance < 10){
reward(player)
}

Is there a better method can make this code more efficient? sometimes it get random chance within 0 and 10 which gives the best reward.


问:
How can I cancel a ProgressBar?
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

```<code><ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>
</code>```

How can I achieve the above?

答:
You use a ProgressBar only to represent the progress of something, it doesn't hold any logic nor make any kind of process, it only gets updated (if you want to) by an external process (like an AsyncTask, for example). That's why it doesn't have any listeners and it's not cancellable, because the ProgressBar only sits in there so another process has the option to update it or set its visibility to GONE when it's finished.

So basically, you shouldn't worry about the progress bar itself, you should worry about the process that the progress bar is representing and how and when this process can get cancelled, so you can call progressBar.setVisibility(View.GONE) when this happens.

Just as an example, I use a ProgressBar to represent the loading of an ImageView with Picasso. Picasso offers a callback to let you know when the loading succeded or failed. In both cases, I set my ProgressBar visibility to GONE and take other actions depending the case. That's why I say you have to know how and when you should manipulate your ProgressBar visibility.

```<code>Picasso.with(this)
                .load("https://image.tmdb.org/t/p/w640" + m.getPosterPath())
                .into(posterImageView, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError() {
                        progressBar.setVisibility(View.GONE);
                        noImageFoundTextView.setVisibility(View.VISIBLE);
                    }
});
</code>```

OK, so if your concern is about UX and you want to make a ProgressBar dismissable by the user, you can implement this kind of workaround:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_marginTop="5dp">
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>

        <ImageView
            android:id="@+id/dismissButton"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:gravity="center"
            android:background="@android:drawable/ic_menu_close_clear_cancel"
            android:layout_gravity="center"/>
</FrameLayout>
</code>```

The imageview will handle the dismiss of the progressbar.

```<code>dismissButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            progressBar.setVisibility(View.GONE);
            dismissButton.setVisibility(View.GONE);
            //Take other actions on dismiss
        }
});
</code>```

Title: How can I cancel a ProgressBar?

Body:
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

<ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

How can I achieve the above?

Body:
You use a ProgressBar only to represent the progress of something, it doesn't hold any logic nor make any kind of process, it only gets updated (if you want to) by an external process (like an AsyncTask, for example). That's why it doesn't have any listeners and it's not cancellable, because the ProgressBar only sits in there so another process has the option to update it or set its visibility to GONE when it's finished.

So basically, you shouldn't worry about the progress bar itself, you should worry about the process that the progress bar is representing and how and when this process can get cancelled, so you can call progressBar.setVisibility(View.GONE) when this happens.

Just as an example, I use a ProgressBar to represent the loading of an ImageView with Picasso. Picasso offers a callback to let you know when the loading succeded or failed. In both cases, I set my ProgressBar visibility to GONE and take other actions depending the case. That's why I say you have to know how and when you should manipulate your ProgressBar visibility.

Picasso.with(this)
                .load("https://image.tmdb.org/t/p/w640" + m.getPosterPath())
                .into(posterImageView, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError() {
                        progressBar.setVisibility(View.GONE);
                        noImageFoundTextView.setVisibility(View.VISIBLE);
                    }
});

OK, so if your concern is about UX and you want to make a ProgressBar dismissable by the user, you can implement this kind of workaround:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_marginTop="5dp">
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>

        <ImageView
            android:id="@+id/dismissButton"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:gravity="center"
            android:background="@android:drawable/ic_menu_close_clear_cancel"
            android:layout_gravity="center"/>
</FrameLayout>

The imageview will handle the dismiss of the progressbar.

dismissButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            progressBar.setVisibility(View.GONE);
            dismissButton.setVisibility(View.GONE);
            //Take other actions on dismiss
        }
});


问:
Handling Soap timeouts in PHP
I'm working on a project where I am verifying information from a user with a SOAP web service. I currently am taking care of errors assuming that I'm receiving responses from the web service, but also need to handle the edge cases of a service timeout or unavailability.

In the case of a timeout or service unavailability, I need to pretend that the request was successful (that the web service approved the info), but I'm not clear on what exceptions are thrown.

Some pseudo-code:

```<code>// $client is PHP's SoapClient class
try {
  $response = $client->SomeSoapRequest();
}
catch(SoapFault $e){
  // handle issues returned by the web service
}
catch(Exception $e){
  // handle PHP issues with the request
}
</code>```

What I can't seem to find is:

Are timeouts a SoapFault? If so, what is the best way to distinguish between a timeout error and web service issues (like a type error, etc.)? I found one page that mentioned an error where the message was something to the effect of "Error loading headers", but didn't mention if this was a Soap fault.

How is a service unavailability potentially going to happen? A PHP exception seems like it would make sense (a SoapFault would be returned from the web service where unavailability would be a socket issue or similar)?

Is there an existing service (e.g. example) that I can test a timeout against? Most timeout related discussions seem to be related to preventing timeouts by extending the default timeout setting, which isn't ideal in this situation.

答:
From my experience, if $e->getMessage is "Error Fetching http headers",  you are dealing with a network timeout.

If $e->getMessage is something like "Cannot connect to host", the service you are trying to reach is down.

Then there is "Looks like we got no XML document", which is more cryptic an can mean different things.

Title: Handling Soap timeouts in PHP

Body:
I'm working on a project where I am verifying information from a user with a SOAP web service. I currently am taking care of errors assuming that I'm receiving responses from the web service, but also need to handle the edge cases of a service timeout or unavailability.

In the case of a timeout or service unavailability, I need to pretend that the request was successful (that the web service approved the info), but I'm not clear on what exceptions are thrown.

Some pseudo-code:

// $client is PHP's SoapClient class
try {
  $response = $client->SomeSoapRequest();
}
catch(SoapFault $e){
  // handle issues returned by the web service
}
catch(Exception $e){
  // handle PHP issues with the request
}

What I can't seem to find is:

Are timeouts a SoapFault? If so, what is the best way to distinguish between a timeout error and web service issues (like a type error, etc.)? I found one page that mentioned an error where the message was something to the effect of "Error loading headers", but didn't mention if this was a Soap fault.

How is a service unavailability potentially going to happen? A PHP exception seems like it would make sense (a SoapFault would be returned from the web service where unavailability would be a socket issue or similar)?

Is there an existing service (e.g. example) that I can test a timeout against? Most timeout related discussions seem to be related to preventing timeouts by extending the default timeout setting, which isn't ideal in this situation.


问:
How to structure model that is broken into database as 36 tables?
I have over 1 billion domain name records which, instead of putting them all in a single table, I decided to break them up into 36 tables (same db structure for each table).

There is a table based on the first character of the domain name (ex tables: domains_a... domains_z).

How can I create a single Domain model in rails that automatically switches between these tables seamlessly based on the character specified?

答:
Generally, this sort of table partitioning is handled at the database level. You should specify what database you are using, because that will be extremely relevant here.

For instance, PostgreSQL has basic table partition support. You would point the Rails model at the master table, and the partitioning would be transparent to the Ruby layer.


问:
Find the Run Time of Select Ruby Code

Problem

Howdy guys, so I want to find the run time of a block of code in Ruby, but I am not entirely sure as to how I could do it. I want to run some code, and then output how long it took to run that code because I have a super huge program and the run time changes a lot. I want to make sure it always has a consistent run time (I could do it by sleeping it for a fraction of a second) but that isn't my problem. I want to find out how long the run time actually is so the program can know if it needs to slow things down or speed things up.

My Thoughts

So, I have an idea as to how it could work. I have never used Time in ruby but I have an idea as to how I could use that. I could have a variable equal to the time (in milliseconds) and then another variable that I make at the end of the code block that does it again, and then I just subtract them, but I have (1) never used Time and (2) I don't actually know if that is the best way.

Thanks in advance!

答:
It is simple. Look at your watch (Time.now) and remember the time, run the code, look at your watch again, subtract.

```<code>t0 = Time.now
# your block of code
puts Time.now - t0
</code>```

Title: Find the Run Time of Select Ruby Code

Body:
It is simple. Look at your watch (Time.now) and remember the time, run the code, look at your watch again, subtract.

t0 = Time.now
# your block of code
puts Time.now - t0


问:
How do linux break 64bit virtual address?
Assuming a 4-level page-tables, where the first 3 levels are 9-bits and the last one is 12 bits, then shouldn't the maximum virtual address be 3*9+12=39 bits?

Today i have noticed by accident that my addresses where 47 bits long.
e.g 0x7fb329caa3c0

答: A page addresses 212 bytes of memory.  A page table is one page large, and each entry is 8 bytes, so a page table contains 29 entries, so a page table addresses 221 bytes. A page directory is similar, and so addresses 230 bytes. A page directory pointer table (PDPT) is one level higher, and so addresses 239 bytes. Lastly, the current Intel architecture has one more level, the PML4, addressing 248 bits. I think you are missing this last level in your analysis. Canonical addressing breaks this up into two halves, so you have a lower 247-byte space and an upper 247-byte space.


问:
Android - Switching between Activities and Screens with same xml file
I'm building an app for educational purposes, with a lot of questions and challenges to the user to solve. But, it would be a HUGE amount of screens if I create a lot of questions and one xml file and activity for each one, as I want to have different kinds of questions, where the user should be able to write the code, select a block of code or select the correct answer about theory and stuff. Is there a way to use the same model of screen(xml file) for one specific kind of question? Like, using one model to all the screens and questions where the user should select the correct answer, and another model to another kind of question..

p.s: Yes, i'm kind newbie in Android

Thanks! :)

答:
Use Fragments to display questions in your activity.

In short, Fragments are mini-Activities with their own layouts, so each different type of question should have a corresponding Fragment. That should be exactly what you need.

For example, you can create a fragment_radiobox and a fragment_codesnippet in your project. In first one you will include a TextView for your question and a few checkboxes for an answer, and in the second one you'd have an EditText field to write some code. You can call any of those two fragments in your main activity depending on which question you want to display.


问:
JS/Jquery: Initiate window resize without actually resizing
So I have a very specific problem that presented itself recently (right before our planned launch day tomorrow) and I am not completely sure how to solve it. I have built our website of an HTML-template with my modest front-end skills and we are very pleased with it. However, I can't seem to solve this.

The problem:
I have a filter system that allows a user to filter articles that are presented on a page. A user can even fill in this filter on the home page, direct to the page with the articles and have the filter applied. However, if then the filter is broadened (less strict) and new articles present itself, the pictures do not show up. Found out this is the case because the flexslider behind it has to be initialized again which happens on a window load (e.g. when the window is resized). The function that controls the initialization of the flexslider is in an external js file and I am not sure whether I can call on it from my own custom.js file, so I am thinking of just calling a resize/reload window function to active it.

The question:
Can I run a resize window function (or something that activates the flexslider) without hindering user experience (more specifically, without ACTUALLY resizing/reloading the window)? I will run this on a change in the filter.

I know this is a very specific question but hopefully somebody can help me out.

Take care!

p.s. it would be ideal if I could run the actual function that loads the flexslider but this is located in an external js file.

EDIT:
Briefly some additional info. If I go straight to the article page, it has no filter active and thus shows all articles, if I then start flipping through the filter, all is good. It is however only if I arrive from the homepage with a set filter that the problems arise. You then arrive on the article page which shows only the articles that are within the boundaries, and when the filter is taken away it has problems loading the images of the new articles showing up. As if it had not loaded these because they were not open on window load the first time.

答:
I managed to solve it after all by delaying the function that drops the filter values into my inputs so it loads in all images initially before applying the filter. It happens at such speed it's hardly noticeable.

Also, I did try to initiate a window resize function, it did work without actually resizing anything, but unfortunately the images did not load in properly (overlap and such).

Anyway, it has been solved. Thanks for all the input!


问:
Django REST Serializer doing N+1 database calls for multiple nested relationship, 3 levels
I have a situation where my model has a Foreign Key relationship:

```<code># models.py
class Child(models.Model):
    parent = models.ForeignKey(Parent,)

class Parent(models.Model):
    pass
</code>```

and my serializer:

```<code>class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        queryset = Child.objects.filter(parent=parent).select_related('parent')
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
        model = Parent
</code>```

When I call Parent in my views for N number of Parents, Django does N number of database calls inside the serializer when it grabs the children. Is there any way to get ALL children for ALL Parents to minimize the number of database calls?

I've tried this but it doesn't seem to solve my issue:

```<code>class ParentList(generics.ListAPIView):

    def get_queryset(self):
        queryset = Parent.objects.prefetch_related('child')
        return queryset

    serializer_class = ParentSerializer
    permission_classes = (permissions.IsAuthenticated,)
</code>```

EDIT

I've updated the code below to reflect Alex's feedback....which solves the N+1 for one nested relationship.

```<code># serializer.py
class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        # The all() call should hit the cache
        serialized_data = ChildSerializer(parent.child.all(), many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
            model = Parent

# views.py
class ParentList(generics.ListAPIView):

    def get_queryset(self):
        children = Prefetch('child', queryset=Child.objects.select_related('parent'))
        queryset = Parent.objects.prefetch_related(children)
        return queryset

    serializer_class = ParentSerializer
    permission_classes = (permissions.IsAuthenticated,)
</code>```

Now let's say I have one more model, which is a grandchild:

```<code># models.py
class GrandChild(models.Model):
    parent = models.ForeignKey(Child,)

class Child(models.Model):
    parent = models.ForeignKey(Parent,)

class Parent(models.Model):
    pass
</code>```

If i place the following in my views.py for the Parent queryset:

queryset = Parent.objects.prefetch_related(children, 'children__grandchildren')

It doesn't look like those grandchildren are being carried on into the ChildSerializer, and thus, again I'm running another N+1 issue. Any thoughts on this one?

EDIT 2

Perhaps this will provide clarity...Maybe the reason i am still running into N + 1 database calls, is because both my children and grandchildren classes are Polymorphic.... i.e.

```<code># models.py
class GrandChild(PolymorphicModel):
    child = models.ForeignKey(Child,)

class GrandSon(GrandChild):
    pass

class GrandDaughter(GrandChild):
    pass

class Child(PolymorphicModel):
    parent = models.ForeignKey(Parent,)

class Son(Child):
    pass

class Daughter(Child):
    pass

class Parent(models.Model):
    pass
</code>```

and my serializers look more like this:

```<code># serializer.py
class ChildSerializer(serializer.ModelSerializer):
    grandchild = serializers.SerializerMethodField('get_children_ordered')

    def to_representation(self, value):
        if isinstance(value, Son):
            return SonSerializer(value, context=self.context).to_representation(value)
        if isinstance(value, Daughter):
            return DaughterSerializer(value, context=self.context).to_representation(value)

    class Meta:
        model = Child

class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        queryset = Child.objects.filter(parent=parent).select_related('parent')
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
        model = Parent
</code>```

Plus the same for Grandaughter, Grandson, I'll spare you the details codewise, but i think you get the picture.

When i run my view for ParentList, and i monitor DB queries, I'm getting something along the lines of 1000s of queries, for only a handful of parents.

If i run the same code in the django shell, i can accomplish the same query at no more than 25 queries. I suspect maybe it has something to do with the fact that I'm using the django-polymorphic library? The reason being is that, there's a Child and GrandChild database table, in additions to each Son/Daughter, Grandson/Granddaughter table, for a total of 6 tables. across those objects. So my gut tells me i'm missing those polymorphic tables.

Or perhaps there's a more elegant solution for my daata model?

答:
This question is a bit old but I just came across a very similar problem and managed to reduce the db calls drastically. It seems to me that Django-mptt would make things much easier for you.

One way would be to define a single model with a ForeignKey to. This way you can find out the hierarchy by it's level in the tree. For example:

```<code>class Person(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
</code>```

You can find out if the object is a parent by checking if Person.level = 0. If it equals 1, it's a child, 2 grandchild, etc...

Then, you could modify your code to the following:

```<code># serializers.py
class ChildSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    def get_children(self, parent):
        queryset = parent.get_children()
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

# views.py
class ParentList(generics.ListAPIView):

    def get_queryset(self):
        queryset = cache_tree_children(Person.objects.all())
</code>```

With this, you'll eliminate your N+1 problem. If you want to add a new ForeignKey to a genre Model, for example, you could simply modify the last line to:

```<code>queryset = cache_tree_children(Person.objects.filter(channel__slug__iexact=channel_slug).select_related('genre'))
</code>```

Body:
I have a situation where my model has a Foreign Key relationship:

# models.py
class Child(models.Model):
    parent = models.ForeignKey(Parent,)

class Parent(models.Model):
    pass

and my serializer:

class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        queryset = Child.objects.filter(parent=parent).select_related('parent')
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
        model = Parent

When I call Parent in my views for N number of Parents, Django does N number of database calls inside the serializer when it grabs the children. Is there any way to get ALL children for ALL Parents to minimize the number of database calls?

I've tried this but it doesn't seem to solve my issue:

class ParentList(generics.ListAPIView):

    def get_queryset(self):
        queryset = Parent.objects.prefetch_related('child')
        return queryset

    serializer_class = ParentSerializer
    permission_classes = (permissions.IsAuthenticated,)

EDIT

I've updated the code below to reflect Alex's feedback....which solves the N+1 for one nested relationship.

# serializer.py
class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        # The all() call should hit the cache
        serialized_data = ChildSerializer(parent.child.all(), many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
            model = Parent

# views.py
class ParentList(generics.ListAPIView):

    def get_queryset(self):
        children = Prefetch('child', queryset=Child.objects.select_related('parent'))
        queryset = Parent.objects.prefetch_related(children)
        return queryset

    serializer_class = ParentSerializer
    permission_classes = (permissions.IsAuthenticated,)

Now let's say I have one more model, which is a grandchild:

# models.py
class GrandChild(models.Model):
    parent = models.ForeignKey(Child,)

class Child(models.Model):
    parent = models.ForeignKey(Parent,)

class Parent(models.Model):
    pass

If i place the following in my views.py for the Parent queryset:

queryset = Parent.objects.prefetch_related(children, 'children__grandchildren')

It doesn't look like those grandchildren are being carried on into the ChildSerializer, and thus, again I'm running another N+1 issue. Any thoughts on this one?

EDIT 2

Perhaps this will provide clarity...Maybe the reason i am still running into N + 1 database calls, is because both my children and grandchildren classes are Polymorphic.... i.e.

# models.py
class GrandChild(PolymorphicModel):
    child = models.ForeignKey(Child,)

class GrandSon(GrandChild):
    pass

class GrandDaughter(GrandChild):
    pass

class Child(PolymorphicModel):
    parent = models.ForeignKey(Parent,)

class Son(Child):
    pass

class Daughter(Child):
    pass

class Parent(models.Model):
    pass

and my serializers look more like this:

# serializer.py
class ChildSerializer(serializer.ModelSerializer):
    grandchild = serializers.SerializerMethodField('get_children_ordered')

    def to_representation(self, value):
        if isinstance(value, Son):
            return SonSerializer(value, context=self.context).to_representation(value)
        if isinstance(value, Daughter):
            return DaughterSerializer(value, context=self.context).to_representation(value)

    class Meta:
        model = Child

class ParentSerializer(serializer.ModelSerializer):
    child = serializers.SerializerMethodField('get_children_ordered')

    def get_children_ordered(self, parent):
        queryset = Child.objects.filter(parent=parent).select_related('parent')
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

    class Meta:
        model = Parent

Plus the same for Grandaughter, Grandson, I'll spare you the details codewise, but i think you get the picture.

When i run my view for ParentList, and i monitor DB queries, I'm getting something along the lines of 1000s of queries, for only a handful of parents.

If i run the same code in the django shell, i can accomplish the same query at no more than 25 queries. I suspect maybe it has something to do with the fact that I'm using the django-polymorphic library? The reason being is that, there's a Child and GrandChild database table, in additions to each Son/Daughter, Grandson/Granddaughter table, for a total of 6 tables. across those objects. So my gut tells me i'm missing those polymorphic tables.

Or perhaps there's a more elegant solution for my daata model?

Body:
This question is a bit old but I just came across a very similar problem and managed to reduce the db calls drastically. It seems to me that Django-mptt would make things much easier for you.

One way would be to define a single model with a ForeignKey to. This way you can find out the hierarchy by it's level in the tree. For example:

class Person(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

You can find out if the object is a parent by checking if Person.level = 0. If it equals 1, it's a child, 2 grandchild, etc...

Then, you could modify your code to the following:

# serializers.py
class ChildSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    def get_children(self, parent):
        queryset = parent.get_children()
        serialized_data = ChildSerializer(queryset, many=True, read_only=True, context=self.context)
        return serialized_data.data

# views.py
class ParentList(generics.ListAPIView):

    def get_queryset(self):
        queryset = cache_tree_children(Person.objects.all())

With this, you'll eliminate your N+1 problem. If you want to add a new ForeignKey to a genre Model, for example, you could simply modify the last line to:

queryset = cache_tree_children(Person.objects.filter(channel__slug__iexact=channel_slug).select_related('genre'))


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答:
Wikipedia : Object Relational Mapping ? :)

To be more precise, an ORM allows you to use Objects directly bound to your Database.

For example, I have a Car, which has 4 object Door, each Door has a Color, each Color a Name.

With an ORM, I get my Car object from the Database. Then I go for a Car.GetDoors(), and I get a collection of my Doors, and for each one of them, I can use a Door.GetColor().GetColorName().

Which means that I didn't bother to write SQL queries to get the Doors from the Door Table, with a CarID, nor get a ColorName from the Color table with a colorID. An ORM thus allows me to write less code :)