问:
ASP.NET Web Api to return XML and get XML
I have a controller which returns a data in json. I would like that method to return XML structure and get data back to XML structure.

I have added following code to WebApiConfig:

```<code>config.Routes.MapHttpRoute(
  name: "defaultapi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
  name: "VehicleApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
</code>```

Global.asax.cs

```<code>GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());
</code>```

答:
I found when using VBA MSXML2.XMLHTTP60 to make requests, setting the request header to Accept: application/xml would only return a blank xml object. To fix this, I added the following line to my WebApiConfig.cs file at the end of the Register function:

```<code>config.Formatters.Add(new XmlMediaTypeFormatter());
</code>```

Then my objects were serialized as expected.

Body:
I have a controller which returns a data in json. I would like that method to return XML structure and get data back to XML structure.

I have added following code to WebApiConfig:

config.Routes.MapHttpRoute(
  name: "defaultapi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
  name: "VehicleApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");

Global.asax.cs

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());

Body:
I found when using VBA MSXML2.XMLHTTP60 to make requests, setting the request header to Accept: application/xml would only return a blank xml object. To fix this, I added the following line to my WebApiConfig.cs file at the end of the Register function:

config.Formatters.Add(new XmlMediaTypeFormatter());

Then my objects were serialized as expected.


来源: stackexchange

问:
ssh "awk -F" '{print $2}' "
```<code>for VM in $VM_LIST;do
    ssh 10.0.0.163 "mkdir $ROOT$VM`date +%F`"
    ssh 10.0.0.163 'find -name "$VM.vmx" | xargs grep -r vmdk >/vmkd.list | cat /vmkd.list | awk -F\" '{print $2}' | while read list; do find -name "$list" ;done'
done
</code>```

I have a problem with this expression - awk -F\" '{print $2}', it broke my code

```<code>awk: cmd. line:1: Unexpected end of string
</code>```

What can I do with that???

答:
You could use here doc</p>

```<code>for VM in $VM_LIST;do
    ssh 10.0.0.163 /bin/sh <<"eocmd"
mkdir $ROOT$VM`date +%F`
find -name "$VM.vmx" |
    xargs grep -r vmdk >/vmkd.list |
    cat /vmkd.list |
    awk -F\" '{print $2}' |
    while read list; do
        find -name "$list"
    done
eocmd
done
</code>```

ContentLicense: CC BY-SA 3.0

Title: ssh "awk -F" '{print $2}' "

Body:
for VM in $VM_LIST;do
    ssh 10.0.0.163 "mkdir $ROOT$VM`date +%F`"
    ssh 10.0.0.163 'find -name "$VM.vmx" | xargs grep -r vmdk >/vmkd.list | cat /vmkd.list | awk -F\" '{print $2}' | while read list; do find -name "$list" ;done'
done

I have a problem with this expression - awk -F\" '{print $2}', it broke my code

awk: cmd. line:1: Unexpected end of string

What can I do with that???

Body:
You could use here doc

for VM in $VM_LIST;do
    ssh 10.0.0.163 /bin/sh <<"eocmd"
mkdir $ROOT$VM`date +%F`
find -name "$VM.vmx" |
    xargs grep -r vmdk >/vmkd.list |
    cat /vmkd.list |
    awk -F\" '{print $2}' |
    while read list; do
        find -name "$list"
    done
eocmd
done


问:
Output variables by "expect"
I use expect and already established an ssh connection.

I want to see the result of ls -1 /etc/folder/.

I tried

```<code>send "files=$(ls -1 /etc/folder/)"
put $files
</code>```

but failed.

How could I do this?

答:
The big problem you've got is that there are variables locally and variables on the remote system and they are not the same thing at all. While yes, it is possible to build systems which make variables (appear to be) shared automatically between systems, it most certainly does not happen by default. This is a conceptual thing that you must get right or you will not ever write correct code except by accident.

Apart from that, you have a lesser problem of that you're not sending the command correctly, and are not handling the result coming back. Assuming you know that the prompt on the remote system is just a $ and that the files don't ever start with that, you need to do this.

```<code># Note the \r; it is like pressing <Return> and is important!
send "ls -1 /etc/folder \r"
# Now we collect the output:
set files {}
expect {
    "$ " {
        puts $files
    }
    -re {^[^$].*$} {
        # This grabs a line that doesn't start with $ and adds it to the list
        lappend files $expect_out(0,string)
        # Now we go back to waiting for another line or the prompt
        exp_continue
    }
}
</code>```

And that's exactly how you do it. Yes, it does take quite a bit of code…

Title: Output variables by "expect"

Body:
I use expect and already established an ssh connection.

I want to see the result of ls -1 /etc/folder/.

I tried

send "files=$(ls -1 /etc/folder/)"
put $files

but failed.

How could I do this?

Body:
The big problem you've got is that there are variables locally and variables on the remote system and they are not the same thing at all. While yes, it is possible to build systems which make variables (appear to be) shared automatically between systems, it most certainly does not happen by default. This is a conceptual thing that you must get right or you will not ever write correct code except by accident.

Apart from that, you have a lesser problem of that you're not sending the command correctly, and are not handling the result coming back. Assuming you know that the prompt on the remote system is just a $ and that the files don't ever start with that, you need to do this.

# Note the \r; it is like pressing <Return> and is important!
send "ls -1 /etc/folder \r"
# Now we collect the output:
set files {}
expect {
    "$ " {
        puts $files
    }
    -re {^[^$].*$} {
        # This grabs a line that doesn't start with $ and adds it to the list
        lappend files $expect_out(0,string)
        # Now we go back to waiting for another line or the prompt
        exp_continue
    }
}

And that's exactly how you do it. Yes, it does take quite a bit of code…


问:
Python function scope
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

```<code>def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()
</code>```

答:
as said before, lists are mutable. If you pass a list and modify it, you do it everywhere.
This applies for all lists in fun0.

in fun2 you pass no lists and and therefore c is calculated within fun2, but not available on the outside.

I'm not sure about fun1, but i think you are overwriting c with a new variable that is not available on the outside as in fun2.

Title: Python function scope

Body:
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()


问:
Automatically passing own type to function call
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

```<code>class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}
</code>```

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

答:
There are a few attributes which might be helpful:

CallerMemberNameAttribute: the name of the calling method or property;

CallerFilePathAttribute: the file path where the calling member is in;

CallerLineNumberAttribute: the line number within the file.

As you see, there is no attribute for the class name, but with the file path you might achieve the same level of information.

How to use this? Decorate an argument in your logging method with the attribute (of course, using the correct type and default).

```<code>public static void LogMsg(string msg, [CallerMemberName] string callingMember = null)
{
     Print($"{callingMember}: {msg}");
}
</code>```

And just call:

```<code>LogMsg("hello!");
</code>```

Body:
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

Body:
There are a few attributes which might be helpful:

CallerMemberNameAttribute: the name of the calling method or property;

CallerFilePathAttribute: the file path where the calling member is in;

CallerLineNumberAttribute: the line number within the file.

As you see, there is no attribute for the class name, but with the file path you might achieve the same level of information.

How to use this? Decorate an argument in your logging method with the attribute (of course, using the correct type and default).

public static void LogMsg(string msg, [CallerMemberName] string callingMember = null)
{
     Print($"{callingMember}: {msg}");
}

And just call:

LogMsg("hello!");


问:
C# Entity Framework 6 - AutoMapper 6 - Collections/List - Add and Update works but removing item throws an error
As the title says I can add and update but when it comes to deleting I get an error.

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.

I understand that the Description in this case only gets a null foreign key but is never deleted. I have seen some examples where they suggest looping through every child item and delete them one by one. Imao I think there should be a better way. What I'm looking for is a solution with minimal impact and just tell EF to delete the entire item and not only null the foreign key.

https://stackoverflow.com/a/5540956/3850405

Using AutoMapper, AutoMapper.Collection and AutoMapper.Collection.EntityFramework.

Controller method:

```<code>public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    await iArticleRepository.UpdateAsync(updatedArticle);
    return Ok();
}
</code>```

Mapping:

```<code>Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

    cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();
</code>```

Viewmodels:

```<code>public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

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

Models:

```<code>public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}
</code>```

答:
Got a solution from this answer

https://stackoverflow.com/a/32983252/3850405

and this blog:

http://www.kianryan.co.uk/2013/03/orphaned-child/

Code:

```<code>public class Description: IEntity<int>
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    [Key, Column(Order = 1)]
    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}
</code>```

I can really recommend reading Mosh's answer about the difference between composition and aggregation since it will help you understand EF better.

Body:
As the title says I can add and update but when it comes to deleting I get an error.

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.

I understand that the Description in this case only gets a null foreign key but is never deleted. I have seen some examples where they suggest looping through every child item and delete them one by one. Imao I think there should be a better way. What I'm looking for is a solution with minimal impact and just tell EF to delete the entire item and not only null the foreign key.

https://stackoverflow.com/a/5540956/3850405

Using AutoMapper, AutoMapper.Collection and AutoMapper.Collection.EntityFramework.

Controller method:

public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    await iArticleRepository.UpdateAsync(updatedArticle);
    return Ok();
}

Mapping:

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

    cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();

Viewmodels:

public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}

Models:

public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}

Body:
Got a solution from this answer

https://stackoverflow.com/a/32983252/3850405

and this blog:

http://www.kianryan.co.uk/2013/03/orphaned-child/

Code:

public class Description: IEntity<int>
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    [Key, Column(Order = 1)]
    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}

I can really recommend reading Mosh's answer about the difference between composition and aggregation since it will help you understand EF better.


问:
print size of ".pdf" is not same as in ".ai"
this is the .pdf file

Hi, I created this image in illustrator, with A4 size and with exact scale measurement, and saved it to .pdf format.
Now I printed this pdf file, but the size is not exact in the print. (3mm is missing).Iam trying this for past three days,but not working.
Can anybody help?

.pictire of printed pdf in A4

答:
In Adobe Reader one can use the measure tool to verify that the dimensions still are correct. Thus, the problem occurs during printing.

When I tried to print your PDF the unmodified print dialog looked like this for me:

In particular the option "Shrink oversized pages" on the left by default was active which results in scaling down to 97%, see the right side.

If the same happens in your Adobe Reader installation, select "Actual Size" or "Custom Scale: 100%" instead.


答:
You can use System.Runtime.CompilerServices with it's CallerMemberNameAttribute

Here is example:

```<code>using System;
using System.Runtime.CompilerServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger.WriteLog("Hello");
        }

    }
    public class Logger
    {
        public static void WriteLog(string msg, [CallerMemberName] string methodName="")
        {
            Console.WriteLine("Method:{0}, Message: {1}",methodName,msg);
        }
    }
}
</code>```

Title: Automatically passing own type to function call

Body:
You can use System.Runtime.CompilerServices with it's CallerMemberNameAttribute

Here is example:

using System;
using System.Runtime.CompilerServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger.WriteLog("Hello");
        }

    }
    public class Logger
    {
        public static void WriteLog(string msg, [CallerMemberName] string methodName="")
        {
            Console.WriteLine("Method:{0}, Message: {1}",methodName,msg);
        }
    }
}


问:
Is there a way to hook a script into Django's test server, so that it executes on each reload?
I have certain files that I want to be static on production but want to be able to write dynamically during development. So I would like to be able to execute a script to accomplish this each time the test server reloads, so that changes I have made will be taken into account, and the file gets updated. Is there any way to hook into the autoreloader to do this, or is this something I would need to do manually?</p>

答:
You can add it to your settings.py which gets loaded on the devserver reload.

```<code># settings.py
# ...
if DEBUG:
    import your_function
    result = your_function()
    print(result)
</code>```

Body:
You can add it to your settings.py which gets loaded on the devserver reload.

# settings.py
# ...
if DEBUG:
    import your_function
    result = your_function()
    print(result)


问:
Prometheus alertmanager order of handling
I'm currently redesigning an existing alert configuration of alert manager. There's only a small issue, I don't understand alert manager fully.

Assume I have the following configuration;

```<code>routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

match_re:
  application:"(foo|bar)"
receiver: "hipchat-teamX"

match_re:
  application:"(barfoo.*)"
receiver: "hipchat-teamY"
</code>```

Then an alert is firing from Prometheus with the following values, application:"barfooOne"
severity:"warning"

To which receiver will the alert send? And why?

Does alert manager handle an up down structure?

And when do you decide to declare a new child of the route (routes)?

答:
I found an solution with some help of the developers at GitHub.

You may see the processing of the config in the following way, similar to an if statement with AND and OR declarations.

Alertmanager applies the config to a up-down, left-right principle. Where the up-down is similar to the OR statement you will use in a regular if statement.

When you're going from left to right, you could compare it with the AND statement in if commands.

Further you should keep in mind that when the first statement matches, and there are no 'AND' parts declared, alertmanager pushes the alert to the receiver without looking further for any other match. So in the example above, if prometheus fires an alert with the following labels {severity: "warning", application: "barfoo"}, the alert is sent to hipchat-teamX.

Note the following, the label value of application matches the route for hipchat-teamY. So why it isn't sent to that route? The answer is not that diffucult, it's because the first one matches, and there are no subroutes declared, so it will stop looking for any other match.

However, if the alertmanager has config like the code below, the alert will be sent to the receiver 'hipchat-teamY'.

```<code>routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamY"

match_re:
  application:"(foo|bar)"
receiver: "hipchat-teamX"

match_re:
  application:"(barfoo.*)"
receiver: "hipchat-teamY"
</code>```

To make it a bit more advanced, asume prometheus sends a new alert with the following labels {severity: "critical", application: "barfoo"}. With the following config, the alert is routed to hipchat-teamX.

And with the labels {severity: "critical", application: "foo"}, the alert is sent to hipchat-teamY.

```<code>routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamY"

  match_re:
    application:"(foo|bar)"
  receiver: "hipchat-teamX"

match:
  severity:"critical"
receiver: "hipchat-teamY"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamX"

  match_re:
    application:"(foo|bar)"
  receiver: "hipchat-teamY"
</code>```

I hope this explanation will help others who are experiencing the same issue or question.

Body:
I'm currently redesigning an existing alert configuration of alert manager. There's only a small issue, I don't understand alert manager fully.

Assume I have the following configuration;

routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

match_re:
  application:"(foo|bar)"
receiver: "hipchat-teamX"

match_re:
  application:"(barfoo.*)"
receiver: "hipchat-teamY"

Then an alert is firing from Prometheus with the following values, application:"barfooOne"
severity:"warning"

To which receiver will the alert send? And why?

Does alert manager handle an up down structure?

And when do you decide to declare a new child of the route (routes)?

Body:
I found an solution with some help of the developers at GitHub.

You may see the processing of the config in the following way, similar to an if statement with AND and OR declarations.

Alertmanager applies the config to a up-down, left-right principle. Where the up-down is similar to the OR statement you will use in a regular if statement.

When you're going from left to right, you could compare it with the AND statement in if commands.

Further you should keep in mind that when the first statement matches, and there are no 'AND' parts declared, alertmanager pushes the alert to the receiver without looking further for any other match. So in the example above, if prometheus fires an alert with the following labels {severity: "warning", application: "barfoo"}, the alert is sent to hipchat-teamX.

Note the following, the label value of application matches the route for hipchat-teamY. So why it isn't sent to that route? The answer is not that diffucult, it's because the first one matches, and there are no subroutes declared, so it will stop looking for any other match.

However, if the alertmanager has config like the code below, the alert will be sent to the receiver 'hipchat-teamY'.

routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamY"

match_re:
  application:"(foo|bar)"
receiver: "hipchat-teamX"

match_re:
  application:"(barfoo.*)"
receiver: "hipchat-teamY"

To make it a bit more advanced, asume prometheus sends a new alert with the following labels {severity: "critical", application: "barfoo"}. With the following config, the alert is routed to hipchat-teamX.

And with the labels {severity: "critical", application: "foo"}, the alert is sent to hipchat-teamY.

routes:

match:
  severity:"warning"
receiver: "hipchat-teamX"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamY"

  match_re:
    application:"(foo|bar)"
  receiver: "hipchat-teamX"

match:
  severity:"critical"
receiver: "hipchat-teamY"

  routes:
  match_re:
    application:"(barfoo.*)"
  receiver: "hipchat-teamX"

  match_re:
    application:"(foo|bar)"
  receiver: "hipchat-teamY"

I hope this explanation will help others who are experiencing the same issue or question.


问:
How to work out total headcount per Month and Year using two date columns?
I have a table called Staff_Starters (https://www.dropbox.com/s/khowqfgytc6fvq8/data.csv?dl=0) which is connected to a Date dimension.

Is it possible to create a calculated column or measure in Staff_Starters which counts everyone that has a DateEmployed & stops counting going forward when it has a Termination_Date.

The formula would count individual multiple time until their end date is not equal to current date.

I currently have a table called Staff_Starterts with the main columns:

StaffID

FullName

DateEmployed

Termination_Date

Team Member

Status

Practice

Region

Cluster

Level

[Starters, Leavers & Nett][1]

The formula used: Headcount Movement = CALCULATE(
  COUNTROWS(Staff),
  FILTER(Staff,
  AND(Staff[Date Employed]<=MIN(Date_Dim[Calendar_Date]),
      Staff[Termination_Date]>=MAX(Date_Dim[Calendar_Date]))))

答:
```<code>Count = CALCULATE(
  COUNTROWS(data),
  FILTER(data,
      AND(data[Date Employed]<MIN('Calendar'[Date]),
          data[TerminationDate]>MAX('Calendar'[Date])
      )
  )
)
</code>```

Results in

```<code>Date        Count
2017-01-01  85
2017-02-01  74
2017-03-01  58
2017-04-01  37
</code>```

Edit: In response to a comment, explanation follows. (quotes from msdn)

CALCULATE:

Evaluates an expression in a context that is modified by the specified filters

COUNTROWS: (obvious, but keeping for completeness)

counts the number of rows in the specified table, or in a table defined by an expression

FILTER:

Returns a table that represents a subset of another table or expression.

AND:

Checks whether both arguments are TRUE.

```<code>AND(data[Date Employed]<MIN('Calendar'[Date]),
</code>```

Includes only entries with Date Employed before the start of current selected period.

```<code>    data[TerminationDate]>MAX('Calendar'[Date])
</code>```

Includes only entries with TerminationDate after the end of current selected period.

This should be enough to adapt the measure to count "leavers", "starters" and so on, as long as you can define it in terms of comparing start, termination and selected period dates.

Body:
Count = CALCULATE(
  COUNTROWS(data),
  FILTER(data,
      AND(data[Date Employed]<MIN('Calendar'[Date]),
          data[TerminationDate]>MAX('Calendar'[Date])
      )
  )
)

Results in

Date        Count
2017-01-01  85
2017-02-01  74
2017-03-01  58
2017-04-01  37

Edit: In response to a comment, explanation follows. (quotes from msdn)

CALCULATE:

Evaluates an expression in a context that is modified by the specified filters

COUNTROWS: (obvious, but keeping for completeness)

counts the number of rows in the specified table, or in a table defined by an expression

FILTER:

Returns a table that represents a subset of another table or expression.

AND:

Checks whether both arguments are TRUE.

AND(data[Date Employed]<MIN('Calendar'[Date]),

Includes only entries with Date Employed before the start of current selected period.

    data[TerminationDate]>MAX('Calendar'[Date])

Includes only entries with TerminationDate after the end of current selected period.

This should be enough to adapt the measure to count "leavers", "starters" and so on, as long as you can define it in terms of comparing start, termination and selected period dates.


问:
How to set some spaces before a link without moving the link position?
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  Click me!
</div></code>```

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

答:
add margin-left:-5px; to your hover class

.container {
  width: 100%;

}
.container:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    margin-left:-5px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
   Click me!
</div></code>```

Body:
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}

  Click me!

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

Body:
add margin-left:-5px; to your hover class

.container {
  width: 100%;

}
.container:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    margin-left:-5px;
  }

<div class='container'>
   <a href='#'>Click me!</a>
</div>


问:
Read .mat files from Unix shell
Is there a way to read .mat files from the UNIX command line shell?

Such as cat mymat.mat ?

I am aware of the possibilities to load it in MATLAB or python, but these are not available for me atm.

答: No. .mat-files are saved in a binary format. You will not be able to interpret their content from the UNIX shell.</p>

Title: Read .mat files from Unix shell


问:
How can I check if the user char input is contained in 2 Strings?
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

```<code>private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}
</code>```

I tried using .indexOf() today, which I have here with this while loop:

```<code>while((a == 0 && b == 0) || (c == 0 && d ==0)){
</code>```

And these variables:

```<code>a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);
</code>```

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

答:
Use regex!
Don't iterate on a string to identify patterns.

Example:

```<code>Pattern pattern = Pattern.compile("<your string/char>");
boolean containsInFrisrt  = pattern.matcher(str1).matches();
boolean containsInSeconds = pattern.matcher(str2).matches();
</code>```

Body:
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}

I tried using .indexOf() today, which I have here with this while loop:

while((a == 0 && b == 0) || (c == 0 && d ==0)){

And these variables:

a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

Body:
Use regex!
Don't iterate on a string to identify patterns.

Example:

Pattern pattern = Pattern.compile("<your string/char>");
boolean containsInFrisrt  = pattern.matcher(str1).matches();
boolean containsInSeconds = pattern.matcher(str2).matches();


问:
Appending a div onclick
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button></code>```

答:
Easy to fix by adding a container.

This should do the trick:

$(".appendbtn").click(function () {
   $("#divcontainer").append('
The div that should be appended
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div id="divcontainer">
  <div class="appendme">The div that should be appended</div>
</div>
<button class="appendbtn" type="button">Click to append</button></code>```

Title: Appending a div onclick

Body:
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});

The div that should be appended

<button class="appendbtn" type="button">Click to append</button>

Body:
Easy to fix by adding a container.

This should do the trick:

$(".appendbtn").click(function () {
   $("#divcontainer").append('<div class="appendme">The div that should be appended</div>');
});

<script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div id="divcontainer">
  <div class="appendme">The div that should be appended</div>
</div>
<button class="appendbtn" type="button">Click to append</button>


问:
Hide/Show an image drawn with Graphics
I have multiple images drawn with Graphics. How can I make them appear and disappear using a JCheckBox ? </p>

```<code>private void drawImages(int index) {
   Graphics g = mNew.getGraphics();
   int x = index % this.width;
   int y = index / this.width;
   g.drawImage(imageLabelPixel.get(idImage-1), x, y, 100, 100, null);
}
</code>```

答:
You wouldn't use graphics to draw something on the screen you want to remove. Graphics just renders it on the screen along with all the other graphics you have drawn, It doesn't keep track of components

Your options are to add an action event to your checkbox and repaint the screen from scratch not drawing the image, or to just use a Label to draw the image and set it to invisible when the box is checked

Title: Hide/Show an image drawn with Graphics

Body:
I have multiple images drawn with Graphics. How can I make them appear and disappear using a JCheckBox ?

private void drawImages(int index) {
   Graphics g = mNew.getGraphics();
   int x = index % this.width;
   int y = index / this.width;
   g.drawImage(imageLabelPixel.get(idImage-1), x, y, 100, 100, null);
}


问:
replace string from tibble with part of that string
I have searched a lot of regex answers here, but can't find the solution to this kind of problem.

My dataset is a tibble with wikipedia links:

```<code>library(tidytext)
library(stringr)
text.raw <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."
</code>```

I'm trying to clean up my text from the links.
This:

```<code>str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])")
# [1] "Duits"     "architect"
</code>```

Selects the words i need from between the brackets.

This:

```<code>str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# [1] "Berthold Speer was een Duits Duits."
</code>```

works as expected, but not quite what i need. This:

```<code>str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# Error: `replacement` must be a character vector
</code>```

gives an error where i expected "Berthold Speer was een Duits architect"

Currently my code looks something like this:

```<code>text.clean <- data_frame(text = text.raw) %>%
  mutate(text = str_replace_all(text, "\\[\\[.*?\\]\\]", str_extract_all(text, "[a-zA-Z\\s]+(?=\\])")))
</code>```

I hope someone knows a solution, or can point me to a duplicate question if there exists one. My desired output is "Berthold Speer was een Duits architect".

答:
You may use a single gsub operation

```<code>text <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."
gsub("\\[{2}(?:[^]|]*\\|)?([^]]*)]{2}", "\\1", text)
</code>```

See the  online R demo.

The pattern will match

\\[{2} - two [ symbols

(?:[^]|]*\\|)? - an optional sequence matching

[^]|]* - zero or more chars other than ] and |

\\| - a pipe symbol

([^]]*) - Group 1: zero or more chars other than ]

]{2} - two ] symbols.

Body:
I have searched a lot of regex answers here, but can't find the solution to this kind of problem.

My dataset is a tibble with wikipedia links:

library(tidytext)
library(stringr)
text.raw <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."

I'm trying to clean up my text from the links.
This:

str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])")
# [1] "Duits"     "architect"

Selects the words i need from between the brackets.

This:

str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# [1] "Berthold Speer was een Duits Duits."

works as expected, but not quite what i need. This:

str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# Error: `replacement` must be a character vector

gives an error where i expected "Berthold Speer was een Duits architect"

Currently my code looks something like this:

text.clean <- data_frame(text = text.raw) %>%
  mutate(text = str_replace_all(text, "\\[\\[.*?\\]\\]", str_extract_all(text, "[a-zA-Z\\s]+(?=\\])")))

I hope someone knows a solution, or can point me to a duplicate question if there exists one. My desired output is "Berthold Speer was een Duits architect".

Body:
You may use a single gsub operation

text <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."
gsub("\\[{2}(?:[^]|]*\\|)?([^]]*)]{2}", "\\1", text)

See the  online R demo.

The pattern will match

\\[{2} - two [ symbols

(?:[^]|]*\\|)? - an optional sequence matching

[^]|]* - zero or more chars other than ] and |

\\| - a pipe symbol

([^]]*) - Group 1: zero or more chars other than ]

]{2} - two ] symbols.


问:
How do you write an error message when an Ajax call is not successful in JavaScript?
I would like to display an error message if my Ajax call is unsuccessful. Simple enough but I cannot modify the Ajax function. I created an onClick listener that does a few things when my AJAX call is successful. I would just like to do something when the call is unsuccessful.

So If I decide to add:

```<code> if (xhr.status !== 200) {
   //Error Message here
   }
</code>```

Where would it be placed?

JSFiddle Example Here

My html is:

```<code><div id="test-form">
      <h2>Add a User:</h2>
      <label for="Username:">
       <input id="username" type="text" name="username" placeholder="Type username here">
     </label>

      <label for="Email:">
      <span id='result'></span>
      <input id="email" type="email" name="email" placeholder="email">
      </label>
      <button id="myButton">add user</button>
      <h2 class="clear">Users:</h2>
      <ul id="users"></ul>
    </div>
</code>```

My code is:

```<code> var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '<li>' + username +'</li>';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {

        message.add("hide");
      }

    }

    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };
</code>```

答:
Without modifying the function addUser(), the seemingly only possible way to do this would be modifying the XMLHttpRequest prototype, as suggested by this answer, to add an event listener for the readystatechange event (using addEventListener()). Also, the onerror function could be overridden to detect when an error causes an XMLHttpRequest transaction to fail.

Bear in mind that would affect ALL XMLHttpRequests on the page!

```<code>var lastResponseCode, oldSendFunction;
// store the native send()
oldSendFunction = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function() {
    //subscribe to ready state change events
    this.addEventListener("readystatechange", function(readyEvent) {
        //store the response code, to be checked later
        lastResponseCode = readyEvent.target.status;
    });
    // call the native send()
    oldSendFunction.apply(this, arguments);
}
function onSuccess(result) {
    if (lastResponseCode == 200) {
        //last request was successful
        //...
    }
    else {
         //other response was received - could have been 2xx,3xx,4xx,5xx
    }
}
</code>```

This is saved in this updated plunker but it seems unlikely that will yield a response code other than 200. To test with failing XHR requests, try this PHPfiddle, where every other XHR request will yield a response code of 500.

Body:
I would like to display an error message if my Ajax call is unsuccessful. Simple enough but I cannot modify the Ajax function. I created an onClick listener that does a few things when my AJAX call is successful. I would just like to do something when the call is unsuccessful.

So If I decide to add:

 if (xhr.status !== 200) {
   //Error Message here
   }

Where would it be placed?

JSFiddle Example Here

My html is:

Add a User:

       <input id="username" type="text" name="username" placeholder="Type username here">

      <input id="email" type="email" name="email" placeholder="email">

      <button id="myButton">add user</button>

Users:

My code is:

 var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '
' + username +'
';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {

        message.add("hide");
      }

    }

    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };

Body:
Without modifying the function addUser(), the seemingly only possible way to do this would be modifying the XMLHttpRequest prototype, as suggested by this answer, to add an event listener for the readystatechange event (using addEventListener()). Also, the onerror function could be overridden to detect when an error causes an XMLHttpRequest transaction to fail.

Bear in mind that would affect ALL XMLHttpRequests on the page!

var lastResponseCode, oldSendFunction;
// store the native send()
oldSendFunction = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function() {
    //subscribe to ready state change events
    this.addEventListener("readystatechange", function(readyEvent) {
        //store the response code, to be checked later
        lastResponseCode = readyEvent.target.status;
    });
    // call the native send()
    oldSendFunction.apply(this, arguments);
}
function onSuccess(result) {
    if (lastResponseCode == 200) {
        //last request was successful
        //...
    }
    else {
         //other response was received - could have been 2xx,3xx,4xx,5xx
    }
}

This is saved in this updated plunker but it seems unlikely that will yield a response code other than 200. To test with failing XHR requests, try this PHPfiddle, where every other XHR request will yield a response code of 500.


问:
Ionic 2 video ad plugin
I`m trying to find some good plugin for Ad showing ( videos ) for ionic2. I've tried with https://github.com/cranberrygame/cordova-plugin-ad-adcolony but I can't adjust it to work with ionic2 and angular2. I've also reviewed AdMob , which is ionic2 plugin , but video ads are not supported , as I read (only banners) . Can you please advise me what should I use and how , for my ionic2 app. Thanks.

By the way , when I'm trying to run adcolony this way  window.plugins.adcolony.showIntersitialAd() with the HTML below

```<code><button ion-button (click)="window.plugins.adcolony.showInterstitialAd();">showInterstitialAd</button>
</code>```

it returns

HomePage.html:15 ERROR TypeError: Cannot read property 'plugins' of undefined

and when I'm trying to run it like this

```<code><button ion-button (click)="window.adcolony.showInterstitialAd();">showInterstitialAd</button>
</code>```

it returns the following error:

```<code>HomePage.html:15 ERROR TypeError: Cannot read property 'adcolony' of undefined
</code>```

any help will be appreciated , thanks :)

By the way , I`m testing the app through https://apps.ionic.io/apps

答:
Try with this plugin: https://github.com/appfeel/admob-google-cordova

```<code>cordova plugin add cordova-admob
</code>```

Notice that you have to wait for interstitial to be loaded and also is a good idea to disable interstitial loading when your app is in background, as there is a delay between the moment you request an interstitial and the moment you show it:

```<code><button ion-button (click)="tryToShowInterstitial();">showInterstitialAd</button>
</code>```

And in your javascript code:

```<code>var isAppForeground = true;
var isInterstitialAvailable = false;

function tryToShowInterstitial() {
    if (isInterstitialAvailable) {
        admob.showInterstitialAd();
    } else {
        // Do your button action here when there are no ads to show
    }
}

function onAdLoaded(e) {
  if (isAppForeground) {
    if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
      isInterstitialAvailable = true;
    }
  }
}

function onAdClosed(e) {
  if (isAppForeground) {
    if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
      // Would you like to prepare next interstitial?
      setTimeout(admob.requestInterstitialAd, 1);
      isInterstitialAvailable = false;
    }
  }
}

function onPause() {
  if (isAppForeground) {
    admob.destroyBannerView();
    isAppForeground = false;
  }
}

function onResume() {
  if (!isAppForeground) {
    setTimeout(admob.createBannerView, 1);
    setTimeout(admob.requestInterstitialAd, 1);
    isAppForeground = true;
  }
}

// optional, in case respond to events
function registerAdEvents() {
  document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
  document.addEventListener(admob.events.onAdClosed, onAdClosed);

  document.addEventListener("pause", onPause, false);
  document.addEventListener("resume", onResume, false);
}

function initAds() {
  if (admob) {
    var adPublisherIds = {
      ios : {
        banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
        interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
      },
      android : {
        banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
        interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
      }
    };

    var admobid = (/(android)/i.test(navigator.userAgent)) ? adPublisherIds.android : adPublisherIds.ios;

    admob.setOptions({
      publisherId:          admobid.banner,
      interstitialAdId:     admobid.interstitial,
      autoShowInterstitial: false
    });

    registerAdEvents();

  } else {
    alert('AdMobAds plugin not ready');
  }
}

function onDeviceReady() {
  document.removeEventListener('deviceready', onDeviceReady, false);
  initAds();

  // display a banner at startup
  admob.createBannerView();

  // request an interstitial
  admob.requestInterstitialAd();
}

document.addEventListener("deviceready", onDeviceReady, false);
</code>```

Title: Ionic 2 video ad plugin

Body:
I`m trying to find some good plugin for Ad showing ( videos ) for ionic2. I've tried with https://github.com/cranberrygame/cordova-plugin-ad-adcolony but I can't adjust it to work with ionic2 and angular2. I've also reviewed AdMob , which is ionic2 plugin , but video ads are not supported , as I read (only banners) . Can you please advise me what should I use and how , for my ionic2 app. Thanks.

By the way , when I'm trying to run adcolony this way  window.plugins.adcolony.showIntersitialAd() with the HTML below

<button ion-button (click)="window.plugins.adcolony.showInterstitialAd();">showInterstitialAd</button>

it returns

HomePage.html:15 ERROR TypeError: Cannot read property 'plugins' of undefined

and when I'm trying to run it like this

<button ion-button (click)="window.adcolony.showInterstitialAd();">showInterstitialAd</button>

it returns the following error:

HomePage.html:15 ERROR TypeError: Cannot read property 'adcolony' of undefined

any help will be appreciated , thanks :)

By the way , I`m testing the app through https://apps.ionic.io/apps

Body:
Try with this plugin: https://github.com/appfeel/admob-google-cordova

cordova plugin add cordova-admob

Notice that you have to wait for interstitial to be loaded and also is a good idea to disable interstitial loading when your app is in background, as there is a delay between the moment you request an interstitial and the moment you show it:

<button ion-button (click)="tryToShowInterstitial();">showInterstitialAd</button>

And in your javascript code:

var isAppForeground = true;
var isInterstitialAvailable = false;

function tryToShowInterstitial() {
    if (isInterstitialAvailable) {
        admob.showInterstitialAd();
    } else {
        // Do your button action here when there are no ads to show
    }
}

function onAdLoaded(e) {
  if (isAppForeground) {
    if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
      isInterstitialAvailable = true;
    }
  }
}

function onAdClosed(e) {
  if (isAppForeground) {
    if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
      // Would you like to prepare next interstitial?
      setTimeout(admob.requestInterstitialAd, 1);
      isInterstitialAvailable = false;
    }
  }
}

function onPause() {
  if (isAppForeground) {
    admob.destroyBannerView();
    isAppForeground = false;
  }
}

function onResume() {
  if (!isAppForeground) {
    setTimeout(admob.createBannerView, 1);
    setTimeout(admob.requestInterstitialAd, 1);
    isAppForeground = true;
  }
}

// optional, in case respond to events
function registerAdEvents() {
  document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
  document.addEventListener(admob.events.onAdClosed, onAdClosed);

  document.addEventListener("pause", onPause, false);
  document.addEventListener("resume", onResume, false);
}

function initAds() {
  if (admob) {
    var adPublisherIds = {
      ios : {
        banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
        interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
      },
      android : {
        banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
        interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
      }
    };

    var admobid = (/(android)/i.test(navigator.userAgent)) ? adPublisherIds.android : adPublisherIds.ios;

    admob.setOptions({
      publisherId:          admobid.banner,
      interstitialAdId:     admobid.interstitial,
      autoShowInterstitial: false
    });

    registerAdEvents();

  } else {
    alert('AdMobAds plugin not ready');
  }
}

function onDeviceReady() {
  document.removeEventListener('deviceready', onDeviceReady, false);
  initAds();

  // display a banner at startup
  admob.createBannerView();

  // request an interstitial
  admob.requestInterstitialAd();
}

document.addEventListener("deviceready", onDeviceReady, false);


问:
FTP/ BlobStorage Trigger to Azure Function App / Logic App
Is there a trigger that can detect or fire an Azure Logic App or an Azure Function app when a new file is added or existing file is modified in my Azure FTP or BlobStorage
Thanks in advance</p>

答:
Yes, both triggers are supported for Function Apps:

FTP trigger is supported by Azure Functions External File bindings

Blob trigger is supported by Azure Functions Blob storage bindings


问:
Python - test a property throws exception
Given:

```<code>def test_to_check_exception_is_thrown(self):
    # Arrange
    c = Class()
    # Act and Assert
    self.assertRaises(NameError, c.do_something)
</code>```

If do_something throws an exception the test passes.

But I have a property, and when I replace c.do_something with c.name = "Name" I get an error about my Test Module not being imported and Eclipse highlights the equals symbol.

How do I test a property throws an exception?

Edit:

setattr and getattr are new to me. They've certainly helped in this case, thanks.

答:
As @interjay stated, it is expecting a callable, but you don't really need to define a named function for this. A lambda will do it:</p>
```<code>self.assertRaises(SomeException, lambda: my_instance.some_property)
</code>```

Body:
Given:

def test_to_check_exception_is_thrown(self):
    # Arrange
    c = Class()
    # Act and Assert
    self.assertRaises(NameError, c.do_something)

If do_something throws an exception the test passes.

But I have a property, and when I replace c.do_something with c.name = "Name" I get an error about my Test Module not being imported and Eclipse highlights the equals symbol.

How do I test a property throws an exception?

Edit:

setattr and getattr are new to me. They've certainly helped in this case, thanks.

Body:
As @interjay stated, it is expecting a callable, but you don't really need to define a named function for this. A lambda will do it:

self.assertRaises(SomeException, lambda: my_instance.some_property)

ContentLicense: CC BY-SA 4.0


问:
How Google App Engine limit Python?
Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.

Shared hosting also do it in some way?

答:
IMO it's not a standard python, but a version specifically patched for app engine. In other words you can think more or less like an "higher level" VM that however is not emulating x86 instructions but python opcodes (if you don't know what they are try writing a small function named "foo" and the doing "import dis; dis.dis(foo)" you will see the python opcodes that the compiler produced).

By patching python you can impose to it whatever limitations you like. Of course you've however to forbid the use of user supplied C/C++ extension modules as a C/C++ module will have access to everything the process can access.

Using such a virtual environment you're able to run safely python code without the need to use a separate x86 VM for every instance.

ContentLicense: CC BY-SA 2.5

Title: How Google App Engine limit Python?


问:
Getting StaleElementReferenceException while trying print the link names
I'm trying to print first 5 pages links displayed in google search.. But getting StateElementReferenceException Not sure which one went wrong.. </p>

```<code>    public class GoogleCoInTest {

    static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();
        List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));

        for(int i=0;i<5;i++){
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();

        }
    }

    public static void printLinksName() throws InterruptedException{

        List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
        System.out.println(allLinks.size());

        //print all list
        for(int i=0;i<allLinks.size();i++){
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

        }
    }
}
</code>```

<p>it prints fine till 2nd page , but there after I am getting </p>

```<code>Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: The element reference of <a class="fl"> stale: either the element is no longer attached to the DOM or the page has been refreshed
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
</code>```

答:
A couple of things:

Your script prints the result from the first 2 pages as expected.

When you call printLinksName() for the first time it works.

Next, you are storing the 10 PageNumbers in a Generic List of type WebElement.

First time within the for() loop you are clicking on the WebElement of Page 2 and then printing all the links by calling printLinksName().

While you are in the second iteration within for() loop, the reference of List<WebElement> fiveLinks is lost as the DOM have changed. Hence, you see StaleElementReferenceException.

Solution

A simple solution to avoid StaleElementReferenceException would be to move the line of code List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a")); with in the for() loop. So your code block will look like:

```<code>    import java.util.List;
    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class Q44970712_stale
    {

        static WebDriver driver = null;

        public static void main(String[] args)  throws InterruptedException
        {
        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();

        for(int i=0;i<5;i++)
        {
            List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();
        }
        }

        public static void printLinksName() throws InterruptedException
        {
            List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
            System.out.println(allLinks.size());

            //print all list
            for(int i=0;i<allLinks.size();i++)
            {
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

            }
        }

    }
</code>```

Note: In this simple solution when you finish printing the second page, next when you will create List<WebElement> fiveLinks through xpath with .//*[@id='nav']/tbody/tr/td/a for second time, Page 1  is the first element which gets stored in the fiveLinks List. Hence you may be again redirected to Page 1. To avoid that you may consider to take help of xpath with proper indexing.

Body:
I'm trying to print first 5 pages links displayed in google search.. But getting StateElementReferenceException Not sure which one went wrong..

    public class GoogleCoInTest {

    static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();
        List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));

        for(int i=0;i<5;i++){
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();

        }
    }

    public static void printLinksName() throws InterruptedException{

        List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
        System.out.println(allLinks.size());

        //print all list
        for(int i=0;i<allLinks.size();i++){
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

        }
    }
}

it prints fine till 2nd page , but there after I am getting

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: The element reference of  stale: either the element is no longer attached to the DOM or the page has been refreshed
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html

Body:
A couple of things:

Your script prints the result from the first 2 pages as expected.

When you call printLinksName() for the first time it works.

Next, you are storing the 10 PageNumbers in a Generic List of type WebElement.

First time within the for() loop you are clicking on the WebElement of Page 2 and then printing all the links by calling printLinksName().

While you are in the second iteration within for() loop, the reference of List<WebElement> fiveLinks is lost as the DOM have changed. Hence, you see StaleElementReferenceException.

Solution

A simple solution to avoid StaleElementReferenceException would be to move the line of code List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a")); with in the for() loop. So your code block will look like:

    import java.util.List;
    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class Q44970712_stale
    {

        static WebDriver driver = null;

        public static void main(String[] args)  throws InterruptedException
        {
        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();

        for(int i=0;i<5;i++)
        {
            List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();
        }
        }

        public static void printLinksName() throws InterruptedException
        {
            List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
            System.out.println(allLinks.size());

            //print all list
            for(int i=0;i<allLinks.size();i++)
            {
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

            }
        }

    }

Note: In this simple solution when you finish printing the second page, next when you will create List<WebElement> fiveLinks through xpath with .//*[@id='nav']/tbody/tr/td/a for second time, Page 1  is the first element which gets stored in the fiveLinks List. Hence you may be again redirected to Page 1. To avoid that you may consider to take help of xpath with proper indexing.


问:
Sql Query results to CSV to a specified file path after stored procedure execution
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

```<code>EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1
</code>```

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

答:
```<code>bcp "SELECT Col1,Col2,Col3 FROM MyDatabase.dbo.MyTable" queryout "D:\MyTable.csv" -c -t , -S SERVERNAME -T
</code>```

docs

Body:
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

Body:
bcp "SELECT Col1,Col2,Col3 FROM MyDatabase.dbo.MyTable" queryout "D:\MyTable.csv" -c -t , -S SERVERNAME -T

docs


问:
Finding average of data within a certain range
How do I find the average of data set within a certain range? Specifically I am looking to find the average for a data set for all data points that are within one standard deviations of the original average. Here is an example:

```<code>Student_ID  Test_Scores
1           3
1           20
1           30
1           40
1           50
1           60
1           95
</code>```

Average = 42.571

Standard Deviation = 29.854

I want to find all data points that are within one standard deviation of this original average, so within the range (42.571-29.854)<=Data<=(42.571+29.854). And from here I want to recalculate a new average.

So my desired data set is:

```<code>Student_ID  Test_Scores
1           20
1           30
1           40
1           50
1           60
</code>```

My desired new average is: 40

Here is my following SQL code and it didn't yield my desired result:

```<code>SELECT
    Student_ID,
    AVG(Test_Scores)
FROM
    Student_Data
WHERE
    Test_Scores BETWEEN (AVG(Test_Scores)-STDEV(Test_Scores)) AND (AVG(Test_Scores)+STDEV(Test_Scores))
ORDER BY
    Student_ID
</code>```

Anyone know how I could fix this?

答:
Use either window functions or do the calculation in a subquery:</p>

```<code>SELECT sd.Student_ID, sd.Test_Scores
FROM Student_Data sd CROSS JOIN
     (SELECT AVG(Test_Scores) as avgts, STDEV(Test_Scores) as stdts
      FROM Student_Data
     ) x
WHERE sd.Test_Scores BETWEEN avgts - stdts AND avgts + stdts
ORDER BY sd.Student_ID;
</code>```

Body:
How do I find the average of data set within a certain range? Specifically I am looking to find the average for a data set for all data points that are within one standard deviations of the original average. Here is an example:

Student_ID  Test_Scores
1           3
1           20
1           30
1           40
1           50
1           60
1           95

Average = 42.571

Standard Deviation = 29.854

I want to find all data points that are within one standard deviation of this original average, so within the range (42.571-29.854)<=Data<=(42.571+29.854). And from here I want to recalculate a new average.

So my desired data set is:

Student_ID  Test_Scores
1           20
1           30
1           40
1           50
1           60

My desired new average is: 40

Here is my following SQL code and it didn't yield my desired result:

SELECT
    Student_ID,
    AVG(Test_Scores)
FROM
    Student_Data
WHERE
    Test_Scores BETWEEN (AVG(Test_Scores)-STDEV(Test_Scores)) AND (AVG(Test_Scores)+STDEV(Test_Scores))
ORDER BY
    Student_ID

Anyone know how I could fix this?

Body:
Use either window functions or do the calculation in a subquery:

SELECT sd.Student_ID, sd.Test_Scores
FROM Student_Data sd CROSS JOIN
     (SELECT AVG(Test_Scores) as avgts, STDEV(Test_Scores) as stdts
      FROM Student_Data
     ) x
WHERE sd.Test_Scores BETWEEN avgts - stdts AND avgts + stdts
ORDER BY sd.Student_ID;


问:
$.post is not send data to web form
Function:

```<code>$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});
</code>```

ServerSide of :

```<code> protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }
</code>```

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

答:
You will need a web method on the server side to receive this ajax call, it can't be done on the page load since this should be an ajax call not a full page refresh.

To know more about web methods:

 Using jQuery for AJAX with ASP.NET Webforms

Calling a webmethod with jquery in asp.net webforms

And personally I used to use services with ajax instead of page methods in asp.net forms : https://channel9.msdn.com/Blogs/ASP-NET-Site-Videos/how-do-i-make-ajax-calls-using-jquery

Title: $.post is not send data to web form

Body:
Function:

$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});

ServerSide of :

 protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.


问:
Debugging Firebase with Swift 3
I'm trying to debug why I can't get messages from firebase on my iPhone,
I am connected to the FCM server, and I've also subscribed to a topic, however, when I try to print data recieved from FCM I get nil values.

This is the code I have from google's tutorial, it gets executed so that does mean the app is being notified correctly that a new topic is available on FCM?

Also how can I debug to see if there's something I'm doing wrong in setting FCM up?

Thanks

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.

     FIRMessaging.messaging().subscribe(toTopic: "/topics/newNotificationtest")
    print("Message ID: \(userInfo["gcm.message_id"])")

    debugPrint(userInfo)
    // Print full message.
    print("%@", userInfo)

}
</code>```

答:
Please Try With this code and debug</p>

```<code> func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

        let aps = userInfo["aps"] as? NSDictionary

        print(aps)

        print(userInfo)

        print("Message ID: \(userInfo["gcm.message_id"]!)")

        print("%@", userInfo)
    }
</code>```

Title: Debugging Firebase with Swift 3

Body:
I'm trying to debug why I can't get messages from firebase on my iPhone,
I am connected to the FCM server, and I've also subscribed to a topic, however, when I try to print data recieved from FCM I get nil values.

This is the code I have from google's tutorial, it gets executed so that does mean the app is being notified correctly that a new topic is available on FCM?

Also how can I debug to see if there's something I'm doing wrong in setting FCM up?

Thanks

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.

     FIRMessaging.messaging().subscribe(toTopic: "/topics/newNotificationtest")
    print("Message ID: \(userInfo["gcm.message_id"])")

    debugPrint(userInfo)
    // Print full message.
    print("%@", userInfo)

}

Body:
Please Try With this code and debug

 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

        let aps = userInfo["aps"] as? NSDictionary

        print(aps)

        print(userInfo)

        print("Message ID: \(userInfo["gcm.message_id"]!)")

        print("%@", userInfo)
    }


问:
Algorithm to time-sort N data streams
So I've got N asynchronous, timestamped data streams. Each stream has a fixed-ish rate. I want to process all of the data, but the catch is that I must process the data in order as close to the time that the data arrived as possible (it is a real-time streaming application).

So far, my implementation has been to create a fixed window of K messages which I sort by timestamp using a priority queue. I then process the entirety of this queue in order before moving on to the next window. This is okay, but its less than ideal because it creates lag proportional to the size of the buffer, and also will sometimes lead to dropped messages if a message arrives just after the end of the buffer has been processed. It looks something like this:

```<code>// Priority queue keeping track of the data in timestamp order.
ThreadSafeProrityQueue<Data> q;
// Fixed buffer size
int K = 10;
// The last successfully processed data timestamp
time_t lastTimestamp = -1;

// Called for each of the N data streams asyncronously
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
   if (q.size() > K) {
       processQueue();
   }
}

// Process all the data in the queue.
void processQueue() {
    while (!q.empty()) {
        const auto& data = q.top();
        // If the data is too old, drop it.
        if (data.timestamp < lastTimestamp) {
            LOG("Dropping message. Too old.");
            q.pop();
            continue;
        }
        // Otherwise, process it.
        processData(data);
        lastTimestamp = data.timestamp;
        q.pop();
    }
}
</code>```

Information about the data: they're guaranteed to be sorted within their own stream. Their rates are between 5 and 30 hz. They consist of images and other bits of data.

Some examples of why this is harder than it appears. Suppose I have two streams, A and B both running at 1 Hz and I get the data in the following order:

```<code>(stream, time)
(A, 2)
(B, 1.5)
(A, 3)
(B, 2.5)
(A, 4)
(B, 3.5)
(A, 5)
</code>```

See how if I processed the data in order of when I received them, B would always get dropped? that's what I wanted to avoid.Now in my algorithm, B would get dropped every 10th frame, and I would process the data with a lag of 10 frames into the past.

答:
I would suggest a producer/consumer structure. Have each stream put data into the queue, and a separate thread reading the queue. That is:

```<code>// your asynchronous update:
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
}

// separate thread that processes the queue
void processQueue()
{
    while (!stopRequested)
    {
        data = q.pop();
        if (data.timestamp >= lastTimestamp)
        {
            processData(data);
            lastTimestamp = data.timestamp;
        }
    }
}
</code>```

This prevents the "lag" that you see in your current implementation when you're processing a batch.

The processQueue function is running in a separate, persistent thread. stopRequested is a flag that the program sets when it wants to shut down--forcing the thread to exit. Some people would use a volatile flag for this. I prefer to use something like a manual reset event.

To make this work, you'll need a priority queue implementation that allows concurrent updates, or you'll need to wrap your queue with a synchronization lock. In particular, you want to make sure that q.pop() waits for the next item when the queue is empty. Or that you never call q.pop() when the queue is empty. I don't know the specifics of your ThreadSafePriorityQueue, so I can't really say exactly how you'd write that.

The timestamp check is still necessary because it's possible for a later item to be processed before an earlier item. For example:

Event received from data stream 1, but thread is swapped out before it can be added to the queue.

Event received from data stream 2, and is added to the queue.

Event from data stream 2 is removed from the queue by the processQueue function.

Thread from step 1 above gets another time slice and item is added to the queue.

This isn't unusual, just infrequent. And the time difference will typically be on the order of microseconds.

If you regularly get updates out of order, then you can introduce an artificial delay. For example, in your updated question you show messages coming in out of order by 500 milliseconds. Let's assume that 500 milliseconds is the maximum tolerance you want to support. That is, if a message comes in more than 500 ms late, then it will get dropped.

What you do is add 500 ms to the timestamp when you add the thing to the priority queue. That is:

```<code>q.push(AddMs(dat.timestamp, 500), dat);
</code>```

And in the loop that processes things, you don't dequeue something before its timestamp. Something like:

```<code>while (true)
{
    if (q.peek().timestamp <= currentTime)
    {
        data = q.pop();
        if (data.timestamp >= lastTimestamp)
        {
            processData(data);
            lastTimestamp = data.timestamp;
        }
    }
}
</code>```

This introduces a 500 ms delay in the processing of all items, but it prevents dropping "late" updates that fall within the 500 ms threshold. You have to balance your desire for "real time" updates with your desire to prevent dropping updates.

Title: Algorithm to time-sort N data streams

Body:
So I've got N asynchronous, timestamped data streams. Each stream has a fixed-ish rate. I want to process all of the data, but the catch is that I must process the data in order as close to the time that the data arrived as possible (it is a real-time streaming application).

So far, my implementation has been to create a fixed window of K messages which I sort by timestamp using a priority queue. I then process the entirety of this queue in order before moving on to the next window. This is okay, but its less than ideal because it creates lag proportional to the size of the buffer, and also will sometimes lead to dropped messages if a message arrives just after the end of the buffer has been processed. It looks something like this:

// Priority queue keeping track of the data in timestamp order.
ThreadSafeProrityQueue<Data> q;
// Fixed buffer size
int K = 10;
// The last successfully processed data timestamp
time_t lastTimestamp = -1;

// Called for each of the N data streams asyncronously
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
   if (q.size() > K) {
       processQueue();
   }
}

// Process all the data in the queue.
void processQueue() {
    while (!q.empty()) {
        const auto& data = q.top();
        // If the data is too old, drop it.
        if (data.timestamp < lastTimestamp) {
            LOG("Dropping message. Too old.");
            q.pop();
            continue;
        }
        // Otherwise, process it.
        processData(data);
        lastTimestamp = data.timestamp;
        q.pop();
    }
}

Information about the data: they're guaranteed to be sorted within their own stream. Their rates are between 5 and 30 hz. They consist of images and other bits of data.

Some examples of why this is harder than it appears. Suppose I have two streams, A and B both running at 1 Hz and I get the data in the following order:

(stream, time)
(A, 2)
(B, 1.5)
(A, 3)
(B, 2.5)
(A, 4)
(B, 3.5)
(A, 5)

See how if I processed the data in order of when I received them, B would always get dropped? that's what I wanted to avoid.Now in my algorithm, B would get dropped every 10th frame, and I would process the data with a lag of 10 frames into the past.

Body:
I would suggest a producer/consumer structure. Have each stream put data into the queue, and a separate thread reading the queue. That is:

// your asynchronous update:
void receiveAsyncData(const Data& dat) {
   q.push(dat.timestamp, dat);
}

// separate thread that processes the queue
void processQueue()
{
    while (!stopRequested)
    {
        data = q.pop();
        if (data.timestamp >= lastTimestamp)
        {
            processData(data);
            lastTimestamp = data.timestamp;
        }
    }
}

This prevents the "lag" that you see in your current implementation when you're processing a batch.

The processQueue function is running in a separate, persistent thread. stopRequested is a flag that the program sets when it wants to shut down--forcing the thread to exit. Some people would use a volatile flag for this. I prefer to use something like a manual reset event.

To make this work, you'll need a priority queue implementation that allows concurrent updates, or you'll need to wrap your queue with a synchronization lock. In particular, you want to make sure that q.pop() waits for the next item when the queue is empty. Or that you never call q.pop() when the queue is empty. I don't know the specifics of your ThreadSafePriorityQueue, so I can't really say exactly how you'd write that.

The timestamp check is still necessary because it's possible for a later item to be processed before an earlier item. For example:

Event received from data stream 1, but thread is swapped out before it can be added to the queue.

Event received from data stream 2, and is added to the queue.

Event from data stream 2 is removed from the queue by the processQueue function.

Thread from step 1 above gets another time slice and item is added to the queue.

This isn't unusual, just infrequent. And the time difference will typically be on the order of microseconds.

If you regularly get updates out of order, then you can introduce an artificial delay. For example, in your updated question you show messages coming in out of order by 500 milliseconds. Let's assume that 500 milliseconds is the maximum tolerance you want to support. That is, if a message comes in more than 500 ms late, then it will get dropped.

What you do is add 500 ms to the timestamp when you add the thing to the priority queue. That is:

q.push(AddMs(dat.timestamp, 500), dat);

And in the loop that processes things, you don't dequeue something before its timestamp. Something like:

while (true)
{
    if (q.peek().timestamp <= currentTime)
    {
        data = q.pop();
        if (data.timestamp >= lastTimestamp)
        {
            processData(data);
            lastTimestamp = data.timestamp;
        }
    }
}

This introduces a 500 ms delay in the processing of all items, but it prevents dropping "late" updates that fall within the 500 ms threshold. You have to balance your desire for "real time" updates with your desire to prevent dropping updates.