问:
facebook application -> on my website?
Basically, when someone visits X page on my website, I want there to be a "content blocker" which shows a popup asking them to Allow/Deny my facebook application.

If they Allow it, it removes the content blocker and shows the content and never shows the content blocker again if they are logged in to facebook as they have already allowed my application.

If they deny it, it removes the content blocker and shows the content but it will always show the content blocker if they are logged in to facebook and not allowed my application.

I basically want it to work like this:

```<code>http://tyler.tc/FBLike/
</code>```

But instead of it showing a box with Like in it, I want it to contain my application - which I want to look something like this:

```<code>http://i56.tinypic.com/vi1xzc.jpg
</code>```

Is there any way I can do this?

I would really appreciate feedback as I'm new to Facebook developing.

Regards.

答:
If you're using the Facebook Graph API, there is some documentation for how to do that dialog here.  Basically, you can create an iframe with its source set to this URL:

```<code>https://graph.facebook.com/oauth/authorize?client_id=...&redirect_uri=...&type=user_agent&display=popup
</code>```

Set client_id to your application ID and redirect_uri to the URL of a server-side handler that can retrieve a user's auth token.

Title: facebook application -> on my website?

Body:
Basically, when someone visits X page on my website, I want there to be a "content blocker" which shows a popup asking them to Allow/Deny my facebook application.

If they Allow it, it removes the content blocker and shows the content and never shows the content blocker again if they are logged in to facebook as they have already allowed my application.

If they deny it, it removes the content blocker and shows the content but it will always show the content blocker if they are logged in to facebook and not allowed my application.

I basically want it to work like this:

http://tyler.tc/FBLike/

But instead of it showing a box with Like in it, I want it to contain my application - which I want to look something like this:

http://i56.tinypic.com/vi1xzc.jpg

Is there any way I can do this?

I would really appreciate feedback as I'm new to Facebook developing.

Regards.

Body:
If you're using the Facebook Graph API, there is some documentation for how to do that dialog here.  Basically, you can create an iframe with its source set to this URL:

https://graph.facebook.com/oauth/authorize?client_id=...&redirect_uri=...&type=user_agent&display=popup

Set client_id to your application ID and redirect_uri to the URL of a server-side handler that can retrieve a user's auth token.


来源: stackexchange

问:
Passing multiple types to std::function C++
I am currently working on a little library and ran into a error. What I am basically trying to do is have syntax like so:

```<code>Client client("", true);

client.on("ready", [](User object) {
    object.test();
});

client.run();
</code>```

and when I call
_eventManager->emit("ready", new User())
The client.on(); method is suppose to fire with the given object I pass in. The object that I pass can be a variety of classes.

The way I design it so that I use a base class called "Object" and all the classes that I want to pass onto emit would be derived from Object. However I get an error when trying to do this:

error C2664: 'void Discord::Client::on(const std::string &,const std::function<void (Discord::Object)> &)': cannot convert argument 2 from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)> &'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: Reason: cannot convert from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)>'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I am clueless on what I did wrong.
Code:

```<code>struct Event {
    std::string name;
    std::function<void(Object object)> function;
};

void Client::on(const std::string& name, const std::function<void(Object object)>& function) {
    _eventManager->add(name, function);
}

void Client::run() {
    User object;

    _eventManager->emit("ready", object);
}

void EventManager::add(const std::string& name, const std::function<void(Object object)>& function) {
    Event event;
    event.name = name;
    event.function = function;

    _events.push_back(event);
}

void EventManager::emit(const std::string& name, const Object& object) {
    for (unsigned int i = 0; i < _events.size(); i++) {
        Event& event = _events[i];

        if (event.name == name) {
            event.function(object);
        }
    }
}
</code>```

Error
Thank you in advance.

答:
Your function is declared to take Object object:

```<code>std::function<void(Object object)> function;
</code>```

but you pass lambda that takes User:

```<code>client.on("ready", [](User object) {
    object.test();
});
</code>```

Is this what you are looking for?

```<code>client.on("ready", [](Object object) {
    auto& user = static_cast<User&>(object);  // not safe
    user.test();
});
</code>```

Note that this might crash your app if you try to access any field that belongs to User class but not to Object class (it's probably an undefined behaviour) since passing by value "slices" data. What you should probably do is pass pointers/refs around:

```<code>client.on("ready", [](Object& object) {   // <-- by ref here
    auto& user = static_cast<User&>(object);  // safer, at least won't crash when you pass User object
    user.test();
});
</code>```

Note that this requires some major refactoring. Not only adding & everywhere but you now have to worry about lifetimes of those objects.

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on a little library and ran into a error. What I am basically trying to do is have syntax like so:

Client client("", true);

client.on("ready", [](User object) {
    object.test();
});

client.run();

and when I call
_eventManager->emit("ready", new User())
The client.on(); method is suppose to fire with the given object I pass in. The object that I pass can be a variety of classes.

The way I design it so that I use a base class called "Object" and all the classes that I want to pass onto emit would be derived from Object. However I get an error when trying to do this:

error C2664: 'void Discord::Client::on(const std::string &,const std::function<void (Discord::Object)> &)': cannot convert argument 2 from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)> &'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: Reason: cannot convert from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)>'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I am clueless on what I did wrong.
Code:

struct Event {
    std::string name;
    std::function<void(Object object)> function;
};

void Client::on(const std::string& name, const std::function<void(Object object)>& function) {
    _eventManager->add(name, function);
}

void Client::run() {
    User object;

    _eventManager->emit("ready", object);
}

void EventManager::add(const std::string& name, const std::function<void(Object object)>& function) {
    Event event;
    event.name = name;
    event.function = function;

    _events.push_back(event);
}

void EventManager::emit(const std::string& name, const Object& object) {
    for (unsigned int i = 0; i < _events.size(); i++) {
        Event& event = _events[i];

        if (event.name == name) {
            event.function(object);
        }
    }
}

Error
Thank you in advance.

Body:
Your function is declared to take Object object:

std::function<void(Object object)> function;

but you pass lambda that takes User:

client.on("ready", [](User object) {
    object.test();
});

Is this what you are looking for?

client.on("ready", [](Object object) {
    auto& user = static_cast<User&>(object);  // not safe
    user.test();
});

Note that this might crash your app if you try to access any field that belongs to User class but not to Object class (it's probably an undefined behaviour) since passing by value "slices" data. What you should probably do is pass pointers/refs around:

client.on("ready", [](Object& object) {   // <-- by ref here
    auto& user = static_cast<User&>(object);  // safer, at least won't crash when you pass User object
    user.test();
});

Note that this requires some major refactoring. Not only adding & everywhere but you now have to worry about lifetimes of those objects.


问:
Keep the lifespan of variable after multiple function calls?
Assuming:

```<code>def myfunc(x):
    my_list  = []
    list.append(x)
</code>```

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

```<code>def myfunc(x):
    NA listv  = []
    list.append(x)
</code>```

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

答:
I guess you are looking for something equivalent to the final keyword in Java. Simply put, there is no such keyword. The Python attitude is "if you don't want this modified at all, just don't modify it, I wont stop you though".

However you can mimic something like it by some tweaks in your class.

```<code>class MyFinalVariablesClass:
    def __setattr__(self, attr, value):
        # if it already has this attribute, complain !
        if hasattr(self, attr):
            raise Exception("Attempting to alter read-only value")

        self.__dict__[attr] = value
</code>```

Or in the case of your variable (haven't tested it)

```<code>class WriteOnceReadWhenever:
    def __setattr__(self, attr, value):
        if attr == 'my_list' and hasattr(self, attr):
            raise Exception("Attempting to alter read-only value")
        self.__dict__[attr] = value
</code>```

Body:
Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

def myfunc(x):
    NA listv  = []
    list.append(x)

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

Body:
I guess you are looking for something equivalent to the final keyword in Java. Simply put, there is no such keyword. The Python attitude is "if you don't want this modified at all, just don't modify it, I wont stop you though".

However you can mimic something like it by some tweaks in your class.

class MyFinalVariablesClass:
    def __setattr__(self, attr, value):
        # if it already has this attribute, complain !
        if hasattr(self, attr):
            raise Exception("Attempting to alter read-only value")

        self.__dict__[attr] = value

Or in the case of your variable (haven't tested it)

class WriteOnceReadWhenever:
    def __setattr__(self, attr, value):
        if attr == 'my_list' and hasattr(self, attr):
            raise Exception("Attempting to alter read-only value")
        self.__dict__[attr] = value


问:
Framework red after importing it into a workspace swift
I have downloaded this https://github.com/MichelDeiman/Programming-Project-4_-Smashtag-Mentions Twitter project to use the Twitter.framework it comes with. When I open it from the download, it loads fine. However, when I move the Twitter.xcodeproj to my Xcode workspace, it turns the framework red and doesn't allow me to use it.

I have searched for a solution and think it has to do with finding the correct path for the framework but have been unsuccessful. Any thoughts?

答: Red means it hasn't been built yet. I suspect you can't use it because it hasn't been imported in the Build settings. I'd check there first. If it's imported correctly then it should built when you build the targets that refer to it.</p>


问:
Rails Generate Model not using inflection rule
I'm trying to generate a 'Status' model in Rails 5.1 and when I run

```<code>rails generate model status
</code>```

I get

```<code>The model name 's' was recognized as a plural, using the singular '' instead. Override with --force-plural or setup custom inflection rules for this noun before running the generator.
</code>```

I then added a new rule in config/initializers/inflections.rb

```<code>ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.irregular 'status', 'statuses'
end
</code>```

ran the command again and I still get the error.

What am I missing?

答: Maybe you can Change name to be state,  so the plural  is states</p>

Body:
I'm trying to generate a 'Status' model in Rails 5.1 and when I run

rails generate model status

I get

The model name 's' was recognized as a plural, using the singular '' instead. Override with --force-plural or setup custom inflection rules for this noun before running the generator.

I then added a new rule in config/initializers/inflections.rb

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.irregular 'status', 'statuses'
end

ran the command again and I still get the error.

What am I missing?


问:
Insert NIC driver into custom install.wim
Up to today, I have been using a single boot.wim file and a single install.wim file (captured from a configured PC, with DISM) to install Windows 10 from my Server 2012R2 WDS server. Now we have purchased new hardware and I need to add a driver to both .wim files. I was able to use the following steps to put the driver into the boot.wim:

Dism.exe /mount-wim /wimfile:d:\temp\boot.wim /index:2 /mountdir:d:\temp\mount

Dism.exe /image:"d:\temp\mount" /add-driver /driver:"d:\temp\drivers\IntelI354"

Once that was done, I PXE booted and was able to pull down my install image. So, I used the same steps to update install.wim, but when I pulled down the updated image, the NIC was not detected.

I followed the steps in scenario 1, from https://technet.microsoft.com/en-us/library/dd348456%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396, to deploy driver packages through WDS, but it obviously didn't work.

What do I need to do, to get this new NIC driver properly installed in my image?

Thanks.

答: I ended up using: https://blogs.technet.microsoft.com/doxley/2007/12/13/editing-the-registry-of-your-wim-without-having-to-recapture/ to load the registry file from the WIM, and https://technet.microsoft.com/en-us/library/cc753716(v=ws.11).aspx to add my desired directory to the DevicePath registry entry. </p>


问:
Get coordinates from leaflet app embedded in webpage using python scraping
I'm trying to download coordinates for points (ATMs in Czech Republic) from a webpage that is using embedded leaflet to visualize these points.

Here is the webpage: (it's in Czech Language)

http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/

I'm using python3

What I have done so far is used urllib to download the webpage and beautiful soup to somehow format it.

```<code>from bs4 import BeautifulSoup
import urllib

url = 'http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/'

raw_text = urllib.request.urlopen(url).read()
utf_text = raw_text.decode('utf-8')
soup = BeautifulSoup(utf_text)

scripts = soup.findAll("script")
scripts
</code>```

What I want to get is hidden in 'point_list' variable - it contains coordinates and names of ATMs, but I am not successful in getting this variable.

```<code>...
point_list = ['', '/static/vizualizace/leaflet/img/icon/banky/zluta_bankomaty.svg', [50.3165463776, 13.535562001, '<b>Česká spořitelna</b><br />Husova 2908, Žatec<br />...
...
</code>```

What I tried and wasn't working:

```<code>for link in soup.find_all("script"):
    if "point" in link:
        print(link)
</code>```

It doesn't print anything.

There must be some important thing that I am missing and can't seem to find an answer to. I don't have a lot of experiences with scraping, I have only scraped some hyperlinks before, which was fairly straightforward.

UPDATE:

Thanks for the answer @vold, I was able to use it as a starter for what I needed as a result.

```<code>list_addresses = []
# first split by left bracket
for item in all_address.split('['):
    # then replace redundant characters
    replace_item1 = item.replace("<br /><b>GPS: </b>", ',')
    replace_item2 = replace_item1.replace("</b><br />", ",")
    replace_item = replace_item2.replace("'<b>", "")
    # and split an element (one ATM) by comma, creating a list of lists
    clean_item = replace_item.split(',')
    # strip whitespace
    strip_list = list(map(str.strip, clean_item))
    # creates list of lists
    list_addresses.append(strip_list)

# I don't need the first element
Table = pd.DataFrame(list_addresses[1:])
Table
</code>```

I think this is not a clean solution and would appreciate if there was something more elegant.

Thanks

答:
You can use parsel library and regex to get desired value from the page source like this:

```<code>import requests
from parsel import Selector

url = 'http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/'
r = requests.get(url)
sel = Selector(r.text)
all_address = sel.xpath('//script[contains(.,"point_list")]').re_first(r'point_list = \[(.*)\]\];')

for item in all_address.split(','):
    print(item)
</code>```

But you can also get that value directly from the page with xpath expression: //div[h2]/text()

Body:
I'm trying to download coordinates for points (ATMs in Czech Republic) from a webpage that is using embedded leaflet to visualize these points.

Here is the webpage: (it's in Czech Language)

http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/

I'm using python3

What I have done so far is used urllib to download the webpage and beautiful soup to somehow format it.

from bs4 import BeautifulSoup
import urllib

url = 'http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/'

raw_text = urllib.request.urlopen(url).read()
utf_text = raw_text.decode('utf-8')
soup = BeautifulSoup(utf_text)

scripts = soup.findAll("script")
scripts

What I want to get is hidden in 'point_list' variable - it contains coordinates and names of ATMs, but I am not successful in getting this variable.

...
point_list = ['', '/static/vizualizace/leaflet/img/icon/banky/zluta_bankomaty.svg', [50.3165463776, 13.535562001, 'Česká spořitelna
Husova 2908, Žatec
...
...

What I tried and wasn't working:

for link in soup.find_all("script"):
    if "point" in link:
        print(link)

It doesn't print anything.

There must be some important thing that I am missing and can't seem to find an answer to. I don't have a lot of experiences with scraping, I have only scraped some hyperlinks before, which was fairly straightforward.

UPDATE:

Thanks for the answer @vold, I was able to use it as a starter for what I needed as a result.

list_addresses = []
# first split by left bracket
for item in all_address.split('['):
    # then replace redundant characters
    replace_item1 = item.replace("
GPS: ", ',')
    replace_item2 = replace_item1.replace("
", ",")
    replace_item = replace_item2.replace("'", "")
    # and split an element (one ATM) by comma, creating a list of lists
    clean_item = replace_item.split(',')
    # strip whitespace
    strip_list = list(map(str.strip, clean_item))
    # creates list of lists
    list_addresses.append(strip_list)

# I don't need the first element
Table = pd.DataFrame(list_addresses[1:])
Table

I think this is not a clean solution and would appreciate if there was something more elegant.

Thanks

Body:
You can use parsel library and regex to get desired value from the page source like this:

import requests
from parsel import Selector

url = 'http://www.kurzy.cz/banky/bankomaty/zatec-okres-louny/'
r = requests.get(url)
sel = Selector(r.text)
all_address = sel.xpath('//script[contains(.,"point_list")]').re_first(r'point_list = \[(.*)\]\];')

for item in all_address.split(','):
    print(item)

But you can also get that value directly from the page with xpath expression: //div[h2]/text()


问:
Android Studio Random.org
I'm new to APIs and Libraries and I want to know how I can implement Random.org into my app. I need a random number from 1 to 6 (I'm making a dice app) and I only need one number to be generated. I've got my API key, bu I don't know what to do next. Random.org itself isn't all that clear on what to do next exactly. Does anyone of you know the exact steps to make a TextView which generates a new number at the press of a button?

答:
Here it explains how to obtain a random integer using an http request.
You will have to program that using an http client or library like okhttp or ion, so as to issue the request and get the random number in the response.

Once you get the response you can update the TextView.

There are some guidelines to use the service. I sugest you also go through that if you plan to use this service.

HTTP Interface Description

The http interface provides this example. I have changed the number of results to one as to match one dice result.

```<code>https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new
</code>```

Title: Android Studio Random.org

Body:
Here it explains how to obtain a random integer using an http request.
You will have to program that using an http client or library like okhttp or ion, so as to issue the request and get the random number in the response.

Once you get the response you can update the TextView.

There are some guidelines to use the service. I sugest you also go through that if you plan to use this service.

HTTP Interface Description

The http interface provides this example. I have changed the number of results to one as to match one dice result.

https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new


问:
ASP.NET -- C# MVC5
Basically I have something a site that a user inputs a image with a title and i want to display it on the website. That title for that image.

Atm I'm saving to a folder and displaying all images but I cant display the title. It just doesnt appear when I do
@Html.DisplayFor(m => m.title)

Something like this: But I wanted the title of the post.
https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

Maybe I need to save the image to the database? Please help me on this.

View:

```<code>    @foreach (var image in Model.Images)
{
    <h2>@Html.DisplayFor(m => m.title)</h2>
    <div class="row">
        <div class="col-md-8 portfolio-item">
            <img class="portrait" src="@Url.Content(image)" alt="Hejsan" />
        </div>
    </div>

}
</code>```

Model

```<code> [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}
</code>```

Controller:

```<code> public class MemesController : Controller
{

    private string memesDirectory = "~/Content/Images/Memes/";

    // GET: Memes/Upload
    public ActionResult Upload()
    {
        var uploadFile = new UploadFileModel();
        return View(uploadFile);
    }

    // GET: Memes/Hot
    public ActionResult Hot(UploadFileModel uploadFileModel)
    {
        //Select every image on the server memesdirectory and posts it
        uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
        return View();
    }

    // GET: Memes/Trending
    public ActionResult Trending()
    {
        return View();
    }

    // GET: Memes/Fresh
    public ActionResult Fresh()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Upload(UploadFileModel uploadModel)
    {
        if(Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            if(file != null && file.ContentLength > 0)
            {
                //saves image to the server
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath(memesDirectory), fileName);
                file.SaveAs(path);

                //saves image-related data to the database
                uploadModel.userID = User.Identity.GetUserId();
                uploadModel.location = path;
                uploadModel.contentType = file.ContentType;
                uploadModel.contentLength = file.ContentLength;

                //saves to the database
                uploadModel.SavetoDatabase(uploadModel);
            }
        }
        return RedirectToAction("Index", "Home");
    }
}
</code>```

}

答:
```<code>    uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
    return View();
</code>```

likely needs to be changed to:

```<code>    // Add code here to get uploadFileModel from the databases
    uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
    uploadFileModel.title = "something you want"; // this line may not be necessary if getting it from the database did this for you already

    return View(uploadFileModel);
</code>```

Title: ASP.NET -- C# MVC5

Body:
Basically I have something a site that a user inputs a image with a title and i want to display it on the website. That title for that image.

Atm I'm saving to a folder and displaying all images but I cant display the title. It just doesnt appear when I do
@Html.DisplayFor(m => m.title)

Something like this: But I wanted the title of the post.
https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

Maybe I need to save the image to the database? Please help me on this.

View:

    @foreach (var image in Model.Images)
{

@Html.DisplayFor(m => m.title)

}

Model

 [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}

Controller:

 public class MemesController : Controller
{

    private string memesDirectory = "~/Content/Images/Memes/";

    // GET: Memes/Upload
    public ActionResult Upload()
    {
        var uploadFile = new UploadFileModel();
        return View(uploadFile);
    }

    // GET: Memes/Hot
    public ActionResult Hot(UploadFileModel uploadFileModel)
    {
        //Select every image on the server memesdirectory and posts it
        uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
        return View();
    }

    // GET: Memes/Trending
    public ActionResult Trending()
    {
        return View();
    }

    // GET: Memes/Fresh
    public ActionResult Fresh()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Upload(UploadFileModel uploadModel)
    {
        if(Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            if(file != null && file.ContentLength > 0)
            {
                //saves image to the server
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath(memesDirectory), fileName);
                file.SaveAs(path);

                //saves image-related data to the database
                uploadModel.userID = User.Identity.GetUserId();
                uploadModel.location = path;
                uploadModel.contentType = file.ContentType;
                uploadModel.contentLength = file.ContentLength;

                //saves to the database
                uploadModel.SavetoDatabase(uploadModel);
            }
        }
        return RedirectToAction("Index", "Home");
    }
}

}

Body:
    uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
    return View();

likely needs to be changed to:

    // Add code here to get uploadFileModel from the databases
    uploadFileModel.Images = Directory.EnumerateFiles(Server.MapPath(memesDirectory)).Select(fn => memesDirectory + Path.GetFileName(fn));
    uploadFileModel.title = "something you want"; // this line may not be necessary if getting it from the database did this for you already

    return View(uploadFileModel);


问:
AVAudioPlayer not playing the MP3
I need to reproduce an MP3 file and I'm using this code:

```<code>import AVFoundation

var player: AVAudioPlayer?

@IBAction func playSound(sender: UIButton) {

   //Making the phone vibrate
   AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

   //Playing a sound
   let url = Bundle.main.url(forResource: "audio_file_name", withExtension: "mp3")!
   do {
      self.player = try AVAudioPlayer(contentsOf: url)
      self.player?.delegate = self
      self.player?.prepareToPlay()
      self.player?.play()
   } catch let error {
      print(error.localizedDescription)
   }
}
</code>```

I'm not getting any error, but no sound is reproduced. I've also enabled Inter-App audio in the App Capabilities, added the MP3 file in "Copy Bundle Resources" and I'm testing on a real device.
Any suggestion? I've tried all the other solutions provided in other questions of this type...

答:
I've solved.

Everything was not working just because I was reproducing this code in a background queue.
Moving it to the main queue just solved the problem.

Title: AVAudioPlayer not playing the MP3

Body:
I need to reproduce an MP3 file and I'm using this code:

import AVFoundation

var player: AVAudioPlayer?

@IBAction func playSound(sender: UIButton) {

   //Making the phone vibrate
   AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

   //Playing a sound
   let url = Bundle.main.url(forResource: "audio_file_name", withExtension: "mp3")!
   do {
      self.player = try AVAudioPlayer(contentsOf: url)
      self.player?.delegate = self
      self.player?.prepareToPlay()
      self.player?.play()
   } catch let error {
      print(error.localizedDescription)
   }
}

I'm not getting any error, but no sound is reproduced. I've also enabled Inter-App audio in the App Capabilities, added the MP3 file in "Copy Bundle Resources" and I'm testing on a real device.
Any suggestion? I've tried all the other solutions provided in other questions of this type...


问:
NodeJS: Integrate with PHP
I've heared that NodeJS is great for making real-time chat applications and I want to implement a chat on my website. Right now I only have the design so I have to make the back-end code now.

However when I'm using socket.io + express it doesn't work out like it should.

Code from server.js:

```<code>var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.php');
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});
</code>```

I simply want to show index.php on localhost:3000, however when I browse to the website it doesn't want to show the page. Instead it downloads the index.php file.

But if I change the extention of the file to html, so it becomes index.html, it works. But that is not what I want.

I know there are some smart guys out there that can solve this problem in no time. I've been sitting for a very long time myself trying to sovle it.

答:
You can use the php-express package to render PHP files with Express:

```<code>npm install --save php-express
</code>```

Then use this (make sure you have PHP installed on your machine):

server.js

```<code>var express = require('express');
var app = express();

var phpExpress = require('php-express')({
  binPath: 'php'
});

// set view engine to php-express
app.set('views', './views');
app.engine('php', phpExpress.engine);
app.set('view engine', 'php');

// routing all .php file to php-express
app.all(/.+\.php$/, phpExpress.router);

var server = app.listen(3000, function () {
  console.log('listening on *:3000');
});
</code>```

Source: https://www.npmjs.com/package/php-express

Title: NodeJS: Integrate with PHP

Body:
I've heared that NodeJS is great for making real-time chat applications and I want to implement a chat on my website. Right now I only have the design so I have to make the back-end code now.

However when I'm using socket.io + express it doesn't work out like it should.

Code from server.js:

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.php');
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

I simply want to show index.php on localhost:3000, however when I browse to the website it doesn't want to show the page. Instead it downloads the index.php file.

But if I change the extention of the file to html, so it becomes index.html, it works. But that is not what I want.

I know there are some smart guys out there that can solve this problem in no time. I've been sitting for a very long time myself trying to sovle it.

Body:
You can use the php-express package to render PHP files with Express:

npm install --save php-express

Then use this (make sure you have PHP installed on your machine):

server.js

var express = require('express');
var app = express();

var phpExpress = require('php-express')({
  binPath: 'php'
});

// set view engine to php-express
app.set('views', './views');
app.engine('php', phpExpress.engine);
app.set('view engine', 'php');

// routing all .php file to php-express
app.all(/.+\.php$/, phpExpress.router);

var server = app.listen(3000, function () {
  console.log('listening on *:3000');
});

Source: https://www.npmjs.com/package/php-express


问:
Laravel select field cannot be null
I'm trying to store a form into my database but this is the error i get:

```<code>Integrity constraint violation: 1048 Column 'rent_product' cannot be null
</code>```

Why is this?

I'm trying to do this in an array because i have an option to show more select fields (to add more products to rent).

This is the HTML:

```<code><div class="col-lg-10">
 <label for="sel1">Selecteer product:</label>
   <select class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option name="product_name[]" value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>
</div>
</code>```

Function:

```<code>public function create_order($id) {

    $customer = Customer::find($id);

    $customer->rent_product = Request::get('product_name');
    $customer->rent_product_count = Request::get('product_count');
    $customer->update();

}
</code>```

Thanks in advance.

答:
The error states that your model does not have a column with the name rent_product. Check your Customer migrations if you have set this column.

Something like this:

```<code>// file: database/migrations/20170000_create_customers_table.php

Schema::create("customers", function (Blueprint $table) {
    $table->increments('id');
    $table->string('rent_product');
    $table->integer('rent_product_count');
    $table->timestamps();
});
</code>```

$customer->rent_product would be rent_product in your customers table. (in the database)

Also check if you have migrated your tables with php artisan migrate.

Title: Laravel select field cannot be null

Body:
I'm trying to store a form into my database but this is the error i get:

Integrity constraint violation: 1048 Column 'rent_product' cannot be null

Why is this?

I'm trying to do this in an array because i have an option to show more select fields (to add more products to rent).

This is the HTML:

 Selecteer product:
   <select class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option name="product_name[]" value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>

Function:

public function create_order($id) {

    $customer = Customer::find($id);

    $customer->rent_product = Request::get('product_name');
    $customer->rent_product_count = Request::get('product_count');
    $customer->update();

}

Thanks in advance.

Body:
The error states that your model does not have a column with the name rent_product. Check your Customer migrations if you have set this column.

Something like this:

// file: database/migrations/20170000_create_customers_table.php

Schema::create("customers", function (Blueprint $table) {
    $table->increments('id');
    $table->string('rent_product');
    $table->integer('rent_product_count');
    $table->timestamps();
});

$customer->rent_product would be rent_product in your customers table. (in the database)

Also check if you have migrated your tables with php artisan migrate.


问:
Android text veiw in linear layout
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>
</code>```

答: Wrap them in a vertical LinearLayout</p>

Title: Android text veiw in linear layout

Body:
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

Body: Wrap them in a vertical LinearLayout


问:
Get multiple solutions in SWI-Prolog using toplevel
I'm beginner in SWI-Prolog (but have some experience in Borland Prolog), and I've faced with a strange behavior for the following test code:

```<code>test(10).
test(1).
</code>```

It is expected for query ?-test(A) to get 2 solutions, something like A = 10; A = 1. However, only A = 10 is produced. I don't use the cut here. Maybe backtracking is off by default in SWI-Prolog?

Thanks in advance

答:
Sorry, the answer is very simple (see SWI-Prolog doc):

The user can type the semi-colon (;) or spacebar, if (s)he wants another solution. Use the return key if you do not want to see the more answers. Prolog completes the output with a full stop (.) if the user uses the return key or Prolog knows there are no more answers. If Prolog cannot find (more) answers, it writes false.

ContentLicense: CC BY-SA 4.0

Body:
I'm beginner in SWI-Prolog (but have some experience in Borland Prolog), and I've faced with a strange behavior for the following test code:

test(10).
test(1).

It is expected for query ?-test(A) to get 2 solutions, something like A = 10; A = 1. However, only A = 10 is produced. I don't use the cut here. Maybe backtracking is off by default in SWI-Prolog?

Thanks in advance


问:
issue with including module to angularjs
I am trying to add 'angularUtils.directives.dirPagination' module to my project :

```<code>angular.module('ClientSideApp',['ngRoute','angularUtils.directives.dirPagination']).config( function($routeProvider) {
</code>```

so like that the console shows Failed to instantiate module angularUtils.directives.dirPagination due to:....

i tried also to add the module in my controller file

```<code>angular.module('ClientSideApp',['angularUtils.directives.dirPagination']).controller('afficheCtrl', function($scope,$http,$location) {
</code>```

and it is the same problem..

答:
You do not have to add the dependency to the controller file, just make sure you have the necessary references to 'angularUtils.directives.dirPagination'

```<code><script src="dirPagination.js"></script>
</code>```

DEMO

Body:
I am trying to add 'angularUtils.directives.dirPagination' module to my project :

angular.module('ClientSideApp',['ngRoute','angularUtils.directives.dirPagination']).config( function($routeProvider) {

so like that the console shows Failed to instantiate module angularUtils.directives.dirPagination due to:....

i tried also to add the module in my controller file

angular.module('ClientSideApp',['angularUtils.directives.dirPagination']).controller('afficheCtrl', function($scope,$http,$location) {

and it is the same problem..

Body:
You do not have to add the dependency to the controller file, just make sure you have the necessary references to 'angularUtils.directives.dirPagination'

<script src="dirPagination.js"></script>

DEMO


问:
Twice call of timer crashes my app: Android
I'm trying to develop a small android App. In that app I need to use Timer control, which will be fired at button click. What problem I'm getting is, First timer task call is working fine but when I'm calling it again my app getting crashes. Code using for timer task is:

```<code>Timer timer = new Timer();
TimerTask refreshRam;
final Handler handler = new Handler();
refreshRam = new TimerTask()
    {
        public void run()
        {
            handler.post(new Runnable()
            {
                public void run()
                {
                    txtFreeRam.setText(String.valueOf(getFreeRam()).toString());
                }
            });
        }};

    }

timer.schedule(refreshRam, 400);
</code>```

I want to call my timer task only when I'm clicking on a button. It shouldn't be repeated...
Thanks

答:
When you reschedule a Timer, it throws:

```<code>java.lang.IllegalStateException: TimerTask is scheduled already
</code>```

It seems that you can only use a timer for once.

In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:

```<code>.
.
.

//first time; works fine!
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);

//second time; also works fine!
//be sure to terminate the timer task that is running by calling timer.cancel()
timer.cancel();
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);
</code>```

Body:
I'm trying to develop a small android App. In that app I need to use Timer control, which will be fired at button click. What problem I'm getting is, First timer task call is working fine but when I'm calling it again my app getting crashes. Code using for timer task is:

Timer timer = new Timer();
TimerTask refreshRam;
final Handler handler = new Handler();
refreshRam = new TimerTask()
    {
        public void run()
        {
            handler.post(new Runnable()
            {
                public void run()
                {
                    txtFreeRam.setText(String.valueOf(getFreeRam()).toString());
                }
            });
        }};

    }

timer.schedule(refreshRam, 400);

I want to call my timer task only when I'm clicking on a button. It shouldn't be repeated...
Thanks

Body:
When you reschedule a Timer, it throws:

java.lang.IllegalStateException: TimerTask is scheduled already

It seems that you can only use a timer for once.

In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:

.
.
.

//first time; works fine!
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);

//second time; also works fine!
//be sure to terminate the timer task that is running by calling timer.cancel()
timer.cancel();
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);


问:
How to add box on "plotLines text" of Highcharts
Hi i have tried several ways to add textboxes to "plotLines". But i don't know how to do it so i question.

The time of plotlines continues to move over the minute. I want to wrap the current time text of plotlines to a white box.

Please refer to jsfiddle and image for details.

jsFiddle - https://jsfiddle.net/develkarmy/9w6czou5/

```<code>var ctime = new Date();

Highcharts.chart('container', {
chart: {
    type: 'areaspline',
    plotBackgroundImage: 'http://www.khoa.go.kr/swtc/inc/img/chart/background.jpg',
    width: 700
},
title: {
    text: 'Average fruit consumption during one week'
},
xAxis: {
plotLines: [{ // mark the weekend
        color: 'white',
        width: 3,
        value: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), ctime.getHours(), ctime.getMinutes()),
        dashStyle: 'solid',
        zIndex: 4,
        label: {
        text: (ctime.getHours() + ':' + ctime.getMinutes()),
        verticalAlign: 'middle',
        align: 'center',
        rotation: 0,
        style: {
                color: '#000',
                fontWeight: 'bold'
            }
        }
    }],
    type: 'datetime',
    //Sets tickInterval to 24 * 3600 * 1000 if display is by day
    tickInterval: 3600 * 3000,
    min: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate()),
    max: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() + 1)),
    dateTimeLabelFormats : {
        hour: '%H',
        day: '%H'
    },
    tickWidth: 0,
    gridLineWidth: 1,
    gridLineDashStyle: "ShortDot",
    gridLineColor: "#c1c2c3",
    startOnTick: true
},
yAxis: {
    tickInterval: 100,
    title: {
        text: '(cm)',
        align: 'high',
        offset: 15,
        rotation: 0,
        y: -10
    },
    tickWidth: 0,
    gridLineWidth: 1,
    gridLineDashStyle: "ShortDot",
    gridLineColor: "#c1c2c3",
    startOnTick: true
},
tooltip: {
    enabled: false
},
credits: {
    enabled: false
},
plotOptions: {
    areaspline: {
        fillOpacity: 0.5
    }
},
legend: {
    enabled: false
},
series: [{
    data: [
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() - 1), 00, 00),
            y: 586,
            marker: {
                enabled: false
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 4, 18),
            y: 211,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_down.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 10, 48),
            y: 744,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 17, 13),
            y: 244,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_down.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 23, 17),
            y: 668,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() + 1), 2, 17),
            y: 200,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        }
    ]
}]
});
</code>```

答:
plotLines of xAxis will be as below

Fiddle demo

```<code>    plotLines: [{ // mark the weekend
        color: 'white',
        width: 3,
        value: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), ctime.getHours(), ctime.getMinutes()),
        dashStyle: 'solid',
        zIndex: 4,
        label: {
        text: (ctime.getHours() + ':' + ctime.getMinutes()),
        verticalAlign: 'middle',
        align: 'right', //placement of label
        x:-15,  //adjustment of label
        rotation: 0,
        useHTML: true, //enables html
        style: {
                borderRadius:"10px",
                padding:'10px 30px',
                backgroundColor:"white",
                color: 'black',
                fontWeight: 'bold'
            }
        }
    }],
</code>```

Body:
Hi i have tried several ways to add textboxes to "plotLines". But i don't know how to do it so i question.

The time of plotlines continues to move over the minute. I want to wrap the current time text of plotlines to a white box.

Please refer to jsfiddle and image for details.

jsFiddle - https://jsfiddle.net/develkarmy/9w6czou5/

var ctime = new Date();

Highcharts.chart('container', {
chart: {
    type: 'areaspline',
    plotBackgroundImage: 'http://www.khoa.go.kr/swtc/inc/img/chart/background.jpg',
    width: 700
},
title: {
    text: 'Average fruit consumption during one week'
},
xAxis: {
plotLines: [{ // mark the weekend
        color: 'white',
        width: 3,
        value: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), ctime.getHours(), ctime.getMinutes()),
        dashStyle: 'solid',
        zIndex: 4,
        label: {
        text: (ctime.getHours() + ':' + ctime.getMinutes()),
        verticalAlign: 'middle',
        align: 'center',
        rotation: 0,
        style: {
                color: '#000',
                fontWeight: 'bold'
            }
        }
    }],
    type: 'datetime',
    //Sets tickInterval to 24 * 3600 * 1000 if display is by day
    tickInterval: 3600 * 3000,
    min: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate()),
    max: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() + 1)),
    dateTimeLabelFormats : {
        hour: '%H',
        day: '%H'
    },
    tickWidth: 0,
    gridLineWidth: 1,
    gridLineDashStyle: "ShortDot",
    gridLineColor: "#c1c2c3",
    startOnTick: true
},
yAxis: {
    tickInterval: 100,
    title: {
        text: '(cm)',
        align: 'high',
        offset: 15,
        rotation: 0,
        y: -10
    },
    tickWidth: 0,
    gridLineWidth: 1,
    gridLineDashStyle: "ShortDot",
    gridLineColor: "#c1c2c3",
    startOnTick: true
},
tooltip: {
    enabled: false
},
credits: {
    enabled: false
},
plotOptions: {
    areaspline: {
        fillOpacity: 0.5
    }
},
legend: {
    enabled: false
},
series: [{
    data: [
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() - 1), 00, 00),
            y: 586,
            marker: {
                enabled: false
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 4, 18),
            y: 211,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_down.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 10, 48),
            y: 744,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 17, 13),
            y: 244,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_down.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), 23, 17),
            y: 668,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        },
        {
            x: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), (ctime.getDate() + 1), 2, 17),
            y: 200,
            marker: {
                symbol: 'url(http://www.khoa.go.kr/swtc/inc/img/chart/graph_up.png)'
            }
        }
    ]
}]
});

Body:
plotLines of xAxis will be as below

Fiddle demo

    plotLines: [{ // mark the weekend
        color: 'white',
        width: 3,
        value: Date.UTC(ctime.getFullYear(), (ctime.getMonth() + 1), ctime.getDate(), ctime.getHours(), ctime.getMinutes()),
        dashStyle: 'solid',
        zIndex: 4,
        label: {
        text: (ctime.getHours() + ':' + ctime.getMinutes()),
        verticalAlign: 'middle',
        align: 'right', //placement of label
        x:-15,  //adjustment of label
        rotation: 0,
        useHTML: true, //enables html
        style: {
                borderRadius:"10px",
                padding:'10px 30px',
                backgroundColor:"white",
                color: 'black',
                fontWeight: 'bold'
            }
        }
    }],


问:
Node / Express Handlebars - Where to define custom helpers
I'm working on a node / express / handlebars app and I just found out about custom helpers, but I have no idea where to define them.

I tried adding some in the actual view template hbs file in a
```

<p>But I get a Uncaught ReferenceError: Handlebars is not defined.</p>

<p>I also found this JSFiddle, but I don't have anything that looks like that code in my app. I've also looked at a dozen tutorials but they pretty much say the exact same thing the official documentation does.</p>

<p>So where do I include this code in the node / express app exactly?</p>

<p>If anyone can shed some light on this issue, it would be appreciated.</p>

<p><strong>EDIT:</strong>
I'm not sure if this is the right way, but you can put it in your app.js after you have set the view engine:</p>

```var hbs = require('hbs');

hbs.registerHelper('test', function(conditional, options) {
  //do something
  if (conditional) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});
```

If this is incorrect or problematic for some reason, please let me know.

答:
I personally create a helpers folder in the root directory and put all my helper methods in there. You can then require into your app.js and tell the hbs engine that you want to use that file for helpers.</p>

```<code>// in app.js

const hbsHelpers = require('./helpers/handlebars');
...
app.engine('handlebars', exphbs({
  helpers: hbsHelpers
});
</code>```

Body:
I'm working on a node / express / handlebars app and I just found out about custom helpers, but I have no idea where to define them.

I tried adding some in the actual view template hbs file in a

But I get a Uncaught ReferenceError: Handlebars is not defined.

I also found this JSFiddle, but I don't have anything that looks like that code in my app. I've also looked at a dozen tutorials but they pretty much say the exact same thing the official documentation does.

So where do I include this code in the node / express app exactly?

If anyone can shed some light on this issue, it would be appreciated.

EDIT:
I'm not sure if this is the right way, but you can put it in your app.js after you have set the view engine:

var hbs = require('hbs');

hbs.registerHelper('test', function(conditional, options) {
  //do something
  if (conditional) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

If this is incorrect or problematic for some reason, please let me know.

Body:
I personally create a helpers folder in the root directory and put all my helper methods in there. You can then require into your app.js and tell the hbs engine that you want to use that file for helpers.

// in app.js

const hbsHelpers = require('./helpers/handlebars');
...
app.engine('handlebars', exphbs({
  helpers: hbsHelpers
});


问:
Kotlin unexpected `unresolved reference`
I'm a beginner to Kotlin, and here's my code:

```<code>class C(val boy: Int = 0) {
    fun <T, E> boy(i: Int) = i
}

fun girl(b1: Boolean, b2: Boolean) = println("boy($b1, $b2)")

fun main(args: Array<String>): Unit {
    val A = 234 // see? A defined!
    val B = 345 // see? B defined!
    val c = C(123) // c is also defined!

    girl(c.boy < A, B > A) // hey look at here
}
</code>```

IntelliJ IDEA gives me:

unresolved reference: A

unresolved reference: B

unresolved reference: c

At the line hey look at here.

I think my code is syntactically correct, what's wrong?

答:
You stumped on a very rare case of syntactic ambiguity. I think it is a first for SO, congrats!

Your initial syntax is technically correct, but in this contexts it also can be interpreted as an attempt to call c.boy. Since the compiler didn't know what you meant, it assumed you wanted the function call.

The easiest fix is adding parenthesis as you did or rearranging the expressions:

```<code>girl(c.boy < A, A < B)
</code>```

P.S. Same thing can happen in C#, so it is not unique to Kotlin

Body:
I'm a beginner to Kotlin, and here's my code:

class C(val boy: Int = 0) {
    fun <T, E> boy(i: Int) = i
}

fun girl(b1: Boolean, b2: Boolean) = println("boy($b1, $b2)")

fun main(args: Array<String>): Unit {
    val A = 234 // see? A defined!
    val B = 345 // see? B defined!
    val c = C(123) // c is also defined!

    girl(c.boy  A) // hey look at here
}

IntelliJ IDEA gives me:

unresolved reference: A

unresolved reference: B

unresolved reference: c

At the line hey look at here.

I think my code is syntactically correct, what's wrong?

Body:
You stumped on a very rare case of syntactic ambiguity. I think it is a first for SO, congrats!

Your initial syntax is technically correct, but in this contexts it also can be interpreted as an attempt to call c.boy<A,B>. Since the compiler didn't know what you meant, it assumed you wanted the function call.

The easiest fix is adding parenthesis as you did or rearranging the expressions:

girl(c.boy < A, A < B)

P.S. Same thing can happen in C#, so it is not unique to Kotlin


问:
NoMethodError - undefined method `safe_constantize' for nil:NilClass
I am trying to create an ActionCable chatroom following the actioncable guide on GoRails.com.

As I am trying to connect to ActionCable I get following error:
NoMethodError - undefined method `safe_constantize' for nil:NilClass

```<code>[ActionCable] [User 1] Could not execute command from
{"command"=>"subscribe", "identifier"=>"
{\"ChatroomsChannel\":\"ChatroomsChannel\",\"room_id\":1}"})
[NoMethodError - undefined method `safe_constantize' for
nil:NilClass]: /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:29:in `add' |
/Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:15:in
`execute_command' | /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/base.rb:88:in
`dispatch_websocket_message' | /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:54:in `block in invoke' |
/Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:39:in `block in work'
</code>```

My app/channels/chatrooms_channel.rb looks like this:

```<code>def subscribed
   @chatroom = Chatroom.find(params[:room_id])
   #puts params[:room_id]
   #current_user.join_room(@chatroom)
   stream_from "chatrooms:#{@chatroom.id}"
   # stream_from "some_channel"
end
</code>```

Maybe it is worth mentioning that I upgraded to rails 5.0.0.rc2 from rails 4.

Thank you,

答:
in assets/javascripts/channels/chatroom.coffee

If you need to assign params, channel name must be in params hash too:

```<code>App['chatroom' + roomId] = App.cable.subscriptions.create {
  channel: 'ChatroomChannel',
  room_id: roomId
}, {
  received: ->
    ...
}
</code>```

And only if you don't need params, you can write channel name without hash:

```<code>App.chatroom = App.cable.subscriptions.create 'ChatroomChannel',
  received: ->
    ...
</code>```

Body:
I am trying to create an ActionCable chatroom following the actioncable guide on GoRails.com.

As I am trying to connect to ActionCable I get following error:
NoMethodError - undefined method `safe_constantize' for nil:NilClass

[ActionCable] [User 1] Could not execute command from
{"command"=>"subscribe", "identifier"=>"
{\"ChatroomsChannel\":\"ChatroomsChannel\",\"room_id\":1}"})
[NoMethodError - undefined method `safe_constantize' for
nil:NilClass]: /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:29:in `add' |
/Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:15:in
`execute_command' | /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/base.rb:88:in
`dispatch_websocket_message' | /Users/Mathias/.rvm/gems/ruby-
2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:54:in `block in invoke' |
/Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:39:in `block in work'

My app/channels/chatrooms_channel.rb looks like this:

def subscribed
   @chatroom = Chatroom.find(params[:room_id])
   #puts params[:room_id]
   #current_user.join_room(@chatroom)
   stream_from "chatrooms:#{@chatroom.id}"
   # stream_from "some_channel"
end

Maybe it is worth mentioning that I upgraded to rails 5.0.0.rc2 from rails 4.

Thank you,

Body:
in assets/javascripts/channels/chatroom.coffee

If you need to assign params, channel name must be in params hash too:

App['chatroom' + roomId] = App.cable.subscriptions.create {
  channel: 'ChatroomChannel',
  room_id: roomId
}, {
  received: ->
    ...
}

And only if you don't need params, you can write channel name without hash:

App.chatroom = App.cable.subscriptions.create 'ChatroomChannel',
  received: ->
    ...


问:
drupal_add_css, drupal_add_js does not work
I am using drupal_add_css() and drupal_add_js() to add CSS and JavaScript files to my Drupal site. I am doing this in a module called control so the function I'm using is  called control_preprocess_page(&$vars).

But in my theme nothing is added!

答:
The reason these functions aren't working within the preprocess_page() function is that template_preprocess_page() (which is called first) has already formatted the structured content into variables $scripts and $styles. If you want to add additional js or css at the preprocess level, you need to regenerate those 2 variables, something like this:

```<code>function control_preprocess_page(&$vars) {
  // Add new CSS.
  drupal_add_css('path/to/css/foo.css');
  // Rebuild the 'styles variable.
  $vars['styles'] = drupal_get_css();

  // Add new JS.
  drupal_add_js(...);
  $vars['scripts'] = drupal_get_js();
}
</code>```

Using drupal_add_js/drupal_add_css in hook_init, or a more precisely targeted function (eg, an alter hook, or nodeapi hook, if applicable), will avoid having to regenerate those variables.

ContentLicense: CC BY-SA 2.5

Body:
The reason these functions aren't working within the preprocess_page() function is that template_preprocess_page() (which is called first) has already formatted the structured content into variables $scripts and $styles. If you want to add additional js or css at the preprocess level, you need to regenerate those 2 variables, something like this:

function control_preprocess_page(&$vars) {
  // Add new CSS.
  drupal_add_css('path/to/css/foo.css');
  // Rebuild the 'styles variable.
  $vars['styles'] = drupal_get_css();

  // Add new JS.
  drupal_add_js(...);
  $vars['scripts'] = drupal_get_js();
}

Using drupal_add_js/drupal_add_css in hook_init, or a more precisely targeted function (eg, an alter hook, or nodeapi hook, if applicable), will avoid having to regenerate those variables.


问:
Keep the lifespan of variable after multiple function calls?
Assuming:

```<code>def myfunc(x):
    my_list  = []
    list.append(x)
</code>```

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

```<code>def myfunc(x):
    NA listv  = []
    list.append(x)
</code>```

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

答:
I believe the behaviour you're seeking is almost exactly how mutable default arguments work in python: instantiated only during function definition.

```<code>def myfunc(x,*args,my_list=[]):
    my_list.append(x)
</code>```

The *args will protect the list from being overwritten by an erroneously passed second argument.

Body:
Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

def myfunc(x):
    NA listv  = []
    list.append(x)

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

Body:
I believe the behaviour you're seeking is almost exactly how mutable default arguments work in python: instantiated only during function definition.

def myfunc(x,*args,my_list=[]):
    my_list.append(x)

The *args will protect the list from being overwritten by an erroneously passed second argument.


问:
Passport Local strategy not called
I use angularJS+passport to perform user authentication and hence, i set up these below.
HTML:

```<code><div ng-controller="logincontroller">
<form>
Email:<input type="text" ng-model="user.email"/>
Password:<input type="password" ng-model="user.password"/>
<div ng-click=loginUser()>Submit</div>
</form>
</div>
</code>```

In client side javascript:

```<code>  app.controller('logincontroller',function($scope,$http){
    $scope.loginUser=function(){
    $http.post('/loginUser',JSON.stringify($scope.user));
   }
   })
</code>```

ON app.js

```<code>var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy();
var session=require('express-session');
app.use(express.session({secret:"flibbertygibbit"}));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
passport.use(new LocalStrategy(
    {usernameField: 'user.email',
    passwordField: 'user.password',
    passReqToCallback: true
  },
    function(username,password,done){
      console.log("am here"+username+" "+password);

}
))

app.post('/loginUser',passport.authenticate('local'));
</code>```

The problem i face is the Local strategy isnot being called at all and all I get Typerror: Local strategy requires a verify callback. I ain't sure where i went wrong, being novice at it. Please help.

答:
The error you're getting is caused by this:

```<code>var LocalStrategy=require('passport-local').Strategy();
                                                    ^^
</code>```

You're calling the Strategy class without any arguments, so this results in the error. You want to store a reference to the class itself, like this:

```<code>var LocalStrategy=require('passport-local').Strategy;
</code>```

Also, because you're setting passReqToCallback : true, the verification callback will take four arguments, not three. It should look like this:

```<code>function(req, username, password, done) { ... }
</code>```

Title: Passport Local strategy not called

Body:
I use angularJS+passport to perform user authentication and hence, i set up these below.
HTML:

<form>
Email:<input type="text" ng-model="user.email"/>
Password:<input type="password" ng-model="user.password"/>

Submit

</form>

In client side javascript:

  app.controller('logincontroller',function($scope,$http){
    $scope.loginUser=function(){
    $http.post('/loginUser',JSON.stringify($scope.user));
   }
   })

ON app.js

var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy();
var session=require('express-session');
app.use(express.session({secret:"flibbertygibbit"}));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
passport.use(new LocalStrategy(
    {usernameField: 'user.email',
    passwordField: 'user.password',
    passReqToCallback: true
  },
    function(username,password,done){
      console.log("am here"+username+" "+password);

}
))

app.post('/loginUser',passport.authenticate('local'));

The problem i face is the Local strategy isnot being called at all and all I get Typerror: Local strategy requires a verify callback. I ain't sure where i went wrong, being novice at it. Please help.

Body:
The error you're getting is caused by this:

var LocalStrategy=require('passport-local').Strategy();
                                                    ^^

You're calling the Strategy class without any arguments, so this results in the error. You want to store a reference to the class itself, like this:

var LocalStrategy=require('passport-local').Strategy;

Also, because you're setting passReqToCallback : true, the verification callback will take four arguments, not three. It should look like this:

function(req, username, password, done) { ... }


问:
Why RewriteRule not working without R flag in .htaccess
I have a Codeigniter project in project folder of web root.

```<code>www
www/.htaccess
www/project/.htaccess ( here are its contents https://pastebin.com/qBbZ0REj )
</code>```

www/.htaccess

```<code> RewriteEngine On
 RewriteRule ^pg/fetchPG/(.*)$ /project/product_groups/fetchPG/$1 [L]
</code>```

Relevant part of www/project/.htaccess

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

If I do

```<code>http://localhost/pg/fetchPG/?groupid=26&response=html&mode=graph&response=html
</code>```

It should show the contents of

```<code>http://localhost/project/product_groups/fetchPG/?groupid=26&response=html&mode=graph&response=html
</code>```

But it just shows me the 404 page of Codeigniter.

I thought Querystring is missing, but I tried printing $_GET in that 404 page and it was fine, it was coming along.

I replaced [L] with [L, R] and it works, it redirects to that URL, but I don't want users to see the final URL.

PS: I have dedicated server, I have control of everything, please suggest if  there any other way to accomplush my goal?

答:
The reason why it works with the R|redirect flag, is that with a redirect the client sends a new request, and as a consequence REQUEST_URI changes.

I assume, that CodeIgniter is configured to look at REQUEST_URI and not at QUERY_STRING, which corresponds to the rule in www/project/.htaccess

```<code>RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

To fix it, change uri_protocol to query_string as described in the user guide

Lastly, add the following new item to the config file (and edit the option if needed):

```<code>/*
|------------------------------------------------
| URI PROTOCOL
|------------------------------------------------
|
| This item determines which server global
| should be used to retrieve the URI string. The
| default setting of "auto" works for most servers.
| If your links do not seem to work, try one of
| the other delicious flavors:
|
| 'auto'         Default - auto detects
| 'path_info'    Uses the PATH_INFO
| 'query_string'        Uses the QUERY_STRING
*/

$config['uri_protocol'] = "auto";
</code>```

In your case this should look like

```<code>$config['uri_protocol'] = "query_string";
</code>```

In order to preserve a query string, you might try path_info instead, e.g.

```<code>$config['uri_protocol'] = "path_info";
</code>```

But you must also change the rewrite rule in www/project/.htaccess to

```<code>RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

Note, that there's no question mark (?) anymore.

Body:
I have a Codeigniter project in project folder of web root.

www
www/.htaccess
www/project/.htaccess ( here are its contents https://pastebin.com/qBbZ0REj )

www/.htaccess

 RewriteEngine On
 RewriteRule ^pg/fetchPG/(.*)$ /project/product_groups/fetchPG/$1 [L]

Relevant part of www/project/.htaccess

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

If I do

http://localhost/pg/fetchPG/?groupid=26&response=html&mode=graph&response=html

It should show the contents of

http://localhost/project/product_groups/fetchPG/?groupid=26&response=html&mode=graph&response=html

But it just shows me the 404 page of Codeigniter.

I thought Querystring is missing, but I tried printing $_GET in that 404 page and it was fine, it was coming along.

I replaced [L] with [L, R] and it works, it redirects to that URL, but I don't want users to see the final URL.

PS: I have dedicated server, I have control of everything, please suggest if  there any other way to accomplush my goal?

Body:
The reason why it works with the R|redirect flag, is that with a redirect the client sends a new request, and as a consequence REQUEST_URI changes.

I assume, that CodeIgniter is configured to look at REQUEST_URI and not at QUERY_STRING, which corresponds to the rule in www/project/.htaccess

RewriteRule ^(.*)$ index.php?/$1 [L]

To fix it, change uri_protocol to query_string as described in the user guide

Lastly, add the following new item to the config file (and edit the option if needed):

/*
|------------------------------------------------
| URI PROTOCOL
|------------------------------------------------
|
| This item determines which server global
| should be used to retrieve the URI string. The
| default setting of "auto" works for most servers.
| If your links do not seem to work, try one of
| the other delicious flavors:
|
| 'auto'         Default - auto detects
| 'path_info'    Uses the PATH_INFO
| 'query_string'        Uses the QUERY_STRING
*/

$config['uri_protocol'] = "auto";

In your case this should look like

$config['uri_protocol'] = "query_string";

In order to preserve a query string, you might try path_info instead, e.g.

$config['uri_protocol'] = "path_info";

But you must also change the rewrite rule in www/project/.htaccess to

RewriteRule ^(.*)$ index.php/$1 [L]

Note, that there's no question mark (?) anymore.


问:
Register generic type in DbContext EF4 CTP5
in EF4 CTP4 we had RegisterSet function to generically register entity in ModelBuilder. We used Configurations.Add() to register the mapping for entities. How to achieve this EF4 CTP 5</p>

答: I found the answer to problem. They have exposed ModelBuilder.Entity().{Configuration} like Property/IsRequired and all for simple types. For complex entities there are functions like ComplexTypes. </p>


问:
Sum Columns with Same ID
I have 2 datatables, i merged them. After merged, I want to show them in datagrid, However If there is same 'id' columns should be sum and group.

Example;
Currently it looks like this

What i want is sum them if 'realid' column is same like below;

I currently did below code and at the end i bind it to datagrid.

What should i do after that ?

```<code>        DataTable dtNewTable = new DataTable();
        DataTable dtCurtable = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            // Add columns
            DataColumn column2 = new DataColumn("counts", typeof(System.Int32));
            DataColumn column3 = new DataColumn("realid", typeof(string));
            dtNewTable.Columns.Add(column2);
            dtNewTable.Columns.Add(column3);

            dtCurtable = dtNewTable.Copy();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataRow row;
            Random r = new Random();

            dtNewTable.Clear();

            for (int i = 0; i <= 1; i++)
            {
                row = dtNewTable.NewRow();
                row["counts"] = r.Next(10,40) ;
                row["realid"] = i + " id";
                dtNewTable.Rows.Add(row);

            }

            dtCurtable.Merge(dtNewTable);
            dataGrid1.DataSource = dtCurtable;

        }
</code>```

答:
You can use Linq here like</p>

```<code>var dt1 = dtCurtable.AsEnumerable()
              .GroupBy(r => r.Field<string>("realid"))
              .Select(g =>
              {
              DataRow row = dtCurtable.NewRow();
              row["realid"] = g.Key;
              row["Count"] = g.Sum(r => r.Field<int>("counts"));

              return row;
          }).CopyToDataTable();
</code>```

Title: Sum Columns with Same ID

Body:
I have 2 datatables, i merged them. After merged, I want to show them in datagrid, However If there is same 'id' columns should be sum and group.

Example;
Currently it looks like this

What i want is sum them if 'realid' column is same like below;

I currently did below code and at the end i bind it to datagrid.

What should i do after that ?

        DataTable dtNewTable = new DataTable();
        DataTable dtCurtable = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            // Add columns
            DataColumn column2 = new DataColumn("counts", typeof(System.Int32));
            DataColumn column3 = new DataColumn("realid", typeof(string));
            dtNewTable.Columns.Add(column2);
            dtNewTable.Columns.Add(column3);

            dtCurtable = dtNewTable.Copy();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataRow row;
            Random r = new Random();

            dtNewTable.Clear();

            for (int i = 0; i <= 1; i++)
            {
                row = dtNewTable.NewRow();
                row["counts"] = r.Next(10,40) ;
                row["realid"] = i + " id";
                dtNewTable.Rows.Add(row);

            }

            dtCurtable.Merge(dtNewTable);
            dataGrid1.DataSource = dtCurtable;

        }

Body:
You can use Linq here like

var dt1 = dtCurtable.AsEnumerable()
              .GroupBy(r => r.Field<string>("realid"))
              .Select(g =>
              {
              DataRow row = dtCurtable.NewRow();
              row["realid"] = g.Key;
              row["Count"] = g.Sum(r => r.Field<int>("counts"));

              return row;
          }).CopyToDataTable();


问:
insert text file into existing xlsx using Python
I have a .xlsx file with 11 worksheets and I need to insert the contents of a text file (tab delim, roughly 30 columns with 100 rows) from Row 3 onwards. I tried the code below but I end up with errors. (using bash/Linux)

```<code>#!/usr/bin/env python

import csv
from openpyxl.reader.excel import load_workbook
from xlrd import open_workbook
from xlutils import copy as xl_copy

with open('S12_final.txt') as tab_file: #open tab text file
    tab_reader = csv.reader(tab_file, delimiter='\t')
    xls_readable_book = load_workbook('S12.xlsx') #load workbook
    xls_writeable_book = xl_copy.copy(xls_readable_book)
    xls_writeable_sheet = xls_writeable_book.get_sheet_by_name('Filtered') #write data on this sheet
    for row_index, row in enumerate(tab_reader):
        xls_writeable_sheet.write(row_index, 0, row[0])
        xls_writeable_sheet.write(row_index, 1, row[1])
    xls_writeable_book.save('S12.xlsx') #save excel file
</code>```

Errors:

```<code>> Traceback (most recent call last):   File "./tab2excel_a.py", line 23,
> in <module>
>     xls_writeable_book = xl_copy.copy(xls_readable_book)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/copy.py",
> line 19, in copy
>     w   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 937, in process
>     reader(chain[0])   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 61, in __call__
>     filter.workbook(workbook,filename)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 287, in workbook
>     self.wtbook.dates_1904 = rdbook.datemode AttributeError: 'Workbook' object has no attribute 'datemode'
</code>```

Any suggestions ?

答:
Consider this openpyxl example:

```<code>from openpyxl.workbook.workbook import Workbook # as _Workbook
import csv

wb = Workbook()
wb.create_sheet('Filtered')
ws = wb['Filtered']

with open('test/S12_final.csv') as tab_file:
    tab_reader = csv.reader(tab_file, delimiter='\t')

    # Skipt first 2 Lines
    [next(tab_reader) for skip in range(2)]

    # Append list(rowData) after Sheets last accessed Row
    for rowData in tab_reader:
        ws.append(rowData)

wb.save('test/S12.xlsx')
</code>```

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2

Body:
I have a .xlsx file with 11 worksheets and I need to insert the contents of a text file (tab delim, roughly 30 columns with 100 rows) from Row 3 onwards. I tried the code below but I end up with errors. (using bash/Linux)

#!/usr/bin/env python

import csv
from openpyxl.reader.excel import load_workbook
from xlrd import open_workbook
from xlutils import copy as xl_copy

with open('S12_final.txt') as tab_file: #open tab text file
    tab_reader = csv.reader(tab_file, delimiter='\t')
    xls_readable_book = load_workbook('S12.xlsx') #load workbook
    xls_writeable_book = xl_copy.copy(xls_readable_book)
    xls_writeable_sheet = xls_writeable_book.get_sheet_by_name('Filtered') #write data on this sheet
    for row_index, row in enumerate(tab_reader):
        xls_writeable_sheet.write(row_index, 0, row[0])
        xls_writeable_sheet.write(row_index, 1, row[1])
    xls_writeable_book.save('S12.xlsx') #save excel file

Errors:

> Traceback (most recent call last):   File "./tab2excel_a.py", line 23,
> in <module>
>     xls_writeable_book = xl_copy.copy(xls_readable_book)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/copy.py",
> line 19, in copy
>     w   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 937, in process
>     reader(chain[0])   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 61, in __call__
>     filter.workbook(workbook,filename)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 287, in workbook
>     self.wtbook.dates_1904 = rdbook.datemode AttributeError: 'Workbook' object has no attribute 'datemode'

Any suggestions ?

Body:
Consider this openpyxl example:

from openpyxl.workbook.workbook import Workbook # as _Workbook
import csv

wb = Workbook()
wb.create_sheet('Filtered')
ws = wb['Filtered']

with open('test/S12_final.csv') as tab_file:
    tab_reader = csv.reader(tab_file, delimiter='\t')

    # Skipt first 2 Lines
    [next(tab_reader) for skip in range(2)]

    # Append list(rowData) after Sheets last accessed Row
    for rowData in tab_reader:
        ws.append(rowData)

wb.save('test/S12.xlsx')

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2


问:
how to filter table by underscorejs
i work by underscore function ,i want to filter table by element not exist in author table
I want to finally display this [[10,20,30,50,60],[80,66],[9,70,4,3] ]   </p>

```<code>var tab=[];
 _.each([[10,20,30,5,50,60],[80,6,66,7,8,2],[9,70,4,3,1]], function (c) {

     var k=   _.filter(c, function (cel) {
         return _.some([1, 2, 5, 6, 8, 7], function (el) {
             return cel != el
         })
     })
     tab.push(k);
});

console.log(tab)
</code>```

答: Use _.every instead of _.some because the some function will return true if ANY of the elements in your filter array do not match the element of your table. So in each case, you are comparing the element of your array to the number 1 (first element of the filter array), and since most of the numbers in your table != 1, the _.some function is returning true so the number is added to the result of the _.filter function.

Title: how to filter table by underscorejs

Body:
i work by underscore function ,i want to filter table by element not exist in author table
I want to finally display this [[10,20,30,50,60],[80,66],[9,70,4,3] ]

var tab=[];
 _.each([[10,20,30,5,50,60],[80,6,66,7,8,2],[9,70,4,3,1]], function (c) {

     var k=   _.filter(c, function (cel) {
         return _.some([1, 2, 5, 6, 8, 7], function (el) {
             return cel != el
         })
     })
     tab.push(k);
});

console.log(tab)


问:
How to achieve behavior of setTimeout in Elm
I'm writing a web game in Elm with lot of time-dependent events and I'm looking for a way to schedule an event at a specific time delay.

In JavaScript I used setTimeout(f, timeout), which obviously worked very well, but - for various reasons - I want to avoid JavaScript code and use Elm alone.

I'm aware that I can subscribe to Tick at specific interval and recieve clock ticks, but this is not what I want - my delays have no reasonable common denominator (for example, two of the delays are 30ms and 500ms), and I want to avoid having to handle a lot of unnecessary ticks.

I also came across Task and Process - it seems that by using them I am somehow able to what I want with Task.perform failHandler successHandler (Process.sleep Time.second).

This works, but is not very intuitive - my handlers simply ignore all possible input and send same message. Moreover, I do not expect the timeout to ever fail, so creating the failure handler feels like feeding the library, which is not what I'd expect from such an elegant language.

Is there something like Task.delayMessage time message which would do exactly what I need to (send me a copy of its message argument after specified time), or do I have to make my own wrapper for it?

答:
An updated and simplified version of @wintvelt's answer for Elm v0.18 is:

```<code>delay : Time.Time -> msg -> Cmd msg
delay time msg =
  Process.sleep time
  |> Task.perform (\_ -> msg)
</code>```

with the same usage

Body:
An updated and simplified version of @wintvelt's answer for Elm v0.18 is:

delay : Time.Time -> msg -> Cmd msg
delay time msg =
  Process.sleep time
  |> Task.perform (\_ -> msg)

with the same usage


问:
What dependencies to use for APACHE ODF TOOLKIT (INCUBATING)
I am trying to load a .ods file with the code:

```<code>import org.odftoolkit.simple.SpreadsheetDocument;
SpreadsheetDocument data = SpreadsheetDocument.loadDocument(f);
</code>```

I've added the import statement to show which package I am using.

However I keep getting java.lang.NoClassDefFoundError. I've tried adding many different libraries. At the moment I have these libraries in my eclipse build path: libraries in my eclipse build path

And am getting this error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/hp/hpl/jena/rdf/model/RDFNode
    at org.odftoolkit.odfdom.pkg.OdfFileDom.initialize(OdfFileDom.java:215)
    at org.odftoolkit.odfdom.pkg.manifest.OdfManifestDom.initialize(OdfManifestDom.java:74)
    at org.odftoolkit.odfdom.pkg.OdfFileDom.<init>(OdfFileDom.java:132)
    at org.odftoolkit.odfdom.pkg.manifest.OdfManifestDom.<init>(OdfManifestDom.java:63)
    at org.odftoolkit.odfdom.pkg.OdfFileDom.newFileDom(OdfFileDom.java:189)
    at org.odftoolkit.odfdom.pkg.OdfPackage.parseManifest(OdfPackage.java:1187)
    at org.odftoolkit.odfdom.pkg.OdfPackage.readZip(OdfPackage.java:454)
    at org.odftoolkit.odfdom.pkg.OdfPackage.initializeZip(OdfPackage.java:425)
    at org.odftoolkit.odfdom.pkg.OdfPackage.<init>(OdfPackage.java:256)
    at org.odftoolkit.odfdom.pkg.OdfPackage.loadPackage(OdfPackage.java:318)
    at org.odftoolkit.simple.Document.loadDocument(Document.java:319)
    at org.odftoolkit.simple.SpreadsheetDocument.loadDocument(SpreadsheetDocument.java:203)
    at FirstLoadComponent.main(FirstLoadComponent.java:11)
Caused by: java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.RDFNode
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more
</code>```

Any suggestion on how to get my code running or any alternative my to do simple read and writes to .ods files would be greatly appeciated.

答:
You have to add commons-validator-1.5.0.jar, jena-core-2.11.2.jar, jena-iri-1.0.2.jar at least.

The full dependencies jars could be got via maven command mvn dependency:tree.

```
org.apache.odftoolkit:odfdom-java:jar:0.8.11-incubating
+- org.apache.odftoolkit:taglets:jar:0.8.11-incubating:compile
|  \- com.sun:tools:jar:1.7.0:system
+- xerces:xercesImpl:jar:2.9.1:compile
+- xml-apis:xml-apis:jar:1.3.04:compile
+- org.apache.jena:jena-core:jar:2.11.2:compile
|  +- org.slf4j:slf4j-api:jar:1.7.6:compile
|  +- org.apache.jena:jena-iri:jar:1.0.2:compile
|  +- org.slf4j:slf4j-log4j12:jar:1.7.6:compile
|  \- log4j:log4j:jar:1.2.17:compile
+- net.rootdev:java-rdfa:jar:0.4.2:compile
\- commons-validator:commons-validator:jar:1.5.0:compile
   +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
   +- commons-digester:commons-digester:jar:1.8.1:compile
   +- commons-logging:commons-logging:jar:1.2:compile
   \- commons-collections:commons-collections:jar:3.2.2:compile
```

If you don't want to get java.lang.NoClassDefFoundError in future,
you should also add these jars. They can be found in odfvalidator-1.1.8-incubating.war of odftoolkit-0.6.2-incubating-bin.zip.

Body:
I am trying to load a .ods file with the code:

import org.odftoolkit.simple.SpreadsheetDocument;
SpreadsheetDocument data = SpreadsheetDocument.loadDocument(f);

I've added the import statement to show which package I am using.

However I keep getting java.lang.NoClassDefFoundError. I've tried adding many different libraries. At the moment I have these libraries in my eclipse build path: libraries in my eclipse build path

And am getting this error

Exception in thread "main" java.lang.NoClassDefFoundError: com/hp/hpl/jena/rdf/model/RDFNode
    at org.odftoolkit.odfdom.pkg.OdfFileDom.initialize(OdfFileDom.java:215)
    at org.odftoolkit.odfdom.pkg.manifest.OdfManifestDom.initialize(OdfManifestDom.java:74)
    at org.odftoolkit.odfdom.pkg.OdfFileDom.<init>(OdfFileDom.java:132)
    at org.odftoolkit.odfdom.pkg.manifest.OdfManifestDom.<init>(OdfManifestDom.java:63)
    at org.odftoolkit.odfdom.pkg.OdfFileDom.newFileDom(OdfFileDom.java:189)
    at org.odftoolkit.odfdom.pkg.OdfPackage.parseManifest(OdfPackage.java:1187)
    at org.odftoolkit.odfdom.pkg.OdfPackage.readZip(OdfPackage.java:454)
    at org.odftoolkit.odfdom.pkg.OdfPackage.initializeZip(OdfPackage.java:425)
    at org.odftoolkit.odfdom.pkg.OdfPackage.<init>(OdfPackage.java:256)
    at org.odftoolkit.odfdom.pkg.OdfPackage.loadPackage(OdfPackage.java:318)
    at org.odftoolkit.simple.Document.loadDocument(Document.java:319)
    at org.odftoolkit.simple.SpreadsheetDocument.loadDocument(SpreadsheetDocument.java:203)
    at FirstLoadComponent.main(FirstLoadComponent.java:11)
Caused by: java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.RDFNode
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more

Any suggestion on how to get my code running or any alternative my to do simple read and writes to .ods files would be greatly appeciated.

Body:
You have to add commons-validator-1.5.0.jar, jena-core-2.11.2.jar, jena-iri-1.0.2.jar at least.

The full dependencies jars could be got via maven command mvn dependency:tree.

org.apache.odftoolkit:odfdom-java:jar:0.8.11-incubating
+- org.apache.odftoolkit:taglets:jar:0.8.11-incubating:compile
|  \- com.sun:tools:jar:1.7.0:system
+- xerces:xercesImpl:jar:2.9.1:compile
+- xml-apis:xml-apis:jar:1.3.04:compile
+- org.apache.jena:jena-core:jar:2.11.2:compile
|  +- org.slf4j:slf4j-api:jar:1.7.6:compile
|  +- org.apache.jena:jena-iri:jar:1.0.2:compile
|  +- org.slf4j:slf4j-log4j12:jar:1.7.6:compile
|  \- log4j:log4j:jar:1.2.17:compile
+- net.rootdev:java-rdfa:jar:0.4.2:compile
\- commons-validator:commons-validator:jar:1.5.0:compile
   +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
   +- commons-digester:commons-digester:jar:1.8.1:compile
   +- commons-logging:commons-logging:jar:1.2:compile
   \- commons-collections:commons-collections:jar:3.2.2:compile

If you don't want to get java.lang.NoClassDefFoundError in future,
you should also add these jars. They can be found in odfvalidator-1.1.8-incubating.war of odftoolkit-0.6.2-incubating-bin.zip.