问:
Is a For Loop always executed at least once?
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

```<code>for (int i=6; i <=5; i++) {
    //irrelevant for this question
}
</code>```

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

答: A for-loop always makes sure the condition is true before running the program. Whereas, a do-loop runs the program at least once and then checks the condition.</p>

Body:
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

for (int i=6; i <=5; i++) {
    //irrelevant for this question
}

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.


来源: stackexchange

问:
copyTo doesn't work on OpenCv4Android
I would like to apply a mask with OpenCV4Android using the method copyTo(image, mask), but it is not working and the console doesn't show any errors.

Any idea?

答:
maybe this is too late but I had the same problem and it was because my "src" had 3 Channels and my "dst" had 4 Channels.

I just wrote this:

```<code>Imgproc.cvtColor(src, auxiliar, Imgproc.COLOR_RGB2RGBA);
auxiliar.copyTo(dst, mask);
</code>```

ContentLicense: CC BY-SA 3.0

Title: copyTo doesn't work on OpenCv4Android

Body:
maybe this is too late but I had the same problem and it was because my "src" had 3 Channels and my "dst" had 4 Channels.

I just wrote this:

Imgproc.cvtColor(src, auxiliar, Imgproc.COLOR_RGB2RGBA);
auxiliar.copyTo(dst, mask);


问:
How do I create a variable length dropdown list on a ViewModel without repeating code in c#?
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

```<code>Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .
</code>```

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

```<code>[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}
</code>```

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

```<code>                      *******QUESTION EDIT***********
</code>```

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

```<code>        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }
</code>```

My Html View

```<code>        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")
</code>```

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

答:
I haven't quite got what you need to so, here's an example of how you can build a list of dates starting from the current one and containing 12 months.

```<code>public static IEnumerable<DateTime> GetDates()
{
    var currentDate = DateTime.Now;
    var numberOfMonthsToShow = 12;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}
</code>```

If you want to start from the previous month, initialise currentDate as DateTime.Now.AddMonths(-1)

Next, you will have to build a string representation of those dates. For your format, use Y format selector.

```<code> var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy"));
</code>```

Now that you have your strings, you can add them to SelectList. I don't have ASP.NET MVC around right now, but it should be pretty trivial. Something like:

```<code>var list = new List<SelectListItem>();
list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0]})

for (int i = 1; i < stringView.Count(); i++)
{
  list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i]);
}

var selectList = new SelectList(list);
</code>```

You have a lot of code which seems redundant for a task of 'give me previous months'. Please try the one I've provided or explain why you need so convoluted code. I might be missing some logic of yours.

Body:
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

                      *******QUESTION EDIT***********

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }

My Html View

        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

Body:
I haven't quite got what you need to so, here's an example of how you can build a list of dates starting from the current one and containing 12 months.

public static IEnumerable<DateTime> GetDates()
{
    var currentDate = DateTime.Now;
    var numberOfMonthsToShow = 12;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}

If you want to start from the previous month, initialise currentDate as DateTime.Now.AddMonths(-1)

Next, you will have to build a string representation of those dates. For your format, use Y format selector.

 var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy"));

Now that you have your strings, you can add them to SelectList. I don't have ASP.NET MVC around right now, but it should be pretty trivial. Something like:

var list = new List<SelectListItem>();
list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0]})

for (int i = 1; i < stringView.Count(); i++)
{
  list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i]);
}

var selectList = new SelectList(list);

You have a lot of code which seems redundant for a task of 'give me previous months'. Please try the one I've provided or explain why you need so convoluted code. I might be missing some logic of yours.


问:
Data cleaning loop in R
I have a dataframe with multiple columns that need I to clean. All columns need to be cleaned with the same logic. I can do this for as many variables as I have

```<code>dsr$DSR23 <- ifelse(dsr$DSR23 == 'Refused', NA, dsr$DSR23)
dsr$DSR24 <- ifelse(dsr$DSR24 == 'Refused', NA, dsr$DSR24)
dsr$DSR25 <- ifelse(dsr$DSR25 == 'Refused', NA, dsr$DSR25)
</code>```

but I would like to do it in one for-loop, if possible.

Can someone come up with the code to do this without copying and pasting the same ifelse statement a million times?

答:
I've used code like this before for cleaning:

```<code>vars<-c("DSR23", "DSR24", "DSR25")
dsr[,vars] = lapply(vars, function(x) ifelse(dsr[,x]=="Refused", NA, dsr[,x]))
</code>```

In R using apply over a for loop is often preferred

Title: Data cleaning loop in R

Body:
I have a dataframe with multiple columns that need I to clean. All columns need to be cleaned with the same logic. I can do this for as many variables as I have

dsr$DSR23 <- ifelse(dsr$DSR23 == 'Refused', NA, dsr$DSR23)
dsr$DSR24 <- ifelse(dsr$DSR24 == 'Refused', NA, dsr$DSR24)
dsr$DSR25 <- ifelse(dsr$DSR25 == 'Refused', NA, dsr$DSR25)

but I would like to do it in one for-loop, if possible.

Can someone come up with the code to do this without copying and pasting the same ifelse statement a million times?

Body:
I've used code like this before for cleaning:

vars<-c("DSR23", "DSR24", "DSR25")
dsr[,vars] = lapply(vars, function(x) ifelse(dsr[,x]=="Refused", NA, dsr[,x]))

In R using apply over a for loop is often preferred


问:
Why does __get__ take an owner while __set__ and __delete__ do not?
From the Python data model documentation:

object.__get__(self, instance, owner=None)

Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). The optional owner argument is the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner.

This method should return the computed attribute value or raise an AttributeError exception.

PEP 252 specifies that __get__() is callable with one or two arguments. Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python’s own __getattribute__() implementation always passes in both arguments whether they are required or not.

object.__set__(self, instance, value)

Called to set the attribute on an instance instance of the owner class to a new value, value.

Note, adding __set__() or __delete__() changes the kind of descriptor to a “data descriptor”. See Invoking Descriptors for more details.

object.__delete__(self, instance)

Called to delete the attribute on an instance instance of the owner class.

Why does __get__ take an owner while __set__ and __delete__ do not?

Does it mean that when a descriptor supplies both __get__ and __set__,

we can get an attribute no matter whether it belongs to an instance of the owner class or to the owner class,

we can set and delete an attribute when it belongs to an instance of the owner class but not when it belongs to the owner class?

My question is actually part of this one.

答:
owner mostly exists for getting the attribute on the class itself, rather than an instance. When you're retrieving the attribute on an instance, the owner argument is redundant, since it's just type(instance).

__set__ doesn't apply to setting the attribute on the class itself, so it has no use for owner.

ContentLicense: CC BY-SA 4.0


问:
Extra gap above div in list element when overflow hidden
I have a div inside of a list element. For some reason, the div is not on the same line as the list style bullet when overflow is hidden on the div. Any thoughts?

HTML:

```<code><ul><li><div>Here is some long text</div></li></ul>
</code>```

CSS:

```<code>ul {width:150px;}
li {list-style-type:square}
div {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</code>```

Fiddle: https://jsfiddle.net/scottchantry/supcsayt/

答:
The div is a block element, which makes it take up a new line. Adding display:inline to your div should do the trick. https://jsfiddle.net/supcsayt/2/

```<code>div {
  display: inline;
}
</code>```

Body:
I have a div inside of a list element. For some reason, the div is not on the same line as the list style bullet when overflow is hidden on the div. Any thoughts?

HTML:

Here is some long text

CSS:

ul {width:150px;}
li {list-style-type:square}
div {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

Fiddle: https://jsfiddle.net/scottchantry/supcsayt/

Body:
The div is a block element, which makes it take up a new line. Adding display:inline to your div should do the trick. https://jsfiddle.net/supcsayt/2/

div {
  display: inline;
}


问:
UITableView Content doesn't get deleted after deletion? [Swift 3.0 - Xcode 8]
Im trying to delete cells in my UITableView, but when I delete them, they reappear after I reload the app. I delete from the same array that I stored the values in with core data. Do I have to directly delete from coreData as well? how do I do that?

Heres my code:

```<code>///Function to remove TableView Cells

public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
    SetTIME.remove(at: indexPath.row)
    if SaveData.count == 4 {
        SaveData.remove(at: myIndex*4)
        SaveData.remove(at: (myIndex*4)+1)
        SaveData.remove(at: (myIndex*4)+2)
        SaveData.remove(at: (myIndex*4)+3)}
        tableView.reloadData()
    }

}

 ///CoreData

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newTrip = NSEntityDescription.insertNewObject(forEntityName: "Sets", into: context)
    if DataGrab.count == 4{ // need to change after storing data in VC2 before sending
    newTrip.setValue(DataGrab[0], forKey: "set1")
    newTrip.setValue(DataGrab[1], forKey: "set4")
    newTrip.setValue(DataGrab[2], forKey: "set3")
    newTrip.setValue(DataGrab[3], forKey: "set2")}

    do {
        try context.save()
        print("Saved")
    }
    catch{
        //ProcessError
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sets")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results {
                if let set1 = (result as AnyObject).value(forKey: "set1") as? String
                {
                    if SaveData.contains(set1){

                    } else {
                    SaveData.append(set1)
                        SetTIME.append(set1)

                if let set2 = (result as AnyObject).value(forKey: "set2") as? String
                {
                    SaveData.append(set2)
                }
                if let set3 = (result as AnyObject).value(forKey: "set3") as? String
                {
                    SaveData.append(set3)
                }
                if let set4 = (result as AnyObject).value(forKey: "set4") as? String
                {
                    SaveData.append(set4)
                        }
                    }
                }
            }
        }
    }
    catch{
        //ProcessErrors
    }
</code>```

答:
You can use NSFetchedResultsController with UITableview. That will take care of the delete/add/edit of the objects in core data.

Below are the links to create NSFetchedResultsController

https://cocoacasts.com/populate-a-table-view-with-nsfetchedresultscontroller-and-swift-3/

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/nsfetchedresultscontroller.html

Body:
Im trying to delete cells in my UITableView, but when I delete them, they reappear after I reload the app. I delete from the same array that I stored the values in with core data. Do I have to directly delete from coreData as well? how do I do that?

Heres my code:

///Function to remove TableView Cells

public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
    SetTIME.remove(at: indexPath.row)
    if SaveData.count == 4 {
        SaveData.remove(at: myIndex*4)
        SaveData.remove(at: (myIndex*4)+1)
        SaveData.remove(at: (myIndex*4)+2)
        SaveData.remove(at: (myIndex*4)+3)}
        tableView.reloadData()
    }

}

 ///CoreData

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newTrip = NSEntityDescription.insertNewObject(forEntityName: "Sets", into: context)
    if DataGrab.count == 4{ // need to change after storing data in VC2 before sending
    newTrip.setValue(DataGrab[0], forKey: "set1")
    newTrip.setValue(DataGrab[1], forKey: "set4")
    newTrip.setValue(DataGrab[2], forKey: "set3")
    newTrip.setValue(DataGrab[3], forKey: "set2")}

    do {
        try context.save()
        print("Saved")
    }
    catch{
        //ProcessError
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sets")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results {
                if let set1 = (result as AnyObject).value(forKey: "set1") as? String
                {
                    if SaveData.contains(set1){

                    } else {
                    SaveData.append(set1)
                        SetTIME.append(set1)

                if let set2 = (result as AnyObject).value(forKey: "set2") as? String
                {
                    SaveData.append(set2)
                }
                if let set3 = (result as AnyObject).value(forKey: "set3") as? String
                {
                    SaveData.append(set3)
                }
                if let set4 = (result as AnyObject).value(forKey: "set4") as? String
                {
                    SaveData.append(set4)
                        }
                    }
                }
            }
        }
    }
    catch{
        //ProcessErrors
    }


问:
Use CSS/IMG/JS with NodeJS
I create a http server with nodeJS and express.
I do the router for html pages but the css, the images and the js files are ignored.

I checked and the paths are ok.

I  tried to use static function of express but it doesn't work.

If you have an idea :)

server.js

```<code>var http = require("http");
var url = require("url");
var fs = require('fs');
//var express = require('express');
//var app = express();

//app.use(express.static( __dirname + "/views/web/assets/img"));

var server = http.createServer(function(req, res)
{
    var pathName = url.parse(req.url).pathname;
    console.log(__dirname + "/views/web" + pathName);
    fs.readFile( __dirname + "/views/web" + pathName , "utf8" , function(error , file){
     if(error) {
          res.writeHead(404 , {"Content-Type" : "text/html" });
          res.end();
     }else{
          res.writeHead(200 , {"Content-Type" : "text/html" });
          res.write(file);
          res.end();
     }
    });
});

server.listen(1337);
console.log("Serveur web lancé sur localhost:1337 ...");
</code>```

An extract of login.html :

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Profile - Login</title>
    <link rel="icon" type="image/png" href="assets/img/logo.png" />
    <!-- BOOTSTRAP STYLES-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
     <!-- FONTAWESOME STYLES-->
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
        <!-- CUSTOM STYLES-->
    <link href="assets/css/custom.css" rel="stylesheet" />
     <!-- GOOGLE FONTS-->
   <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

</head>
</code>```

The verification of paths :

```<code>proux@DESKTOP-VDRS1QF:/mnt/d/Users/Elodie/Desktop/server$ node server.js
Serveur web lancé sur localhost:1337 ...
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/login.html
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/bootstrap.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/font-awesome.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/custom.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery-1.10.2.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/bootstrap.min.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery.metisMenu.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/custom.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/nom_blanc.png
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png
</code>```

Elodie

答:
You're express static is serving /public, what is under that? Because I noticed that you had this originally:

```<code>app.use(express.static( __dirname + "/views/web/assets/img"));
<link rel="icon" type="image/png" href="assets/img/logo.png" />
</code>```

You should have something like this instead:

```<code>app.use(express.static( __dirname + "/views/web"));
<link rel="icon" type="image/png" href="/assets/img/logo.png" />
</code>```

given your path looks like:

```<code>/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png
</code>```

Title: Use CSS/IMG/JS with NodeJS

Body:
I create a http server with nodeJS and express.
I do the router for html pages but the css, the images and the js files are ignored.

I checked and the paths are ok.

I  tried to use static function of express but it doesn't work.

If you have an idea :)

server.js

var http = require("http");
var url = require("url");
var fs = require('fs');
//var express = require('express');
//var app = express();

//app.use(express.static( __dirname + "/views/web/assets/img"));

var server = http.createServer(function(req, res)
{
    var pathName = url.parse(req.url).pathname;
    console.log(__dirname + "/views/web" + pathName);
    fs.readFile( __dirname + "/views/web" + pathName , "utf8" , function(error , file){
     if(error) {
          res.writeHead(404 , {"Content-Type" : "text/html" });
          res.end();
     }else{
          res.writeHead(200 , {"Content-Type" : "text/html" });
          res.write(file);
          res.end();
     }
    });
});

server.listen(1337);
console.log("Serveur web lancé sur localhost:1337 ...");

An extract of login.html :

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Profile - Login</title>
    <link rel="icon" type="image/png" href="assets/img/logo.png" />

    <link href="assets/css/bootstrap.css" rel="stylesheet" />

    <link href="assets/css/font-awesome.css" rel="stylesheet" />

    <link href="assets/css/custom.css" rel="stylesheet" />

   <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

The verification of paths :

proux@DESKTOP-VDRS1QF:/mnt/d/Users/Elodie/Desktop/server$ node server.js
Serveur web lancé sur localhost:1337 ...
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/login.html
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/bootstrap.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/font-awesome.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/custom.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery-1.10.2.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/bootstrap.min.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery.metisMenu.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/custom.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/nom_blanc.png
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png

Elodie

Body:
You're express static is serving /public, what is under that? Because I noticed that you had this originally:

app.use(express.static( __dirname + "/views/web/assets/img"));
<link rel="icon" type="image/png" href="assets/img/logo.png" />

You should have something like this instead:

app.use(express.static( __dirname + "/views/web"));
<link rel="icon" type="image/png" href="/assets/img/logo.png" />

given your path looks like:

/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png


问:
Enumerable.Repeat for reference type objects initialization
I have a question about Enumerable.Repeat function.

If I will have a class:

```<code>class A
{
//code
}
</code>```

And I will create an array, of that type objects:

```<code>A [] arr = new A[50];
</code>```

And next, I will want to initialize those objects, calling Enumerable.Repeat:

```<code>arr = Enumerable.Repeat(new A(), 50);
</code>```

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

```<code>bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();
</code>```

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

答:
Just to help clarify for Camilo, here's some test code that shows the issue at hand:

```<code>void Main()
{
    var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
    foos[0].Name = "Jack";
    foos[1].Name = "Jill";
    Console.WriteLine(foos[0].Name);
}

public class Foo
{
    public string Name;
}
</code>```

This prints "Jill". Thus it shows that Enumerable.Repeat is only creating one instance of the Foo class.

Body:
I have a question about Enumerable.Repeat function.

If I will have a class:

class A
{
//code
}

And I will create an array, of that type objects:

A [] arr = new A[50];

And next, I will want to initialize those objects, calling Enumerable.Repeat:

arr = Enumerable.Repeat(new A(), 50);

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

Body:
Just to help clarify for Camilo, here's some test code that shows the issue at hand:

void Main()
{
    var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
    foos[0].Name = "Jack";
    foos[1].Name = "Jill";
    Console.WriteLine(foos[0].Name);
}

public class Foo
{
    public string Name;
}

This prints "Jill". Thus it shows that Enumerable.Repeat is only creating one instance of the Foo class.


问:
JAXB 2 annotation and XSD
In the JAXB 1.0 era, the recommended way of working with java object, XSD and XML is to start with XSD definition, use JAXB to generate java classes from the XSD and maintain the XSDs.

But now with JAXB 2.0 annotations, it's very convenient to generate XSDs from java classes. Is it recommended to take the approach of starting with java classes and annotations and generate XSD's?

Thanks,

答:
I recommend that developers start with the object model and annotate it to get the desired XML.  This gives you more flexibility when creating your application (such as also mapping the to a database using JPA).  You only need to generate an XML schema when you want to share the structure (for example as part of a WSDL).

Check out my blog for examples of JAXB starting with model classes:

http://bdoughan.blogspot.com

ContentLicense: CC BY-SA 2.5

Title: JAXB 2 annotation and XSD


问:
Indexing in Titan/Janus
I have 2 questions:

How to index this query?

```<code>g.V(vertexId).repeat(out().hasLabel('location')).emit().tree().next()
</code>```

in the Titan 1.0 documentation, there are only ways given to index the graph once when the data is already inserted  .
However in the generate-modern.groovy file here

we see that indexing is done before the creation of vertices which seems reasonable. However I am unable to do it when trying to use buildMixedIndex as it is throwing me

illegal argument exception :Unknown external index backend search

My approach was

```<code>def location = mgmt.makeVertexLabel("location").make()
def displayName = mgmt.makePropertyKey("displayName").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def shortName = mgmt.makePropertyKey("shortName").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def description = mgmt.makePropertyKey("description").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def latitude = mgmt.makePropertyKey("latitude").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def longitude = mgmt.makePropertyKey("longitude").dataType(String.class).cardinality(Cardinality.SINGLE).make()

def locationByName = mgmt.buildIndex("displayNameAndShortNameAndDescriptionAndLatitudeAndLongitude", Vertex.class).addKey(displayName).addKey(shortName).addKey(description)
.addKey(latitude).addKey(longitude).indexOnly(location).buildMixedIndex('search')
</code>```

Where I am getting it wrong?

答:
Here's an answer.
Both composite and mixed index are only avaiable for the first level gremlin query, not for the second level. Vertex-Centric index is required for the second level query.</p>

Title: Indexing in Titan/Janus

Body:
I have 2 questions:

How to index this query?

g.V(vertexId).repeat(out().hasLabel('location')).emit().tree().next()

in the Titan 1.0 documentation, there are only ways given to index the graph once when the data is already inserted  .
However in the generate-modern.groovy file here

we see that indexing is done before the creation of vertices which seems reasonable. However I am unable to do it when trying to use buildMixedIndex as it is throwing me

illegal argument exception :Unknown external index backend search

My approach was

def location = mgmt.makeVertexLabel("location").make()
def displayName = mgmt.makePropertyKey("displayName").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def shortName = mgmt.makePropertyKey("shortName").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def description = mgmt.makePropertyKey("description").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def latitude = mgmt.makePropertyKey("latitude").dataType(String.class).cardinality(Cardinality.SINGLE).make()
def longitude = mgmt.makePropertyKey("longitude").dataType(String.class).cardinality(Cardinality.SINGLE).make()

def locationByName = mgmt.buildIndex("displayNameAndShortNameAndDescriptionAndLatitudeAndLongitude", Vertex.class).addKey(displayName).addKey(shortName).addKey(description)
.addKey(latitude).addKey(longitude).indexOnly(location).buildMixedIndex('search')

Where I am getting it wrong?


问:
C++ member initialization from derived class to base class
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?</p>

```<code>class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}
</code>```

答:
In C++ we can't (almost always) create function init, we use constructors
e.g

```<code>class Base {
};
class A : public Base {
public:
    int a1;
    A():Base(), a1(0) {}
};
class B : public Base {
public:
    int b1;
    B():Base(), b1(1){}
};
</code>```

Construct "child" is A():Base(),a1(0), it's initializer list (:Base(),a1(0)), which create Base object, and int b1.
You should remember about ; after class.

Body:
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?

class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}

Body:
In C++ we can't (almost always) create function init, we use constructors
e.g

class Base {
};
class A : public Base {
public:
    int a1;
    A():Base(), a1(0) {}
};
class B : public Base {
public:
    int b1;
    B():Base(), b1(1){}
};

Construct "child" is A():Base(),a1(0), it's initializer list (:Base(),a1(0)), which create Base object, and int b1.
You should remember about ; after class.


问:
How to create the file inside a folder in google drive?
I am facing the issue in creating the file inside a folder , i created the separate file and separate folder in google drive but i can't create the file inside a folder in google drive

I have used the for creating the file inside the folder in google drive is posted below

```<code>public void onClickFolderInRootFlder(View view)
{

    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New CallLog folders").build();
    Drive.DriveApi.getRootFolder(mGoogleApiClient).createFolder(
            mGoogleApiClient, changeSet).setResultCallback(callback);
}

final ResultCallback<DriveFolder.DriveFolderResult> callback = new ResultCallback<DriveFolder.DriveFolderResult>() {
    @Override
    public void onResult(DriveFolder.DriveFolderResult result) {
        if (!result.getStatus().isSuccess()) {
            Toast.makeText(MainActivity.this,"Error while trying to create the folder",Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(MainActivity.this,"Created a folder with content: " +
                result.getDriveFolder().getDriveId(),Toast.LENGTH_SHORT).show();
        Drive.DriveApi.fetchDriveId(mGoogleApiClient, String.valueOf(result.getDriveFolder().getDriveId()))
                .setResultCallback(idCallback);
    }
};

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {
      //      showMessage("Cannot find DriveId. Are you authorized to view this file?");
            Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
            return;
        }
     DriveId   mFolderDriveId = result.getDriveId();
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(driveContentsCallback);
    }
};

final   ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
        new ResultCallback<DriveApi.DriveContentsResult>() {
            @Override
            public void onResult(DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    // display an error saying file can't be opened
                    return;
                }

                else{
                    CreateFileOnGoogleDrive(result);
                }
                // DriveContents object contains pointers
                // to the actual byte stream
                DriveContents contents = result.getDriveContents();
            }

        };

public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result){

    final DriveContents driveContents = result.getDriveContents();

    // Perform I/O off the UI thread.
    new Thread() {
        @Override
        public void run() {
            // write content to DriveContents
            OutputStream outputStream = driveContents.getOutputStream();
            Writer writer = new OutputStreamWriter(outputStream);
            try {
                writer.write("Hello World");
                writer.close();

            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("prabha")
                    .setMimeType("text/plain")
                    .setStarred(true).build();

            // create a file in root folder
            Drive.DriveApi.getRootFolder(mGoogleApiClient)
                    .createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
        }
    }.start();
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
        ResultCallback<DriveFolder.DriveFileResult>() {
            @Override
            public void onResult(DriveFolder.DriveFileResult result) {
                if (!result.getStatus().isSuccess()) {
                    Toast.makeText(MainActivity.this,"Error while trying to create the file",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(MainActivity.this,"Created a file with content: " +
                        result.getDriveFile().getDriveId(),Toast.LENGTH_SHORT).show();
            }
        };
</code>```

I tried this method but the issue is occurring in the line

```<code>final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {
      //      showMessage("Cannot find DriveId. Are you authorized to view this file?");
            Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
            return;
        }
     DriveId   mFolderDriveId = result.getDriveId();
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(driveContentsCallback);
    }
};
</code>```

The result.getStatus.isSuccess is false is returning .Please help me how to create the file inside a folder in google drive.

答:
You are calling

```<code>Drive.DriveApi.getRootFolder(mGoogleApiClient).createFile
</code>```

which (unsurprisingly) creates a file in the Root Folder.
Instead you should call

```<code> DriveFolder.createFile
</code>```

as described at  https://developers.google.com/android/reference/com/google/android/gms/drive/DriveFolder.html#createFile(com.google.android.gms.common.api.GoogleApiClient,com.google.android.gms.drive.MetadataChangeSet,com.google.android.gms.drive.DriveContents)

Body:
I am facing the issue in creating the file inside a folder , i created the separate file and separate folder in google drive but i can't create the file inside a folder in google drive

I have used the for creating the file inside the folder in google drive is posted below

public void onClickFolderInRootFlder(View view)
{

    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New CallLog folders").build();
    Drive.DriveApi.getRootFolder(mGoogleApiClient).createFolder(
            mGoogleApiClient, changeSet).setResultCallback(callback);
}

final ResultCallback<DriveFolder.DriveFolderResult> callback = new ResultCallback<DriveFolder.DriveFolderResult>() {
    @Override
    public void onResult(DriveFolder.DriveFolderResult result) {
        if (!result.getStatus().isSuccess()) {
            Toast.makeText(MainActivity.this,"Error while trying to create the folder",Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(MainActivity.this,"Created a folder with content: " +
                result.getDriveFolder().getDriveId(),Toast.LENGTH_SHORT).show();
        Drive.DriveApi.fetchDriveId(mGoogleApiClient, String.valueOf(result.getDriveFolder().getDriveId()))
                .setResultCallback(idCallback);
    }
};

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {
      //      showMessage("Cannot find DriveId. Are you authorized to view this file?");
            Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
            return;
        }
     DriveId   mFolderDriveId = result.getDriveId();
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(driveContentsCallback);
    }
};

final   ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
        new ResultCallback<DriveApi.DriveContentsResult>() {
            @Override
            public void onResult(DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    // display an error saying file can't be opened
                    return;
                }

                else{
                    CreateFileOnGoogleDrive(result);
                }
                // DriveContents object contains pointers
                // to the actual byte stream
                DriveContents contents = result.getDriveContents();
            }

        };

public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result){

    final DriveContents driveContents = result.getDriveContents();

    // Perform I/O off the UI thread.
    new Thread() {
        @Override
        public void run() {
            // write content to DriveContents
            OutputStream outputStream = driveContents.getOutputStream();
            Writer writer = new OutputStreamWriter(outputStream);
            try {
                writer.write("Hello World");
                writer.close();

            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("prabha")
                    .setMimeType("text/plain")
                    .setStarred(true).build();

            // create a file in root folder
            Drive.DriveApi.getRootFolder(mGoogleApiClient)
                    .createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
        }
    }.start();
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
        ResultCallback<DriveFolder.DriveFileResult>() {
            @Override
            public void onResult(DriveFolder.DriveFileResult result) {
                if (!result.getStatus().isSuccess()) {
                    Toast.makeText(MainActivity.this,"Error while trying to create the file",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(MainActivity.this,"Created a file with content: " +
                        result.getDriveFile().getDriveId(),Toast.LENGTH_SHORT).show();
            }
        };

I tried this method but the issue is occurring in the line

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {
      //      showMessage("Cannot find DriveId. Are you authorized to view this file?");
            Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
            return;
        }
     DriveId   mFolderDriveId = result.getDriveId();
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(driveContentsCallback);
    }
};

The result.getStatus.isSuccess is false is returning .Please help me how to create the file inside a folder in google drive.

Body:
You are calling

Drive.DriveApi.getRootFolder(mGoogleApiClient).createFile

which (unsurprisingly) creates a file in the Root Folder.
Instead you should call

 DriveFolder.createFile

as described at  https://developers.google.com/android/reference/com/google/android/gms/drive/DriveFolder.html#createFile(com.google.android.gms.common.api.GoogleApiClient,com.google.android.gms.drive.MetadataChangeSet,com.google.android.gms.drive.DriveContents)


答:
I'd probably structure code like this:

```<code>class Base {
public:
   void init() { sub_init(); }
protected:
   virtual void sub_init() = 0;
}
class A: public Base {
public:
   int a1;
protected:
   void sub_init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
protected:
   void sub_init() { b1 = 1;}
}
</code>```

The alternative of doing something like (syntax probably not correct...):

```<code>class Base {
public:
   virtual void init() = 0;
protected:
   void generic_init<T>(T &foo, T const &bar) { foo = bar; }
}
class A: public Base {
public:
   int a1;
   void init() { generic_init<int>(a1, 0); }
}
class B: public Base {
public:
   int b1;
   void init() { generic_init<int>(b1, 1); }
}
</code>```

Looks awful to me!

Title: C++ member initialization from derived class to base class

Body:
I'd probably structure code like this:

class Base {
public:
   void init() { sub_init(); }
protected:
   virtual void sub_init() = 0;
}
class A: public Base {
public:
   int a1;
protected:
   void sub_init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
protected:
   void sub_init() { b1 = 1;}
}

The alternative of doing something like (syntax probably not correct...):

class Base {
public:
   virtual void init() = 0;
protected:
   void generic_init<T>(T &foo, T const &bar) { foo = bar; }
}
class A: public Base {
public:
   int a1;
   void init() { generic_init<int>(a1, 0); }
}
class B: public Base {
public:
   int b1;
   void init() { generic_init<int>(b1, 1); }
}

Looks awful to me!


问:
Laravel Url won't work for two different files
I am working with Laravel on a homestead box. I have created two files under resources>views>profile (index.blade.php & pic.blade.php).

I am having trouble making the link for the image work across both files

```<code><img src="{{url('../')}}/public/img/{{Auth::user()->pic}}" width="100px" height="100px" /><br>

<img src="{{url('../')}}/img/{{Auth::user()->pic}}" width="100px" height="100px" /><br>
</code>```

each of these work but one will only display the image for one page at a time. I'm sure it has something to do with the path and the homestead environment, but not really sure.

答:
Your images seems to be stored in /public/img, you could use the helper asset()

```<code><img src="{{ asset('img/'.auth()->user()->pic) }}" width="100px" height="100px" /><br>
</code>```

Body:
I am working with Laravel on a homestead box. I have created two files under resources>views>profile (index.blade.php & pic.blade.php).

I am having trouble making the link for the image work across both files

pic}}" width="100px" height="100px" />

pic}}" width="100px" height="100px" />

each of these work but one will only display the image for one page at a time. I'm sure it has something to do with the path and the homestead environment, but not really sure.

Body:
Your images seems to be stored in /public/img, you could use the helper asset()

<img src="{{ asset('img/'.auth()->user()->pic) }}" width="100px" height="100px" /><br>


问:
Why does this happen IEnumerable versus List
I have the following BL method

```<code>public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

```<code>public void Save()
{
   group.SomeProp = true;
}
</code>```

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

```<code>public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

答:
In the first example you are using IEnumerable. Think about it like a query, not a list of objects. So then you are iterating through entire collection "group" using above query that says "iterate only elements that have SomeProp equal to false".

Then in your foreach statement you modify the state of the object in "group" list.

And then you are applying additional predicate on you query that states "Are there any elements in "group" list that have some prop equal to false?" And you obviously recieve an answer "no there are none of them".

In the second example you just getting new collection of elements, NOT a query. So then you iterate over it, chage state and then ask "Are there any elements?" And recive an "yes" answer. There are the same elements as before but with changed SomeProp property value.

Body:
I have the following BL method

public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

public void Save()
{
   group.SomeProp = true;
}

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks


问:
reactjs npm start ELIFECYCLE error
This is my first attempt at learning react, and it's started terribly. I've gone through the instructions directed here: https://facebook.github.io/react/docs/installation.html on the "Create a New App" tab exactly. Haven't done anything differently.

I'm using node 8.1.3, and npm 5.0.4

(I've also tried downgrading node to 6.11 without success).

I don't get any errors at all during installation.

When I run npm start, I get this super unhelpful error:

```<code>Starting the development server...

events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: watch /var/phil-machine/Code/react/test1/public ENOSPC
at exports._errnoException (util.js:1022:11)
at FSWatcher.start (fs.js:1384:19)
at Object.fs.watch (fs.js:1410:11)
at createFsWatchInstance (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:37:15)
at setFsWatchListener (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:80:15)
at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:228:14)
at FSWatcher.NodeFsHandler._handleDir (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:407:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:455:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:460:16)
at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test1@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test1@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/phil/.npm/_logs/2017-07-05T23_52_25_652Z-debug.log
</code>```

I'm at a loss. I've googled it (as best as I can - I'm not even sure what to google apart from the generic "react start error"), and got this answer https://stackoverflow.com/a/39960890/1569591 but that didn't help either.

When I run npm start it brings up the above error, and opens the bowser with a "Site cant be reached" error.

Can anyone help point me in the direction of how to fix this?

I've also tried changing the start command to use a different port:

```<code>PORT=3001 react-scripts start
</code>```

Didn't work either.

答:
Looks like an issue with node, ENOSPC means that there is no space on the drive.

Perhaps /tmp is full? You can configure npm to use a different temp folder by setting npm config set tmp /path/to/some/other/dir, or maybe delete everything out of the /tmp folder.

Source: ENOSPC in npm's repo in github.

Title: reactjs npm start ELIFECYCLE error

Body:
This is my first attempt at learning react, and it's started terribly. I've gone through the instructions directed here: https://facebook.github.io/react/docs/installation.html on the "Create a New App" tab exactly. Haven't done anything differently.

I'm using node 8.1.3, and npm 5.0.4

(I've also tried downgrading node to 6.11 without success).

I don't get any errors at all during installation.

When I run npm start, I get this super unhelpful error:

Starting the development server...

events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: watch /var/phil-machine/Code/react/test1/public ENOSPC
at exports._errnoException (util.js:1022:11)
at FSWatcher.start (fs.js:1384:19)
at Object.fs.watch (fs.js:1410:11)
at createFsWatchInstance (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:37:15)
at setFsWatchListener (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:80:15)
at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:228:14)
at FSWatcher.NodeFsHandler._handleDir (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:407:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:455:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:460:16)
at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test1@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test1@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/phil/.npm/_logs/2017-07-05T23_52_25_652Z-debug.log

I'm at a loss. I've googled it (as best as I can - I'm not even sure what to google apart from the generic "react start error"), and got this answer https://stackoverflow.com/a/39960890/1569591 but that didn't help either.

When I run npm start it brings up the above error, and opens the bowser with a "Site cant be reached" error.

Can anyone help point me in the direction of how to fix this?

I've also tried changing the start command to use a different port:

PORT=3001 react-scripts start

Didn't work either.


问:
create a template url-routing script
I want to create an url-routing script using javascript as much as possible, but also accepting jQuery in the code. The js file has to change the url path (although I used location.hash instead of location.pathname) and the content of a div with the view id (from external files) accordingly.

Example configuration:

root/index.html

root/tpl/home.html

root/tpl/about.html

home.html content:

```<code><p>This is content of home page</p>
</code>```

about.html content:

```<code><p>This is the content of the about page </p>
</code>```

What I have done so far:

```<code>'use strict';
var Router = {
root: '/',
routes: [],
urls: [],
titles: [],
navigate: function() {
    location.hash = this.root;
    return this;
},
add: function(thePath, theUrl, theTitle) {
    this.routes.push(thePath);
    this.urls.push(theUrl);
    this.titles.push(theTitle);
},
loading: function() {
    this.navigate();
    var r = this.routes;
    var u = this.urls;
    window.onload = function() {
        $("#view").load("tpl/home.html");
    };
    window.onhashchange = function() {
        for (var i = 0; i < r.length; i++) {
            if (location.hash == r[i]) {
                $("#view").load(u[i]);
            }
        }
    };
}
};
Router.add("#/home", "tpl/home.html", "Home Page");
Router.add("#/about", "tpl/about.html", "About Page");
Router.loading();
</code>```

Desired type of url:

```<code>http://mywebsite.com/
http://mywebsite.com/about
</code>```

I know there are more than enough libraries that make the routing, like AngularJS and Crossroad, I want to know how this could be done.

答:
You might be interested by frontexpress.

My library fix your case like below:

```<code>// Front-end application
const app = frontexpress();

const homeMiddleware = (req, res) => {
  document.querySelector('#view').innerHTML = '<p>This is content of home page</p>';
}

app.get('/', homeMiddleware);

app.get('/home', homeMiddleware);

app.get('/about', (req, res) => {
  document.querySelector('#view').innerHTML = '<p>This is the content of the about page </p>';
});
</code>```

Obviously, you can get the template files from the server.
The #view will be feeded as below:

```<code>document.querySelector('#view').innerHTML = res.responseText;
</code>```

More detailed sample in this gist

Title: create a template url-routing script

Body:
I want to create an url-routing script using javascript as much as possible, but also accepting jQuery in the code. The js file has to change the url path (although I used location.hash instead of location.pathname) and the content of a div with the view id (from external files) accordingly.

Example configuration:

root/index.html

root/tpl/home.html

root/tpl/about.html

home.html content:

This is content of home page

about.html content:

This is the content of the about page

What I have done so far:

'use strict';
var Router = {
root: '/',
routes: [],
urls: [],
titles: [],
navigate: function() {
    location.hash = this.root;
    return this;
},
add: function(thePath, theUrl, theTitle) {
    this.routes.push(thePath);
    this.urls.push(theUrl);
    this.titles.push(theTitle);
},
loading: function() {
    this.navigate();
    var r = this.routes;
    var u = this.urls;
    window.onload = function() {
        $("#view").load("tpl/home.html");
    };
    window.onhashchange = function() {
        for (var i = 0; i < r.length; i++) {
            if (location.hash == r[i]) {
                $("#view").load(u[i]);
            }
        }
    };
}
};
Router.add("#/home", "tpl/home.html", "Home Page");
Router.add("#/about", "tpl/about.html", "About Page");
Router.loading();

Desired type of url:

http://mywebsite.com/
http://mywebsite.com/about

I know there are more than enough libraries that make the routing, like AngularJS and Crossroad, I want to know how this could be done.

Body:
You might be interested by frontexpress.

My library fix your case like below:

// Front-end application
const app = frontexpress();

const homeMiddleware = (req, res) => {
  document.querySelector('#view').innerHTML = '<p>This is content of home page</p>';
}

app.get('/', homeMiddleware);

app.get('/home', homeMiddleware);

app.get('/about', (req, res) => {
  document.querySelector('#view').innerHTML = '<p>This is the content of the about page </p>';
});

Obviously, you can get the template files from the server.
The #view will be feeded as below:

document.querySelector('#view').innerHTML = res.responseText;

More detailed sample in this gist


问:
CERTIFICATE_VERIFY_FAILED error when trying to use Google's Assistant SDK with RPi 3
I am trying to use Google Assistant SDK for the Raspberry Pi 3. I managed to install everything correctly, and the date is perfectly correct. However, when I try to Authorize the Google Assistant SDK sample, I get the error described in the title. It can't verify the certificate.

When I use date, the result is Thu Jun 29 17:16:42 CST 2017, which is very much correct at the time I use it. I am located in Costa Rica.

This is the complete error output.

```<code>Traceback (most recent call last):
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 345, in _make_request
    self._validate_conn(conn)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 844, in _validate_conn
    conn.connect()
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connection.py", line 326, in connect
    ssl_context=context)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/util/ssl_.py", line 325, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/usr/lib/python3.4/ssl.py", line 364, in wrap_socket
    _context=self)
  File "/usr/lib/python3.4/ssl.py", line 577, in __init__
    self.do_handshake()
  File "/usr/lib/python3.4/ssl.py", line 804, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/env/lib/python3.4/site-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 630, in urlopen
    raise SSLError(e)
urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/env/bin/google-oauthlib-tool", line 11, in <module>
    sys.exit(main())
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/tool/__main__.py", line 106, in main
    creds = flow.run_console()
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/flow.py", line 358, in run_console
    self.fetch_token(code=code)
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/flow.py", line 235, in fetch_token
    **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests_oauthlib/oauth2_session.py", line 221, in fetch_token
    verify=verify, proxies=proxies)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 549, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests_oauthlib/oauth2_session.py", line 360, in request
    headers=headers, data=data, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 502, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 612, in send
    r = adapter.send(request, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
</code>```

答:
I had the same problem. I found a guide saying the following dependencies are required. This fixed it for me.</p>

```<code>sudo apt-get install portaudio19-dev libffi-dev libssl-dev
</code>```

Body:
I am trying to use Google Assistant SDK for the Raspberry Pi 3. I managed to install everything correctly, and the date is perfectly correct. However, when I try to Authorize the Google Assistant SDK sample, I get the error described in the title. It can't verify the certificate.

When I use date, the result is Thu Jun 29 17:16:42 CST 2017, which is very much correct at the time I use it. I am located in Costa Rica.

This is the complete error output.

Traceback (most recent call last):
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 345, in _make_request
    self._validate_conn(conn)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 844, in _validate_conn
    conn.connect()
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connection.py", line 326, in connect
    ssl_context=context)
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/util/ssl_.py", line 325, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/usr/lib/python3.4/ssl.py", line 364, in wrap_socket
    _context=self)
  File "/usr/lib/python3.4/ssl.py", line 577, in __init__
    self.do_handshake()
  File "/usr/lib/python3.4/ssl.py", line 804, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/env/lib/python3.4/site-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/home/pi/env/lib/python3.4/site-packages/urllib3/connectionpool.py", line 630, in urlopen
    raise SSLError(e)
urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/env/bin/google-oauthlib-tool", line 11, in <module>
    sys.exit(main())
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/pi/env/lib/python3.4/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/tool/__main__.py", line 106, in main
    creds = flow.run_console()
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/flow.py", line 358, in run_console
    self.fetch_token(code=code)
  File "/home/pi/env/lib/python3.4/site-packages/google_auth_oauthlib/flow.py", line 235, in fetch_token
    **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests_oauthlib/oauth2_session.py", line 221, in fetch_token
    verify=verify, proxies=proxies)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 549, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests_oauthlib/oauth2_session.py", line 360, in request
    headers=headers, data=data, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 502, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/sessions.py", line 612, in send
    r = adapter.send(request, **kwargs)
  File "/home/pi/env/lib/python3.4/site-packages/requests/adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

Body:
I had the same problem. I found a guide saying the following dependencies are required. This fixed it for me.

sudo apt-get install portaudio19-dev libffi-dev libssl-dev


问:
Getting random number from 6502 assembler
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

```<code>. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK
</code>```

Now when I try to iterate say 10 times with the following code, it never returns.

```<code>. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK
</code>```

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.

答: You are essentially calling RND(0) which uses the timer to generate a seed. However, that is not directly usuable in assembly. First try switching to a positive number (any number) and see if it starts producing values.

Body:
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK

Now when I try to iterate say 10 times with the following code, it never returns.

. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.


问:
How do I create a variable length dropdown list on a ViewModel without repeating code in c#?
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

```<code>Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .
</code>```

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

```<code>[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}
</code>```

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

```<code>                      *******QUESTION EDIT***********
</code>```

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

```<code>        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }
</code>```

My Html View

```<code>        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")
</code>```

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

答:
given a generic function to get the list of dates :-

```<code>public static IEnumerable<string> ReverseMonthList(string format, DateTime start, int count)
    {
        return Enumerable.Range(0, count).Select(n => start.AddMonths(-(n + 1)).ToString(format));
    }
</code>```

then

```<code>var from = new DateTime(2016, 7, 5);
var now = new DateTime(2017, 7, 5);
var monthsSinceStart = ((now.Year - @from.Year) * 12) + now.Month - @from.Month;
var dates = ReverseMonthList("MMM yyyy", now, monthsSinceStart);
</code>```

gives

Body:
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

                      *******QUESTION EDIT***********

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }

My Html View

        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

Body:
given a generic function to get the list of dates :-

public static IEnumerable<string> ReverseMonthList(string format, DateTime start, int count)
    {
        return Enumerable.Range(0, count).Select(n => start.AddMonths(-(n + 1)).ToString(format));
    }

then

var from = new DateTime(2016, 7, 5);
var now = new DateTime(2017, 7, 5);
var monthsSinceStart = ((now.Year - @from.Year) * 12) + now.Month - @from.Month;
var dates = ReverseMonthList("MMM yyyy", now, monthsSinceStart);

gives


问:
How to figure out the type parameter for nested type parameter
With the following code,new Box(10),  new Box("20") works well for me. But for the new Box(Seq(20)), new Box(Seq("20"))),
I would like to figure out the type of type parameter for the Seq, so that I could print Seq[Int], Seq[String]

```<code>      @Test
      def testClassTag(): Unit = {
        class Box[T:ClassTag](val data: T) {
          def printTypeParameter() = {
            val tag = implicitly[ClassTag[T]].runtimeClass
            tag match {
              case _ if tag == classOf[Int] => println("Int")
              case _ if tag == classOf[String] => println("String")
              case _ if tag == classOf[Seq[_]] => println( "Seq")
            }
          }
        }
        val boxes = Seq(new Box(10),  new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
        boxes.foreach(_.printTypeParameter())

  }
</code>```

答:
@dima's answer is elegant, I would put another way that detects the type parameter step by step.</p>

```<code> @Test
  def testTypeTag1(): Unit = {
    class Box[T: TypeTag](val data: T) {
      def printTypeParameter() = {
        typeOf[T] match {
          case t if t =:= typeOf[Int] => println("Int")
          case t if t =:= typeOf[String] => println("String")
          case t if t <:< typeOf[Seq[Any]] => {
            val TypeRef(_, _, Seq(elementType)) =  typeOf[T]
            elementType match {
              case t if t =:= typeOf[Int] =>println("Seq[Int]")
              case t if t =:= typeOf[String] =>println("Seq[String]")
              case _=>println("Seq[Unknown]")
            }
          }
          case _ => println("Unknown")
        }
      }
    }
    val boxes = Seq(new Box(10), new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
    boxes.foreach(_.printTypeParameter())
  }
</code>```

Body:
With the following code,new Box(10),  new Box("20") works well for me. But for the new Box(Seq(20)), new Box(Seq("20"))),
I would like to figure out the type of type parameter for the Seq, so that I could print Seq[Int], Seq[String]

      @Test
      def testClassTag(): Unit = {
        class Box[T:ClassTag](val data: T) {
          def printTypeParameter() = {
            val tag = implicitly[ClassTag[T]].runtimeClass
            tag match {
              case _ if tag == classOf[Int] => println("Int")
              case _ if tag == classOf[String] => println("String")
              case _ if tag == classOf[Seq[_]] => println( "Seq")
            }
          }
        }
        val boxes = Seq(new Box(10),  new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
        boxes.foreach(_.printTypeParameter())

  }

Body:
@dima's answer is elegant, I would put another way that detects the type parameter step by step.

 @Test
  def testTypeTag1(): Unit = {
    class Box[T: TypeTag](val data: T) {
      def printTypeParameter() = {
        typeOf[T] match {
          case t if t =:= typeOf[Int] => println("Int")
          case t if t =:= typeOf[String] => println("String")
          case t if t <:< typeOf[Seq[Any]] => {
            val TypeRef(_, _, Seq(elementType)) =  typeOf[T]
            elementType match {
              case t if t =:= typeOf[Int] =>println("Seq[Int]")
              case t if t =:= typeOf[String] =>println("Seq[String]")
              case _=>println("Seq[Unknown]")
            }
          }
          case _ => println("Unknown")
        }
      }
    }
    val boxes = Seq(new Box(10), new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
    boxes.foreach(_.printTypeParameter())
  }


答:
In case of live deployed system,  you should use

```<code><img src="{{url('/img/'.Auth::user()->pic)}}" width="100px" height="100px" /><br>
</code>```

Or if it is just a normal local server  with /public included in URL

```<code><img src="{{url('/public/img/'.Auth::user()->pic)}}" width="100px" height="100px" /><br>
</code>```

this should generate URL to img folder which is accessible publically

Title: Laravel Url won't work for two different files

Body:
In case of live deployed system,  you should use

<img src="{{url('/img/'.Auth::user()->pic)}}" width="100px" height="100px" /><br>

Or if it is just a normal local server  with /public included in URL

<img src="{{url('/public/img/'.Auth::user()->pic)}}" width="100px" height="100px" /><br>

this should generate URL to img folder which is accessible publically


答:
The list is unusual because it must populate backward from last month up until a year ago.

It's easy to do. First - generate dates. You have the start date (previous month) and a total number of months required (12). Then project each date into SelectListItem:

```<code>var today = DateTime.Today;
var startOfMonth = new DateTime(today.Year, today.Month, 1);

var items = from i in Enumerable.Range(1, 12)
            let date = startOfMonth.AddMonths(-i)
            select new SelectListItem {
                Text = date.ToString("MMM yyyy"),
                Value = date.ToString("MMM"),
                Selected = i == 1
            };

ViewBag.MonthList = items.ToList();
</code>```

Notes:

You should calculate dates relative to the start of the current month. Otherwise, you can have a problem with February 29.

Use string format to produce the date in the format you want. Do not format parts of the date and concatenate them.

Year format string is lowercase yyyy

SelectListItem item[y] = ... is incorrect syntax. It's a mix of assignment and declaration. If you want to assign an item in the list, then you should refer to the item by index item[y] = .... But you should check before if the list contains enough items. Actually what you really need to do here is add an item to the list, which is achieved by items.Add(...).

Consider to learn LINQ - it allows you to write queries (in a declarative way) to easily filter, project, etc data

Title: How do I create a variable length dropdown list on a ViewModel without repeating code in c#?

Body:
The list is unusual because it must populate backward from last month up until a year ago.

It's easy to do. First - generate dates. You have the start date (previous month) and a total number of months required (12). Then project each date into SelectListItem:

var today = DateTime.Today;
var startOfMonth = new DateTime(today.Year, today.Month, 1);

var items = from i in Enumerable.Range(1, 12)
            let date = startOfMonth.AddMonths(-i)
            select new SelectListItem {
                Text = date.ToString("MMM yyyy"),
                Value = date.ToString("MMM"),
                Selected = i == 1
            };

ViewBag.MonthList = items.ToList();

Notes:

You should calculate dates relative to the start of the current month. Otherwise, you can have a problem with February 29.

Use string format to produce the date in the format you want. Do not format parts of the date and concatenate them.

Year format string is lowercase yyyy

SelectListItem item[y] = ... is incorrect syntax. It's a mix of assignment and declaration. If you want to assign an item in the list, then you should refer to the item by index item[y] = .... But you should check before if the list contains enough items. Actually what you really need to do here is add an item to the list, which is achieved by items.Add(...).

Consider to learn LINQ - it allows you to write queries (in a declarative way) to easily filter, project, etc data


问:
how to pass list of ids to mysql delete query from NodeJs
i need to do a multiple row delete query with the where clause in list (id1,id2..)
But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:

```<code> let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 connection.query(Query,list, function (err, result) {
     `enter code here`
 };
</code>```

when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.

PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.

答:
Simply append the list of items to the query string:</p>

```<code> let list = [1, 2, 3];
 let Query = `DELETE FROM Table WHERE id IN (${list})`;
 connection.query(Query, function (err, result) {
     `enter code here`
 };
</code>```

Body:
i need to do a multiple row delete query with the where clause in list (id1,id2..)
But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:

 let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 connection.query(Query,list, function (err, result) {
     `enter code here`
 };

when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.

PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.

Body:
Simply append the list of items to the query string:

 let list = [1, 2, 3];
 let Query = `DELETE FROM Table WHERE id IN (${list})`;
 connection.query(Query, function (err, result) {
     `enter code here`
 };