问:
Encoding floats in a dictionary using custom python JSON encoder
Here's a simple JSON encoder that convert float values to string:

```<code>class NestedEncoder(json.JSONEncoder):
    '''
    A JSON Encoder that converts floats/decimals to strings and allows nested objects
    '''

    def default(self, obj):

        if isinstance(obj, float) or obj.__class__.__name__ == "float32":
            return self.floattostr(obj)
        elif obj.__class__.__name__ == "type":
            return str(obj)
        elif hasattr(obj, 'repr_json'):
            return obj.repr_json()
        else:
            return json.JSONEncoder.default(self, obj)

    def floattostr(self,o,_inf=float('Inf'), _neginf=-float('-Inf'),nan_str="None"):
        if o != o:
            text = nan_str
        elif o == _inf:
            text = 'Infinity'
        elif o == _neginf:
            text = '-Infinity'
        else:
            return o.__repr__()

        return text
</code>```

Now here's two tests. The first creates a Infinity valued float and encodes it using the custom encoder. Test passes.

```<code>def test_inf():
    inf = float('Inf')
    as_json = json.dumps(inf,cls=NestedEncoder)
    assert as_json == "Infinity"
</code>```

The second test does the same but puts the float in a dictionary:

```<code>def test_inf_dic():
    inf = float('Inf')
    as_json = json.dumps({'key':inf},cls=NestedEncoder)
    assert as_json == "{'key':'Infinity'}"
</code>```

OUTPUT:

```<code>=================================== FAILURES ===================================
_________________________________ test_inf_dic _________________________________

    def test_inf_dic():
        inf = float('Inf')
        as_json = json.dumps({'key':inf},cls=NestedEncoder)
>       assert as_json == "{'key':'Infinity'}"
E       assert '{"key": Infinity}' == "{'key':'Infinity'}"
E         - {"key": Infinity}
E         ?  ^   ^ ^
E         + {'key':'Infinity'}
E         ?  ^   ^ ^        +
</code>```

EDIT:

The custom encoder only gets called for the first test, not the second.

答:
You are correct that your custom function is not getting called during your test. The reason for this is explained in the docs:

If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.

Since float is an object that it already knows how to serialized, it is not called. For float serialization, you can override the encode function.

Body:
Here's a simple JSON encoder that convert float values to string:

class NestedEncoder(json.JSONEncoder):
    '''
    A JSON Encoder that converts floats/decimals to strings and allows nested objects
    '''

    def default(self, obj):

        if isinstance(obj, float) or obj.__class__.__name__ == "float32":
            return self.floattostr(obj)
        elif obj.__class__.__name__ == "type":
            return str(obj)
        elif hasattr(obj, 'repr_json'):
            return obj.repr_json()
        else:
            return json.JSONEncoder.default(self, obj)

    def floattostr(self,o,_inf=float('Inf'), _neginf=-float('-Inf'),nan_str="None"):
        if o != o:
            text = nan_str
        elif o == _inf:
            text = 'Infinity'
        elif o == _neginf:
            text = '-Infinity'
        else:
            return o.__repr__()

        return text

Now here's two tests. The first creates a Infinity valued float and encodes it using the custom encoder. Test passes.

def test_inf():
    inf = float('Inf')
    as_json = json.dumps(inf,cls=NestedEncoder)
    assert as_json == "Infinity"

The second test does the same but puts the float in a dictionary:

def test_inf_dic():
    inf = float('Inf')
    as_json = json.dumps({'key':inf},cls=NestedEncoder)
    assert as_json == "{'key':'Infinity'}"

OUTPUT:

=================================== FAILURES ===================================
_________________________________ test_inf_dic _________________________________

    def test_inf_dic():
        inf = float('Inf')
        as_json = json.dumps({'key':inf},cls=NestedEncoder)
>       assert as_json == "{'key':'Infinity'}"
E       assert '{"key": Infinity}' == "{'key':'Infinity'}"
E         - {"key": Infinity}
E         ?  ^   ^ ^
E         + {'key':'Infinity'}
E         ?  ^   ^ ^        +

EDIT:

The custom encoder only gets called for the first test, not the second.


来源: stackexchange

问:
Hawtio read only options based on roles enabled
I am trying to integrate Hawtio with my Java applications.  I have an use case to display few features to level-2 support and few more to level-1 support,etc by enabling roles.

I am able keep separate creds for level-1/2 by using tomcat roles but I couldn't control the tabs likes Thread/dashboard,etc.

Is there anyway.  I am using Hawtio-1.5.2-offline as a war format.

答:
Currently it's not possible to control shows/hides of top-level tabs based on user roles.

You can show/hide top-level tabs on a per-user basis, or just customise the complete package itself. See this Q&A for more info:

How to hide the Tabs in Hawtio? Also, how to stop the default landing on ActiveMQ after connecting to remote server?

ContentLicense: CC BY-SA 3.0


问:
executable jar using ant and ivy - CLASSPATH issues
I'm trying to build an executable jar file using ant managed by ivy but am stuck. Our original build-script assembles the jar file more or less okay. The dependencies are in the manifest.mf but not under Class-Path but rather Compile-Class-Path entry.

I can simply set the Main-Class entry in the menifest file but having an impossible foe in trying to get the ivy dependencies in the Class-Path. While this seems simple enough using gradle I can't find any solution for ivy dependencies.

Is there a way of getting the resolves ivy dependencies and put them in the manifest? These dependencies are just paths to a network location where the jar files are.

答:
I'm giving a standard way to do this. If you can provide your actual build file, I can be more specific in the answer.

You can do this in the ant target for jar creation. For ex:

```<code><!-- create a classpath variable with all the jars needed for runtime -->
<path id="cls.path">
   <!-- declare all the paths that you need. For ex: all resolved jars in "runtime" conf -->
</path>
<!-- If your path has folder prefix, you'll have to do <pathconvert> -->
<jar jarfile="${jar_name}" basedir="${classes.dir}">
   <manifest>
      <attribute name="Class-Path" value="${cls.path}"/>
      ...
      <!-- You can add standard jar properties and any custom property here -->
   </manifest>
</jar>
</code>```

Body:
I'm giving a standard way to do this. If you can provide your actual build file, I can be more specific in the answer.

You can do this in the ant target for jar creation. For ex:

<!-- create a classpath variable with all the jars needed for runtime -->
<path id="cls.path">
   <!-- declare all the paths that you need. For ex: all resolved jars in "runtime" conf -->
</path>
<!-- If your path has folder prefix, you'll have to do <pathconvert> -->
<jar jarfile="${jar_name}" basedir="${classes.dir}">
   <manifest>
      <attribute name="Class-Path" value="${cls.path}"/>
      ...
      <!-- You can add standard jar properties and any custom property here -->
   </manifest>
</jar>


问:
How to switch environment on Jupyter notebook for new notebook?
I have an instance with various environment and some notebooks are compatible with different environment for e.g. notebook1 is for MXNet and notebook2 is for Tensorflow.

How do I jump to new environment when I move from notebook1 to notebook2?
I tried doing that but this doesn't quite work with Jupyter notebook? Any suggestion?

So I need to do it from conda environment but looks like jupyter notebook  UI doesn't respect (calls right activation function) to set the path.

答:
Along with this package I think also need to change the ~/.jupyter/jupyter_notebook_config.py  file with following config</p>

```<code>c.NotebookApp.kernel_spec_manager_class = 'environment_kernels.EnvironmentKernelSpecManager'
</code>```

Body:
Along with this package I think also need to change the ~/.jupyter/jupyter_notebook_config.py  file with following config

c.NotebookApp.kernel_spec_manager_class = 'environment_kernels.EnvironmentKernelSpecManager'


问:
How to Full Control (Read/Write) of custom resource resw file (Universal Windows)
How can I read/write Keys/Values on a custom Resource File (resw) (storing string and conditional resources) ?

I added  Resource File(resw) for storing settings of app. And Then ?

```<code> private void button1_Click(object sender, RoutedEventArgs e)
    {
        ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
        ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");//resources.resw accessing in root is ok.
        var resourceValue = resourceMap.GetValue("PicPath", resourceContext);

        resourceMap.SetValue("DBPath", resourceContext,"PicPath2");//no write avaible ? ERROR LINE
    }
</code>```

答:
To store read / write app values, you should use the ApplicationData API. You can have local and / or roaming settings.

Resources are read-only and are for things like UI strings, images, etc. that you load at runtime and might want to change based on things like the user's language, the accessibility settings, the display's scale factor, etc.

Body:
How can I read/write Keys/Values on a custom Resource File (resw) (storing string and conditional resources) ?

I added  Resource File(resw) for storing settings of app. And Then ?

 private void button1_Click(object sender, RoutedEventArgs e)
    {
        ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
        ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");//resources.resw accessing in root is ok.
        var resourceValue = resourceMap.GetValue("PicPath", resourceContext);

        resourceMap.SetValue("DBPath", resourceContext,"PicPath2");//no write avaible ? ERROR LINE
    }


问:
How can I get rid of the text next to the navigation back button in Swift?
How can I get rid of the text and just have the back arrow show up for ALL view controllers that show up on the navigation stack.

I already know that this code will work to remove the text on a single view controller:

```<code>let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = item
</code>```

However, I am looking for a solution where I don't have to copy and paste code into each individual view controller.

I am already subclassing every single navigation controller in my app to the same class, so I'm trying to find a solution I can write once in this UINavigationController subclass that will cause all children view controllers that might show up on the stack to show only the back arrow with no text.

答:
How about implementing UINavigationControllerDelegate like this:

```<code>func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}
</code>```

backBarButtonItem is nil by default and it affects next pushed controller, so you just set it for all controllers

Body:
How can I get rid of the text and just have the back arrow show up for ALL view controllers that show up on the navigation stack.

I already know that this code will work to remove the text on a single view controller:

let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = item

However, I am looking for a solution where I don't have to copy and paste code into each individual view controller.

I am already subclassing every single navigation controller in my app to the same class, so I'm trying to find a solution I can write once in this UINavigationController subclass that will cause all children view controllers that might show up on the stack to show only the back arrow with no text.

Body:
How about implementing UINavigationControllerDelegate like this:

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}

backBarButtonItem is nil by default and it affects next pushed controller, so you just set it for all controllers


问:
Editing bot for Line
I got bot script from https://github.com/merkremont/LineVodka

and I want to add this script but it say syntax error / unexpected indent

```<code>elif msg.text in ["Tag all","Tagall"]:
    if msg.from_ in admin:
        group = client.getGroup(msg.to)
        nama = [contact.mid for contact in group.members]

        cb = ""
        cb2 = ""
        strt = int(0)
        akh = int(0)
        for md in nama:
           akh = akh + int(6)

           cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""

           strt = strt + int(7)
           akh = akh + 1
           cb2 += "@nrik \n"

        cb = (cb[:int(len(cb)-1)])
        msg.contentType = 0
        msg.text = cb2
        msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'4'}

        try:
           sendMessage(msg)
        except Exception as error:
           print error
</code>```

答:
The problem may be in this line

```<code>cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""
</code>```

where you input the string as single double quote ("), but close it with triple (""").

Try

```<code>cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"
</code>```

edit:
Sorry, reading the question one more time I realized that that's not the problem. Nonetheless I was expecting an error for that. Anyway... Check again if your indentation is consistent with the script, especially if your elif lines with the other if and else statements.

Title: Editing bot for Line

Body:
I got bot script from https://github.com/merkremont/LineVodka

and I want to add this script but it say syntax error / unexpected indent

elif msg.text in ["Tag all","Tagall"]:
    if msg.from_ in admin:
        group = client.getGroup(msg.to)
        nama = [contact.mid for contact in group.members]

        cb = ""
        cb2 = ""
        strt = int(0)
        akh = int(0)
        for md in nama:
           akh = akh + int(6)

           cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""

           strt = strt + int(7)
           akh = akh + 1
           cb2 += "@nrik \n"

        cb = (cb[:int(len(cb)-1)])
        msg.contentType = 0
        msg.text = cb2
        msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'4'}

        try:
           sendMessage(msg)
        except Exception as error:
           print error

Body:
The problem may be in this line

cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""

where you input the string as single double quote ("), but close it with triple (""").

Try

cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"

edit:
Sorry, reading the question one more time I realized that that's not the problem. Nonetheless I was expecting an error for that. Anyway... Check again if your indentation is consistent with the script, especially if your elif lines with the other if and else statements.


问:
Docusign - Can we get a copy of signed documents for our database automatically?
We would like to get/download/retrieve a copy of all signed DocuSign document pdfs to store in our database with the other associated data like name, date etc...  Is this possible to obtain in an automated fashion?</p>

答: You can use either API or there is a desktop application called as DocuSign Retrieve -  https://www.docusign.com/supportdocs/pdf/retrieve-quick-start-guide.pdf to download the DocuSign envelopes in a drive. Or you can use DocuSign Connect as well - https://www.docusign.com/supportdocs/pdf/connect-guide.pdf</p>


问:
Compound Couchbase 4.x Global Secondary Indexes
When creating compound Global Secondary Indexes in Couchbase 4.x, I'm curious about the performance based on the ordering of the fields provided during the CREATE INDEX statement.

To illustrate, let me start with an example:

```<code>CREATE INDEX Index_1
 ON `bucket`(field1, field2)
 USING GSI;
</code>```

Now when we execute the following query:

```<code>SELECT * FROM `bucket`
 WHERE `bucket`.field1 = "value1"
 AND `bucket`.field2 = "value2";
</code>```

It's very clear to me that using Index1 is obvious. However, there are a few cases I'm unclear about:

What if field2 is just provided and not field 1?

SELECT * FROM bucket  WHERE bucket.field2 = "value2";

What if field2 and field1 have reverse order in the WHERE clause?

SELECT * FROM bucket  WHERE bucket.field2 = "value2" AND bucket.field1 = "value1";

I know this example is only for 2 fields, but In my case I have something like 10 fields. In this case, creating many indexes to cover all the possibilities seems like a combinatorial explosion (factorial even, if you consider all possible orderings and ordering is important). It's even worse if missing fields is important because then you would need all possible orderings on possible subset of fields. That is, [(field1, field2), (field1), (field2, field1), (field2)], and this is only for 2 fields.

答:
Field order in the CREATE INDEX statement does matter. Your queries must include the leading field, field1, but can optionally include the trailing fields.  Your index has only one trailing field, field2.

Your first query will not use the index because it is missing the leading field. Be sure to drop your primary index when testing indexes or check the plan to make sure it does not include a PrimaryScan.

Reordering query predicates, as in your second example, does not change how the index is used. All leading fields are used in the IndexScan, regardless of where they appear in query predicates.

But, if you have an index with more than two fields, for example:

```<code>CREATE INDEX Index_2
  ON `bucket`(field1, field2, field3, field4)
  USING GSI;
</code>```

And your query excludes the second field:

```<code>SELECT * FROM `bucket`
  WHERE `bucket`.field1 = "value1"
    // field2 not specified
    AND `bucket`.field3 = "value3";
</code>```

Only one leading field is specified, so the index is only scanned using the field1 predicate.  The query service must do the remaining work to filter items with the field3 value.

Body:
When creating compound Global Secondary Indexes in Couchbase 4.x, I'm curious about the performance based on the ordering of the fields provided during the CREATE INDEX statement.

To illustrate, let me start with an example:

CREATE INDEX Index_1
 ON `bucket`(field1, field2)
 USING GSI;

Now when we execute the following query:

SELECT * FROM `bucket`
 WHERE `bucket`.field1 = "value1"
 AND `bucket`.field2 = "value2";

It's very clear to me that using Index1 is obvious. However, there are a few cases I'm unclear about:

What if field2 is just provided and not field 1?

SELECT * FROM bucket  WHERE bucket.field2 = "value2";

What if field2 and field1 have reverse order in the WHERE clause?

SELECT * FROM bucket  WHERE bucket.field2 = "value2" AND bucket.field1 = "value1";

I know this example is only for 2 fields, but In my case I have something like 10 fields. In this case, creating many indexes to cover all the possibilities seems like a combinatorial explosion (factorial even, if you consider all possible orderings and ordering is important). It's even worse if missing fields is important because then you would need all possible orderings on possible subset of fields. That is, [(field1, field2), (field1), (field2, field1), (field2)], and this is only for 2 fields.

Body:
Field order in the CREATE INDEX statement does matter. Your queries must include the leading field, field1, but can optionally include the trailing fields.  Your index has only one trailing field, field2.

Your first query will not use the index because it is missing the leading field. Be sure to drop your primary index when testing indexes or check the plan to make sure it does not include a PrimaryScan.

Reordering query predicates, as in your second example, does not change how the index is used. All leading fields are used in the IndexScan, regardless of where they appear in query predicates.

But, if you have an index with more than two fields, for example:

CREATE INDEX Index_2
  ON `bucket`(field1, field2, field3, field4)
  USING GSI;

And your query excludes the second field:

SELECT * FROM `bucket`
  WHERE `bucket`.field1 = "value1"
    // field2 not specified
    AND `bucket`.field3 = "value3";

Only one leading field is specified, so the index is only scanned using the field1 predicate.  The query service must do the remaining work to filter items with the field3 value.


问:
Linux I2C kernel driver binding
I am learning about how to develop a Linux I2C kernel driver, and I learn from websites below.

How to instantiate I2C devices

I2C Driver for Linux Based Embedded System

...

Next, I found a sample that shows how to implement a I2C touchpad driver, but it really confused me.

linux/drivers/input/mouse/synaptics_i2c.c

My question is, how Linux kernel bind this driver to correctly device?
 This driver don't provide 'detect' callback, no specify the I2C slave address via i2c_driver.address_list, and there is seems no anyone to call i2c_board_info to register the address info (I grep a whole Linux codebase).

I thought the driver MUST be specify the slave address or provide the 'detect' callback, just like

drivers/hwmon/adc128d818.c

or
linux/drivers/rtc/rtc-ds1307.c (it will be register by i2c_board_info)

Please let me know what I missed, thanks.

答:
I finally figured out my question.

Refer to http://www.embedded-bits.co.uk/2009/i2c-in-the-2632-linux-kernel/

There is need to register my I2C device with i2c_new_probed_device() or i2c_new_device on Kernel to let it have a mapping table about slave address and device name.

Title: Linux I2C kernel driver binding


问:
How can AWS lambda function validate the token coming from another lambda function?
I am trying to implement a custom authorizer for AWS API Gateway. I need to make two lambda functions, one that will generate the token and the other to validate the token. However, how can the latter validate the token that came from the former? In some c# tutorials they have set the same machine key so that the validator can decrypt the token sent by the authorization server. How can I do that in aws lambda functions?

Any help would be highly appreciated.

Thank you.

答:
I would store the signing key (I am assuming JWT tokens) in EC2 Systems Manager Parameter Store. Each Lambda function will need permissions to access the parameter store.

Very easy service to work with. This service is located on the Amazon Management Console EC2 page left hand side under Systems Manager Shared Resources.

Amazon EC2 Systems Manager Parameter Store provides secure,
  hierarchical storage for configuration data management and secrets
  management. You can store data such as passwords, database strings,
  and license codes as parameter values. You can store values as plain
  text or encrypted data. You can then reference values by using the
  unique name that you specified when you created the parameter.
  Parameter Store is easily accessible by using the AWS Management
  console and the AWS CLI. Highly scalable, available, and durable,
  Parameter Store is backed by the AWS Cloud. Parameter Store is offered
  at no additional charge and includes generous limits.

Systems Manager Parameter Store

The Right Way to Store Secrets using Parameter Store

You should use SSM Parameter Store over Lambda env variables


问:
Mapping an ImmutableJS collection
I have an ImmutableJS structure that looks like this:

```<code>let state = fromJS({
  // ...
  foo: [{
    bar: ['id1', 'id2']
  },{
    bar: ['id2', 'id3']
  }]
});
</code>```

I want to map over foo and for each item, filter the associated bar against another array of ids to exclude (idsToExclude).

I have come up with this:

```<code>const idsToExclude = ['id3', 'id4'];
state = {
    ...state,
    foo: state.get('foo').map((i) =>
        i.set(['bar'], i.get(['bar']
            .filterNot(b => idsToExclude.some(id => id === b))))
};
</code>```

Is there a better, more idiomatic or terser way?

I ask because this seems quite verbose.

答:
I think you can get this a little cleaner by using .update, though this is still fairly long. You can also simplify .some(id => id === b) to .contains(b).

```<code>state = state.update('foo', foo =>
    foo.map(item =>
        item.update('bar',
            bar => bar.filterNot(
                id => idsToExclude.contains(id)))));
</code>```

Title: Mapping an ImmutableJS collection

Body:
I have an ImmutableJS structure that looks like this:

let state = fromJS({
  // ...
  foo: [{
    bar: ['id1', 'id2']
  },{
    bar: ['id2', 'id3']
  }]
});

I want to map over foo and for each item, filter the associated bar against another array of ids to exclude (idsToExclude).

I have come up with this:

const idsToExclude = ['id3', 'id4'];
state = {
    ...state,
    foo: state.get('foo').map((i) =>
        i.set(['bar'], i.get(['bar']
            .filterNot(b => idsToExclude.some(id => id === b))))
};

Is there a better, more idiomatic or terser way?

I ask because this seems quite verbose.

Body:
I think you can get this a little cleaner by using .update, though this is still fairly long. You can also simplify .some(id => id === b) to .contains(b).

state = state.update('foo', foo =>
    foo.map(item =>
        item.update('bar',
            bar => bar.filterNot(
                id => idsToExclude.contains(id)))));


问:
Ajax.BeginForm, Loading partial view help
I have a project that I am working on, it's being developed in ASP.NET MVC2

Currently I have used Ajax to load some data. It works great on firefox and chrome however I have an issue with IE.

My controller:

```<code>    public ActionResult UpdateSearchResults(FormCollection formValues)
    {
        var equipmentsResults = EquipmentQueries.GetEquipments(Request.Form["Voltage"],
                                                               Request.Form["EquipmentType"],
                                                               Request.Form["Word"]);
        return PartialView("SearchResults", equipmentsResults);
    }
</code>```

My view:

```<code><% using (Ajax.BeginForm("UpdateSearchResults",
       new AjaxOptions {UpdateTargetId = "loadingData",
                        LoadingElementId = "loadingImage",
                        HttpMethod = "POST"}))
   { %>
    <fieldset>
        <legend>Filters</legend>
        <label>Voltage: </label>
        <%=Html.DropDownList("Voltage", (SelectList)ViewData["Voltage"], "Select Voltage", new { onchange = "this.form.submit();" })%>
        <br />

        <label>Equipment Type: </label>
        <%=Html.DropDownList("EquipmentType", (SelectList)ViewData["Equipment"], "Select Equipment Type")%>
        <br />

        <label>Station Keyword Search: </label>
        <%=Html.TextBox("Word")%>
        <br />

        <input id="btnSubmit" type="submit" value="Submit" name="submit" />
        <br />
    </fieldset>

    <img id="loadingImage" src="../../Images/ajax-loader.gif" alt="loading"/>
    <div id="loadingData"></div>
<% }%>
</code>```

I have included the following scripts

```<code><script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</code>```

What I found during debugging is that in chrome and firefox all the DropDownList populate the Request.Form ( Request.Form("Voltage") actually displays what the user has picked on the DropDownList), however in IE this Request.Form doesn't get populated at all, it's just an empty string...

Thanks for the help everyone

答:
While I have no clue why your code doesn't work on IE I have some suggestions about improving it. So as usual we start by defining a view model which will represent the data we are dealing with on the view:

Model:

```<code>public class ProductViewModel
{
    public string SelectedVoltage { get; set; }
    public IEnumerable<SelectListItem> Voltages
    {
        get
        {
            return new SelectList(new[] {
                new SelectListItem { Value = "110", Text = "110V" },
                new SelectListItem { Value = "220", Text = "220V" },
            }, "Value", "Text");
        }
    }

    public string SelectedEquipementType { get; set; }
    public IEnumerable<SelectListItem> EquipementTypes
    {
        get
        {
            return new SelectList(new[]
            {
                new SelectListItem { Value = "t1", Text = "Equipement type 1" },
                new SelectListItem { Value = "t2", Text = "Equipement type 2" },
            }, "Value", "Text");
        }
    }

    public string Word { get; set; }
}
</code>```

Controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new ProductViewModel());
    }

    [HttpPost]
    public ActionResult Search(ProductViewModel product)
    {
        var equipmentsResults = EquipmentQueries.GetEquipments(product);
        return View(equipmentsResults);
    }
}
</code>```

View:

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

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

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/form/raw/master/jquery.form.js"></script>
<!-- TODO: Put this in an external javascript file -->
<!-- I've left it here just to illustrate -->
<script type="text/javascript">
    $(function () {
        var options = {
            success: function (result) {
                $('#loadingData').html(result);
            }
        };
        $('form').ajaxForm(options);
        $('#SelectedVoltage').change(function () {
            $('form').ajaxSubmit(options);
        });
    });
</script>

<% using (Html.BeginForm("search", "home")) { %>
    <fieldset>
        <legend>Filters</legend>
        <label for="SelectedVoltage">Voltage: </label>
        <%= Html.DropDownListFor(x => x.SelectedVoltage, Model.Voltages, "Select Voltage")%>
        <br />

        <label for="SelectedEquipementType">Equipment Type: </label>
        <%= Html.DropDownListFor(x => x.SelectedEquipementType, Model.EquipementTypes, "Select Equipment Type")%>
        <br />

        <label for="Word">Station Keyword Search: </label>
        <%= Html.TextBoxFor(x => x.Word)%>
        <br />

        <input id="btnSubmit" type="submit" value="Submit" name="submit" />
    </fieldset>
<% } %>
<br />
<div id="loadingData"></div>

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

Now you can safely dump all the MSAjax* scripts as well as all Ajax.* helpers. Do it the proper way: unobtrusively, the jquery way.

ContentLicense: CC BY-SA 2.5

Body:
I have a project that I am working on, it's being developed in ASP.NET MVC2

Currently I have used Ajax to load some data. It works great on firefox and chrome however I have an issue with IE.

My controller:

    public ActionResult UpdateSearchResults(FormCollection formValues)
    {
        var equipmentsResults = EquipmentQueries.GetEquipments(Request.Form["Voltage"],
                                                               Request.Form["EquipmentType"],
                                                               Request.Form["Word"]);
        return PartialView("SearchResults", equipmentsResults);
    }

My view:

<% using (Ajax.BeginForm("UpdateSearchResults",
       new AjaxOptions {UpdateTargetId = "loadingData",
                        LoadingElementId = "loadingImage",
                        HttpMethod = "POST"}))
   { %>
    <fieldset>
        <legend>Filters</legend>
        Voltage:
        <%=Html.DropDownList("Voltage", (SelectList)ViewData["Voltage"], "Select Voltage", new { onchange = "this.form.submit();" })%>

        Equipment Type:
        <%=Html.DropDownList("EquipmentType", (SelectList)ViewData["Equipment"], "Select Equipment Type")%>

        Station Keyword Search:
        <%=Html.TextBox("Word")%>

        <input id="btnSubmit" type="submit" value="Submit" name="submit" />

    </fieldset>

<% }%>

I have included the following scripts

What I found during debugging is that in chrome and firefox all the DropDownList populate the Request.Form ( Request.Form("Voltage") actually displays what the user has picked on the DropDownList), however in IE this Request.Form doesn't get populated at all, it's just an empty string...

Thanks for the help everyone

Body:
While I have no clue why your code doesn't work on IE I have some suggestions about improving it. So as usual we start by defining a view model which will represent the data we are dealing with on the view:

Model:

public class ProductViewModel
{
    public string SelectedVoltage { get; set; }
    public IEnumerable<SelectListItem> Voltages
    {
        get
        {
            return new SelectList(new[] {
                new SelectListItem { Value = "110", Text = "110V" },
                new SelectListItem { Value = "220", Text = "220V" },
            }, "Value", "Text");
        }
    }

    public string SelectedEquipementType { get; set; }
    public IEnumerable<SelectListItem> EquipementTypes
    {
        get
        {
            return new SelectList(new[]
            {
                new SelectListItem { Value = "t1", Text = "Equipement type 1" },
                new SelectListItem { Value = "t2", Text = "Equipement type 2" },
            }, "Value", "Text");
        }
    }

    public string Word { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new ProductViewModel());
    }

    [HttpPost]
    public ActionResult Search(ProductViewModel product)
    {
        var equipmentsResults = EquipmentQueries.GetEquipments(product);
        return View(equipmentsResults);
    }
}

View:

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

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

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/form/raw/master/jquery.form.js"></script>
<!-- TODO: Put this in an external javascript file -->
<!-- I've left it here just to illustrate -->
<script type="text/javascript">
    $(function () {
        var options = {
            success: function (result) {
                $('#loadingData').html(result);
            }
        };
        $('form').ajaxForm(options);
        $('#SelectedVoltage').change(function () {
            $('form').ajaxSubmit(options);
        });
    });
</script>

<% using (Html.BeginForm("search", "home")) { %>
    <fieldset>
        <legend>Filters</legend>
        <label for="SelectedVoltage">Voltage: </label>
        <%= Html.DropDownListFor(x => x.SelectedVoltage, Model.Voltages, "Select Voltage")%>
        <br />

        <label for="SelectedEquipementType">Equipment Type: </label>
        <%= Html.DropDownListFor(x => x.SelectedEquipementType, Model.EquipementTypes, "Select Equipment Type")%>
        <br />

        <label for="Word">Station Keyword Search: </label>
        <%= Html.TextBoxFor(x => x.Word)%>
        <br />

        <input id="btnSubmit" type="submit" value="Submit" name="submit" />
    </fieldset>
<% } %>
<br />
<div id="loadingData"></div>

</asp:Content>

Now you can safely dump all the MSAjax* scripts as well as all Ajax.* helpers. Do it the proper way: unobtrusively, the jquery way.


问:
Javascript get 3 day before from date formate '2017-11-10' without time
I have a variable has a value of 2017-11-10 and like to get 3 days before from 2017-11-10 which is 2017-11-7

Seems like it only works if you have entire timestamp. However, I removed time from my timestamp.

```<code>let d = new Date();
d.setDate(d.getDate()-1);
</code>```

Is there any ways to do this without time?

答:
Here are few options to get a date string in yyyy-m-d format:

var d = new Date( new Date("2017-11-10" + "z") - 3 * 864e5 ) // specify Zulu time zone to avoid conversion to local time

console.log( d.toJSON().slice(0, 10) ) // "2017-11-07"

console.log( d.toJSON().slice(0, 10).replace('-0', '-') ) // "2017-11-7"

console.log( d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() ) // "2017-11-7"```
</div>
</div>
</p>

<hr>

<p>Timezone information can be added to the date string to avoid conversion to local time:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log( new Date("2000-1-2") ) // "2000-01-01T05:00:00.000Z" ("T05:" because converted to local time)

// correct "2000-01-01T00:00:00.000Z"
console.log( new Date("2000-01-02") )
console.log( new Date("2000-1-2 Z") )
console.log( new Date("2000-1-2 GMT") )
console.log( new Date("2000-1-2 UTC") )

console.log( new Date("2000-1-2 z-1234") ) // "2000-01-02T12:34:00.000Z" ha ..</code>```

Body:
I have a variable has a value of 2017-11-10 and like to get 3 days before from 2017-11-10 which is 2017-11-7

Seems like it only works if you have entire timestamp. However, I removed time from my timestamp.

let d = new Date();
d.setDate(d.getDate()-1);

Is there any ways to do this without time?

Body:
Here are few options to get a date string in yyyy-m-d format:

var d = new Date( new Date("2017-11-10" + "z") - 3 * 864e5 ) // specify Zulu time zone to avoid conversion to local time

console.log( d.toJSON().slice(0, 10) ) // "2017-11-07"

console.log( d.toJSON().slice(0, 10).replace('-0', '-') ) // "2017-11-7"

console.log( d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() ) // "2017-11-7"

Timezone information can be added to the date string to avoid conversion to local time:

console.log( new Date("2000-1-2") ) // "2000-01-01T05:00:00.000Z" ("T05:" because converted to local time)

// correct "2000-01-01T00:00:00.000Z"
console.log( new Date("2000-01-02") )
console.log( new Date("2000-1-2 Z") )
console.log( new Date("2000-1-2 GMT") )
console.log( new Date("2000-1-2 UTC") )

console.log( new Date("2000-1-2 z-1234") ) // "2000-01-02T12:34:00.000Z" ha ..


问:
Minimization of a difference between model and observation by optimizing a single parameter
I admit I am not sure whether this question is better suited here on StackOverflow or elsewhere, because I am not sure if it is just programming or the whole concept that I need to understand. If off-topic, I apologise.

In Python, I am creating a rather simple model. It is a function that takes an array x, several coefficients c1, c2 etc., and a parameter P that I want to optimize.
I want to minimize the difference between the measured and modelled values by changing the parameter P and as an output, I would like the resulting parameter (scalar) and the resulting difference between the model and the measurement (array).

I have been studying the scipy.optimize.minimize documentation for a while, but I don't seem to get it. In particular, I don't understand:

How to define the scalar function that enters the minimization so that only the P gets modified.

Which minimization method would be best in this case (I have assumed least-squares, but looking at the documentation there are so many other methods that I don't even know that if another is recommended, I am open to that option, provided an explanation comes with the recommendation).

How do I get my desired output (as it seems the optimization result is a python object as a whole, but I only want very specific outputs stated above)

Example:

```<code>import numpy as np

array1 = np.random.rand(10)
array2 = np.arange(5.,55,5)

from scipy.optimize import minimize

def model(c1, c2, c3, x, P):
    modelY = x*c1 + c2*x*P + c3 # some random function for which I need to optimize P
    return modelY
</code>```

Now what syntax would I use with scipy.optimize.minimize if the function whose minimum I want is np.abs(measured - modelY) and the only parameter that I want to change is P, which is an argument of the model function, and use the measured data as an initial guess? Or should I put them into a single function? But then how would I specify to NOT modify all the other arguments of the function except the one?
And how do I extract the difference and the resulting P from the minimization result?

答:
Your question, imho, suffered a lot from the description and parameter-names, but i think i'm getting now what you want to achieve.

I simplified it a bit and present some code with two approaches, the good one and the bad one. The good one: optimizing one variable is done by using optimizers for a single variable (minimize_scalar)! The bad one: using any multivariate-optimizer (minimize).

One probably could talk ages about how to use scipy's optimizers, but i won't do that. I will just say: follow the docs! The most important thing (here some excerpt from the minimize-docs):

The callable is called as method(fun, x0, args, **kwargs, **options) where kwargs corresponds to any other parameters passed to minimize (such as callback, hess, etc.), except the options dict, which has its contents also passed as method parameters pair by pair. Also, if jac has been passed as a bool type, jac and fun are mangled so that fun returns just the function values and jac is converted to a function returning the Jacobian. The method shall return an OptimizeResult object.

This means: P is your first parameter in your function you give to scipy's optimizer (in both cases). Everything else, you use either by python's scope rules (variable available for our functions) or by using args.

Code:

```<code>import numpy as np
from scipy.optimize import minimize, minimize_scalar
np.random.seed(1)                                            # make this demo deterministic

# Let's define some random-data and use names people can understand!
f_x = np.random.rand(10)
f_y = np.arange(5.,55,5)
c1, c2, c3 = 2, 1.5, 0.321

# Simple loss-function
def loss(P, c1, c2, c3, f_x, f_y):
    modelY = f_x*c1 + f_x*c2*P + c3                                    # prediction (vector)
    return np.linalg.norm(f_y - modelY, 1)                             # l1-loss (scalar)

# GOOD APPROACH: minimize_scalar
result = minimize_scalar(loss, args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x  # i'm a scalar!
print('minimize_scalar result: ', p_at_minimum)

# BAD APPROACH: minimize (multivariate) -> need guess / initial value!
result = minimize(loss, np.zeros(1), args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x   # i'm a vector!!!
print('minimize result: ', p_at_minimum)
</code>```

Output:

```<code>minimize_scalar result:  60.1334526945
minimize result:  [ 60.1334535]
</code>```

Edit: just recognized, that my var-names are also bad. f_x is not some eval of some function and should be called just x, but careful: x is usually the parameter to optimize!

Remark: and always check the results!

E.g.

```<code>result = minimize_scalar(loss, args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x  # i'm a scalar!
print('minimize_scalar result: ', p_at_minimum)
print('success: ', result.success)
# True

result = minimize(loss, np.zeros(1), args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x   # i'm a vector!!!
print('minimize result: ', p_at_minimum)
print('success: ', result.success)
# False (precision-loss -> you can check result.message
</code>```

This status is why i recommended minimize_scalar, which uses more assumptions and therefore is more robust (less tuning needed)!

Body:
I admit I am not sure whether this question is better suited here on StackOverflow or elsewhere, because I am not sure if it is just programming or the whole concept that I need to understand. If off-topic, I apologise.

In Python, I am creating a rather simple model. It is a function that takes an array x, several coefficients c1, c2 etc., and a parameter P that I want to optimize.
I want to minimize the difference between the measured and modelled values by changing the parameter P and as an output, I would like the resulting parameter (scalar) and the resulting difference between the model and the measurement (array).

I have been studying the scipy.optimize.minimize documentation for a while, but I don't seem to get it. In particular, I don't understand:

How to define the scalar function that enters the minimization so that only the P gets modified.

Which minimization method would be best in this case (I have assumed least-squares, but looking at the documentation there are so many other methods that I don't even know that if another is recommended, I am open to that option, provided an explanation comes with the recommendation).

How do I get my desired output (as it seems the optimization result is a python object as a whole, but I only want very specific outputs stated above)

Example:

import numpy as np

array1 = np.random.rand(10)
array2 = np.arange(5.,55,5)

from scipy.optimize import minimize

def model(c1, c2, c3, x, P):
    modelY = x*c1 + c2*x*P + c3 # some random function for which I need to optimize P
    return modelY

Now what syntax would I use with scipy.optimize.minimize if the function whose minimum I want is np.abs(measured - modelY) and the only parameter that I want to change is P, which is an argument of the model function, and use the measured data as an initial guess? Or should I put them into a single function? But then how would I specify to NOT modify all the other arguments of the function except the one?
And how do I extract the difference and the resulting P from the minimization result?

Body:
Your question, imho, suffered a lot from the description and parameter-names, but i think i'm getting now what you want to achieve.

I simplified it a bit and present some code with two approaches, the good one and the bad one. The good one: optimizing one variable is done by using optimizers for a single variable (minimize_scalar)! The bad one: using any multivariate-optimizer (minimize).

One probably could talk ages about how to use scipy's optimizers, but i won't do that. I will just say: follow the docs! The most important thing (here some excerpt from the minimize-docs):

The callable is called as method(fun, x0, args, **kwargs, **options) where kwargs corresponds to any other parameters passed to minimize (such as callback, hess, etc.), except the options dict, which has its contents also passed as method parameters pair by pair. Also, if jac has been passed as a bool type, jac and fun are mangled so that fun returns just the function values and jac is converted to a function returning the Jacobian. The method shall return an OptimizeResult object.

This means: P is your first parameter in your function you give to scipy's optimizer (in both cases). Everything else, you use either by python's scope rules (variable available for our functions) or by using args.

Code:

import numpy as np
from scipy.optimize import minimize, minimize_scalar
np.random.seed(1)                                            # make this demo deterministic

# Let's define some random-data and use names people can understand!
f_x = np.random.rand(10)
f_y = np.arange(5.,55,5)
c1, c2, c3 = 2, 1.5, 0.321

# Simple loss-function
def loss(P, c1, c2, c3, f_x, f_y):
    modelY = f_x*c1 + f_x*c2*P + c3                                    # prediction (vector)
    return np.linalg.norm(f_y - modelY, 1)                             # l1-loss (scalar)

# GOOD APPROACH: minimize_scalar
result = minimize_scalar(loss, args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x  # i'm a scalar!
print('minimize_scalar result: ', p_at_minimum)

# BAD APPROACH: minimize (multivariate) -> need guess / initial value!
result = minimize(loss, np.zeros(1), args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x   # i'm a vector!!!
print('minimize result: ', p_at_minimum)

Output:

minimize_scalar result:  60.1334526945
minimize result:  [ 60.1334535]

Edit: just recognized, that my var-names are also bad. f_x is not some eval of some function and should be called just x, but careful: x is usually the parameter to optimize!

Remark: and always check the results!

E.g.

result = minimize_scalar(loss, args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x  # i'm a scalar!
print('minimize_scalar result: ', p_at_minimum)
print('success: ', result.success)
# True

result = minimize(loss, np.zeros(1), args=(c1, c2, c3, f_x, f_y))
p_at_minimum = result.x   # i'm a vector!!!
print('minimize result: ', p_at_minimum)
print('success: ', result.success)
# False (precision-loss -> you can check result.message

This status is why i recommended minimize_scalar, which uses more assumptions and therefore is more robust (less tuning needed)!


问:
How do I add two weeks to Time.now?
How can I add two weeks to the current Time.now in Ruby? I have a small Sinatra project that uses DataMapper and before saving, I have a field populated with the current time PLUS two weeks, but is not working as needed. Any help is greatly appreciated! I get the following error:

```<code>NoMethodError at /
undefined method `weeks' for 2:Fixnum
</code>```

Here is the code for the Model:

```<code>class Job
  include DataMapper::Resource

  property :id,           Serial
  property :position,     String
  property :location,     String
  property :email,        String
  property :phone,        String
  property :description,  Text
  property :expires_on,   Date
  property :status,       Boolean
  property :created_on,   DateTime
  property :updated_at,   DateTime

  before :save do
    t = Time.now
    self.expires_on = t + 2.week
    self.status = '0'
  end
end
</code>```

答:
You can use these 3 patterns

```<code># you have NoMethod Error undefined method
require 'active_support/all'

# Tue, 28 Nov 2017 11:46:37 +0900
Time.now + 2.weeks

# Tue, 28 Nov 2017 11:46:37 +0900
Time.now + 2.week

# Tue Nov 28 11:48:24 +0900 2017
2.weeks.from_now
</code>```

Title: How do I add two weeks to Time.now?

Body:
How can I add two weeks to the current Time.now in Ruby? I have a small Sinatra project that uses DataMapper and before saving, I have a field populated with the current time PLUS two weeks, but is not working as needed. Any help is greatly appreciated! I get the following error:

NoMethodError at /
undefined method `weeks' for 2:Fixnum

Here is the code for the Model:

class Job
  include DataMapper::Resource

  property :id,           Serial
  property :position,     String
  property :location,     String
  property :email,        String
  property :phone,        String
  property :description,  Text
  property :expires_on,   Date
  property :status,       Boolean
  property :created_on,   DateTime
  property :updated_at,   DateTime

  before :save do
    t = Time.now
    self.expires_on = t + 2.week
    self.status = '0'
  end
end

Body:
You can use these 3 patterns

# you have NoMethod Error undefined method
require 'active_support/all'

# Tue, 28 Nov 2017 11:46:37 +0900
Time.now + 2.weeks

# Tue, 28 Nov 2017 11:46:37 +0900
Time.now + 2.week

# Tue Nov 28 11:48:24 +0900 2017
2.weeks.from_now


问:
Display running total textbox values' sum in the label
I want to display the sum and the parentage of the performance values for the department vise filtered employees.

When I add values to the second row, the values add to the first row's sum.

Can some one help me to find the coding issue on my code??? Thanks.

This is my calculation view.

This is PHP code:

```<code>                      <tbody>

                        <?php

                        if(isset($_POST['filter'])){
                        $department = $_POST['department'];

                        $query1 = "SELECT * FROM employee_personal_details e INNER JOIN department_details a ON e.dep_id=a.dep_id WHERE dep_name = '$department' ";

                        $employees = mysqli_query($connection,$query1);

                        while ($list = mysqli_fetch_array($employees)) {

                            echo "<tr>";
                            echo "<td>".$list['emp_fullName']."</td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td><input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\"></td>";
                            echo "<td id=\"sum\"></td>";
                            echo "<td id=\"prec\"></td>";

                        }
                    }
                    ?>

                </tbody>
</code>```

and this is my javascript code:

```<code>          $(document).ready(function () {

              $(".cal").each(function () {
                   $(this).keyup(function () {
                    //Initialize total to 0
                        var total = 0;
                         $(".cal").each(function () {

                            if (!isNaN(this.value) && this.value.length != 0 && this.value < 4) {
                              total += parseFloat(this.value);
                              precentage = (total/21)*100;
                         }
                    });

                    $('#sum').html(total);
                    $('#prec').html(precentage.toFixed(2));
               });
          });
     });
</code>```

答:
Here you go with a solution

$(document).ready(function () {
  $('.cal').keyup(function(){
    var sum = 0;
    var precentage = 0;
    $('.cal').each(function(){
      var curVal = parseFloat($(this).val());
      if(!isNaN(curVal) && curVal.length != 0 && curVal < 4){
        sum += curVal;
        precentage = (sum/21)*100;
      }
    });

    $('#sum').html(sum);
    $('#prec').html(precentage.toFixed(2));
  });
});```
<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>
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">

SUM: <div id="sum"></div>
Precentage: <div id="prec"></div></code>```

Updated solution

$(document).ready(function () {
  $('.cal').keyup(function(){
    var sum = 0;
    var precentage = 0;
    $(this).closest('tr').find('td').each(function(){
      var curVal = parseFloat($(this).find('.cal').val());
      if(!isNaN(curVal) && curVal.length != 0 && curVal < 4){
        sum += curVal;
        precentage = (sum/21)*100;
      }
    });

    $(this).closest('tr').find('td').find('.sum').html(sum);
    $(this).closest('tr').find('td').find('.prec').html(precentage.toFixed(2));
  });
});```
<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>
<table>
  <tr>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td>
      SUM: <div class="sum"></div>
      Precentage: <div class="prec"></div>
    </td>
  </tr>
  <tr>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td>
      SUM: <div class="sum"></div>
      Precentage: <div class="prec"></div>
    </td>
  </tr>
</table></code>```

Hope this will help you.

Body:
I want to display the sum and the parentage of the performance values for the department vise filtered employees.

When I add values to the second row, the values add to the first row's sum.

Can some one help me to find the coding issue on my code??? Thanks.

This is my calculation view.

This is PHP code:

                        <?php

                        if(isset($_POST['filter'])){
                        $department = $_POST['department'];

                        $query1 = "SELECT * FROM employee_personal_details e INNER JOIN department_details a ON e.dep_id=a.dep_id WHERE dep_name = '$department' ";

                        $employees = mysqli_query($connection,$query1);

                        while ($list = mysqli_fetch_array($employees)) {

                            echo "
";
                            echo "".$list['emp_fullName']."	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "<input type=\"text\" name=\"amount\" class=\"cal\" size=\"1\">	";
                            echo "	";
                            echo "	";

                        }
                    }
                    ?>

and this is my javascript code:

          $(document).ready(function () {

              $(".cal").each(function () {
                   $(this).keyup(function () {
                    //Initialize total to 0
                        var total = 0;
                         $(".cal").each(function () {

                            if (!isNaN(this.value) && this.value.length != 0 && this.value < 4) {
                              total += parseFloat(this.value);
                              precentage = (total/21)*100;
                         }
                    });

                    $('#sum').html(total);
                    $('#prec').html(precentage.toFixed(2));
               });
          });
     });

Body:
Here you go with a solution

$(document).ready(function () {
  $('.cal').keyup(function(){
    var sum = 0;
    var precentage = 0;
    $('.cal').each(function(){
      var curVal = parseFloat($(this).val());
      if(!isNaN(curVal) && curVal.length != 0 && curVal < 4){
        sum += curVal;
        precentage = (sum/21)*100;
      }
    });

    $('#sum').html(sum);
    $('#prec').html(precentage.toFixed(2));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">
<input type="text" name="amount" class="cal" size="1">

SUM: <div id="sum"></div>
Precentage: <div id="prec"></div>

Updated solution

$(document).ready(function () {
  $('.cal').keyup(function(){
    var sum = 0;
    var precentage = 0;
    $(this).closest('tr').find('td').each(function(){
      var curVal = parseFloat($(this).find('.cal').val());
      if(!isNaN(curVal) && curVal.length != 0 && curVal < 4){
        sum += curVal;
        precentage = (sum/21)*100;
      }
    });

    $(this).closest('tr').find('td').find('.sum').html(sum);
    $(this).closest('tr').find('td').find('.prec').html(precentage.toFixed(2));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td>
      SUM: <div class="sum"></div>
      Precentage: <div class="prec"></div>
    </td>
  </tr>
  <tr>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td><input type="text" name="amount" class="cal" size="1"></td>
    <td>
      SUM: <div class="sum"></div>
      Precentage: <div class="prec"></div>
    </td>
  </tr>
</table>

Hope this will help you.


问:
How to use a word at end of function signature?
I'm trying to write a delegate interface like this:

```<code>// This delegate is just a sample. It could be any delegate.
// What's important here is the third function's signature.
protocol MyViewDelegate {
    func myView(_ myView: MyView, didDoSomething something: String)
    func myView(_ myView: MyView, didDoAnotherThing thing: String at: Date)
    func myView(_ myView: MyView, didDoYetSomethingElse)
}
</code>```

However, the third function is invalid syntax. It's used to notify the delegate that some specific event happened, so the signature is important and I want to keep all function signatures consistent.

Question: What's the recommended signature for the third function?

答:
You are trying to give the delegate a choice of two kinds of thing that happened: said something, or asked user name. That sort of choice among possibilities, in Swift, is an enum:

```<code>enum WhatHappened {
    case didSaySomething(String)
    case didAskUserName
}
</code>```

Now write your method signature like this:

```<code>protocol MyViewDelegate {
    func myView(_ myView: MyView, _ whatHappened: WhatHappened)
}
</code>```

The method can be called by saying

```<code>myView(theView, .didSaySomething("hello"))
</code>```

or by saying

```<code>myView(theView, .didAskUserName)
</code>```

Body:
I'm trying to write a delegate interface like this:

// This delegate is just a sample. It could be any delegate.
// What's important here is the third function's signature.
protocol MyViewDelegate {
    func myView(_ myView: MyView, didDoSomething something: String)
    func myView(_ myView: MyView, didDoAnotherThing thing: String at: Date)
    func myView(_ myView: MyView, didDoYetSomethingElse)
}

However, the third function is invalid syntax. It's used to notify the delegate that some specific event happened, so the signature is important and I want to keep all function signatures consistent.

Question: What's the recommended signature for the third function?

Body:
You are trying to give the delegate a choice of two kinds of thing that happened: said something, or asked user name. That sort of choice among possibilities, in Swift, is an enum:

enum WhatHappened {
    case didSaySomething(String)
    case didAskUserName
}

Now write your method signature like this:

protocol MyViewDelegate {
    func myView(_ myView: MyView, _ whatHappened: WhatHappened)
}

The method can be called by saying

myView(theView, .didSaySomething("hello"))

or by saying

myView(theView, .didAskUserName)


问:
Why is this way of randomly generating a graph unfair?
My aim is to generate a directed graph of n vertices such that each vertex has an edge going out and an edge coming in.  I thought one way of doing this would be to put all the vertices in a pot and for the vertices to take turns shuffling it and pulling out entries -- so for example if vertex 1 pulls out vertex 3 then that means there will be an edge going from 1 to 3.  If a vertex pulls itself out of the pot, it just puts it back and reshuffles.  If at the end, the last vertex finds that the pot only contains itself, then we need to start over.  Here's my Kotlin code:

```<code>fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        for (vertex in 1 until n) {
            do {
                java.util.Collections.shuffle(pot)
            } while (pot[0] == vertex)
            result.put(vertex, pot.removeAt(0))
        }
        if (pot[0] != n) {
            result.put(n, pot.removeAt(0))
            return result
        }
        else {
            // The last vertex left in the pot is also the last one unassigned.  Try again...
        }
    }
}
</code>```

It seems to work.  However when testing I'm finding it comes out with some graphs more than others.  When n is 3 the only valid graphs are the cycles

```<code>{1=3, 2=1, 3=2}
{1=2, 2=3, 3=1}
</code>```

but I'm finding the first comes up twice as many times as the second:

```<code>fun main(args: Array<String>) {
    val n = 3
    val patternCounts = mutableMapOf<Map<Int, Int>, Int>()
    val trials = 10000
    (1..trials).forEach({
        val graph = generateGraph(n)
        patternCounts[graph] = patternCounts.getOrDefault(graph, 0) + 1
    })
    println(patternCounts)
}
</code>```

A run of this just now printed

```<code>{{1=3, 2=1, 3=2}=6669, {1=2, 2=3, 3=1}=3331}
</code>```

What am I missing?  And, is there a way to make this fair?

答:
What am I missing? And, is there a way to make this fair?

What you are missing is that your algrothim is unfair.

First, you need to know that software random number generator is not real random. It always make it seems to be fair, unlike real random.

Then, consider the following

```<code>java.util.Collections.shuffle(pot)
</code>```

give you 3 outcomes.

```<code>1, 2, 3
1, 3, 2
2, 1, 3
2, 3, 1
3, 1, 2
3, 2, 1
</code>```

If you remove your do-while condition and if condition, all of the outcome has similar count.

However, you do-while condition prevents position = value. The possible outcomes are

```<code>2, 1, 3
2, 3, 1
3, 1, 2
</code>```

Note that the distribution of the outcomes are NOT even. Consider the following:

```<code>When vertex == 1:
    case pot[0] == 1:
        reroll
    case pot[0] == 2:
        continue // 50%
    case pot[0] == 3:
        continue // 50%

If the result[0] == 2:
    When vertex == 2:
        case pot[0] == 1:
            continue // 25%
        case pot[0] == 3:
            continue // 25%

If the result[0] == 3:
    When vertex == 2:
        case pot[0] == 1:
            continue // 50%
        case pot[0] == 2:
            reroll

Result:
    2, 1, 3 (25%)
    2, 3, 1 (25%)
    3, 1, 2 (50%)
</code>```

Then, the if-condition DISCARD 2, 1, 3 (Not rerolling which is different from while loop. It started from scratch again. The remaining outcomes are

```<code>    2, 3, 1 (25%)
    3, 1, 2 (50%)
</code>```

(3, 1, 2):(2, 3, 1) is about 2:1 which matches your result.

Solution

```<code>fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    loop@ while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        // No need to shuffle evey position
        java.util.Collections.shuffle(pot)
        for (vertex in 1..n) {
            val value = pot[vertex-1]
            // if position == value, always start from scratch
            if (value == vertex)
                continue@loop
            result.put(vertex, value)
        }
        return result
    }
}
</code>```

Also, you should improve you math on probability and statistics before you doubt the number distribution of a random number generator.

Body:
My aim is to generate a directed graph of n vertices such that each vertex has an edge going out and an edge coming in.  I thought one way of doing this would be to put all the vertices in a pot and for the vertices to take turns shuffling it and pulling out entries -- so for example if vertex 1 pulls out vertex 3 then that means there will be an edge going from 1 to 3.  If a vertex pulls itself out of the pot, it just puts it back and reshuffles.  If at the end, the last vertex finds that the pot only contains itself, then we need to start over.  Here's my Kotlin code:

fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        for (vertex in 1 until n) {
            do {
                java.util.Collections.shuffle(pot)
            } while (pot[0] == vertex)
            result.put(vertex, pot.removeAt(0))
        }
        if (pot[0] != n) {
            result.put(n, pot.removeAt(0))
            return result
        }
        else {
            // The last vertex left in the pot is also the last one unassigned.  Try again...
        }
    }
}

It seems to work.  However when testing I'm finding it comes out with some graphs more than others.  When n is 3 the only valid graphs are the cycles

{1=3, 2=1, 3=2}
{1=2, 2=3, 3=1}

but I'm finding the first comes up twice as many times as the second:

fun main(args: Array<String>) {
    val n = 3
    val patternCounts = mutableMapOf<Map<Int, Int>, Int>()
    val trials = 10000
    (1..trials).forEach({
        val graph = generateGraph(n)
        patternCounts[graph] = patternCounts.getOrDefault(graph, 0) + 1
    })
    println(patternCounts)
}

A run of this just now printed

{{1=3, 2=1, 3=2}=6669, {1=2, 2=3, 3=1}=3331}

What am I missing?  And, is there a way to make this fair?

Body:
What am I missing? And, is there a way to make this fair?

What you are missing is that your algrothim is unfair.

First, you need to know that software random number generator is not real random. It always make it seems to be fair, unlike real random.

Then, consider the following

java.util.Collections.shuffle(pot)

give you 3 outcomes.

1, 2, 3
1, 3, 2
2, 1, 3
2, 3, 1
3, 1, 2
3, 2, 1

If you remove your do-while condition and if condition, all of the outcome has similar count.

However, you do-while condition prevents position = value. The possible outcomes are

2, 1, 3
2, 3, 1
3, 1, 2

Note that the distribution of the outcomes are NOT even. Consider the following:

When vertex == 1:
    case pot[0] == 1:
        reroll
    case pot[0] == 2:
        continue // 50%
    case pot[0] == 3:
        continue // 50%

If the result[0] == 2:
    When vertex == 2:
        case pot[0] == 1:
            continue // 25%
        case pot[0] == 3:
            continue // 25%

If the result[0] == 3:
    When vertex == 2:
        case pot[0] == 1:
            continue // 50%
        case pot[0] == 2:
            reroll

Result:
    2, 1, 3 (25%)
    2, 3, 1 (25%)
    3, 1, 2 (50%)

Then, the if-condition DISCARD 2, 1, 3 (Not rerolling which is different from while loop. It started from scratch again. The remaining outcomes are

    2, 3, 1 (25%)
    3, 1, 2 (50%)

(3, 1, 2):(2, 3, 1) is about 2:1 which matches your result.

Solution

fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    loop@ while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        // No need to shuffle evey position
        java.util.Collections.shuffle(pot)
        for (vertex in 1..n) {
            val value = pot[vertex-1]
            // if position == value, always start from scratch
            if (value == vertex)
                continue@loop
            result.put(vertex, value)
        }
        return result
    }
}

Also, you should improve you math on probability and statistics before you doubt the number distribution of a random number generator.


问:
Holoviews Dynamic Map with existing Pandas dataframe
I have a pandas dataframe that I read from a database, with a structure similar to

```<code>dt  t1  t2 val1 val2
12  A   C  12   33
13  A   B  42   39
14  T   C  12   09
</code>```

and I'm trying to generate a DynamicMap from the dataframe. The problem is that all examples for Dynamic Maps are for generating functions:

```<code>def gen_values(alpha, beta):
    return np.random.rand()* alpha +  beta

hv.DynamicMap(gen_values, kdims=['alpha', 'beta'])
</code>```

and so on. The problem is that I want to do something similar but with the existing dataframe, and if I try to pass it to the generating function I get an error of missing kdims:

```<code>def gen_from_pandas(col1, col2, filter_1, filter_2, df):
   df2 = df[(df[col1] == filter_1) & df[col2] == filter2]
   return hv.Curve(df2['dt'], df2['val1'])

hv.DynamicMap(gen_from_pandas, kdims=['col1', 'col2'])
</code>```

Is there a way to do it?

答:
You can simply omit ", df" from the argument list of gen_from_pandas, as long as you have defined df before defining that function.  You'll be able to refer to it in the enclosing namespace instead.

ETA: If you can't refer to the enclosing namespace, just make a closure:

```<code>df = pd.DataFrame(dict(dt=[12,13,14], t1=['A','A','T'], t2=['C','B','C'], val1=[12,42,12], val2=[33,39,9]))

class fngen(object):
    def __init__(self, df):
        self.df = df

    def __call__(self, column):
        return df[column]

fn = fngen(df)

fn("t1")
</code>```

Body:
I have a pandas dataframe that I read from a database, with a structure similar to

dt  t1  t2 val1 val2
12  A   C  12   33
13  A   B  42   39
14  T   C  12   09

and I'm trying to generate a DynamicMap from the dataframe. The problem is that all examples for Dynamic Maps are for generating functions:

def gen_values(alpha, beta):
    return np.random.rand()* alpha +  beta

hv.DynamicMap(gen_values, kdims=['alpha', 'beta'])

and so on. The problem is that I want to do something similar but with the existing dataframe, and if I try to pass it to the generating function I get an error of missing kdims:

def gen_from_pandas(col1, col2, filter_1, filter_2, df):
   df2 = df[(df[col1] == filter_1) & df[col2] == filter2]
   return hv.Curve(df2['dt'], df2['val1'])

hv.DynamicMap(gen_from_pandas, kdims=['col1', 'col2'])

Is there a way to do it?

Body:
You can simply omit ", df" from the argument list of gen_from_pandas, as long as you have defined df before defining that function.  You'll be able to refer to it in the enclosing namespace instead.

ETA: If you can't refer to the enclosing namespace, just make a closure:

df = pd.DataFrame(dict(dt=[12,13,14], t1=['A','A','T'], t2=['C','B','C'], val1=[12,42,12], val2=[33,39,9]))

class fngen(object):
    def __init__(self, df):
        self.df = df

    def __call__(self, column):
        return df[column]

fn = fngen(df)

fn("t1")


问:
driver.manage().window().maximize() issue with ChromeDriver 2.33
The release notes for ChromeDriver 2.33 says that ""Fixes a bug which caused Resizing/Positioning Window commands to fail on Chrome 62+" however this still seems to be an issue when i am using Chrome 62+ browser. Maximizing chrome window using chrome driver results in below exception. Does anyone know a solution please?

Another thing i noticed is, though i installed latest chromedriver (v2.33) from https://chromedriver.storage.googleapis.com/index.html?path=2.33/, the log printed below says Driver info: chromedriver=2.25.426923 !!

Exception in thread "main" org.openqa.selenium.WebDriverException:
  unknown error: cannot get automation extension from unknown error:
  page could not be found:
  chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=62.0.3202.62)   (Driver info:
  chromedriver=2.25.426923
  (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT
  10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information)

答: I believe there were some old chrome driver processes running in backend and same were being picked up when it was invoked via code. I deleted all processes instances, deleted old version of chrome driver, added the new 2.33 version and it worked. Thanks all for your suggestions.</p>


问:
angular wont reset form after ng-click?
My form won't reset after I do a ng-click, am I doing it right?

I can submit just fine, but the form will not reset, here is my log:

angular.js:12701 POST http://127.0.0.1:8000/auth/post 500 (Internal
  Server Error)

But my post submits fine, it just doesn't reset.

jsfiddle

https://jsfiddle.net/2fyynf6p/

main.js

```<code>var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.postform = "";

        });

    };

}]);
</code>```

html

```<code>            <form  name="postform" method="POST" novalidate>
                   {{ csrf_field() }}
                <div class="form-group">
                    <label for="post.title">Title</label>
                    <input ng-model="post.title"  class="form-control" type="text" name="title" placeholder="Enter a title" required/>
                </div>

                <div class="form-group">
                    <label for="post.title">Post</label>
                    <textarea ng-model="post.body" type="text" class="form-control" name="body" id="" cols="10" rows="5"></textarea>
                </div>

                <button id="eli-style-button" ng-click="addPost()" class="btn btn-primary" type="submit">Submit</button>
            </form>
</code>```

答:
solved it by doing this, still within the scope function, but outside of the http post .</p>

```<code>var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);

        });

        $scope.post.title = '';
        $scope.post.body = '';

    };

}]);
</code>```

Title: angular wont reset form after ng-click?

Body:
My form won't reset after I do a ng-click, am I doing it right?

I can submit just fine, but the form will not reset, here is my log:

angular.js:12701 POST http://127.0.0.1:8000/auth/post 500 (Internal
  Server Error)

But my post submits fine, it just doesn't reset.

jsfiddle

https://jsfiddle.net/2fyynf6p/

main.js

var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.postform = "";

        });

    };

}]);

html

            <form  name="postform" method="POST" novalidate>
                   {{ csrf_field() }}

                    Title
                    <input ng-model="post.title"  class="form-control" type="text" name="title" placeholder="Enter a title" required/>

                    Post
                    <textarea ng-model="post.body" type="text" class="form-control" name="body" id="" cols="10" rows="5"></textarea>

                <button id="eli-style-button" ng-click="addPost()" class="btn btn-primary" type="submit">Submit</button>
            </form>

Body:
solved it by doing this, still within the scope function, but outside of the http post .

var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);

        });

        $scope.post.title = '';
        $scope.post.body = '';

    };

}]);


问:
My array look like the following
In PHP, my array look like the following.

```<code>Array ([0] => Array ( [ReasonCode] => TS ) [1] => Array ( [ReasonCode] => TS3 ) [2] => Array ( [ReasonCode] => TS4 ) [3] => Array ( [ReasonCode] => TEST-OO1 ) [4] => Array ( [ReasonCode] => ROO1 ) ).
</code>```

But i want my array like the following Array(TS,TS3,TS4,TEST-001,ROO1).

答:
```<code>Let Your be   $reasonCode = Array(0 => Array ( 'ReasonCode' => "TS"),
                   1 => Array ( 'ReasonCode' => "TS3" ),
                   2 => Array ( 'ReasonCode' => "TS4"),
                   3 => Array ( 'ReasonCode' => "TEST-OO1"),
                   4 => Array ( 'ReasonCode' => "ROO1"));
    $result = [];
    foreach ($reasonCode as $reasonCodeKeys => $reasonCodeValue) {
        foreach ($reasonCodeValue as $reasonkey => $reasonValue) {
            $result[]=$reasonValue;
        }
    }

echo "```";
print_r($result);
echo "```";
exit;
</code>```

Title: My array look like the following

Body:
In PHP, my array look like the following.

Array ([0] => Array ( [ReasonCode] => TS ) [1] => Array ( [ReasonCode] => TS3 ) [2] => Array ( [ReasonCode] => TS4 ) [3] => Array ( [ReasonCode] => TEST-OO1 ) [4] => Array ( [ReasonCode] => ROO1 ) ).

But i want my array like the following Array(TS,TS3,TS4,TEST-001,ROO1).

Body:
Let Your be   $reasonCode = Array(0 => Array ( 'ReasonCode' => "TS"),
                   1 => Array ( 'ReasonCode' => "TS3" ),
                   2 => Array ( 'ReasonCode' => "TS4"),
                   3 => Array ( 'ReasonCode' => "TEST-OO1"),
                   4 => Array ( 'ReasonCode' => "ROO1"));
    $result = [];
    foreach ($reasonCode as $reasonCodeKeys => $reasonCodeValue) {
        foreach ($reasonCodeValue as $reasonkey => $reasonValue) {
            $result[]=$reasonValue;
        }
    }

echo "<pre>";
print_r($result);
echo "</pre>";
exit;


问:
how to create Plugin for Kibana 5.6.3
I want to create a plugin for kibana version 5.6.3,due to this i follow the link "https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#contributing-code",the github provider the source code of the latest version kibana 7.0.0 https://github.com/elastic/kibana .but i need the kibana version 5.6.3 to create a plugin, where I get the source code </p>

答:
Here is an SAO generater: https://github.com/elastic/template-kibana-plugin/

The video tutorial provided by Lax was created a couple weeks ago, and is up-to-date.

Title: how to create Plugin for Kibana 5.6.3


问:
Django haystack whoosh super slow
I have a simple setup with django-haystack and whoosh engine. A search yielding 19 objects took me 8 seconds. I used the django-debug-toolbar to determine that i had a bunch of repeated queries.

I then updated my search view to prefetch relations, so that duplicate queries would not happen:

```<code>class MySearchView(SearchView):
    template_name = 'search_results.html'
    form_class = SearchForm
    queryset = RelatedSearchQuerySet().load_all().load_all_queryset(
        models.Customer, models.Customer.objects.all().select_related('customer_number').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Contact, models.Contact.objects.all().select_related('customer')
    ).load_all_queryset(
        models.Account, models.Account.objects.all().select_related(
            'customer', 'account_number', 'main_contact', 'main_contact__customer'
        )
    ).load_all_queryset(
        models.Invoice, models.Invoice.objects.all().select_related(
            'customer', 'end_customer', 'customer__original', 'end_customer__original', 'quote_number', 'invoice_number'
        )
    ).load_all_queryset(
        models.File, models.File.objects.all().select_related('file_number', 'customer').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Import, models.Import.objects.all().select_related('import_number', 'customer').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Event, models.Event.objects.all().prefetch_related('customers', 'contracts', 'accounts', 'keywords')
    )
</code>```

But even then, the search still takes 5 seconds. I then used the profiler from django-debug-toolbar, which gave me this information:

From what I can tell, the issue lies in haystack/query:779::__getitem__, which is hit twice, each costing 1.5 seconds. I have glanced through the code in question, but cannot make sense of it. So where do I go from here?

答:
You say in the question:

I then updated my search view to prefetch relations […]

The code you present, though, does not use QuerySet.prefetch_related for most of them. Instead, your sample code uses QuerySet.select_related for most of them; this does not pre-fetch the objects.

The documentation for each of those methods is extensive and can help to decide which is correct for your case.

In particular, the QuerySet.prefetch_related documentation says:

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

Title: Django haystack whoosh super slow

Body:
I have a simple setup with django-haystack and whoosh engine. A search yielding 19 objects took me 8 seconds. I used the django-debug-toolbar to determine that i had a bunch of repeated queries.

I then updated my search view to prefetch relations, so that duplicate queries would not happen:

class MySearchView(SearchView):
    template_name = 'search_results.html'
    form_class = SearchForm
    queryset = RelatedSearchQuerySet().load_all().load_all_queryset(
        models.Customer, models.Customer.objects.all().select_related('customer_number').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Contact, models.Contact.objects.all().select_related('customer')
    ).load_all_queryset(
        models.Account, models.Account.objects.all().select_related(
            'customer', 'account_number', 'main_contact', 'main_contact__customer'
        )
    ).load_all_queryset(
        models.Invoice, models.Invoice.objects.all().select_related(
            'customer', 'end_customer', 'customer__original', 'end_customer__original', 'quote_number', 'invoice_number'
        )
    ).load_all_queryset(
        models.File, models.File.objects.all().select_related('file_number', 'customer').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Import, models.Import.objects.all().select_related('import_number', 'customer').prefetch_related(
            'keywords'
        )
    ).load_all_queryset(
        models.Event, models.Event.objects.all().prefetch_related('customers', 'contracts', 'accounts', 'keywords')
    )

But even then, the search still takes 5 seconds. I then used the profiler from django-debug-toolbar, which gave me this information:

From what I can tell, the issue lies in haystack/query:779::__getitem__, which is hit twice, each costing 1.5 seconds. I have glanced through the code in question, but cannot make sense of it. So where do I go from here?


问:
node app on azure occasionally redirecting to server.js
I have a Node.js (Express) app that is running on Azure App Service. Every once in a while, when I visit my domain, rather than executing the Node app, I will be taken to https://example.com/server.js. This doesn't happen often, but occasionally we'll have a user report that they can't get to our app and this ends up being the culprit.

To make matters worse, it's very hard, if not impossible, to reproduce. I have had some luck reproducing with a fresh install of a new browser, but not always.

I'm basically using the default web.config with a couple of added lines for HSTS/HTTPS. See below:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->

<configuration>
  <system.webServer>
    <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
    <webSocket enabled="false"/>
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add modules="iisnode" name="iisnode" path="server.js" verb="*"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?"/>
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>

        <!-- Redirect all HTTP to HTTPS -->
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)"/>
          <conditions>
            <add ignoreCase="true" input="{HTTPS}" pattern="off"/>
          </conditions>
          <action redirectType="Permanent" type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
        </rule>
      </rules>

      <outboundRules>
        <rule enabled="true" name="Add Strict-Transport-Security when HTTPS">
          <match pattern=".*" serverVariable="RESPONSE_Strict_Transport_Security"/>
          <conditions>
            <add ignoreCase="true" input="{HTTPS}" pattern="on"/>
          </conditions>
          <action type="Rewrite" value="max-age=31536000"/>
        </rule>
      </outboundRules>

    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough"/>

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
    -->
    <!--<iisnode watchedFiles="web.config;*.js"/>-->
  </system.webServer>
</configuration>
</code>```

Any suggestions on why this might be occurring?

答: I would recommend you install the extension named Redirect HTTP to HTTPS via the Azure portal rather than add a rule manually.

Body:
I have a Node.js (Express) app that is running on Azure App Service. Every once in a while, when I visit my domain, rather than executing the Node app, I will be taken to https://example.com/server.js. This doesn't happen often, but occasionally we'll have a user report that they can't get to our app and this ends up being the culprit.

To make matters worse, it's very hard, if not impossible, to reproduce. I have had some luck reproducing with a fresh install of a new browser, but not always.

I'm basically using the default web.config with a couple of added lines for HSTS/HTTPS. See below:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.webServer>

    <webSocket enabled="false"/>
    <handlers>

      <add modules="iisnode" name="iisnode" path="server.js" verb="*"/>
    </handlers>
    <rewrite>
      <rules>

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?"/>
        </rule>

        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>

        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)"/>
          <conditions>
            <add ignoreCase="true" input="{HTTPS}" pattern="off"/>
          </conditions>
          <action redirectType="Permanent" type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
        </rule>
      </rules>

      <outboundRules>
        <rule enabled="true" name="Add Strict-Transport-Security when HTTPS">
          <match pattern=".*" serverVariable="RESPONSE_Strict_Transport_Security"/>
          <conditions>
            <add ignoreCase="true" input="{HTTPS}" pattern="on"/>
          </conditions>
          <action type="Rewrite" value="max-age=31536000"/>
        </rule>
      </outboundRules>

    </rewrite>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough"/>

  </system.webServer>
</configuration>

Any suggestions on why this might be occurring?


问:
Customizing each element created by the `EditorFor` helper
The EditorFor helper can be used for automatically scaffolding a model if used as EditorFor(x=> x, new {htmlAttributes = new {@class = "x"}}). The question is that, since it automatically generates labels, fields, and validation messages, is there anyway to customize the styles and classes for each one of these elements in the anonymous type passed into this method (new { htmlAttributes = ..}) ?

答:
You have to use an EditorTemplate and the EditorFor helper will automatically render your model based on your template and you wouldn't need to rely on the htmlAttributes property for customizing your view. The advantage of this is that, your template can be reused over and over specially if it is for types such as DateTime, IFormFile, etc. You can refer to the following example:

```<code>UserModelTemplate.cshtml:
-------------------------
@model UserModel

<div class="form-group">
    <label class="hero-label">
         @Html.DisplayNameFor(m=> m.Username)
         <span class="text-danger">
            @Html.ValidationMessageFor(m=> m.Username)
         </span>
     </label>
     @Html.TextBoxFor(m=> m.Username, new { @class = "form-control"})
</div>
</code>```

And you can keep going like that. Once you are done developing your template, you can use it together with the EditorFor helper (Place it in the Shared folder, and maybe in a subfolder for better organization)

```<code>@Html.EditorFor(model=> model, "UserModelTemplate")
</code>```

Body:
You have to use an EditorTemplate and the EditorFor helper will automatically render your model based on your template and you wouldn't need to rely on the htmlAttributes property for customizing your view. The advantage of this is that, your template can be reused over and over specially if it is for types such as DateTime, IFormFile, etc. You can refer to the following example:

UserModelTemplate.cshtml:
-------------------------
@model UserModel

<div class="form-group">
    <label class="hero-label">
         @Html.DisplayNameFor(m=> m.Username)
         <span class="text-danger">
            @Html.ValidationMessageFor(m=> m.Username)
         </span>
     </label>
     @Html.TextBoxFor(m=> m.Username, new { @class = "form-control"})
</div>

And you can keep going like that. Once you are done developing your template, you can use it together with the EditorFor helper (Place it in the Shared folder, and maybe in a subfolder for better organization)

@Html.EditorFor(model=> model, "UserModelTemplate")