问:
Incorrect class prediction using Weka
I am using the WEKA API weka-stable-3.8.1.

I have been trying to use J48 decision tree(C4.5 implementation of weka).
My data has around 22 features and a nominal class with 2 possible values : yes or no.

While evaluating with the following code :

```<code>Classifier model = (Classifier) weka.core.SerializationHelper.read(trainedModelDestination);
Evaluation evaluation = new Evaluation(trainingInstances);
evaluation.evaluateModel(model, testingInstances);
System.out.println("Number of correct predictions : "+evaluation.correct());
</code>```

I get all predictions correct.
But when I try these test cases individually using :

```<code>for(Instance i : testingInstances){
    double predictedClassLabel = model.classifyInstance(i);
    System.out.println("predictedClassLabel : "+predictedClassLabel);
}
</code>```

I always get the same output, i.e. 0.0.

Why is this happening ?

答:
If the provided snippet is indeed from your code, you seem to be always classifying the first test instance: "testingInstances.firstInstance()".

Rather, you may want to make a loop to classify each test instance.

```<code>for(Instance i : testingInstances){
    double predictedClassLabel = model.classifyInstance(i);
    System.out.println("predictedClassLabel : "+predictedClassLabel);
}
</code>```

Title: Incorrect class prediction using Weka

Body:
I am using the WEKA API weka-stable-3.8.1.

I have been trying to use J48 decision tree(C4.5 implementation of weka).
My data has around 22 features and a nominal class with 2 possible values : yes or no.

While evaluating with the following code :

Classifier model = (Classifier) weka.core.SerializationHelper.read(trainedModelDestination);
Evaluation evaluation = new Evaluation(trainingInstances);
evaluation.evaluateModel(model, testingInstances);
System.out.println("Number of correct predictions : "+evaluation.correct());

I get all predictions correct.
But when I try these test cases individually using :

for(Instance i : testingInstances){
    double predictedClassLabel = model.classifyInstance(i);
    System.out.println("predictedClassLabel : "+predictedClassLabel);
}

I always get the same output, i.e. 0.0.

Why is this happening ?

Body:
If the provided snippet is indeed from your code, you seem to be always classifying the first test instance: "testingInstances.firstInstance()".

Rather, you may want to make a loop to classify each test instance.

for(Instance i : testingInstances){
    double predictedClassLabel = model.classifyInstance(i);
    System.out.println("predictedClassLabel : "+predictedClassLabel);
}


来源: stackexchange

问:
Acumatica REST API New ID based on numbering sequence
I have a custom webservice endpoint based on the Customer object and can successfully POST (actually PUT in Acumatica) new records. However, I am required to pass a CustomerId with the request.

Can anyone point me in the right direction so that the CustomerId is assigned based on the numbering sequence configuration please?

答: Solved: I had a configuration issue on the Segmented Keys ScreenId=CS202000. The Customers Segmented Key was not flagged to Auto Number</p>

ContentLicense: CC BY-SA 3.0


问:
How to sort a string using custom compare function in C++?
I need to sort characters of a string and need to have lower letters appear first. For example, "acDbA" would become "abcAD" after sorting.

The code below is what I came up with:

```<code>bool compare(const char& c1, const char& c2) {
    if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
    if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
    return c1<c2;
}
void sortLetters(string &letters) {
    sort(letters.begin(), letters.end(), compare);
}
</code>```

However in Visual Studio I got:

```<code>'sort': no matching overloaded function found
'SortLetters::compare': non-standard syntax; use '&' to create a pointer to member
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided
</code>```

How should I create custom compare function for sorting a string, I couldn't seem to find examples online with string sorting.

答:
The above code does compile just fine when using a free function. I your case, you're using a object's method, which isn't simply callable.

You could pass a functor object or a lambda object too. By the way, since std::sort is a function template, it doesn't matter what the exact parameters of the comparator are. The only thing that matters that it is able to take the both values and return something that can be converted to bool.

Body:
I need to sort characters of a string and need to have lower letters appear first. For example, "acDbA" would become "abcAD" after sorting.

The code below is what I came up with:

bool compare(const char& c1, const char& c2) {
    if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
    if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
    return c1<c2;
}
void sortLetters(string &letters) {
    sort(letters.begin(), letters.end(), compare);
}

However in Visual Studio I got:

'sort': no matching overloaded function found
'SortLetters::compare': non-standard syntax; use '&' to create a pointer to member
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided

How should I create custom compare function for sorting a string, I couldn't seem to find examples online with string sorting.


问:
Add the same domain user account to two Azure AD Domains
I have access to two different Azure AD domains (a.com and b.com)  In both domains I have a local account (me@a.com and me@b.com).  What i'd really like to do use me@a.com to sign into both domains.

I know from reading https://learn.microsoft.com/en-us/azure/active-directory/active-directory-create-users-external that it is possible to do so but the caveat is:

```<code>You can select a user in another directory only if you're also a member of that directory.
</code>```

I can't see how this is performed however - does this mean I need a Microsoft Account in both domains (as these aren't domain specific) to be able to insert the user?

答:
You can use B2B for this scenario.

First add the user me@a.com to the tenant b.com: How do Azure Active Directory admins add B2B collaboration users?

Then assign a role to that user: Grant permissions to users from partner organizations in your Azure Active Directory tenant

Body:
I have access to two different Azure AD domains (a.com and b.com)  In both domains I have a local account (me@a.com and me@b.com).  What i'd really like to do use me@a.com to sign into both domains.

I know from reading https://learn.microsoft.com/en-us/azure/active-directory/active-directory-create-users-external that it is possible to do so but the caveat is:

You can select a user in another directory only if you're also a member of that directory.

I can't see how this is performed however - does this mean I need a Microsoft Account in both domains (as these aren't domain specific) to be able to insert the user?


问:
Mapping a simple array
I'm using fluent Nhibernate to map a simple class

And using Schema Generation to create this class on MySQL DB.

I can't use IList<> for my properties (I'm mapping cross-language domain classes)

So I have to use simple arrays..

I Want NHibernate to create a connection table between the two classes,

These are the domain classes:

```<code>    public class ClassOne
    {
        public virtual Guid Guid { get; set; }
        public virtual String Title { get; set; }
        public virtual ClassTwo[] Tags { get; set; }
    }

    public class ClassTwo
    {
        public virtual Guid Guid { get; set; }
        public virtual string Title { get; set; }
    }
</code>```

And this is the map:

```<code> public class ClassOneMap : ClassMap<ClassOneMap>
    {
        public ClassOneMap ()
        {
            Id(x => x.Guid).GeneratedBy.GuidComb();
            Map(x => x.Title);
            HasManyToMany(x => x.Tags)
                .Cascade.SaveUpdate());

        }
    }

    public class ClassTwoMap : ClassMap<ClassTwo>
    {
        public ClassTwoMap()
        {
            Id(x => x.Guid).GeneratedBy.GuidComb();
            Map(x => x.Title);
        }
    }
</code>```

The schema generates great! It has a ClassOne, ClassTwo and ClassTwoToClassOne Tables
But when I'm trying to persist an instance of ClassOne I have an Invalid Cast exception..
This is solved by changing the arrays to IList's but I can't really do that..

Can anyone tell me how to configure the Fluent mapping to use Arrays without changing the schema architecture?

Thanks A'lot!

答:
Ok, played around this and hope that solve the question.

So models are:

```<code> public class ClassOne : Entity
    {
        public virtual string Title { get; set; }

        public virtual ClassTwo[] Tags { get; set; }

     }

    public class ClassTwo : Entity
    {
        public virtual string Title { get; set; }
    }
</code>```

Base class contains the Id definition which is long in my case. Should not be a problem with Guids

Mapping class: We are using FluentNhibernate with some convention, also the idea is in HasManyToMany

```<code>public class ClassOneMappingOverride : IAutoMappingOverride<ClassOne>
    {
        public void Override(AutoMapping<ClassOne> mapping)
        {
            mapping.HasManyToMany(x => x.Tags).AsArray(x => x.Id).ParentKeyColumn("classOneId")
                .ChildKeyColumn("classTwoId")
                .Table("ClassOneLinkClassTwo")
                .Cascade.SaveUpdate();
        }
    }
</code>```

Please note that if you not indicate ParentKey, ChildKey and Table it will not create the link table.

The unit test which insert data looks like:

```<code> public class ClassOneDataPart : DataPartBase, IDataPart
{
    public void AddToDatabase()
    {
        var classOne = new ClassOne { Title = "classOne" };

        var classTwo1 = new ClassTwo { Title = "class21" };
        var classTwo2 = new ClassTwo { Title = "class22" };

        var tags = new[] { classTwo1, classTwo2 };

        classOne.Tags = tags;

        this.SaveData(classOne);
        this.SaveData(classTwo1);
        this.SaveData(classTwo2);
    }
}
</code>```

and the result into database is:

Regards,
Ion

ContentLicense: CC BY-SA 2.5

Title: Mapping a simple array

Body:
I'm using fluent Nhibernate to map a simple class

And using Schema Generation to create this class on MySQL DB.

I can't use IList<> for my properties (I'm mapping cross-language domain classes)

So I have to use simple arrays..

I Want NHibernate to create a connection table between the two classes,

These are the domain classes:

    public class ClassOne
    {
        public virtual Guid Guid { get; set; }
        public virtual String Title { get; set; }
        public virtual ClassTwo[] Tags { get; set; }
    }

    public class ClassTwo
    {
        public virtual Guid Guid { get; set; }
        public virtual string Title { get; set; }
    }

And this is the map:

 public class ClassOneMap : ClassMap<ClassOneMap>
    {
        public ClassOneMap ()
        {
            Id(x => x.Guid).GeneratedBy.GuidComb();
            Map(x => x.Title);
            HasManyToMany(x => x.Tags)
                .Cascade.SaveUpdate());

        }
    }

    public class ClassTwoMap : ClassMap<ClassTwo>
    {
        public ClassTwoMap()
        {
            Id(x => x.Guid).GeneratedBy.GuidComb();
            Map(x => x.Title);
        }
    }

The schema generates great! It has a ClassOne, ClassTwo and ClassTwoToClassOne Tables
But when I'm trying to persist an instance of ClassOne I have an Invalid Cast exception..
This is solved by changing the arrays to IList's but I can't really do that..

Can anyone tell me how to configure the Fluent mapping to use Arrays without changing the schema architecture?

Thanks A'lot!

Body:
Ok, played around this and hope that solve the question.

So models are:

 public class ClassOne : Entity
    {
        public virtual string Title { get; set; }

        public virtual ClassTwo[] Tags { get; set; }

     }

    public class ClassTwo : Entity
    {
        public virtual string Title { get; set; }
    }

Base class contains the Id definition which is long in my case. Should not be a problem with Guids

Mapping class: We are using FluentNhibernate with some convention, also the idea is in HasManyToMany

public class ClassOneMappingOverride : IAutoMappingOverride<ClassOne>
    {
        public void Override(AutoMapping<ClassOne> mapping)
        {
            mapping.HasManyToMany(x => x.Tags).AsArray(x => x.Id).ParentKeyColumn("classOneId")
                .ChildKeyColumn("classTwoId")
                .Table("ClassOneLinkClassTwo")
                .Cascade.SaveUpdate();
        }
    }

Please note that if you not indicate ParentKey, ChildKey and Table it will not create the link table.

The unit test which insert data looks like:

 public class ClassOneDataPart : DataPartBase, IDataPart
{
    public void AddToDatabase()
    {
        var classOne = new ClassOne { Title = "classOne" };

        var classTwo1 = new ClassTwo { Title = "class21" };
        var classTwo2 = new ClassTwo { Title = "class22" };

        var tags = new[] { classTwo1, classTwo2 };

        classOne.Tags = tags;

        this.SaveData(classOne);
        this.SaveData(classTwo1);
        this.SaveData(classTwo2);
    }
}

and the result into database is:

Regards,
Ion


问:
IntelliJ IDE shows Gson successfully converts strings to objects, but when I export to Jar it says "Expected BEGIN_OBJECT but was STRING
I have two text files: PatientForms.txt and MasterCodeList.txt.

Each file holds a JSON string on each line. I use the following method to read in the contents of the file and store it in a SortedMap for example.

Here is my ServiceCode.java code:

```<code>public class ServiceCode {

//class variables
@SerializedName("code")
private String code;

@SerializedName("description")
private String description;

@SerializedName("cost")
private double fullRetailPrice;

//constructor: default - creates an empty code that can be modified by user
public ServiceCode() {
    setCode("Empty");
    setDescription("Empty");
    setFullRetailPrice(0.0);
}

//constructor: non-default - creates a code with values passed to it for code, description, and fullRetailPrice
public ServiceCode(String code, String description, double fullRetailPrice) {
    setCode(code);
    setDescription(description);
    setFullRetailPrice(fullRetailPrice);
}

//setters
public void setCode(String code) { this.code = code; }
public void setDescription(String description) { this.description = description; }
public void setFullRetailPrice(double fullRetailPrice) { this.fullRetailPrice = fullRetailPrice; }

//getters
public String getCode() { return code; }
public String getDescription() { return description; }
public double getFullRetailPrice() { return fullRetailPrice; }
</code>```

Here is my method that reads in the file and places it in a map:

```<code>public class CodeFileHandler {

//static final File dir = new File(".");
static final Gson gson = new Gson();

public SortedMap<String, ServiceCode> loadCodeList() {
    SortedMap<String, ServiceCode> map = new TreeMap<>();
    List<String> codeStrings = new ArrayList<>();

    try {
        String loc = "MasterCodeList.txt";
        BufferedReader br = new BufferedReader(new FileReader(loc));

        for(String line; (line = br.readLine()) != null; ) {
            codeStrings.add(line);
            System.out.println(line);
        }
        // line is not visible here.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String s : codeStrings) {
        //used to show that string is a valid JSON format
        System.out.println(s);

        ServiceCode c = gson.fromJson(s, ServiceCode.class);
        map.put(c.getCode(), c);
    }

    return map;
}
</code>```

So, the problem is that this works without error in IntelliJ, but when I run it from my jar file I get an error. The string as output by the IDE when I run the program shows a valid format:

```<code>{"code":"D0120","description":"Periodic oral evaluation-established pt","cost":39.0}
</code>```

When I run it from the jar file I get this:

F:\BLCHC_MCv1\out\artifacts\BLCHC_MCv1_jar>java -jar BLCHC_MCv1.jar
  ï»¿{"code":"D0120","description":"Periodic oral evaluation-established pt","cost":39.0}
  Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
          at com.google.gson.Gson.fromJson(Gson.java:887)
          at com.google.gson.Gson.fromJson(Gson.java:852)
          at com.google.gson.Gson.fromJson(Gson.java:801)
          at com.google.gson.Gson.fromJson(Gson.java:773)
          at com.olsen.blchc.CodeFileHandler.loadCodeList(CodeFileHandler.java:39)

All sources I have looked at for the last couple of days point to the string being read in having a " in place of a { at the beginning. This is not the case.

Does anybody know why this would happen? It has no problem loading from a different file when I access PatientForms.txt, even when it is run from the jar.

UPDATE!

I changed my loadCodeList method to this:

```<code>  public void loadCodeList() {
    try {
        String loc = "MasterCodeList.txt";
        BufferedReader br = new BufferedReader(new FileReader(loc));

        for(String line; (line = br.readLine()) != null; ) {
            ServiceCode s = gson.fromJson(line, ServiceCode.class);
            codeMap.put(s.getCode(), s);
        }
        // line is not visible here.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

My code reads in each line and converts it to a ServiceCode object from the string in JSON format, using gson.fromJson(String, ServiceCode); where String is the JSON string read in from the file.

OUTPUT FROM IntelliJ IDE

IDE Output: No Errors

In the IDE I can run everything without fail and access the ServiceCode objects in my SortedMap.

JAR FILE OUTPUT
JAR FILE CONSOLE OUTPUT

Am I not packaging my jar file correctly? I included the Gson Jar inside of my Jar directory.

答: It took a lot of hours and I finally found a way to do it without errors! I was reading how to save load my map (saved in a JSON file with full formatting and everyting) and I came upon this: https://stackoverflow.com/a/32066515/8250178. Now it works when I run it from my .jar file as well as in my IDE. </p>

Body:
I have two text files: PatientForms.txt and MasterCodeList.txt.

Each file holds a JSON string on each line. I use the following method to read in the contents of the file and store it in a SortedMap for example.

Here is my ServiceCode.java code:

public class ServiceCode {

//class variables
@SerializedName("code")
private String code;

@SerializedName("description")
private String description;

@SerializedName("cost")
private double fullRetailPrice;

//constructor: default - creates an empty code that can be modified by user
public ServiceCode() {
    setCode("Empty");
    setDescription("Empty");
    setFullRetailPrice(0.0);
}

//constructor: non-default - creates a code with values passed to it for code, description, and fullRetailPrice
public ServiceCode(String code, String description, double fullRetailPrice) {
    setCode(code);
    setDescription(description);
    setFullRetailPrice(fullRetailPrice);
}

//setters
public void setCode(String code) { this.code = code; }
public void setDescription(String description) { this.description = description; }
public void setFullRetailPrice(double fullRetailPrice) { this.fullRetailPrice = fullRetailPrice; }

//getters
public String getCode() { return code; }
public String getDescription() { return description; }
public double getFullRetailPrice() { return fullRetailPrice; }

Here is my method that reads in the file and places it in a map:

public class CodeFileHandler {

//static final File dir = new File(".");
static final Gson gson = new Gson();

public SortedMap<String, ServiceCode> loadCodeList() {
    SortedMap<String, ServiceCode> map = new TreeMap<>();
    List<String> codeStrings = new ArrayList<>();

    try {
        String loc = "MasterCodeList.txt";
        BufferedReader br = new BufferedReader(new FileReader(loc));

        for(String line; (line = br.readLine()) != null; ) {
            codeStrings.add(line);
            System.out.println(line);
        }
        // line is not visible here.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String s : codeStrings) {
        //used to show that string is a valid JSON format
        System.out.println(s);

        ServiceCode c = gson.fromJson(s, ServiceCode.class);
        map.put(c.getCode(), c);
    }

    return map;
}

So, the problem is that this works without error in IntelliJ, but when I run it from my jar file I get an error. The string as output by the IDE when I run the program shows a valid format:

{"code":"D0120","description":"Periodic oral evaluation-established pt","cost":39.0}

When I run it from the jar file I get this:

F:\BLCHC_MCv1\out\artifacts\BLCHC_MCv1_jar>java -jar BLCHC_MCv1.jar
  ï»¿{"code":"D0120","description":"Periodic oral evaluation-established pt","cost":39.0}
  Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
          at com.google.gson.Gson.fromJson(Gson.java:887)
          at com.google.gson.Gson.fromJson(Gson.java:852)
          at com.google.gson.Gson.fromJson(Gson.java:801)
          at com.google.gson.Gson.fromJson(Gson.java:773)
          at com.olsen.blchc.CodeFileHandler.loadCodeList(CodeFileHandler.java:39)

All sources I have looked at for the last couple of days point to the string being read in having a " in place of a { at the beginning. This is not the case.

Does anybody know why this would happen? It has no problem loading from a different file when I access PatientForms.txt, even when it is run from the jar.

UPDATE!

I changed my loadCodeList method to this:

  public void loadCodeList() {
    try {
        String loc = "MasterCodeList.txt";
        BufferedReader br = new BufferedReader(new FileReader(loc));

        for(String line; (line = br.readLine()) != null; ) {
            ServiceCode s = gson.fromJson(line, ServiceCode.class);
            codeMap.put(s.getCode(), s);
        }
        // line is not visible here.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

My code reads in each line and converts it to a ServiceCode object from the string in JSON format, using gson.fromJson(String, ServiceCode); where String is the JSON string read in from the file.

OUTPUT FROM IntelliJ IDE

IDE Output: No Errors

In the IDE I can run everything without fail and access the ServiceCode objects in my SortedMap.

JAR FILE OUTPUT
JAR FILE CONSOLE OUTPUT

Am I not packaging my jar file correctly? I included the Gson Jar inside of my Jar directory.


问:
Ruby on Rails ajax pop up messages
I'm using bootstrap in my ruby on rails application. I sometimes show messages to users by using pop-up. I created following css and html lines:

```<code>.modal-dialog {
  display: none;
  position: fixed;
  z-index: 988888;
  padding-top: 20px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.7);
  margin: 0px!important;
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 600px;
  height: 550px;
  border-radius: 2px!important;
}
</code>```

I want to show popup-2

```<code><div class="modal-dialog">
    <div class="modal-content">
       <span class="model_box_close">×</span>
       Popup 1
    </div>
</div>
</code>```

I want to show popup-2

```<code><div class="modal-dialog">
    <div id="message-content" class="modal-content">
       <span class="model_box_close">×</span>
       Popup 2
    </div>
</div>
</code>```

What I want to do is create message content with ajax and append it to popup. How can I achieve that.

In ruby on rails we can execute ruby on rails ajax event like that:

```<code>$("<%= escape_javascript(render "popupcontent" ) %>").appendTo("#message-content");
</code>```

I want to use my message box by clicking hyperlinks with ajax.

Any suggestions,

Thanks.

答:
If I understand correctly, you have 2 routes that you can take, you can have the modal open and then fire off an Ajax request and update the content, as seen in this example from the bootstrap site

```<code>$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})
</code>```

or, if you want to click a link and send of an Ajax request and upon completion of the request show a modal you could use .modal('show') after updating the contents in your Ajax callback.

```<code>$("a[data-remote]").on("ajax:success", function() {
  $('#myModal').modal('show')
})
</code>```

Title: Ruby on Rails ajax pop up messages

Body:
I'm using bootstrap in my ruby on rails application. I sometimes show messages to users by using pop-up. I created following css and html lines:

.modal-dialog {
  display: none;
  position: fixed;
  z-index: 988888;
  padding-top: 20px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.7);
  margin: 0px!important;
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 600px;
  height: 550px;
  border-radius: 2px!important;
}

I want to show popup-2

       ×
       Popup 1

I want to show popup-2

       ×
       Popup 2

What I want to do is create message content with ajax and append it to popup. How can I achieve that.

In ruby on rails we can execute ruby on rails ajax event like that:

$("<%= escape_javascript(render "popupcontent" ) %>").appendTo("#message-content");

I want to use my message box by clicking hyperlinks with ajax.

Any suggestions,

Thanks.

Body:
If I understand correctly, you have 2 routes that you can take, you can have the modal open and then fire off an Ajax request and update the content, as seen in this example from the bootstrap site

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

or, if you want to click a link and send of an Ajax request and upon completion of the request show a modal you could use .modal('show') after updating the contents in your Ajax callback.

$("a[data-remote]").on("ajax:success", function() {
  $('#myModal').modal('show')
})


问:
How to reference these packages with Mono in order to compile
I'm trying to compile a C# script with Mono on Debian by command line, like this:

```<code>gmcs Main.cs
</code>```

However, I get the following error:

```<code>Main.cs(6,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(7,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(12,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(13,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(1526,31): error CS0246: The type or namespace name `Bitmap' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(6,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(7,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(12,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(13,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Compilation failed: 9 error(s), 1 warnings
</code>```

These the references at the top of Main.cs:

```<code>using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;
</code>```

I understand that I have to tell Mono which libraries to include by adding -pkg:whatever. My problem is that I do not know what these libraries are called, so I don't know what command is used to include them. Actually, I don't even know whether I have to download these libraries from somewhere or whether they come with Mono.

Note also that the last 2 are the iTextSharp library, for which I have itextsharp.dll just placed in the same directory as the script, since I don't know what else to do with it.

Please could someone explain to me how to get the file to compile!

答:
I got this error, and when I just needed to use System.Net.Http, I used:

```<code>$mcs /reference:System.Net.Http.dll Program.cs
</code>```

and it worked fine for me. When I tried to include the full path to System.Net.Http.dll, it didn't work. That is to say, heads up, mono keeps track of paths. Also, I have the latest version of mono.

Body:
I'm trying to compile a C# script with Mono on Debian by command line, like this:

gmcs Main.cs

However, I get the following error:

Main.cs(6,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(7,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(12,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(13,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(1526,31): error CS0246: The type or namespace name `Bitmap' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(6,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(7,14): error CS0234: The type or namespace name `Drawing' does not exist in the namespace `System'. Are you missing an assembly reference?
Main.cs(12,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Main.cs(13,7): error CS0246: The type or namespace name `iTextSharp' could not be found. Are you missing a using directive or an assembly reference?
Compilation failed: 9 error(s), 1 warnings

These the references at the top of Main.cs:

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;

I understand that I have to tell Mono which libraries to include by adding -pkg:whatever. My problem is that I do not know what these libraries are called, so I don't know what command is used to include them. Actually, I don't even know whether I have to download these libraries from somewhere or whether they come with Mono.

Note also that the last 2 are the iTextSharp library, for which I have itextsharp.dll just placed in the same directory as the script, since I don't know what else to do with it.

Please could someone explain to me how to get the file to compile!

Body:
I got this error, and when I just needed to use System.Net.Http, I used:

$mcs /reference:System.Net.Http.dll Program.cs

and it worked fine for me. When I tried to include the full path to System.Net.Http.dll, it didn't work. That is to say, heads up, mono keeps track of paths. Also, I have the latest version of mono.


问:
Codeigniter webhost client-side ajax error (deny 501)
Hi currently im watching my website showing the info if my IP is on whitelist in my webhost if it doesn't, then it wont get the news or load correctly php/JS.

The reason for this happen is the following but idk if some of you have had this before and if is an http request function missing or some protocol of server-sides (common one).

Error from server-side :

```<code>[client ip ... ] ModSecurity: Access denied with code 501 (phase 2).
 Match of "rx ^((?:(?:POS|GE)T|OPTIONS|HEAD))$" against "REQUEST_METHOD" required.
[file "/usr/local/apache/conf/modsec2.user.conf"]
[line "38"]
[id "1234123435"]
[msg "Method is not allowed by policy"]
[severity "CRITICAL"]
[tag "POLICY/METHOD_NOT_ALLOWED"]
[hostname "link"]
[uri "/showTopNews"]
[unique_id "WVukp1ka8AEAChYSbGQAAAAP"]
</code>```

答:
That's a mod_security2 error. More specifically, caused by rule 1234123435

Seems you're violating the REQUEST_METHOD regex. The accepted request types are POST, GET, OPTIONS, HEAD.

You have a few options:

1) fix the request type in your code (use a type that is allowed - open Developer Tools and watch the Newtork tab to see what you're sending)

2) update your rule to allow other types as well (not extremely dangerous if you know what you're adding)

3) You can remove the rule altogether by using this in your apache vhost .conf file (it won't work in .htaccess):

```<code><IfModule mod_security2.c>
SecRuleRemoveById 1234123435
</IfModule>
</code>```

I'd go with the first one.

The limitation to those 4 request types is fairly reasonable. But it does exclude some types. See HTTP/Methods for more details

Body:
Hi currently im watching my website showing the info if my IP is on whitelist in my webhost if it doesn't, then it wont get the news or load correctly php/JS.

The reason for this happen is the following but idk if some of you have had this before and if is an http request function missing or some protocol of server-sides (common one).

Error from server-side :

[client ip ... ] ModSecurity: Access denied with code 501 (phase 2).
 Match of "rx ^((?:(?:POS|GE)T|OPTIONS|HEAD))$" against "REQUEST_METHOD" required.
[file "/usr/local/apache/conf/modsec2.user.conf"]
[line "38"]
[id "1234123435"]
[msg "Method is not allowed by policy"]
[severity "CRITICAL"]
[tag "POLICY/METHOD_NOT_ALLOWED"]
[hostname "link"]
[uri "/showTopNews"]
[unique_id "WVukp1ka8AEAChYSbGQAAAAP"]

Body:
That's a mod_security2 error. More specifically, caused by rule 1234123435

Seems you're violating the REQUEST_METHOD regex. The accepted request types are POST, GET, OPTIONS, HEAD.

You have a few options:

1) fix the request type in your code (use a type that is allowed - open Developer Tools and watch the Newtork tab to see what you're sending)

2) update your rule to allow other types as well (not extremely dangerous if you know what you're adding)

3) You can remove the rule altogether by using this in your apache vhost .conf file (it won't work in .htaccess):

<IfModule mod_security2.c>
SecRuleRemoveById 1234123435
</IfModule>

I'd go with the first one.

The limitation to those 4 request types is fairly reasonable. But it does exclude some types. See HTTP/Methods for more details


问:
Does FileServer handler only serve what is inside the directory you specify?
For example, can a user put your url with linux commands to go up a folder/directory?

Let's say my server consist of:

```<code>bin/
    serverfile.go
    ...
public/
    index.html
    style.css
</code>```

"www.example.com/../bin/etc"

with serverfile.go consisting of:

```<code> pacakage main
 import "net/http"

 func main() {
     htttp.ListenAndServe(":8000", http.FileServer(http.Dir("public")))
 }
</code>```

答:
The http.FileServer inhibits a breakout of the root directory you specify.

In contrast you could build your own file server with http.ServeFile which would potentially be a dangerous undertaking.

See also Golang. What to use? http.ServeFile(..) or http.FileServer(..)?

Body:
For example, can a user put your url with linux commands to go up a folder/directory?

Let's say my server consist of:

bin/
    serverfile.go
    ...
public/
    index.html
    style.css

"www.example.com/../bin/etc"

with serverfile.go consisting of:

 pacakage main
 import "net/http"

 func main() {
     htttp.ListenAndServe(":8000", http.FileServer(http.Dir("public")))
 }


问:
How to get fastest streaming video using URL in android
I am a beginner in Android ,I am playing  video using URL in my android app but the video is not streaming that much  fast as compare to other app like showbox .l  had also used different url but the result is same  . Please help .</p>

答:
It depends on your internet speed and the server response you are using. ShowBox must be using it's own dedicated server, but maybe you are using a third party server that is not so fast.

Another cause in the speed difference can be the size and the quality of video. A video with low quality will take less time to load as compared to a video with high quality.

There is a solution that can work, you have to keep saving packets of data in cache and keep playing the video from cache. In this way App will take some time to start the video but after that it will be working with speed. It's just a small push to your streaming but mainly it depends on the server.


问:
Windows service to control access to a file in "All Users\Application Data"
Here is my situation:

I have an application that use a configuration file. The configuration file applies to all users of the system and all users can make change to the configuration.

I decided to put the configuration file in "All Users\Application Data" folder.

The problem is that the file is writable only by the user who created it.

Here is my temporary solution:

When creating the file, the application set its security options so that it can be written by all users of the system.

However, I think this is a hack and I think I have to create a service that will manage access to the file.

My application is written in C++ (MFC) and I'm not an expert with all the .Net stuff. So my first idea is to write a Windows C++ service with COM interfaces that will be called by the application.

My questions:

Is my idea a good idea or someone knows a better way to do?

Is there any new more up to date way to do a service in Windows than plain C++ and COM?

EDIT:

I know it's easy to set write permission to all users.

Back with Windows XP it was also easy to write files under "Program Files" and registry keys under "HKLM" with a limited user. But now, if you want an application to have the Vista logo certification, you must not write to these location (event if Virtual Stores can 'save' you).

Maybe my final solution will be the "make it writable to all users" one, but my question really is : "Is my solution good or do you have another easier solution that does not rely hacking a behavior fixed by Microsoft".

I'm really sorry to not have made it clear from the beginning.

Thanks a lot,

Nic

答:
Raymond Chen's articles are interesting and detailed, but usually overly dogmatic and impractical. Unless this is some mission-critical system with danger of tampering, I'd take his perspective with a huge pile of NaCl.

Are your users going to open and modify the file directly?  If not, just make the file global writable and enforce sane changes in your app's interface. For most classes of application it isn't worth the time and effort to protect a multiuser system from tampering.

Or, use a database.

OwnerDisplayName: Nicolas

LastEditorDisplayName: Nicolas

OwnerDisplayName: ajryan


问:
Computer Vision: Detecting Parabolas using the Hough Transform
Papers have been written describing how the Hough transform can be generalised to detect shapes like circles and parabolas.  I'm new to computer vision though and find these papers pretty tough going.  There is also code out there that does this detection but this is more than I want.  I was wondering if anyone could briefly describe in bullet points or pseudo-code really simply how Hough Transforms are used to detect parabolas in images.  That would be amazing.  Or if anyone knows any basic explanations online that I haven't come across than that would be good enough too :).

Thanks very much :).

答:
Interesting question. This looks like a great resource. I included a summary (loosely quoted). Also see the source from Mathworks at the bottom of this answer - Matlab has houghlines and houghpeaks functions which will be useful for you. Hope it helps.

Run edge detection algorithm, such as the Canny edge detector, on subject image

Input edge/boundary points into Hough Transform (line detecting)

Generate a curve in polar space (radius, angle) for each point
  in Cartesian space (also called
  accumulator array)

Extract local maxima from the accumulator array, for example using a
  relative threshold

In other words, we take only those local maxima in the accumulator
  array whose values are equal to or
  greater than some fixed percentage of
  the global maximum value.

De-Houghing into Cartesian space yields a set of line descriptions of the image subject

cs.jhu.edu:
http://www.cs.jhu.edu/~misha/Fall04/GHT1.pdf

Code from Mathworks: http://www.mathworks.com/help/toolbox/images/ref/hough.html


问:
/usr/bin/sudo must be owned by uid 0 and have the setuid bit set
I have a usr/bin/sudo problem on my Mac (El Capitan).

It started when I ran into a permissions problem installing from NPM and followed their directions here:
https://docs.npmjs.com/getting-started/fixing-npm-permissions

I found out that was a really stupid thing I did here:

/usr/bin/sudo must be owned by uid 0 and have the setuid bit set version .ubantu14.04 LTS

I open up my terminal and get:

malloc: * error for object 0x7fff38418900: pointer being freed was not     allocated * set a breakpoint in malloc_error_break to debug [Process was     terminated by signal 6]

This essentially kills my terminal and therefore my work.

I Command-S while rebooting to start in single user mode.  I run

```<code>fsck -fy
</code>```

and my hard drive appears to be OK. I then got to:
http://osxdaily.com/2015/11/04/verify-repair-permissions-mac-os-x/ which tells me to fix the permissions as I have El Capitan and therefore cannot use Disk Utility for this.  I run:

```<code>sudo /usr/linexec/repair_packages --verify -standard-pkgs /
</code>```

The terminal spits back:

```<code>sudo: effective uid is not 0, is sudo installed setuid root?
</code>```

I dig deeper:
https://apple.stackexchange.com/questions/194854/sudo-effective-uid-is-not-0-is-sudo-installed-setuid-root/194856

```<code>$ type sudo
sudo is hashed (/usr/bin/sudo)

$ ls -@@eil /usr/bin/sudo
-r-s--x--x 1 501 wheel 168448 Dec 2 2015 /usr/bin/sudo

$ md5 /usr/bin/sudo
MD5 (/usr/bin/sudo) = 7d986f7707c0f11264554cd4354ef80d
</code>```

I then

```<code>$ /usr/bin/sudo mv /usr/local/bin/sudo /usr/local/bin/sudo-strange
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
</code>```

I find a truly depressing answer here: https://askubuntu.com/questions/452860/usr-bin-sudo-must-be-owned-by-uid-0-and-have-the-setuid-bit-set .   But I'm an optimist so I ignore the first answer and do what the second answer tells me to:

```<code>$ chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
chown: root: illegal group name
</code>```

which tells root doesn't exist.  But when I

```<code>$ whoami
root
</code>```

So I'm at a dead end and I really don't want to take two days reinstalling EVERYTHING.

Any suggestions?

答:
I faced the same issue with macOS sierra.
After trying few other things and failing each time, I noticed that I had a pending update for my OS, installed the update and everything went back to normal.</p>

Body:
I have a usr/bin/sudo problem on my Mac (El Capitan).

It started when I ran into a permissions problem installing from NPM and followed their directions here:
https://docs.npmjs.com/getting-started/fixing-npm-permissions

I found out that was a really stupid thing I did here:

/usr/bin/sudo must be owned by uid 0 and have the setuid bit set version .ubantu14.04 LTS

I open up my terminal and get:

malloc: * error for object 0x7fff38418900: pointer being freed was not     allocated * set a breakpoint in malloc_error_break to debug [Process was     terminated by signal 6]

This essentially kills my terminal and therefore my work.

I Command-S while rebooting to start in single user mode.  I run

fsck -fy

and my hard drive appears to be OK. I then got to:
http://osxdaily.com/2015/11/04/verify-repair-permissions-mac-os-x/ which tells me to fix the permissions as I have El Capitan and therefore cannot use Disk Utility for this.  I run:

sudo /usr/linexec/repair_packages --verify -standard-pkgs /

The terminal spits back:

sudo: effective uid is not 0, is sudo installed setuid root?

I dig deeper:
https://apple.stackexchange.com/questions/194854/sudo-effective-uid-is-not-0-is-sudo-installed-setuid-root/194856

$ type sudo
sudo is hashed (/usr/bin/sudo)

$ ls -@@eil /usr/bin/sudo
-r-s--x--x 1 501 wheel 168448 Dec 2 2015 /usr/bin/sudo

$ md5 /usr/bin/sudo
MD5 (/usr/bin/sudo) = 7d986f7707c0f11264554cd4354ef80d

I then

$ /usr/bin/sudo mv /usr/local/bin/sudo /usr/local/bin/sudo-strange
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set

I find a truly depressing answer here: https://askubuntu.com/questions/452860/usr-bin-sudo-must-be-owned-by-uid-0-and-have-the-setuid-bit-set .   But I'm an optimist so I ignore the first answer and do what the second answer tells me to:

$ chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
chown: root: illegal group name

which tells root doesn't exist.  But when I

$ whoami
root

So I'm at a dead end and I really don't want to take two days reinstalling EVERYTHING.

Any suggestions?


问:
Java 8 method reference does not start thread?
Why does a method reference not start a thread in this example?

```<code>package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}
</code>```

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

答:
Because those are different things - passing es::calculate is the same as passing:

```<code>new Runnable() {
     @Override
     public void run() {
         es.calculate();
     }
}
</code>```

Which, obviously, is not the same as:

```<code>new Runnable() {
     @Override
     public void run() {
         es.calculate().run();
     }
}
</code>```

Body:
Why does a method reference not start a thread in this example?

package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

Body:
Because those are different things - passing es::calculate is the same as passing:

new Runnable() {
     @Override
     public void run() {
         es.calculate();
     }
}

Which, obviously, is not the same as:

new Runnable() {
     @Override
     public void run() {
         es.calculate().run();
     }
}


问:
Extending User Profile
Please i need help .I have a problem in extending userprofile.At first everything seems to be working good until now .Please  i need help in resolving this  bellow is my code .
    Model.py

```<code>class UserProfile(models.Model):
     user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile")
     date =models.DateField(blank=False,null= True)
     bio = models.TextField(max_length=500,blank=False)
     picture = models.ImageField(upload_to="profile_image",null=True,blank=True)
     company = models.CharField(max_length=500,null=True)
     def __str__(self):
         return self.user.username

     @receiver(post_save,sender=User)
     def create_profile(sender,instance,created,**kwargs):
         if created:
             UserProfile.objects.create(user=instance)
     @receiver(post_save,sender=User)
     def save_user_profile(sender,instance,**kwargs):
         instance.UserProfile.save()
</code>```

views.py

```<code>def update_profile(request):
    if request.method == 'POST':

        profile_form = ProfileForm(request.POST,request.FILES,instance=request.user.userprofile)
        if  profile_form.is_valid():
            profile_form.save()
            messages.success(request,'Your Profile has been Updated')
            return redirect('success:profile_account')
        else:
            messages.error(request,'fill out the fields correctly')
    else:

         profile_form = ProfileForm(instance=request.user.userprofile)
    return render(request,"success/user_account/edit_profile.html",{'profile_form':profile_form})
</code>```

html.form

```<code> <form action='{{ action_url }}' method="post" enctype="multipart/form-data">
    {% csrf_token %}

       {{ profile_form.bio}}{{profile_form.bio.error}}

     {{ profile_form.picture}}{{profile_form.picture.error}}

        <div class="pc"><label>Company Name:</label>{{ profile_form.company}}{{profile_form.company.error}}

    {{ profile_form.date}}{{profile_form.date.error}}
    <button type="submit">Save changes</button>
</code>```

Error I get

Forbidden (403)

CSRF verification failed. Request aborted. Help

Reason given for failure:

```<code>CSRF token missing or incorrect.
</code>```

In general, this can occur when there is a genuine Cross Site Request
  Forgery, or when Django's CSRF mechanism has not been used correctly.
  For POST forms, you need to ensure:

```<code>Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as
</code>```

well as those that accept the POST data.
      The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to
  reload the page with the form, because the token is rotated after a
  login.

You're seeing the help section of this page because you have DEBUG =
  True in your Django settings file. Change that to False, and only the
  initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

答:
this is the best way to extend user model profile

```<code>from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import BaseUserManager

class AccountManager(BaseUserManager):
    def create_user(self, username, password=None, **kwargs):
        if not username:
            raise ValueError('Users must have a valid email username.')

        if not kwargs.get('email'):
            raise ValueError('Users must have a valid email.')

        email = kwargs.get('email')
        account = self.model(
            username=username, email=self.normalize_email(email)
        )

        account.set_password(password)
        account.save()

        return account

    def create_superuser(self, username, password, **kwargs):
        account = self.create_user(username, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

class Account(AbstractBaseUser):
    username = models.CharField(max_length=40, unique=True)
    email = models.EmailField(unique=True)

    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.first_name
</code>```

modify this example and then in forms.py just import you model user profile

Title: Extending User Profile

Body:
Please i need help .I have a problem in extending userprofile.At first everything seems to be working good until now .Please  i need help in resolving this  bellow is my code .
    Model.py

class UserProfile(models.Model):
     user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile")
     date =models.DateField(blank=False,null= True)
     bio = models.TextField(max_length=500,blank=False)
     picture = models.ImageField(upload_to="profile_image",null=True,blank=True)
     company = models.CharField(max_length=500,null=True)
     def __str__(self):
         return self.user.username

     @receiver(post_save,sender=User)
     def create_profile(sender,instance,created,**kwargs):
         if created:
             UserProfile.objects.create(user=instance)
     @receiver(post_save,sender=User)
     def save_user_profile(sender,instance,**kwargs):
         instance.UserProfile.save()

views.py

def update_profile(request):
    if request.method == 'POST':

        profile_form = ProfileForm(request.POST,request.FILES,instance=request.user.userprofile)
        if  profile_form.is_valid():
            profile_form.save()
            messages.success(request,'Your Profile has been Updated')
            return redirect('success:profile_account')
        else:
            messages.error(request,'fill out the fields correctly')
    else:

         profile_form = ProfileForm(instance=request.user.userprofile)
    return render(request,"success/user_account/edit_profile.html",{'profile_form':profile_form})

html.form

 <form action='{{ action_url }}' method="post" enctype="multipart/form-data">
    {% csrf_token %}

       {{ profile_form.bio}}{{profile_form.bio.error}}

     {{ profile_form.picture}}{{profile_form.picture.error}}

Company Name:{{ profile_form.company}}{{profile_form.company.error}}

    {{ profile_form.date}}{{profile_form.date.error}}
    <button type="submit">Save changes</button>

Error I get

Forbidden (403)

CSRF verification failed. Request aborted. Help

Reason given for failure:

CSRF token missing or incorrect.

In general, this can occur when there is a genuine Cross Site Request
  Forgery, or when Django's CSRF mechanism has not been used correctly.
  For POST forms, you need to ensure:

Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as

well as those that accept the POST data.
      The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to
  reload the page with the form, because the token is rotated after a
  login.

You're seeing the help section of this page because you have DEBUG =
  True in your Django settings file. Change that to False, and only the
  initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

Body:
this is the best way to extend user model profile

from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import BaseUserManager

class AccountManager(BaseUserManager):
    def create_user(self, username, password=None, **kwargs):
        if not username:
            raise ValueError('Users must have a valid email username.')

        if not kwargs.get('email'):
            raise ValueError('Users must have a valid email.')

        email = kwargs.get('email')
        account = self.model(
            username=username, email=self.normalize_email(email)
        )

        account.set_password(password)
        account.save()

        return account

    def create_superuser(self, username, password, **kwargs):
        account = self.create_user(username, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

class Account(AbstractBaseUser):
    username = models.CharField(max_length=40, unique=True)
    email = models.EmailField(unique=True)

    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.first_name

modify this example and then in forms.py just import you model user profile


问:
Limiting the times that .split() splits, rather than truncating the resulting array
Really, pretty much what the title says.

Say you have this string:

```<code>var theString = "a=b=c=d";
</code>```

Now, when you run theString.split("=") the result is ["a", "b", "c", "d"] as expected. And, of course, when you run theString.split("=", 2) you get ["a", "b"], which after reading the MDN page for String#split() makes sense to me.

However, the behavior I'm looking for is more like Java's String#split(): Instead of building the array normally, then returning the first n elements, it builds an array of the first n-1 matches, then adds all the remaining characters as the last element of the array. See the relevant docs for a better description.

How can I get this effect in Javascript?

I'm looking for the answer with the best performance that works like the Java implementation, though the actual way it works can be different.

I'd post my attempt, but I don't know how to go about writing this at all.

答:
Are you looking for something closer to PHP's explode?

Here's a method I've devised:

```<code>String.prototype.explode = function(sep, n) {
  var arr = this.split(sep, n)
  if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length);
  return arr;
}
</code>```

This method splits the string like normal, determines if we've hit our limit, and uses substring to append the text beyond our last split (we can directly access the offset of the first character beyond the last split by getting the length of a join used on the array with any single character as the separator)

This method is used just like split:

```<code>str = 'my/uri/needs/to/be/split';
splitResult = str.split('/', 4);
explodeResult = str.explode('/', 4);
console.log(splitResult);
console.log(explodeResult);

// The following will be written to the console:
// splitResult:   ["my", "uri", "needs", "to"]
// explodeResult: ["my", "uri", "needs", "to/be/split"]
</code>```

And of course, this can be spun as a function too:

```<code>function explode(str, sep, n) {
  var arr = str.split(sep, n)
  if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length);
  return arr;
}

str = 'my/uri/needs/to/be/split';
explodeResult = explode(str, '/', 4);
</code>```

Body:
Really, pretty much what the title says.

Say you have this string:

var theString = "a=b=c=d";

Now, when you run theString.split("=") the result is ["a", "b", "c", "d"] as expected. And, of course, when you run theString.split("=", 2) you get ["a", "b"], which after reading the MDN page for String#split() makes sense to me.

However, the behavior I'm looking for is more like Java's String#split(): Instead of building the array normally, then returning the first n elements, it builds an array of the first n-1 matches, then adds all the remaining characters as the last element of the array. See the relevant docs for a better description.

How can I get this effect in Javascript?

I'm looking for the answer with the best performance that works like the Java implementation, though the actual way it works can be different.

I'd post my attempt, but I don't know how to go about writing this at all.

Body:
Are you looking for something closer to PHP's explode?

Here's a method I've devised:

String.prototype.explode = function(sep, n) {
  var arr = this.split(sep, n)
  if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length);
  return arr;
}

This method splits the string like normal, determines if we've hit our limit, and uses substring to append the text beyond our last split (we can directly access the offset of the first character beyond the last split by getting the length of a join used on the array with any single character as the separator)

This method is used just like split:

str = 'my/uri/needs/to/be/split';
splitResult = str.split('/', 4);
explodeResult = str.explode('/', 4);
console.log(splitResult);
console.log(explodeResult);

// The following will be written to the console:
// splitResult:   ["my", "uri", "needs", "to"]
// explodeResult: ["my", "uri", "needs", "to/be/split"]

And of course, this can be spun as a function too:

function explode(str, sep, n) {
  var arr = str.split(sep, n)
  if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length);
  return arr;
}

str = 'my/uri/needs/to/be/split';
explodeResult = explode(str, '/', 4);


问:
Wordpress add different menu group in home page and inner page
I want to display different menus on home page and inner page,
My site home page link is: http://www.cognitiveasia.com/
and inner site link like : http://www.cognitiveasia.com/brand-advocacy/what-is-lorem-ipsum/

How i can manage by custom codding or plugin?

答:
first, in your functions.php define 2 menu positions:

```<code>function my_menus() {
    register_nav_menu('home-menu-location','Home Location');
    register_nav_menu('inner-menu-location','Inner Page Location');

}
add_action( 'init', 'my_menus' );
</code>```

then, in your header.php use:

```<code><nav>
<?php
if (is_home()) {
    wp_nav_menu( array( 'theme_location' => 'home-menu-location' ) );
} else {
    wp_nav_menu( array( 'theme_location' => 'inner-menu-location' ) );
}
?>
</nav>
</code>```

after this, you will have two menu positions in wordpress backend and you can add a diferent menu for each position

Body:
first, in your functions.php define 2 menu positions:

function my_menus() {
    register_nav_menu('home-menu-location','Home Location');
    register_nav_menu('inner-menu-location','Inner Page Location');

}
add_action( 'init', 'my_menus' );

then, in your header.php use:

<nav>
<?php
if (is_home()) {
    wp_nav_menu( array( 'theme_location' => 'home-menu-location' ) );
} else {
    wp_nav_menu( array( 'theme_location' => 'inner-menu-location' ) );
}
?>
</nav>

after this, you will have two menu positions in wordpress backend and you can add a diferent menu for each position


问:
Impossible to have two sagas that handle the same message type
I have 2 different sagas (I mean saga types) that handle the same message.

```<code>     public class AttachMessageToBugSaga : TpSaga<AttachMessageToBugSagaData>, IAmStartedByMessages<MessageIsNotAttached>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }
        public void Handle(MessageIsNotAttachedToBug message)
        {
            Send(new AttachMessageToGeneralCommand { MessageId = 66, GeneralId = 13 });
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuf fhere
        }
    }

    public class AttachMessageToBugSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

    public class AttachMessageToRequestSaga : TpSaga<AttachMessageToRequestSagaData>, IAmStartedByMessages<MessageIsNotAttachedToRequest>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }

        public void Handle(MessageIsNotAttachedMessageToRequest message)
        {
            //do some stuff here
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuff here
        }
    }

    public class AttachMessageToRequestSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }
</code>```

When I run the sample I get an exception :

System.InvalidCastException: Unable to cast object of type 'MyCustomPlugin.AttachMessageToGeneralSagaData' to type 'MyCustomPlugin.AttachMessageToRequestSagaData'.

I understand why it happens, but I still need some workaround. I tried to implement my own IFindSagas class :

```<code>public class SagaFinder : IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToRequest>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToBug>
{
    AttachMessageToGeneralSagaData IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToGeneralSagaData>();
    }

    AttachMessageToRequestSagaData IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToRequestSagaData>();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToRequest message)
    {
        return new AttachMessageToRequestSagaData();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToBug message)
    {
        return new AttachMessageToRequestSagaData();
    }
}
</code>```

But I do not get into my finders for "MessageAttachedToGeneralMessage".
Please tell me if there is some other workaround, or how to make this example working.

答:
I'm not sure that having more than one Saga within the same process boundary works very well - at least, I've had problems with it too.  It's probably better (in general) to have Sagas separated into two different processes anyway, because otherwise it would cause a lot of locking and potentially deadlocks on your saga storage.

Is your message that is handled by 2 Sagas Sent or Published?  If it's published (or can be made to), it would be easy to separate the Sagas into two separate assemblies.  Just be sure to manually call Bus.Subscribe() for the message type in each Saga, since Sagas don't auto-subscribe to messages listed in the app.config.

If your message is Sent, and there's nothing you can do to change it, then create a central handler for your existing message type that either Publishes a second message type to go to both Sagas, or Sends two separate messages to each saga.

Body:
I have 2 different sagas (I mean saga types) that handle the same message.

     public class AttachMessageToBugSaga : TpSaga<AttachMessageToBugSagaData>, IAmStartedByMessages<MessageIsNotAttached>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }
        public void Handle(MessageIsNotAttachedToBug message)
        {
            Send(new AttachMessageToGeneralCommand { MessageId = 66, GeneralId = 13 });
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuf fhere
        }
    }

    public class AttachMessageToBugSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

    public class AttachMessageToRequestSaga : TpSaga<AttachMessageToRequestSagaData>, IAmStartedByMessages<MessageIsNotAttachedToRequest>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }

        public void Handle(MessageIsNotAttachedMessageToRequest message)
        {
            //do some stuff here
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuff here
        }
    }

    public class AttachMessageToRequestSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

When I run the sample I get an exception :

System.InvalidCastException: Unable to cast object of type 'MyCustomPlugin.AttachMessageToGeneralSagaData' to type 'MyCustomPlugin.AttachMessageToRequestSagaData'.

I understand why it happens, but I still need some workaround. I tried to implement my own IFindSagas class :

public class SagaFinder : IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToRequest>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToBug>
{
    AttachMessageToGeneralSagaData IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToGeneralSagaData>();
    }

    AttachMessageToRequestSagaData IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToRequestSagaData>();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToRequest message)
    {
        return new AttachMessageToRequestSagaData();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToBug message)
    {
        return new AttachMessageToRequestSagaData();
    }
}

But I do not get into my finders for "MessageAttachedToGeneralMessage".
Please tell me if there is some other workaround, or how to make this example working.


问:
EmmetInstall from a list - VI/Neovim
I'm setting up a [neo]vim dotfile and to do that I have the next list

```<code>let filetypesWithTag = ['html', 'htmldjango', 'javascript.jsx', ...]
</code>```

because I use it in many places, with the same list I'm trying to enable Emmet

```<code>au FileType join(filetypesWithTag, ',') EmmetInstall
</code>```

but it isn't working so here is the question, how can I achieve this?

Here is the complete file so you can check it out.

答:
Since you appear to already be using vim-plug, you can achieve what you want in this way:

```<code>" On-demand loading
Plug 'mattn/emmet-vim', { 'for': ['html', 'htmldjango', 'javascript.jsx', ...] }
</code>```

vim-plug enables lazy loading of plugins by filetype. To set filetypes correctly for arbitrary extensions, you can leverage an auto command. Take a look at this example for the many variations of Markdown file extensions:

```<code>autocmd BufNewFile,BufRead *.{md,mdwn,mkd,mkdn,mark*} setlocal ft=markdown
</code>```

Title: EmmetInstall from a list - VI/Neovim

Body:
I'm setting up a [neo]vim dotfile and to do that I have the next list

let filetypesWithTag = ['html', 'htmldjango', 'javascript.jsx', ...]

because I use it in many places, with the same list I'm trying to enable Emmet

au FileType join(filetypesWithTag, ',') EmmetInstall

but it isn't working so here is the question, how can I achieve this?

Here is the complete file so you can check it out.

Body:
Since you appear to already be using vim-plug, you can achieve what you want in this way:

" On-demand loading
Plug 'mattn/emmet-vim', { 'for': ['html', 'htmldjango', 'javascript.jsx', ...] }

vim-plug enables lazy loading of plugins by filetype. To set filetypes correctly for arbitrary extensions, you can leverage an auto command. Take a look at this example for the many variations of Markdown file extensions:

autocmd BufNewFile,BufRead *.{md,mdwn,mkd,mkdn,mark*} setlocal ft=markdown


问:
RxJS Observable: Emit when specific part of the object changes
I have a complex object having child objects and arrays and so on.

I can easily create a Subject/BehaviourSubject or Observable from this object so that I can "next" (emit) the new state to the subscribers.

[ex: let appEnv$ = new Rx.BehaviorSubject<IWebSocketAppEnv>(appEnv);]

However I don't want all my subscribers to be notified every time the object changes. For instance for one of my subscriber, I only want to be notified when a change occurs on an elements of an array of that object.

Actually what I want is something redux is already doing. In redux, I can subscribe to the store but selecting only a child element.

I want to implement the same infrastructure for my back-end websocket server application.

How can I achieve that with RxJS?

答:
we can resolve it by partial subscription to the source observable (complex object in your case) based on a condition.

Rxjs takeWhile helps to do that.
Subscription can be made only when a certain condition is satisfied and then process the emitted output.

https://www.learnrxjs.io/operators/filtering/takewhile.html


问:
Django python iteration through a query set error
The code that is giving me the problem

```<code>   pk = request.POST['pk']
    medrec = MedicalRec.objects.get(pk=pk)
    med = Medicine.objects.filter(medicalrec=medrec)
    for f in med:
              print("med check")
              print(f.pk)
              print(f.stockpk)
     for ed in med:
                print("printing dtock")
                print(ed.stockpk)
                print("end of doc")
                a= pks()
                a.pk = ed.stockpk
                a.count = request.POST[str(ed.pk)]
                ls.append(a)
     for l in ls:
           print(l.pk)
           print(l.count)
     for n in ls:
           s= Stock.objects.get(pk=n.pk)
           print(s.name)
           s.quantity = s.quantity- int(n.count)
           s.save()

            return redirect('/billing')
</code>```

Output

```<code>med check
3
1
med check
4
2
med check
5
3
3
printing dtock
1
end of doc
printing dtock
2
end of doc
Internal Server Error: /mbill/
Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
    list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: '4'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\Develop\web\ayur\main\views.py", line 136, in mbill
    a.count = request.POST[str(ed.pk)]
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'4'"
</code>```

I am not able to find the error. The iteration just stops in the middle. The same med query set gives until output until 3 but the med set again is giving only output upto 2. What is the bug?

答:
MultiValueDict has a get method. This is also present on standard dicts. It help you fetch a value from a dict and provide a default value if it doesn't exist.

```<code>a.count = = request.POST.get(str(ed.pk), <default_value>)
</code>```

In general,

```<code>my_var = dict.get(<key>, <default>)
</code>```

Body:
The code that is giving me the problem

   pk = request.POST['pk']
    medrec = MedicalRec.objects.get(pk=pk)
    med = Medicine.objects.filter(medicalrec=medrec)
    for f in med:
              print("med check")
              print(f.pk)
              print(f.stockpk)
     for ed in med:
                print("printing dtock")
                print(ed.stockpk)
                print("end of doc")
                a= pks()
                a.pk = ed.stockpk
                a.count = request.POST[str(ed.pk)]
                ls.append(a)
     for l in ls:
           print(l.pk)
           print(l.count)
     for n in ls:
           s= Stock.objects.get(pk=n.pk)
           print(s.name)
           s.quantity = s.quantity- int(n.count)
           s.save()

            return redirect('/billing')

Output

med check
3
1
med check
4
2
med check
5
3
3
printing dtock
1
end of doc
printing dtock
2
end of doc
Internal Server Error: /mbill/
Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
    list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: '4'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\Develop\web\ayur\main\views.py", line 136, in mbill
    a.count = request.POST[str(ed.pk)]
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'4'"

I am not able to find the error. The iteration just stops in the middle. The same med query set gives until output until 3 but the med set again is giving only output upto 2. What is the bug?

Body:
MultiValueDict has a get method. This is also present on standard dicts. It help you fetch a value from a dict and provide a default value if it doesn't exist.

a.count = = request.POST.get(str(ed.pk), <default_value>)

In general,

my_var = dict.get(<key>, <default>)