问:
In reality, are server controls rarely added programmatically to aspx pages?
I mean, it's easy to add a Button programmactically to an aspx page, but a server control's event handler probably has to be set early in the page life cycle (maybe before Control.Load event). As a result in reality, are dynamic controls rarely added to apsx pages?

I wish there is a way to call postback at the server, so that a event is never too late.

答: Best thing to do would be read Truly Understanding ViewState and Truly Understanding Dynamic Controls -- you really can't start to do anything really hinky in webforms without that knowledge.</p>


来源: stackexchange

问:
How to create permanent group using ejabber xmpp in iOS
Note:- Before down grade question read description.

We are implement ejabberd for chat application personal chat working fine with all functionality. now we need to create permanent group using ejabberd MUC/SUB service.

We read https://docs.ejabberd.im/developer/xmpp-clients-bots/proposed-extensions/muc-sub/ documents.

Now my question is that how we can send all this IQ using iOS if you guys have any demo or sample code then share here.

We also try with PHP rest API but not getting any presence or ping into iOS application.

答:
Ejabberd never remember groupJID which is created by us. but you can achieve with the help of web service by storing group info while creating group and every-time fetch group info from server and join manually,

```<code> let xmppRoom = self.getRoomObject(roomJid: roomID.appending(GroupConfernce))

 let history = DDXMLElement.element(withName: "history") as! DDXMLElement

 history.addAttribute(withName: "maxstanzas", stringValue: "10")

 xmppRoom.addDelegate(self.appDelegate, delegateQueue: DispatchQueue.main)
 xmppRoom.join(usingNickname: self.appDelegate.xmppStream?.myJID.user, history: history)
</code>```

otherwise you can use MongooseIM Server, it has capability to remember group info and no need of any manual process.

check below link

https://github.com/esl/MongooseIM

ContentLicense: CC BY-SA 3.0

Body:
Ejabberd never remember groupJID which is created by us. but you can achieve with the help of web service by storing group info while creating group and every-time fetch group info from server and join manually,

 let xmppRoom = self.getRoomObject(roomJid: roomID.appending(GroupConfernce))

 let history = DDXMLElement.element(withName: "history") as! DDXMLElement

 history.addAttribute(withName: "maxstanzas", stringValue: "10")

 xmppRoom.addDelegate(self.appDelegate, delegateQueue: DispatchQueue.main)
 xmppRoom.join(usingNickname: self.appDelegate.xmppStream?.myJID.user, history: history)

otherwise you can use MongooseIM Server, it has capability to remember group info and no need of any manual process.

check below link

https://github.com/esl/MongooseIM


问:
Python MySQLQuery result returns extra characters
I'm making a mysql request with python, when I'm printing the result it gives me the results but it adds some characters extra for me xD

What I need is:

Asia TAG

Australia TAG

...

What I get is:

('Asia TAG',)

('Australia TAG',)

...

Those ('...',) how does this get in my results?

```<code>current = con_mysql.cursor()
current_query = "SELECT name FROM event_categories WHERE visible=1"
current.execute(current_query)

for name in current:
    print(name)
</code>```

答: the records returned from MySQL are tuples, so you need to convert it to what you need, e.g.: print(name[0])

Body:
I'm making a mysql request with python, when I'm printing the result it gives me the results but it adds some characters extra for me xD

What I need is:

Asia TAG

Australia TAG

...

What I get is:

('Asia TAG',)

('Australia TAG',)

...

Those ('...',) how does this get in my results?

current = con_mysql.cursor()
current_query = "SELECT name FROM event_categories WHERE visible=1"
current.execute(current_query)

for name in current:
    print(name)


问:
In keycloak 3.3 is it possible to flag Users as invalid or delete them, when they didn't activate after some specific time?
As my Question is already stating:

In my Keycloak application, the User registers and get's an activation Email.

When the user doesn't click the email, he/she stays as a kind of zombie in the database.

My Question is: Is there a mechanism where longevity of a non-activated user can be set so that the user is deleted after some time.

答:
Not that I'm aware of.

But you could implement an EventListener SPI detecting when a user is disabled. Then the SPI could start a scheduled Task in order to delete the user after a certain time.
The Task should be aborted, if the user is enabled again.

There is a Timer SPI for Scheduled Tasks, as well, but I never used this SPI by myself.

The 'Register' event may also be a good hook for adding such Task functionality.


问:
c# .net: Extend existing class with method that should be overriden when initialized
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

```<code>String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}
</code>```

How is this solved in C#?

答:
as far as I know it is not possible to change classes you do not own the sourcecode. E.g. .Net Classes.

You can extend existing classs with Extensionmethods:

```<code>public static classe StringExtension
{
    public static void DoStingCalc(this string str)
    {
         //Do your Stuff here
    }
}
</code>```

If you want to Force a specific Method. You have to derive from your class an decorate it with the interface you want to ensure. Or make an abstact method declaration.

Body:
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}

How is this solved in C#?

Body:
as far as I know it is not possible to change classes you do not own the sourcecode. E.g. .Net Classes.

You can extend existing classs with Extensionmethods:

public static classe StringExtension
{
    public static void DoStingCalc(this string str)
    {
         //Do your Stuff here
    }
}

If you want to Force a specific Method. You have to derive from your class an decorate it with the interface you want to ensure. Or make an abstact method declaration.


问:
Django: "projects" vs "apps"
I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django.

Projects can have many apps. Apps can be shared among many projects. Fine.

I'm not reinventing the blog or forum - I don't see any portion of my product being reusable in any context. Intuitively, I would call this one "application." Do I then do all my work in a single "app" folder?

If so... in terms of Django's project.app namespace, my inclination is to use myproduct.myproduct, but of course this isn't allowed (but the application I'm building is my project, and my project is an application!). I'm therefore lead to believe that perhaps I'm supposed to approach Django by building one app per "significant" model, but I don't know where to draw the boundaries in my schema to separate it into apps - I have a lot of models with relatively complex relationships.

I'm hoping there's a common solution to this...

答:
Here Django creators points out that difference themselves.
I think that thinking about Apps as they have to be reusable in other projects is good. Also a good way of thinking about Apps in Django provide modern web applications.

Imagine that you are creating big dynamic web app basing on JavaScript.

You can create then in django App named e.g "FrontEnd" <-- in thins app you will display content.

Then you create some backend Apps. E.g App named "Comments" that will store user comments. And "Comments" App will not display anything itself. It will be just API for AJAX requests of your dynamic JS website.

In this way you can always reuse your "Comments" app. You can make it open source without opening source of whole project. And you keep clean logic of your project.

ContentLicense: CC BY-SA 2.5

Title: Django: "projects" vs "apps"


问:
Getting value from associated model
My setup: Rails 2.3.10, Ruby 1.8.7

Here are my models

```<code>class User
 has_many :user_projects
end

class Project
 has_many :user_projects
 #has a column named "project_type"
end

class UserProject
 belongs_to :user
 belongs_to :project
 #fields: project_id, user_id
end
</code>```

When I return a JSON string of a user and his related user_projects records, I also want to include in the user_project record the project.project_type column. Note: I don't want to also include the entire project record in the results. A possible solution is dup the project_type field in user_projects but I prefer not to do that if possible, is there another way to accomplish this during the find/read action?

Just to be clear, here's the JSON output I'm looking for

```<code>{
  "user": {
    "username": "bob",
    "id": 1,
    "email": "bob@blah.com"
    "user_projects": [
      {
            "id": 15,
            "user_id": 1,
            "project_id": 10,
            "project_type": "marketing"
      }
      {
            "id": 22,
            "user_id": 1,
            "project_id": 11,
            "project_type": "sales"
      }
     ]
}
</code>```

答:
```<code>class UserProject
   belongs_to :user
   belongs_to :project
   #fields: project_id, user_id
   attr_reader :type

  def type
    self.project.type
  end
 end

 class MyController < AC

   def action
     @model = whatever
     respond_to do |format|
       format.json { render :json => @model.to_json(:methods => :type)}
     end

   end
 end
</code>```

Hope this helps.

Title: Getting value from associated model

Body:
My setup: Rails 2.3.10, Ruby 1.8.7

Here are my models

class User
 has_many :user_projects
end

class Project
 has_many :user_projects
 #has a column named "project_type"
end

class UserProject
 belongs_to :user
 belongs_to :project
 #fields: project_id, user_id
end

When I return a JSON string of a user and his related user_projects records, I also want to include in the user_project record the project.project_type column. Note: I don't want to also include the entire project record in the results. A possible solution is dup the project_type field in user_projects but I prefer not to do that if possible, is there another way to accomplish this during the find/read action?

Just to be clear, here's the JSON output I'm looking for

{
  "user": {
    "username": "bob",
    "id": 1,
    "email": "bob@blah.com"
    "user_projects": [
      {
            "id": 15,
            "user_id": 1,
            "project_id": 10,
            "project_type": "marketing"
      }
      {
            "id": 22,
            "user_id": 1,
            "project_id": 11,
            "project_type": "sales"
      }
     ]
}

Body:
class UserProject
   belongs_to :user
   belongs_to :project
   #fields: project_id, user_id
   attr_reader :type

  def type
    self.project.type
  end
 end

 class MyController < AC

   def action
     @model = whatever
     respond_to do |format|
       format.json { render :json => @model.to_json(:methods => :type)}
     end

   end
 end

Hope this helps.


问:
Koa js : Err: Can't set headers after they're sent. mongoDB
I'm using Koa 2's async functions.

I get the following error.

events.js:163
  1:56 PM
        throw er; // Unhandled 'error' event
  1:56 PM
        ^
  1:56 PM
  1:56 PM
  Error: Can't set headers after they are sent.
  1:56 PM
      at ServerResponse.setHeader (_http_outgoing.js:371:11)
  1:56 PM
      at Object.set (/app/node_modules/koa/lib/response.js:440:16)
  1:56 PM
      at Object.redirect (/app/node_modules/koa/lib/response.js:261:10)
  1:56 PM
      at Object.proto.(anonymous function) [as redirect] (/app/node_modules/delegates/index.js:40:31)
  1:56 PM
  Jump to
  at url.findOne (/app/server.js:126:9)
  1:56 PM
      at model.Query. (/app/node_modules/mongoose/lib/model.js:3737:16)
  1:56 PM
      at /app/node_modules/kareem/index.js:277:21
  1:56 PM
      at /app/node_modules/kareem/index.js:131:16
  1:56 PM
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
  1:56 PM
      at process._tickCallback (internal/process/next_tick.js:104:9)
  1:56 PM
  6 minutes ago

This is part of my code.

```<code>async function red(ctx) {
  let redurl = "//url here";
  url.findOne({ shortenedLink: redurl }, (err, data) => {
    //find if short url matches long url in db
    if (err) throw err;
    if (data) {
      //if matches then redirect to long url
      ctx.redirect(data.url); //getting the error here
      console.log("matched");
    } else console.error("--");
  });
}
</code>```

My full code can be found here.

答:
I was having the same issue, as I used chained sendStatus function in my code as preceding.

```<code>Country.count({ name: name }, (error, count) => {
        if (count > 0) {
            console.log(count);
            error = name + alreadyExists;
            res.sendStatus(500).sendStatus(500);
        }
});
</code>```

Removing the extra sendStatus fixed my issue.

```<code>Country.count({ name: name }, (error, count) => {
        if (count > 0) {
            console.log(count);
            error = name + alreadyExists;
            res.sendStatus(500);
        }
});
</code>```

Body:
I'm using Koa 2's async functions.

I get the following error.

events.js:163
  1:56 PM
        throw er; // Unhandled 'error' event
  1:56 PM
        ^
  1:56 PM
  1:56 PM
  Error: Can't set headers after they are sent.
  1:56 PM
      at ServerResponse.setHeader (_http_outgoing.js:371:11)
  1:56 PM
      at Object.set (/app/node_modules/koa/lib/response.js:440:16)
  1:56 PM
      at Object.redirect (/app/node_modules/koa/lib/response.js:261:10)
  1:56 PM
      at Object.proto.(anonymous function) [as redirect] (/app/node_modules/delegates/index.js:40:31)
  1:56 PM
  Jump to
  at url.findOne (/app/server.js:126:9)
  1:56 PM
      at model.Query. (/app/node_modules/mongoose/lib/model.js:3737:16)
  1:56 PM
      at /app/node_modules/kareem/index.js:277:21
  1:56 PM
      at /app/node_modules/kareem/index.js:131:16
  1:56 PM
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
  1:56 PM
      at process._tickCallback (internal/process/next_tick.js:104:9)
  1:56 PM
  6 minutes ago

This is part of my code.

async function red(ctx) {
  let redurl = "//url here";
  url.findOne({ shortenedLink: redurl }, (err, data) => {
    //find if short url matches long url in db
    if (err) throw err;
    if (data) {
      //if matches then redirect to long url
      ctx.redirect(data.url); //getting the error here
      console.log("matched");
    } else console.error("--");
  });
}

My full code can be found here.

Body:
I was having the same issue, as I used chained sendStatus function in my code as preceding.

Country.count({ name: name }, (error, count) => {
        if (count > 0) {
            console.log(count);
            error = name + alreadyExists;
            res.sendStatus(500).sendStatus(500);
        }
});

Removing the extra sendStatus fixed my issue.

Country.count({ name: name }, (error, count) => {
        if (count > 0) {
            console.log(count);
            error = name + alreadyExists;
            res.sendStatus(500);
        }
});


问:
Android device as a receiver for A2DP profile
Basically, what I am trying to do right now is use an android device as an A2DP receiver and when pairing established, android plays sound that is received from a transmitter. I am worrying that if I use STP profile, it may cause delay of streaming. So, I want to use A2DP but is this possible to use an android device as a receiver of A2DP? and how to do it? </p>

答: You may-not be able to do it manually between 2 phones  because to stream one device needs to be A2DP sink and other other A2DP source, Phones are typically only Source devices (Source of the stream that can stream to sink devices) , Sinks are Headsets or Bluetooth speakers.</p>


问:
cross platform native open/save file dialogs
I'm writing a UI for my program using opengl with SDL in a combination of Lua and C++

What I need now is some library that will allow me to call a function that presents the user with a file select dialog for opening/saving a file. But if the OS offers native functionality for such a dialog, then I want to use that dialog (eg Window's GetOpenFileName).

The only platforms I need to support are Windows and Linux, but I want to be able to still use most of the SDL & openGL code I've already written.

What options are available?

答:
tinyfiledialogs offers many modal dialogs and popup notifications (both for graphic and console modes). It is a cross-platform C file (with a header) to add to your C or C++ project. It aims to be extremely easy to use, has no init, no main loop, and no external dependencies. It is used by hundreds of projects on GitHub and of course, I am the author. Get it here: http://tinyfiledialogs.sourceforge.net

Usage example:

```<code>    char const * selection = tinyfd_openFileDialog( // there is also a wchar_t version
        "Select file", // title
        "C:\\", // optional initial directory
        2, // number of filter patterns
        lFilterPatterns, // char const * lFilterPatterns[2] = { "*.txt", "*.jpg" };
        NULL, // optional filter description
        0 // forbid multiple selections
        );

</code>```

tinyfiledialogs handles char strings as UTF-8 (on windows and on unix). On Windows, It also offers UTF-16 / wchar_t functions.

*** v3.10 (2023): NEW FORTRAN module fully implemented with examples ***

*** v3.13 (2023): NEW PASCAL unit fully implemented with examples ***

Body:
tinyfiledialogs offers many modal dialogs and popup notifications (both for graphic and console modes). It is a cross-platform C file (with a header) to add to your C or C++ project. It aims to be extremely easy to use, has no init, no main loop, and no external dependencies. It is used by hundreds of projects on GitHub and of course, I am the author. Get it here: http://tinyfiledialogs.sourceforge.net

Usage example:

    char const * selection = tinyfd_openFileDialog( // there is also a wchar_t version
        "Select file", // title
        "C:\\", // optional initial directory
        2, // number of filter patterns
        lFilterPatterns, // char const * lFilterPatterns[2] = { "*.txt", "*.jpg" };
        NULL, // optional filter description
        0 // forbid multiple selections
        );

tinyfiledialogs handles char strings as UTF-8 (on windows and on unix). On Windows, It also offers UTF-16 / wchar_t functions.

*** v3.10 (2023): NEW FORTRAN module fully implemented with examples ***

*** v3.13 (2023): NEW PASCAL unit fully implemented with examples ***

ContentLicense: CC BY-SA 4.0


问:
Push data to an embedded array using mongoose
My Schema look like this

```<code>var Company ={
    Name
    Email
    Location
    Industry
    Creator
    PostedJobs : [{
        JobName
        JobType
        JobLocation
        JobSalary
        Applicants : [{
            Name
            Status
        }]
    }]
}
</code>```

to push job here is my route code which is working

```<code>router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalary:Salary};
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
        Company.PostedJobs.push(postedJob);
        Company.save();
        req.flash('sucess_msg' , 'Job Added Sucessfully');
        res.render('dashboard',{
            "Company" : Company
        });
    });
});
</code>```

now i want to push applicants on apply button
apply code is

```<code>router.get('/:id/apply' , isLoggedIn , function(req , res , next) {
    var appicant = { Name : req.user.FirstName,
            Status : "Applied"
        };
        Company.find({'PostedJobs._id' : req.params.id}).then(function(job) {
        Company.PostedJobs.Applicants.push(applicant);
        Company.save();
        req.flash('sucess_msg' , 'Job Added Sucessfully');
        res.redirect('/jobs');
    });

 });
</code>```

i also tried

which is not working and i wont know what to do with this

答:
Can you try this? when pushing applicants.     </p>

```<code>Company.PostedJobs[0].Applicants.push(applicant);
</code>```

Body:
My Schema look like this

var Company ={
    Name
    Email
    Location
    Industry
    Creator
    PostedJobs : [{
        JobName
        JobType
        JobLocation
        JobSalary
        Applicants : [{
            Name
            Status
        }]
    }]
}

to push job here is my route code which is working

router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalary:Salary};
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
        Company.PostedJobs.push(postedJob);
        Company.save();
        req.flash('sucess_msg' , 'Job Added Sucessfully');
        res.render('dashboard',{
            "Company" : Company
        });
    });
});

now i want to push applicants on apply button
apply code is

router.get('/:id/apply' , isLoggedIn , function(req , res , next) {
    var appicant = { Name : req.user.FirstName,
            Status : "Applied"
        };
        Company.find({'PostedJobs._id' : req.params.id}).then(function(job) {
        Company.PostedJobs.Applicants.push(applicant);
        Company.save();
        req.flash('sucess_msg' , 'Job Added Sucessfully');
        res.redirect('/jobs');
    });

 });

i also tried

which is not working and i wont know what to do with this

Body:
Can you try this? when pushing applicants.

Company.PostedJobs[0].Applicants.push(applicant);


问:
Comapring Objects of TreeSet and HashSet
```<code>List<String> list = Arrays.asList("Snehal", "Masne", "Anything", "Else");

HashSet<String> hashSet = new HashSet<String>(list);
TreeSet<String> treeSet = new TreeSet<String>(list);

System.out.println("Equality  = " + hashSet.equals(treeSet));  // returns True
</code>```

How the equals() is evaluating the result by comparing diff structures? How come its true? Is just Hashcode being compared? If so, how come its same?

答:
The Javadoc of Set has the answer:

boolean java.util.Set.equals(Object o)

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

As long as the two Sets have the exact same elements, it doesn't matter if they have different implementations of the Set interface.

Body:
List<String> list = Arrays.asList("Snehal", "Masne", "Anything", "Else");

HashSet<String> hashSet = new HashSet<String>(list);
TreeSet<String> treeSet = new TreeSet<String>(list);

System.out.println("Equality  = " + hashSet.equals(treeSet));  // returns True

How the equals() is evaluating the result by comparing diff structures? How come its true? Is just Hashcode being compared? If so, how come its same?


问:
ScaffoldColumn(false) doesn't work
Goal:
Display a website to fill out a form and also be enable to make a validation before clicking on the send button.

problem:
The code [ScaffoldColumn(false)] doesn't work when I use  <%: Html.EditorForModel() %> in the view.

Questions:
What should I do?

// Fullmetalboy

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
 Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.Models.Order>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Address and Payment
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) {%>

    <h2>Address and Payment</h2>

    <fieldset>
        <legend>Shipping Information</legend>
        <%: Html.EditorForModel() %>
    </fieldset>

    <input type="submit" value="Submit Order" />
    <% } %>

</asp:Content>
</code>```

```<code>private BokButikEntities _myBokButikEntities = new BokButikEntities();

//
// GET: /Checkout/

public ActionResult AddressAndPayment()
{
    return View();
}

//
// POST: /Checkout/AddressAndPayment

[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
    var order = new Order();
    TryUpdateModel(order);

    try
    {

        var cart = ShoppingCart.GetCart(this.HttpContext);

        order.Anvandarnamn = User.Identity.Name;
        order.OrderDatum = DateTime.Now;
        order.TotalKostnad = cart.KalkyleraTotalKostnad();

        //Save Order
        _myBokButikEntities.AddToOrders(order);
        _myBokButikEntities.SaveChanges();

        //Process the order
        cart.CreateOrder(order);

        return RedirectToAction("Complete", new { id = order.OrderID });

    }
    catch
    {
        //Invalid - redisplay with errors
        return View(order);
    }
}
</code>```

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace BokButik1.Models.Validation
{
    [MetadataType(typeof(OrderMetadata))]
    public partial class Order
    {
        // Validerar data

        [Bind(Exclude = "OrderID")]
        public class OrderMetadata
        {
            [Required(ErrorMessage = "Förnamn saknas")]
            [DisplayName("Förnamn")]
            [StringLength(50)]
            public object Fornamn { get; set; }

            [Required(ErrorMessage = "Efternamn saknas")]
            [DisplayName("Efternamn")]
            [StringLength(50)]
            public object Efternamn { get; set; }

            [Required(ErrorMessage = "Mobilnummer saknas")]
            [DisplayName("Mobilnummer")]
            public int Mobilnummer { get; set; }

            [Required(ErrorMessage = "Gatuadress saknas")]
            [DisplayName("Gatuadress")]
            [StringLength(50)]
            public object Gatuadress { get; set; }

            [Required(ErrorMessage = "Postnummer saknas")]
            [DisplayName("Postnummer")]
            public object Postnummer { get; set; }

            [Required(ErrorMessage = "Ort saknas")]
            [DisplayName("Ort")]
            [StringLength(50)]
            public object Ort { get; set; }

            [ScaffoldColumn(false)]
            public object OrderID { get; set; }

            [ScaffoldColumn(false)]
            public object OrderDatum { get; set; }

            [ScaffoldColumn(false)]
            public object TotalKostnad { get; set; }

            [ScaffoldColumn(false)]
            public object Anvandarnamn { get; set; }
        }
    }
}
</code>```

答:
it doesn't work because your view is not strongly typed to anything.

it should be

```<code><%@ Page ... Inherits="System.Web.Mvc.ViewPage<Order>" %>
</code>```

also if you would have an Order.ascx in your editor templates, the ScaffoldColumn would also don't do anything

Title: ScaffoldColumn(false) doesn't work

Body:
Goal:
Display a website to fill out a form and also be enable to make a validation before clicking on the send button.

problem:
The code [ScaffoldColumn(false)] doesn't work when I use  <%: Html.EditorForModel() %> in the view.

Questions:
What should I do?

// Fullmetalboy

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
 Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.Models.Order>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Address and Payment
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) {%>

Address and Payment

    <fieldset>
        <legend>Shipping Information</legend>
        <%: Html.EditorForModel() %>
    </fieldset>

    <input type="submit" value="Submit Order" />
    <% } %>

</asp:Content>

private BokButikEntities _myBokButikEntities = new BokButikEntities();

//
// GET: /Checkout/

public ActionResult AddressAndPayment()
{
    return View();
}

//
// POST: /Checkout/AddressAndPayment

[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
    var order = new Order();
    TryUpdateModel(order);

    try
    {

        var cart = ShoppingCart.GetCart(this.HttpContext);

        order.Anvandarnamn = User.Identity.Name;
        order.OrderDatum = DateTime.Now;
        order.TotalKostnad = cart.KalkyleraTotalKostnad();

        //Save Order
        _myBokButikEntities.AddToOrders(order);
        _myBokButikEntities.SaveChanges();

        //Process the order
        cart.CreateOrder(order);

        return RedirectToAction("Complete", new { id = order.OrderID });

    }
    catch
    {
        //Invalid - redisplay with errors
        return View(order);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace BokButik1.Models.Validation
{
    [MetadataType(typeof(OrderMetadata))]
    public partial class Order
    {
        // Validerar data

        [Bind(Exclude = "OrderID")]
        public class OrderMetadata
        {
            [Required(ErrorMessage = "Förnamn saknas")]
            [DisplayName("Förnamn")]
            [StringLength(50)]
            public object Fornamn { get; set; }

            [Required(ErrorMessage = "Efternamn saknas")]
            [DisplayName("Efternamn")]
            [StringLength(50)]
            public object Efternamn { get; set; }

            [Required(ErrorMessage = "Mobilnummer saknas")]
            [DisplayName("Mobilnummer")]
            public int Mobilnummer { get; set; }

            [Required(ErrorMessage = "Gatuadress saknas")]
            [DisplayName("Gatuadress")]
            [StringLength(50)]
            public object Gatuadress { get; set; }

            [Required(ErrorMessage = "Postnummer saknas")]
            [DisplayName("Postnummer")]
            public object Postnummer { get; set; }

            [Required(ErrorMessage = "Ort saknas")]
            [DisplayName("Ort")]
            [StringLength(50)]
            public object Ort { get; set; }

            [ScaffoldColumn(false)]
            public object OrderID { get; set; }

            [ScaffoldColumn(false)]
            public object OrderDatum { get; set; }

            [ScaffoldColumn(false)]
            public object TotalKostnad { get; set; }

            [ScaffoldColumn(false)]
            public object Anvandarnamn { get; set; }
        }
    }
}

Body:
it doesn't work because your view is not strongly typed to anything.

it should be

<%@ Page ... Inherits="System.Web.Mvc.ViewPage<Order>" %>

also if you would have an Order.ascx in your editor templates, the ScaffoldColumn would also don't do anything


问:
How to handle database changes with older version of application
I am working on a desktop application(WPF) which is using sql server database to store and fetch the data. Now due to change in user requirement, there are some extra columns added in some tables and I have made changes in NHibernate mapping classes as well and application is ready for new release.

Now if I make database related changes in Production environment, the users who are using old version of the application will get NHibernate exception since the mappings are changed.

Is there any solution to avoid these kind of scenarios? Please need suggestions.

答:
You should need to do manually. I have experience like this case.

1.Take backup for those table in production server which tables are all you changed mapping and altered new columns.
2.Drop those tables from production server.
3.move local tables schema (tables which you have mapping and new columns) into production server.
4.Now move the production data from backup table into source table based on mapping.


问:
HTML Select Input Bug on iOS11
HTML Select Input Dropdown is not getting dismissed properly on iOS 11. Upon closing the dropdown, an empty dropdown with blank options reappears in its place.

Nothing has changed, and we started getting complaints from iOS users, we could not replicate. Updated iOS to latest and now can replicate. The issue is, that they are always blank, from then on.

Pressure has been put on us to resolve this issue, has anyone came across this issue and have a workaround to resolve?

This is a cordova application, jQuery, bootstrap and knockoutjs. Any help be appreciated. I know it may be vague and no code but this is basic html selects.

答: Update to ios 11.2 and issue has been resolved. After reading plenty of news articles this was nothing compared to the list of bugs that went out on this version.</p>

Title: HTML Select Input Bug on iOS11


问:
Travis CI and GitLab CI disappointing - Other options for GitHub?
I have started a Django (private) project on GitHub. I'd like that my repo tell me if my unit tests passed or failed to each commit. I know there exists Travis CI, but it is expensive and a service en GitLab, but I use GitHub, so...

What other free services, options could I use with GitHub?

答:
You can run the Gitlab-ci runner locally in Docker or mirror your repository from GitHub to Gitlab if you really want to keep using GitHub.

Gitlab can pull from your GitHub repository each x minutes and automatically run jobs with gitlab-ci, see https://docs.gitlab.com/ee/workflow/repository_mirroring.html for details.


问:
mysql : match against and having query with max
I have the following query

SELECT *,MATCH(title,text) AGAINST('my home' in boolean mode)  as
  relevance FROM blog where active = 1

The above query returns 5 rows with relevance 2,2,0,0,0

Now I want to select only the rows with maximum relevance.
So it should return only the rows which has 2 as their relevance.

I tried the following query.

SELECT *,MATCH(title,text) AGAINST('my home' in boolean mode)
  as relevance FROM blog where active = 1 having
  relevance=max(MATCH(title,text) AGAINST('my home' in boolean
  mode))

But it returns only one row..

Is there any way to get only that two rows?

答:
```<code>SELECT *, MATCH(title,text) AGAINST('my home' in boolean mode) as relevance
FROM blog
where active = 1
and MATCH(title,text) AGAINST('my home' in boolean mode) = (select max(MATCH(title,text) AGAINST('my home' in boolean mode)) from blog)
</code>```


问:
how can i split the longest word in the sentence
```<code>String s = "сотрудник компании ГазТехСтройСнабСервис";
String[] parts = s.split(" ");
System.out.println(Arrays.toString(parts));
</code>```

how can i split the longest word in the sentence for example if it has more than 10 characters and return String?

答:
If i get it right you want to split at each space or if a word has more than n chars at index n. Try something like this:</p>

```<code>    int size = 10;
    String s = "сотрудник компании ГазТехСтройСнабСервис";
    String[] parts = s.split("(?<=\\G.{"+size+"})|\\s+");
    System.out.println(Arrays.toString(parts));
</code>```

Body:
String s = "сотрудник компании ГазТехСтройСнабСервис";
String[] parts = s.split(" ");
System.out.println(Arrays.toString(parts));

how can i split the longest word in the sentence for example if it has more than 10 characters and return String?

Body:
If i get it right you want to split at each space or if a word has more than n chars at index n. Try something like this:

    int size = 10;
    String s = "сотрудник компании ГазТехСтройСнабСервис";
    String[] parts = s.split("(?<=\\G.{"+size+"})|\\s+");
    System.out.println(Arrays.toString(parts));


问:
Get List of Available WiFi networks without location services in Android
EDIT:
I know that SCAN_RESULTS_AVAILABLE_ACTION returns a list of size '0' if location services are off.The question was how to do it without location services.

PREVIOUS:
I need a list of all available WiFi networks to the phone,and use that list to populate a ListView in my app. I will later connect to the desired network from my app.

I have achieved the above by using ,

```<code> wifiManager.startScan();
</code>```

and I have registered a BroadcastReciever for receiving an intimation when a scan is complete like below,

```<code>registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
</code>```

receiver code is as follows,

```<code> class WifiReceiver extends BroadcastReceiver {

        // This method call when number of wifiManager connections changed
        public void onReceive(Context c, Intent intent) {
            wifiResults.clear();
            wifiList = wifiManager.getScanResults();
            for(int i = 0; i < wifiList.size(); i++){
                if(!wifiList.get(i).SSID.equals(""))
                wifiResults.add(wifiList.get(i).SSID+" signal:"+wifiList.get(i).level);
            }
            adapter.notifyDataSetChanged();
            wifiRefreshLayout.setRefreshing(false);

        }
    }
</code>```

the problem is I am having to enable location services every time I want the above information.I don't really see the point here as I don't need the location services here as other apps like "SHAREit" do the same without needing location services .Is there a better approach for achieving this?

答: We can get the list of available WIFI without GPS turned on by setting the app's targetSDKversion to 21 or lower.

Body:
EDIT:
I know that SCAN_RESULTS_AVAILABLE_ACTION returns a list of size '0' if location services are off.The question was how to do it without location services.

PREVIOUS:
I need a list of all available WiFi networks to the phone,and use that list to populate a ListView in my app. I will later connect to the desired network from my app.

I have achieved the above by using ,

 wifiManager.startScan();

and I have registered a BroadcastReciever for receiving an intimation when a scan is complete like below,

registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

receiver code is as follows,

 class WifiReceiver extends BroadcastReceiver {

        // This method call when number of wifiManager connections changed
        public void onReceive(Context c, Intent intent) {
            wifiResults.clear();
            wifiList = wifiManager.getScanResults();
            for(int i = 0; i < wifiList.size(); i++){
                if(!wifiList.get(i).SSID.equals(""))
                wifiResults.add(wifiList.get(i).SSID+" signal:"+wifiList.get(i).level);
            }
            adapter.notifyDataSetChanged();
            wifiRefreshLayout.setRefreshing(false);

        }
    }

the problem is I am having to enable location services every time I want the above information.I don't really see the point here as I don't need the location services here as other apps like "SHAREit" do the same without needing location services .Is there a better approach for achieving this?


问:
BACKUP_FAILED web deploy IIS remote server. Publishing failed. Web deployment task failed. Illegal characters in path
How can I get backup to work before deploy.

Windows Server 2008 R2 Standard

Local Machine Windows 10 Visual Studio Pro 2017

I can publish site. But backup does not work.

```<code>An error occurred when the request was processed on the remote computer.
Illegal characters in path.
   at Microsoft.Web.Deployment.BackupManager.HandleExceptionForBackupFailure(DeploymentBaseContext baseContext, BackupSettings settings, Exception ex, Boolean suppressLogging)

   at Microsoft.Web.Deployment.BackupRuleHandler.PreSync(DeploymentSyncContext syncContext)

   at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable`1 passId, String user, String siteName)
   at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
   at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObject sourceObject, DeploymentSyncContext syncContext, Nullable`1 syncPass, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncOptions)
   at CallSite.Target(Closure , CallSite , Object , Object , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Web.Publishing.Tasks.VSMSDeployObject.SyncTo(VSMSDeployObject destObject, Object syncOptions, IVSMSDeployHost _host)
   at CallSite.Target(Closure , CallSite , VSMSDeployObject , VSMSDeployObject , Object , IVSMSDeployHost )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Web.Publishing.Tasks.BaseMSDeployDriver.InvokeMSdeploySync()
   at Microsoft.Web.Publishing.Tasks.VSMSDeployDriverInCmd.StartSync()
   at Microsoft.Web.Publishing.Tasks.BaseMSDeployDriver.SyncThruMSDeploy()
   at Microsoft.Web.Publishing.Tasks.VSMSDeploy.Execute()
        VSMSDeploy: Publish failed to deploy.
        Output Property: _PublishResult=False
        Done executing task "VSMSDeploy" -- FAILED.
</code>```

答:
The error was Notepad++ kept a wierd copy of the file
C:\Windows\System32\inetsrv\config\applicationHost.config
on the server.

Opened it in regular notepad, and saw other content and fixed it:
(Probably has something to do with the system file is locked etc)

```<code><location path="www.xxxxx.com">
        <system.webServer>
            <security>
                <access sslFlags="Ssl" />
            </security>
            <wdeploy>
                <backup enabled="true" backupPath="E:\temp" continueSyncOnBackupFailure="false" />
            </wdeploy>
        </system.webServer>
</code>```

Body:
How can I get backup to work before deploy.

Windows Server 2008 R2 Standard

Local Machine Windows 10 Visual Studio Pro 2017

I can publish site. But backup does not work.

An error occurred when the request was processed on the remote computer.
Illegal characters in path.
   at Microsoft.Web.Deployment.BackupManager.HandleExceptionForBackupFailure(DeploymentBaseContext baseContext, BackupSettings settings, Exception ex, Boolean suppressLogging)

   at Microsoft.Web.Deployment.BackupRuleHandler.PreSync(DeploymentSyncContext syncContext)

   at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable`1 passId, String user, String siteName)
   at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
   at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObject sourceObject, DeploymentSyncContext syncContext, Nullable`1 syncPass, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
   at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncOptions)
   at CallSite.Target(Closure , CallSite , Object , Object , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Web.Publishing.Tasks.VSMSDeployObject.SyncTo(VSMSDeployObject destObject, Object syncOptions, IVSMSDeployHost _host)
   at CallSite.Target(Closure , CallSite , VSMSDeployObject , VSMSDeployObject , Object , IVSMSDeployHost )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Web.Publishing.Tasks.BaseMSDeployDriver.InvokeMSdeploySync()
   at Microsoft.Web.Publishing.Tasks.VSMSDeployDriverInCmd.StartSync()
   at Microsoft.Web.Publishing.Tasks.BaseMSDeployDriver.SyncThruMSDeploy()
   at Microsoft.Web.Publishing.Tasks.VSMSDeploy.Execute()
        VSMSDeploy: Publish failed to deploy.
        Output Property: _PublishResult=False
        Done executing task "VSMSDeploy" -- FAILED.

Body:
The error was Notepad++ kept a wierd copy of the file
C:\Windows\System32\inetsrv\config\applicationHost.config
on the server.

Opened it in regular notepad, and saw other content and fixed it:
(Probably has something to do with the system file is locked etc)

<location path="www.xxxxx.com">
        <system.webServer>
            <security>
                <access sslFlags="Ssl" />
            </security>
            <wdeploy>
                <backup enabled="true" backupPath="E:\temp" continueSyncOnBackupFailure="false" />
            </wdeploy>
        </system.webServer>


问:
How to fix broken transform-origin on iOS11 and macOS10.12 Safari?
I'm trying to implement CSS animation by using svg.

I am expecting that 2 svg boxes is rotating (spinning) with transform-origin: center center; 360 degrees. Looks like it behave what I expected with Chrome and Firefox but not with macOS 10.12 (High Sierra) and iOS 11.0.x and 11.1 beta Safari.

Seems like transform-origin: center center; does not work in Safari?

Is there any way to fix this issue?

What I expect:

What I see on Safari:

Here is a sample code

HTML:

```<code>svg(width=500, height=500, viewBox='0 0 500 500')
  rect(x=100, y=100, width=50, height=100)
  rect(x=400, y=100, width=50, height=100)
</code>```

CSS:

```<code>@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

rect {
  transform-origin: center center;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}
</code>```

You can see the behavior here by accessing with Chrome and Safari:
https://codepen.io/manaten/pen/aLeXjW

EDIT:

https://codepen.io/manaten/pen/aVzeEK
Another example of the issue. Looks like origin is set to be the center of svg element by Safari.

答:
transform-box: fill-box; seems to solve the issue.

```<code>rect {
  transform-origin: center center;
  transform-box: fill-box;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}
</code>```

Your first sample with transform-box:

https://codepen.io/MichaelSchober/pen/QOPbKx

Works on MacOs HighSierra 10.13.1 with Safari 11.0.1

The property is still experimental tough. So make sure to check if you are okay with the browser compabtility:

https://developer.mozilla.org/de/docs/Web/CSS/transform-box

Body:
I'm trying to implement CSS animation by using svg.

I am expecting that 2 svg boxes is rotating (spinning) with transform-origin: center center; 360 degrees. Looks like it behave what I expected with Chrome and Firefox but not with macOS 10.12 (High Sierra) and iOS 11.0.x and 11.1 beta Safari.

Seems like transform-origin: center center; does not work in Safari?

Is there any way to fix this issue?

What I expect:

What I see on Safari:

Here is a sample code

HTML:

svg(width=500, height=500, viewBox='0 0 500 500')
  rect(x=100, y=100, width=50, height=100)
  rect(x=400, y=100, width=50, height=100)

CSS:

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

rect {
  transform-origin: center center;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}

You can see the behavior here by accessing with Chrome and Safari:
https://codepen.io/manaten/pen/aLeXjW

EDIT:

https://codepen.io/manaten/pen/aVzeEK
Another example of the issue. Looks like origin is set to be the center of svg element by Safari.

Body:
transform-box: fill-box; seems to solve the issue.

rect {
  transform-origin: center center;
  transform-box: fill-box;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}

Your first sample with transform-box:

https://codepen.io/MichaelSchober/pen/QOPbKx

Works on MacOs HighSierra 10.13.1 with Safari 11.0.1

The property is still experimental tough. So make sure to check if you are okay with the browser compabtility:

https://developer.mozilla.org/de/docs/Web/CSS/transform-box


问:
Unable to compile applescript from NSString
I've been trying to figure out how to run applescript in a objective-c program but so far haven't been able to.

Regardless of how I load the source into the NSAppleScript object, I simply can't get it to compile. Loading from a file returns a nil and loading from source just plain refuses to compile.

I am not an objective-c programmer in any respect and I am having a hard time figuring out how this brain dead language works. Any and all problems are likely correlated to my inability to comprehend why a constructor changes its name based on the arguments you give it.

Example source of one of my many attempts: (note, the script is correct and works fine in Script Editor)

```<code>#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString * source =
        @"to go_home()\n"
        "    tell application \"Finder\" to open \"Home\"\n"
        "end go_home\n"
        "go_home()";

        NSAppleScript * script = [[NSAppleScript alloc] initWithSource: source];

        if ( script == nil)
            NSLog(@"Script is nil");

        NSLog(@"Script source = %@", script.source);

        [script compileAndReturnError: nil];
        [script executeAndReturnError: nil];

        if ([script isCompiled])
            NSLog(@"Script is compiled");
        else
            NSLog(@"Script is not compiled");
    }
    return 0;
}
</code>```

Example output:

```<code>2017-12-05 11:05:48.249206+0100 applescript[11826:744415] Script source = to go_home()
    tell application "Finder" to open "Home"
end go_home
go_home()
2017-12-05 11:05:48.262797+0100 applescript[11826:744415] Script is not compiled
Program ended with exit code: 0
</code>```

Edit: It appears that the problem is related to XCode. When I compile the program in a terminal, everything works fine.

答:
i am getting Script is compiled
Program ended with exit code: 0 for same code.
you can check error by replacing

```<code>[script compileAndReturnError: nil];
[script executeAndReturnError: nil];
</code>```

with

```<code> NSDictionary *error;
 [script compileAndReturnError: &error];
 [script executeAndReturnError: &error];
</code>```

Body:
I've been trying to figure out how to run applescript in a objective-c program but so far haven't been able to.

Regardless of how I load the source into the NSAppleScript object, I simply can't get it to compile. Loading from a file returns a nil and loading from source just plain refuses to compile.

I am not an objective-c programmer in any respect and I am having a hard time figuring out how this brain dead language works. Any and all problems are likely correlated to my inability to comprehend why a constructor changes its name based on the arguments you give it.

Example source of one of my many attempts: (note, the script is correct and works fine in Script Editor)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString * source =
        @"to go_home()\n"
        "    tell application \"Finder\" to open \"Home\"\n"
        "end go_home\n"
        "go_home()";

        NSAppleScript * script = [[NSAppleScript alloc] initWithSource: source];

        if ( script == nil)
            NSLog(@"Script is nil");

        NSLog(@"Script source = %@", script.source);

        [script compileAndReturnError: nil];
        [script executeAndReturnError: nil];

        if ([script isCompiled])
            NSLog(@"Script is compiled");
        else
            NSLog(@"Script is not compiled");
    }
    return 0;
}

Example output:

2017-12-05 11:05:48.249206+0100 applescript[11826:744415] Script source = to go_home()
    tell application "Finder" to open "Home"
end go_home
go_home()
2017-12-05 11:05:48.262797+0100 applescript[11826:744415] Script is not compiled
Program ended with exit code: 0

Edit: It appears that the problem is related to XCode. When I compile the program in a terminal, everything works fine.

Body:
i am getting Script is compiled
Program ended with exit code: 0 for same code.
you can check error by replacing

[script compileAndReturnError: nil];
[script executeAndReturnError: nil];

with

 NSDictionary *error;
 [script compileAndReturnError: &error];
 [script executeAndReturnError: &error];


问:
Unable to debug in WebStorm "bad option: --expose_debug_as=v8debug"
I am trying to debug my NodeJS code using WebStorm 2016.3 and NodeV8 and I am unable to debug it with this error</p>

```<code>"bad option: - expose_debug_as=v8debug"
</code>```

答: I got this fixed by updating my Webstorm to Webstorm 2017.x This will debug with Node 8.</p>

Body:
I am trying to debug my NodeJS code using WebStorm 2016.3 and NodeV8 and I am unable to debug it with this error

"bad option: - expose_debug_as=v8debug"


问:
Converting degrees and minutes to radians in prolog
Assume I have facts defined as follows,

```<code>airport(atl, 'Atlanta ', degmin(33,39 ), degmin(84,25 ) ).
</code>```

and I want to convert degmin to radians. Here is my attempt:

```<code>toRadians(Source, LatRad, LongRad) :-
        airport(Source, _, degmin(X_1, Y_1 ), degmin(X_2, Y_2)),
        radians(X_1,Y_1,res),
        radians(X_2,Y_2,res2),
        LatRad is res, LongRad is res2.
radians(Deg,Min,res) :- res is (Deg + Min/60).
</code>```

However I get this when I run it.

```<code>?- toRadians(atl,Lat,Long).
false.
</code>```

I am expecting something like

```<code> ?- toRadians(atl,Lat,Long).
    Lat = some number
    Long = some number
    True.
</code>```

What went wrong?

答:
This is your program corrected:

```<code>airport(atl, 'Atlanta ', degmin(33,39 ), degmin(84,25 ) ).

toRadians(Source, LatRad, LongRad) :-
        airport(Source, _, degmin(X_1, Y_1 ), degmin(X_2, Y_2)),
        radians(X_1,Y_1,Res),
        radians(X_2,Y_2,Res2),
        LatRad is Res, LongRad is Res2.
radians(Deg,Min,Res) :- Res is (Deg + Min/60).

?-toRadians(atl,Lat,Long).
Lat = 33.65,
Long = 84.41666666666667
</code>```

(I don't know if this is the value you want to obtain). Anyway, the problem comes from the fact that, for instance, you wrote res and not Res with capital R. This is important because in prolog variables MUST be written with a capital letter as the first letter, read this.

Body:
Assume I have facts defined as follows,

airport(atl, 'Atlanta ', degmin(33,39 ), degmin(84,25 ) ).

and I want to convert degmin to radians. Here is my attempt:

toRadians(Source, LatRad, LongRad) :-
        airport(Source, _, degmin(X_1, Y_1 ), degmin(X_2, Y_2)),
        radians(X_1,Y_1,res),
        radians(X_2,Y_2,res2),
        LatRad is res, LongRad is res2.
radians(Deg,Min,res) :- res is (Deg + Min/60).

However I get this when I run it.

?- toRadians(atl,Lat,Long).
false.

I am expecting something like

 ?- toRadians(atl,Lat,Long).
    Lat = some number
    Long = some number
    True.

What went wrong?

Body:
This is your program corrected:

airport(atl, 'Atlanta ', degmin(33,39 ), degmin(84,25 ) ).

toRadians(Source, LatRad, LongRad) :-
        airport(Source, _, degmin(X_1, Y_1 ), degmin(X_2, Y_2)),
        radians(X_1,Y_1,Res),
        radians(X_2,Y_2,Res2),
        LatRad is Res, LongRad is Res2.
radians(Deg,Min,Res) :- Res is (Deg + Min/60).

?-toRadians(atl,Lat,Long).
Lat = 33.65,
Long = 84.41666666666667

(I don't know if this is the value you want to obtain). Anyway, the problem comes from the fact that, for instance, you wrote res and not Res with capital R. This is important because in prolog variables MUST be written with a capital letter as the first letter, read this.


问:
How to create streams from string in Node.Js?
I am using a library, ya-csv, that expects either a file or a stream as input, but I have a string.

How do I convert that string into a stream in Node?

答:
Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)

```<code>var s = new Readable({read(size) {
    this.push("your string here")
    this.push(null)
  }});
</code>```

you can after use s.pipe for exemple

Body:
Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)

var s = new Readable({read(size) {
    this.push("your string here")
    this.push(null)
  }});

you can after use s.pipe for exemple


问:
Detecting ctrl+f6 from javascript
I am working on an application where I need to detect whether user has pressed ctrl+f6 for certain navigation path. How to capture ctrl+f6 key press event in javascript/jquery?

答:
Hope this helps (source)

$(window).keydown(function(event) {
  if(event.ctrlKey && event.keyCode == 117 ) { //f6 keycode
    console.log("Hey! Ctrl + F6 event captured!");
    event.preventDefault();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hit Ctrl + F6 to see console log on this event.</code>```

Title: Detecting ctrl+f6 from javascript

Body:
Hope this helps (source)

$(window).keydown(function(event) {
  if(event.ctrlKey && event.keyCode == 117 ) { //f6 keycode
    console.log("Hey! Ctrl + F6 event captured!");
    event.preventDefault();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hit Ctrl + F6 to see console log on this event.


问:
Extjs : Selecting same value in multiselect combo not removing value
I am using ext5 multiselect combo. If we select a value from the dropdown, say 'Other' and click outside to cancel the dropdown.
Now the value 'Other' will be shown in combo.
Again click the dropdown and select tha same value 'Other', it should remove 'Other' from its values. But rather it adds same value once again.

My code is given below:

```<code>        xtype: 'combo',
        emptyText: 'Retail BI',
        name: 'chainRefId',
        store: Ext.create('shared.store.filter.ChainRefs'),
        displayField: 'name',
        multiSelect: true,
        valueField: 'chain_ref_id',
        listeners: {
            expand: function(){
                this.getStore().load();
            },
            change: function(combo, newVal) {
                if (!combo.eventsSuspended) {
                    var storeCombo = Ext.ComponentQuery.query('combo[name=storeId]')[0];
                    storeCombo.getStore().removeAll();
                    storeCombo.setValue(null);
                    var chainCombo = Ext.ComponentQuery.query('combo[name=chainId]')[0];
                    chainCombo.getStore().removeAll();
                    chainCombo.setValue(null);
                }
            }
        }
</code>```

Is there a solution for this?
Thanks in advance.

答:
I have faced the same problem. I have provided a workaround for this. This fix holds good for tagfield too.</p>

```<code>//on combo store load event
load: function () {
    // I am assuming reference to combo
    var rawVal = combo.getValue();
    // If combo is multiselct, getValue returns an array of selected items.
    // When combo is configured as remote, everytime it loads with new records and therefore removes the old reference.
    // Hence, do setValue to set the value again based on old reference.
    combo.setValue(rawVal);
    // Here you can see, based on old reference of selected items, the drop down will be highlighted.
}
</code>```

Body:
I am using ext5 multiselect combo. If we select a value from the dropdown, say 'Other' and click outside to cancel the dropdown.
Now the value 'Other' will be shown in combo.
Again click the dropdown and select tha same value 'Other', it should remove 'Other' from its values. But rather it adds same value once again.

My code is given below:

        xtype: 'combo',
        emptyText: 'Retail BI',
        name: 'chainRefId',
        store: Ext.create('shared.store.filter.ChainRefs'),
        displayField: 'name',
        multiSelect: true,
        valueField: 'chain_ref_id',
        listeners: {
            expand: function(){
                this.getStore().load();
            },
            change: function(combo, newVal) {
                if (!combo.eventsSuspended) {
                    var storeCombo = Ext.ComponentQuery.query('combo[name=storeId]')[0];
                    storeCombo.getStore().removeAll();
                    storeCombo.setValue(null);
                    var chainCombo = Ext.ComponentQuery.query('combo[name=chainId]')[0];
                    chainCombo.getStore().removeAll();
                    chainCombo.setValue(null);
                }
            }
        }

Is there a solution for this?
Thanks in advance.

Body:
I have faced the same problem. I have provided a workaround for this. This fix holds good for tagfield too.

//on combo store load event
load: function () {
    // I am assuming reference to combo
    var rawVal = combo.getValue();
    // If combo is multiselct, getValue returns an array of selected items.
    // When combo is configured as remote, everytime it loads with new records and therefore removes the old reference.
    // Hence, do setValue to set the value again based on old reference.
    combo.setValue(rawVal);
    // Here you can see, based on old reference of selected items, the drop down will be highlighted.
}


问:
Could not loade type "xx.xx" in global.asax

I'm frequently getting this error, I tried changing Codebehind to CodeFile in Global.asax file, but not luck. Any help will be heartly appreciated.

答: Simply go to project properties > build > Output Path = bin\ (value to output path to 'bin\'). Clean, rebuild and enjoy.</p>


问:
R: When using data.table how do I get columns of y when I do x[y]?
UPDATE: Old question ... it was resolved by data.table v1.5.3 in Feb 2011.

I am trying to use the data.table package, and really like the speedups I am getting, but I am stumped by this error when I do x[y, <expr>] where x and y are "data-tables" with the same key, and <expr> contains column names of both x and y:

```<code>require(data.table)
x <- data.table( foo = 1:5, a = 5:1 )
y <- data.table( foo = 1:5, boo = 10:14)
setkey(x, foo)
setkey(y, foo)
> x[y, foo*boo]
Error in eval(expr, envir, enclos) : object 'boo' not found
</code>```

UPDATE...
To clarify the functionality I am looking for in the above example: I need to do the equivalent of the following:

```<code>with(merge(x,y), foo*boo)
</code>```

However according to the below extract from the data.table FAQ, this should have worked:

Finally, although it appears as though
  x[y] does not return the columns in y,
  you can actually use the columns from
  y in the j expression. This is what we
  mean by join inherited scope. Why not
  just return the union of all the
  columns from x and y and then run
  expressions on that? It boils down to
  eciency of code and what is quicker
  to program. When you write
  x[y,fooboo], data.table automatically
  inspects the j expression to see which
  columns it uses. It will only subset,
  or group, those columns only. Memory
  is only created for the columns the j
  uses. Let's say foo is in x, and boo
  is in y (along with 20 other columns
  in y). Isn't x[y,fooboo] quicker to
  program and quicker to run than a
  merge step followed by another subset
  step ?

I am aware of this question that addressed a similar issue, but it did not seem to have been resolved satisfactorily. Anyone know what I am missing or misunderstanding? Thanks.

UPDATE: I asked on the data-table help mailing list and the package author (Matthew Dowle) replied that indeed the FAQ quoted above is wrong, so the syntax I am using will not work currently, i.e. I cannot refer to the y columns in the j (i.e. second) argument when I do x[y,...].

答:
I am not sure if I understand the problem well, and I also just started to read the docs of data.table library, but I think if you would like to get the columns of y and also do something to those by the columns of a, you might try something like:

```<code>> x[y,a*y]
     foo boo
[1,]   5  50
[2,]   8  44
[3,]   9  36
[4,]   8  26
[5,]   5  14
</code>```

Here, you get back the columns of y multiplied by the a column of x. If you want to get x's foo multiplied by y's boo, try:

```<code>> y[,x*boo]
     foo  a
[1,]  10 50
[2,]  22 44
[3,]  36 36
[4,]  52 26
[5,]  70 14
</code>```

After editing: thank you @Prasad Chalasani making the question clearer for me.

If simple merging is preferred, then the following should work. I made up a more complex data to see the actions deeper:

```<code>x <- data.table( foo = 1:5, a=20:24, zoo = 5:1 )
y <- data.table( foo = 1:5, b=30:34, boo = 10:14)
setkey(x, foo)
setkey(y, foo)
</code>```

So only an extra column was added to each data.table. Let us see merge and doing it with data.tables:

```<code>> system.time(merge(x,y))
   user  system elapsed
  0.027   0.000   0.023
> system.time(x[,list(y,x)])
   user  system elapsed
  0.003   0.000   0.006
</code>```

From which the latter looks a lot faster. The results are not identical though, but can be used in the same way (with an extra column of the latter run):

```<code>> merge(x,y)
     foo  a zoo  b boo
[1,]   1 20   5 30  10
[2,]   2 21   4 31  11
[3,]   3 22   3 32  12
[4,]   4 23   2 33  13
[5,]   5 24   1 34  14
> x[,list(x,y)]
     foo  a zoo foo.1  b boo
[1,]   1 20   5     1 30  10
[2,]   2 21   4     2 31  11
[3,]   3 22   3     3 32  12
[4,]   4 23   2     4 33  13
[5,]   5 24   1     5 34  14
</code>```

So to get xy we might use: xy <- x[,list(x,y)]. To compute a one-column data.table from xy$foo * xy$boo, the following might work:

```<code>> xy[,foo*boo]
[1] 10 22 36 52 70
</code>```

Well, the result is not a data.table but a vector instead.

Update (29/03/2012): thanks for @David for pointing my attention to the fact that merge.data.table were used in the above examples.

Body:
UPDATE: Old question ... it was resolved by data.table v1.5.3 in Feb 2011.

I am trying to use the data.table package, and really like the speedups I am getting, but I am stumped by this error when I do x[y, <expr>] where x and y are "data-tables" with the same key, and <expr> contains column names of both x and y:

require(data.table)
x <- data.table( foo = 1:5, a = 5:1 )
y <- data.table( foo = 1:5, boo = 10:14)
setkey(x, foo)
setkey(y, foo)
> x[y, foo*boo]
Error in eval(expr, envir, enclos) : object 'boo' not found

UPDATE...
To clarify the functionality I am looking for in the above example: I need to do the equivalent of the following:

with(merge(x,y), foo*boo)

However according to the below extract from the data.table FAQ, this should have worked:

Finally, although it appears as though
  x[y] does not return the columns in y,
  you can actually use the columns from
  y in the j expression. This is what we
  mean by join inherited scope. Why not
  just return the union of all the
  columns from x and y and then run
  expressions on that? It boils down to
  eciency of code and what is quicker
  to program. When you write
  x[y,fooboo], data.table automatically
  inspects the j expression to see which
  columns it uses. It will only subset,
  or group, those columns only. Memory
  is only created for the columns the j
  uses. Let's say foo is in x, and boo
  is in y (along with 20 other columns
  in y). Isn't x[y,fooboo] quicker to
  program and quicker to run than a
  merge step followed by another subset
  step ?

I am aware of this question that addressed a similar issue, but it did not seem to have been resolved satisfactorily. Anyone know what I am missing or misunderstanding? Thanks.

UPDATE: I asked on the data-table help mailing list and the package author (Matthew Dowle) replied that indeed the FAQ quoted above is wrong, so the syntax I am using will not work currently, i.e. I cannot refer to the y columns in the j (i.e. second) argument when I do x[y,...].

Body:
I am not sure if I understand the problem well, and I also just started to read the docs of data.table library, but I think if you would like to get the columns of y and also do something to those by the columns of a, you might try something like:

> x[y,a*y]
     foo boo
[1,]   5  50
[2,]   8  44
[3,]   9  36
[4,]   8  26
[5,]   5  14

Here, you get back the columns of y multiplied by the a column of x. If you want to get x's foo multiplied by y's boo, try:

> y[,x*boo]
     foo  a
[1,]  10 50
[2,]  22 44
[3,]  36 36
[4,]  52 26
[5,]  70 14

After editing: thank you @Prasad Chalasani making the question clearer for me.

If simple merging is preferred, then the following should work. I made up a more complex data to see the actions deeper:

x <- data.table( foo = 1:5, a=20:24, zoo = 5:1 )
y <- data.table( foo = 1:5, b=30:34, boo = 10:14)
setkey(x, foo)
setkey(y, foo)

So only an extra column was added to each data.table. Let us see merge and doing it with data.tables:

> system.time(merge(x,y))
   user  system elapsed
  0.027   0.000   0.023
> system.time(x[,list(y,x)])
   user  system elapsed
  0.003   0.000   0.006

From which the latter looks a lot faster. The results are not identical though, but can be used in the same way (with an extra column of the latter run):

> merge(x,y)
     foo  a zoo  b boo
[1,]   1 20   5 30  10
[2,]   2 21   4 31  11
[3,]   3 22   3 32  12
[4,]   4 23   2 33  13
[5,]   5 24   1 34  14
> x[,list(x,y)]
     foo  a zoo foo.1  b boo
[1,]   1 20   5     1 30  10
[2,]   2 21   4     2 31  11
[3,]   3 22   3     3 32  12
[4,]   4 23   2     4 33  13
[5,]   5 24   1     5 34  14

So to get xy we might use: xy <- x[,list(x,y)]. To compute a one-column data.table from xy$foo * xy$boo, the following might work:

> xy[,foo*boo]
[1] 10 22 36 52 70

Well, the result is not a data.table but a vector instead.

Update (29/03/2012): thanks for @David for pointing my attention to the fact that merge.data.table were used in the above examples.


问:
Sum outputs from atoi
I am trying to learn C++14 (with a "modern"/non-C style). I am trying to sum the digits in a string, for the digits that are equal to the next digit (or the first digit, if at the end of the string). I solved it in Python, but in C++14, I get unexpected output.

main.cpp:

```<code>#include <iostream>
#include <stdlib.h>

using namespace std;

using sum_t =  uint64_t; // int; // unsigned long long;

// sum_digits sums the digits in the given std::string and returns an integer of type sum_t
sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits) {
        total += atoi(new char(digit));
        cout << "sum this far: " << total << endl;
    }
    return total;
}

// return the last char
// returns ' ' if given an empty string
char last(std::string digits) {
    auto dl = digits.length();
    if (dl < 1) {
        return ' ';
    }
    return digits.at(dl - 1);
}

// sum_equal_digits returns a sum of the digits that are equal to the next one
sum_t sum_equal_digits(std::string digits) {
    auto equal_digits = ""s; // a list of equal digits, as std::string
    auto prev_digit = last(digits); // start with the last digit, since the digit list is supposed to be circular
    for (const auto &digit : digits) {
        if (digit == prev_digit) {
            equal_digits += digit;
        }
        prev_digit = digit;
    }
    return sum_digits(equal_digits);
}

void equal(sum_t a, sum_t b) {
    if (a == b) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
        exit(EXIT_FAILURE);
    }
}

int main() {
    equal(sum_equal_digits("1122"s), 3);
    equal(sum_equal_digits("1111"s), 4);
    equal(sum_equal_digits("1234"s), 0);
    equal(sum_equal_digits("91212129"s), 9);
    equal(sum_equal_digits("823936645345581272695677318513459491834641129844393742672553544439126314399846773234845535593355348931499496184839582118817689171948635864427852215325421433717458975771369522138766248225963242168658975326354785415252974294317138511141826226866364555761117178764543435899886711426319675443679829181257496966219435831621565519667989898725836639626681645821714861443141893427672384716732765884844772433374798185955741311116365899659833634237938878181367317218635539667357364295754744829595842962773524584225427969467467611641591834876769829719248136613147351298534885563144114336211961674392912181735773851634298227454157885241769156811787611897349965331474217223461176896643242975397227859696554492996937235423272549348349528559432214521551656971136859972232854126262349381254424597348874447736545722261957871275935756764184378994167427983811716675476257858556464755677478725146588747147857375293675711575747132471727933773512571368467386151966568598964631331428869762151853634362356935751298121849281442128796517663482391226174256395515166361514442624944181255952124524815268864131969151433888721213595267927325759562132732586252438456569556992685896517565257787464673718221817783929691626876446423134331749327322367571432532857235214364221471769481667118117729326429556357572421333798517168997863151927281418238491791975399357393494751913155219862399959646993428921878798119215675548847845477994836744929918954159722827194721564121532315459611433157384994543332773796862165243183378464731546787498174844781781139571984272235872866886275879944921329959736315296733981313643956576956851762149275521949177991988236529475373595217665112434727744235789852852765675189342753695377219374791548554786671473733124951946779531847479755363363288448281622183736545494372344785112312749694167483996738384351293899149136857728545977442763489799693492319549773328626918874718387697878235744154491677922317518952687439655962477734559232755624943644966227973617788182213621899579391324399386146423427262874437992579573858589183571854577861459758534348533553925167947139351819511798829977371215856637215221838924612644785498936263849489519896548811254628976642391428413984281758771868781714266261781359762798"), 1144);
    return 0;
}
</code>```

The last two lines of the output are:

```<code>sum this far: 18446744073627459815
NO
</code>```

But I was expecting:

```<code>sum this far: 1144
YES
</code>```

I compiled the program with:

```<code>g++ -O2 -std=c++14 -Wfatal-errors -pedantic -Wall main.cpp -o main
</code>```

I also tried using sum_t = int; and using sum_t = uint64_t;.

How can the program be corrected?

答:
atoi takes argument as null-terminated string.

So you should make something like:

```<code>sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    char tmp[2] = { 0 };
    for (const auto &digit : digits) {
    tmp[0] = digit;
    total += atoi(tmp);
        cout << "sum this far: " << total << endl;
    }
    return total;
}
</code>```

P.S.

new without delete leads to memory leaks (atoi(new char(digit))).

Title: Sum outputs from atoi

Body:
I am trying to learn C++14 (with a "modern"/non-C style). I am trying to sum the digits in a string, for the digits that are equal to the next digit (or the first digit, if at the end of the string). I solved it in Python, but in C++14, I get unexpected output.

main.cpp:

#include <iostream>
#include <stdlib.h>

using namespace std;

using sum_t =  uint64_t; // int; // unsigned long long;

// sum_digits sums the digits in the given std::string and returns an integer of type sum_t
sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits) {
        total += atoi(new char(digit));
        cout << "sum this far: " << total << endl;
    }
    return total;
}

// return the last char
// returns ' ' if given an empty string
char last(std::string digits) {
    auto dl = digits.length();
    if (dl < 1) {
        return ' ';
    }
    return digits.at(dl - 1);
}

// sum_equal_digits returns a sum of the digits that are equal to the next one
sum_t sum_equal_digits(std::string digits) {
    auto equal_digits = ""s; // a list of equal digits, as std::string
    auto prev_digit = last(digits); // start with the last digit, since the digit list is supposed to be circular
    for (const auto &digit : digits) {
        if (digit == prev_digit) {
            equal_digits += digit;
        }
        prev_digit = digit;
    }
    return sum_digits(equal_digits);
}

void equal(sum_t a, sum_t b) {
    if (a == b) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
        exit(EXIT_FAILURE);
    }
}

int main() {
    equal(sum_equal_digits("1122"s), 3);
    equal(sum_equal_digits("1111"s), 4);
    equal(sum_equal_digits("1234"s), 0);
    equal(sum_equal_digits("91212129"s), 9);
    equal(sum_equal_digits("823936645345581272695677318513459491834641129844393742672553544439126314399846773234845535593355348931499496184839582118817689171948635864427852215325421433717458975771369522138766248225963242168658975326354785415252974294317138511141826226866364555761117178764543435899886711426319675443679829181257496966219435831621565519667989898725836639626681645821714861443141893427672384716732765884844772433374798185955741311116365899659833634237938878181367317218635539667357364295754744829595842962773524584225427969467467611641591834876769829719248136613147351298534885563144114336211961674392912181735773851634298227454157885241769156811787611897349965331474217223461176896643242975397227859696554492996937235423272549348349528559432214521551656971136859972232854126262349381254424597348874447736545722261957871275935756764184378994167427983811716675476257858556464755677478725146588747147857375293675711575747132471727933773512571368467386151966568598964631331428869762151853634362356935751298121849281442128796517663482391226174256395515166361514442624944181255952124524815268864131969151433888721213595267927325759562132732586252438456569556992685896517565257787464673718221817783929691626876446423134331749327322367571432532857235214364221471769481667118117729326429556357572421333798517168997863151927281418238491791975399357393494751913155219862399959646993428921878798119215675548847845477994836744929918954159722827194721564121532315459611433157384994543332773796862165243183378464731546787498174844781781139571984272235872866886275879944921329959736315296733981313643956576956851762149275521949177991988236529475373595217665112434727744235789852852765675189342753695377219374791548554786671473733124951946779531847479755363363288448281622183736545494372344785112312749694167483996738384351293899149136857728545977442763489799693492319549773328626918874718387697878235744154491677922317518952687439655962477734559232755624943644966227973617788182213621899579391324399386146423427262874437992579573858589183571854577861459758534348533553925167947139351819511798829977371215856637215221838924612644785498936263849489519896548811254628976642391428413984281758771868781714266261781359762798"), 1144);
    return 0;
}

The last two lines of the output are:

sum this far: 18446744073627459815
NO

But I was expecting:

sum this far: 1144
YES

I compiled the program with:

g++ -O2 -std=c++14 -Wfatal-errors -pedantic -Wall main.cpp -o main

I also tried using sum_t = int; and using sum_t = uint64_t;.

How can the program be corrected?

Body:
atoi takes argument as null-terminated string.

So you should make something like:

sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    char tmp[2] = { 0 };
    for (const auto &digit : digits) {
    tmp[0] = digit;
    total += atoi(tmp);
        cout << "sum this far: " << total << endl;
    }
    return total;
}

P.S.

new without delete leads to memory leaks (atoi(new char(digit))).


问:
Zero should be accepted in the input type number but not Negative values
I am doing some validations for the input type.

```<code><input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">
</code>```

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

答:
You should use like this,</p>

```<code>    var number = document.getElementById('ctc');
    number.onkeydown = function(e) {
        if(!((e.keyCode > 95 && e.keyCode < 106)
          || (e.keyCode > 47 && e.keyCode < 58)
          || e.keyCode == 8)) {
            return false;

          }
    }
</code>```

Body:
I am doing some validations for the input type.

<input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

Body:
You should use like this,

    var number = document.getElementById('ctc');
    number.onkeydown = function(e) {
        if(!((e.keyCode > 95 && e.keyCode < 106)
          || (e.keyCode > 47 && e.keyCode < 58)
          || e.keyCode == 8)) {
            return false;

          }
    }


问:
Theme.AppCompat theme stacktrace. No solution found in my case
I try to show a dialog in my Activity and I get this error :
"You need to use a Theme.AppCompat theme"

There are lots of question/answers about this, but I don't get it in my situation:
Can someone help me ? I know it has something to do with the app theme, but I think this is ok in my situation. Can please someone take a look:

Error:

```<code>java.lang.RuntimeException:

    Unable to start activity ComponentInfo{chronicbrowser_maps_en/chronicbrowser.ChronicBrowser}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                      Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                         at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
                                                         at android.support.v7.app.AlertController.installContent(AlertController.java:225)
</code>```

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxxxxxxxxx.chronicbrowser"
    android:versionCode="${versionCode}"
    android:versionName="${versionName}"
    android:installLocation="auto">

    <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="22"/>
    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <supports-screens
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        />

    <application android:name=".ChronicaApplication" android:largeHeap="true" android:icon="${iconpath}" android:label="@string/app_name" android:theme="@style/AppTheme">>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${facebookid}" />
            />

        <activity android:name=".ChronicBrowser"  android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

styles.xml:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

My Activity is extending Activity

```<code>public class ChronicBrowser extends Activity {
</code>```

答:
Make the activity extend AppCompatActivity instead.

Most of the AppCompat stuff requires AppCompat classes, for an instance AppCompatActiviity or the fragment import from the support package i stead

Body:
I try to show a dialog in my Activity and I get this error :
"You need to use a Theme.AppCompat theme"

There are lots of question/answers about this, but I don't get it in my situation:
Can someone help me ? I know it has something to do with the app theme, but I think this is ok in my situation. Can please someone take a look:

Error:

java.lang.RuntimeException:

    Unable to start activity ComponentInfo{chronicbrowser_maps_en/chronicbrowser.ChronicBrowser}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                      Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                         at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
                                                         at android.support.v7.app.AlertController.installContent(AlertController.java:225)

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxxxxxxxxx.chronicbrowser"
    android:versionCode="${versionCode}"
    android:versionName="${versionName}"
    android:installLocation="auto">

    <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="22"/>
    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <supports-screens
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        />

    <application android:name=".ChronicaApplication" android:largeHeap="true" android:icon="${iconpath}" android:label="@string/app_name" android:theme="@style/AppTheme">>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${facebookid}" />
            />

        <activity android:name=".ChronicBrowser"  android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

styles.xml:

My Activity is extending Activity

public class ChronicBrowser extends Activity {


问:
How to color code a categorical variable in a mosaic
I am trying to display a relationship between my categorical variables.  I finally got my data into what I believe is a contingency table

```<code>subs_count
##                [,1] [,2] [,3] [,4]
## carbohydrate      2    0   11    2
## cellulose        18    0   60    0
## chitin            0    4    0    4
## hemicellulose    21    3   10    0
## monosaccharide    3    0    0    0
## pectin            8    0    2    2
## starch            1    0    4    0
</code>```

Where each column represents an organism.  So for my plot I put in

```<code>barplot(subs_count, ylim = c(0, 100), col = predicted.substrate,
  xlab = "organism", ylab = "ESTs per substrate")
</code>```

But my substrates are not consistently the same color.  What am I doing wrong?

答:
Your data seems to be a matrix with row names which is close to a contingency table in R but not exactly the same. Some plotting methods have additional support for tables.

More importantly, I couldn't run your code because it is unclear what predicted.substrate is. If it were a palette with 7 colors then it should do what you intend to do (or at least what I think you intend).

I replicated your data with:

```<code>subs_count <- structure(c(2, 18, 0, 21, 3, 8, 1, 0, 0,
  4, 3, 0, 0, 0, 11, 60, 0, 10, 0, 2, 4, 2, 0, 4, 0, 0, 2, 0),
  .Dim = c(7L, 4L), .Dimnames = list(c("carbohydrate", "cellulose",
  "chitin", "hemicellulose", "monosaccharide", "pectin", "starch"), NULL))
</code>```

And then transformed them into a table by:

```<code>subs_count <- as.table(subs_count)
names(dimnames(subs_count)) <- c("EST", "Organism")
</code>```

Then I used a qualitative palette from the colorspace package:

```<code>subs_pal <- colorspace::qualitative_hcl(7)
</code>```

And with your barplot seems to be reasonable:

```<code>barplot(subs_count, ylim = c(0,100), col = subs_pal,
  xlab = "organism", ylab = "ESTs per substrate", legend = TRUE)
</code>```

And a mosaic display (as indicated in your title) would be:

```<code>mosaicplot(t(subs_count), col = subs_pal, off = 5, las = 1, main = "")
</code>```

For visualizing patterns of dependence (or rather departures from independence) a mosaic plot shaded with residuals from the independence model might be even more useful.

```<code>mosaicplot(t(subs_count), shade = TRUE, off = 5, las = 1, main = "")
</code>```

More refined versions of shaded mosaic displays are available in package vcd (see doi:10.18637/jss.v017.i03).

Body:
I am trying to display a relationship between my categorical variables.  I finally got my data into what I believe is a contingency table

subs_count
##                [,1] [,2] [,3] [,4]
## carbohydrate      2    0   11    2
## cellulose        18    0   60    0
## chitin            0    4    0    4
## hemicellulose    21    3   10    0
## monosaccharide    3    0    0    0
## pectin            8    0    2    2
## starch            1    0    4    0

Where each column represents an organism.  So for my plot I put in

barplot(subs_count, ylim = c(0, 100), col = predicted.substrate,
  xlab = "organism", ylab = "ESTs per substrate")

But my substrates are not consistently the same color.  What am I doing wrong?

Body:
Your data seems to be a matrix with row names which is close to a contingency table in R but not exactly the same. Some plotting methods have additional support for tables.

More importantly, I couldn't run your code because it is unclear what predicted.substrate is. If it were a palette with 7 colors then it should do what you intend to do (or at least what I think you intend).

I replicated your data with:

subs_count <- structure(c(2, 18, 0, 21, 3, 8, 1, 0, 0,
  4, 3, 0, 0, 0, 11, 60, 0, 10, 0, 2, 4, 2, 0, 4, 0, 0, 2, 0),
  .Dim = c(7L, 4L), .Dimnames = list(c("carbohydrate", "cellulose",
  "chitin", "hemicellulose", "monosaccharide", "pectin", "starch"), NULL))

And then transformed them into a table by:

subs_count <- as.table(subs_count)
names(dimnames(subs_count)) <- c("EST", "Organism")

Then I used a qualitative palette from the colorspace package:

subs_pal <- colorspace::qualitative_hcl(7)

And with your barplot seems to be reasonable:

barplot(subs_count, ylim = c(0,100), col = subs_pal,
  xlab = "organism", ylab = "ESTs per substrate", legend = TRUE)

And a mosaic display (as indicated in your title) would be:

mosaicplot(t(subs_count), col = subs_pal, off = 5, las = 1, main = "")

For visualizing patterns of dependence (or rather departures from independence) a mosaic plot shaded with residuals from the independence model might be even more useful.

mosaicplot(t(subs_count), shade = TRUE, off = 5, las = 1, main = "")

More refined versions of shaded mosaic displays are available in package vcd (see doi:10.18637/jss.v017.i03).