问:
Constructing a Select List with OptGroup groups
Current project:

ASP.NET 4.5.2

MVC 5

I am trying to build a select menu with OptGroups from the Model, but my problem is that I cannot seem to build the OptGroups themselves.

My model:

```<code>[DisplayName("City")]
public string CityId { get; set; }
private IList<SelectListItem> _CityName;
public IList<SelectListItem> CityName {
  get {
    List<SelectListItem> list = new List<SelectListItem>();
    Dictionary<Guid, SelectListGroup> groups = new Dictionary<Guid, SelectListGroup>();
    List<Region> region = db.Region.Where(x => x.Active == true).OrderBy(x => x.RegionName).ToList();
    foreach(Region item in region) {
      groups.Add(item.RegionId, new SelectListGroup() { Name = item.RegionName });
    }
    List<City> city = db.City.Where(x => x.Active == true).ToList();
    foreach(City item in city) {
      list.Add(new SelectListItem() { Text = item.CityName, Value = item.CityId.ToString(), Group = groups[item.RegionId] });
    }
    return list;
  }
  set { _CityName = value; }
}
</code>```

Each city can be in a region. I want a select menu to group the cities by region. By all that I can figure out, the code above is supposed to do the job, but instead I get a drop-down menu with all cities grouped under the OptGroup named System.Web.Mvc.SelectListGroup

The key thing in the above code is that I first iterate through the Regions, and put them into a Dictionary, with the RegionId set to be the key that brings back the RegionName (which itself is formatted as a SelectListGroup).

Then I iterate through the Cities, and assign to each city the group that matches the city’s RegionId.

I have not seen any examples on the Internet that actually pull content from a database -- 100% of all examples use hard-coded SelectListGroup and SelectListItem values.

My View is also correct, AFAIK:

```<code>@Html.DropDownListFor(x => x.CityId, new SelectList(Model.CityName, "Value", "Text", "Group", 1), "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
</code>```

As you can see, the Group is supposed to be brought into the SelectList, and the DropDownList is being created with OptGroups, just not the correct ones.

My resulting drop-down menu looks something like this:

```<code>« ‹ Select › »
System.Web.Mvc.SelectListGroup
  City1
  City2
  ...
  LastCity
</code>```

When it should be like this:

```<code>« ‹ Select › »
Region1
  City2
  City4
  City5
Region2
  City3
  City1
  City6
</code>```

Suggestions?

Modified solution: I have followed the solution provided by Stephen Muecke, but have modified it slightly.

One of the general rules of MVC is that you have a model that is heavier than the controller, and that the model defines your business logic. Stephen asserts that all database access should be done in the controller. I have come to agree with both.

One of my biggest “issues” is that any creation of a drop-down menu or any other pre-populated form element needs to be called every time the page is called. That means, for either a creation or edit page, you need to call it not only on the [HttpGet] method, but also in the [HttpPost] method where the model is sent back to the view because it did not properly validate. This means you have to add code (traditionally via ViewBags) to each Method, just to pre-populate elements like drop-down lists. This is called code duplication, and is not a Good Thing. There has to be a better way, and thanks to Stephen’s guidance, I have found one.

The problem with keeping data access out of the Model is that you need to populate your model with the data. The problem with avoiding code reuse and avoiding potential errors is that you should not do the job of binding data to elements in the controller. This latter action is business logic, and rightfully belongs in the model. The business logic in my case is that I need to limit user input to a list of cities, grouped by region, that the administrator can select from a drop-down. So while we might assemble the data in the controller, we bind it to the model in the model. My mistake before was doing both in the model, which was entirely inappropriate.

By binding the data to the model in the model, we avoid having to bind it twice - once in each of the [HttpGet] and [HttpPost] methods of the controller. We only have to bind it once, in the model that is handled by both methods. And if we have a more generic model that can be shared between Create and Edit functions, we can do this binding in only one spot instead of four (but I don’t have this degree of genericness, so I won’t give that as an example)

So to start out, we actually peel off the entire data-assembly, and stick it inside its own class:

```<code>public class SelectLists {
  public static IEnumerable<SelectListItem> CityNameList() {
    ApplicationDbContext db = new ApplicationDbContext();
    List<City> items = db.City.Where(x => x.Active == true).OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName).ToList();
    return new SelectList(items, "CityId", "CityName", "Region.RegionName", 1);
  }
}
</code>```

This exists within the namespace, but beneath the controller of the section we are dealing with. For clarity’s sake, I stuck it at the very end of the file, just before the closing of the namespace.

Then we look at the model for this page:

```<code>public string CityId { get; set; }
private IEnumerable<SelectListItem> _CityName;
public IEnumerable<SelectListItem> CityName {
  get { return SelectLists.CityNameList(); }
  set { _CityName = value; }
}
</code>```

Note: Even though the CityId is a Guid and the DB field is a uniqueidentifier, I am bringing this value in as a string through the view because client-side validation sucks donkey balls for Guids. It’s far easier to do client-side validation on a drop-down menu if the Value is handled as a string instead of a Guid. You just convert it back into a Guid before you plunk it back into the master model for that table. Plus, CityName is not an actual field in the City table - it exists purely as a placeholder for the drop-down menu itself, which is why it exists in the CreateClientViewModel for the Create page. That way, in the view we can create a DropDownListFor that explicitly binds the CityId to the drop-down menu, actually allowing client-side validation in the first place (Guids are just an added headache).

The key thing is the get {}. As you can see, no more copious code which does DB access, just a simple SelectLists which targets the class, and a calling of the method CityNameList(). You can even pass variables on to the method, so you can have the same method bring back different variations of the same drop-down menu. Say, if you wanted one drop-down on one page (Create) to have its options grouped by OptGroups, and another drop-down (Edit) to not have any groupings of options.

The actual model ends up being even simpler than before:

```<code>@Html.DropDownListFor(x => x.CityId, Model.CityName, "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
</code>```

No need to modify the element that brings in the drop-down list’s data -- you just call it via Model.ElementName.

I hope this helps.

答:
I used this brilliant library: DropDownList Optgroup MVC 1.0.0

Nuget link

This is how to use it:

Get your list ready:

```<code>var ethnicityData = new List<GroupedSelectListItem> {
        new GroupedSelectListItem() { Value="British", Text ="British", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Irish", Text ="Irish", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="White Other", Text ="White Other", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Other Ethin Group", Text ="Other Ethin Group", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Chinese", Text ="Chinese", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Other mixed background", Text ="Other mixed background", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Asian", Text ="White and Asian", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black African", Text ="White and Black African", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black Caribbean", Text ="White and Black Caribbean", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="Other Black background", Text ="Other Black background", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Caribbean", Text ="Caribbean", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="African", Text ="African", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Bangladeshi", Text ="Bangladeshi", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Other Asian background", Text ="Other Asian background", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Indian", Text ="Indian", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Pakistani", Text ="Pakistani", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Not Stated", Text ="Not Stated", GroupName = "Not Stated", GroupKey="3"}
</code>```

};

Use it like this:

@Html.DropDownGroupListFor(model => model.Ethnicity,ethnicityData, "", new { @class = "form-control" })

Body:
Current project:

ASP.NET 4.5.2

MVC 5

I am trying to build a select menu with OptGroups from the Model, but my problem is that I cannot seem to build the OptGroups themselves.

My model:

[DisplayName("City")]
public string CityId { get; set; }
private IList<SelectListItem> _CityName;
public IList<SelectListItem> CityName {
  get {
    List<SelectListItem> list = new List<SelectListItem>();
    Dictionary<Guid, SelectListGroup> groups = new Dictionary<Guid, SelectListGroup>();
    List<Region> region = db.Region.Where(x => x.Active == true).OrderBy(x => x.RegionName).ToList();
    foreach(Region item in region) {
      groups.Add(item.RegionId, new SelectListGroup() { Name = item.RegionName });
    }
    List<City> city = db.City.Where(x => x.Active == true).ToList();
    foreach(City item in city) {
      list.Add(new SelectListItem() { Text = item.CityName, Value = item.CityId.ToString(), Group = groups[item.RegionId] });
    }
    return list;
  }
  set { _CityName = value; }
}

Each city can be in a region. I want a select menu to group the cities by region. By all that I can figure out, the code above is supposed to do the job, but instead I get a drop-down menu with all cities grouped under the OptGroup named System.Web.Mvc.SelectListGroup

The key thing in the above code is that I first iterate through the Regions, and put them into a Dictionary, with the RegionId set to be the key that brings back the RegionName (which itself is formatted as a SelectListGroup).

Then I iterate through the Cities, and assign to each city the group that matches the city’s RegionId.

I have not seen any examples on the Internet that actually pull content from a database -- 100% of all examples use hard-coded SelectListGroup and SelectListItem values.

My View is also correct, AFAIK:

@Html.DropDownListFor(x => x.CityId, new SelectList(Model.CityName, "Value", "Text", "Group", 1), "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })

As you can see, the Group is supposed to be brought into the SelectList, and the DropDownList is being created with OptGroups, just not the correct ones.

My resulting drop-down menu looks something like this:

« ‹ Select › »
System.Web.Mvc.SelectListGroup
  City1
  City2
  ...
  LastCity

When it should be like this:

« ‹ Select › »
Region1
  City2
  City4
  City5
Region2
  City3
  City1
  City6

Suggestions?

Modified solution: I have followed the solution provided by Stephen Muecke, but have modified it slightly.

One of the general rules of MVC is that you have a model that is heavier than the controller, and that the model defines your business logic. Stephen asserts that all database access should be done in the controller. I have come to agree with both.

One of my biggest “issues” is that any creation of a drop-down menu or any other pre-populated form element needs to be called every time the page is called. That means, for either a creation or edit page, you need to call it not only on the [HttpGet] method, but also in the [HttpPost] method where the model is sent back to the view because it did not properly validate. This means you have to add code (traditionally via ViewBags) to each Method, just to pre-populate elements like drop-down lists. This is called code duplication, and is not a Good Thing. There has to be a better way, and thanks to Stephen’s guidance, I have found one.

The problem with keeping data access out of the Model is that you need to populate your model with the data. The problem with avoiding code reuse and avoiding potential errors is that you should not do the job of binding data to elements in the controller. This latter action is business logic, and rightfully belongs in the model. The business logic in my case is that I need to limit user input to a list of cities, grouped by region, that the administrator can select from a drop-down. So while we might assemble the data in the controller, we bind it to the model in the model. My mistake before was doing both in the model, which was entirely inappropriate.

By binding the data to the model in the model, we avoid having to bind it twice - once in each of the [HttpGet] and [HttpPost] methods of the controller. We only have to bind it once, in the model that is handled by both methods. And if we have a more generic model that can be shared between Create and Edit functions, we can do this binding in only one spot instead of four (but I don’t have this degree of genericness, so I won’t give that as an example)

So to start out, we actually peel off the entire data-assembly, and stick it inside its own class:

public class SelectLists {
  public static IEnumerable<SelectListItem> CityNameList() {
    ApplicationDbContext db = new ApplicationDbContext();
    List<City> items = db.City.Where(x => x.Active == true).OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName).ToList();
    return new SelectList(items, "CityId", "CityName", "Region.RegionName", 1);
  }
}

This exists within the namespace, but beneath the controller of the section we are dealing with. For clarity’s sake, I stuck it at the very end of the file, just before the closing of the namespace.

Then we look at the model for this page:

public string CityId { get; set; }
private IEnumerable<SelectListItem> _CityName;
public IEnumerable<SelectListItem> CityName {
  get { return SelectLists.CityNameList(); }
  set { _CityName = value; }
}

Note: Even though the CityId is a Guid and the DB field is a uniqueidentifier, I am bringing this value in as a string through the view because client-side validation sucks donkey balls for Guids. It’s far easier to do client-side validation on a drop-down menu if the Value is handled as a string instead of a Guid. You just convert it back into a Guid before you plunk it back into the master model for that table. Plus, CityName is not an actual field in the City table - it exists purely as a placeholder for the drop-down menu itself, which is why it exists in the CreateClientViewModel for the Create page. That way, in the view we can create a DropDownListFor that explicitly binds the CityId to the drop-down menu, actually allowing client-side validation in the first place (Guids are just an added headache).

The key thing is the get {}. As you can see, no more copious code which does DB access, just a simple SelectLists which targets the class, and a calling of the method CityNameList(). You can even pass variables on to the method, so you can have the same method bring back different variations of the same drop-down menu. Say, if you wanted one drop-down on one page (Create) to have its options grouped by OptGroups, and another drop-down (Edit) to not have any groupings of options.

The actual model ends up being even simpler than before:

@Html.DropDownListFor(x => x.CityId, Model.CityName, "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })

No need to modify the element that brings in the drop-down list’s data -- you just call it via Model.ElementName.

I hope this helps.

Body:
I used this brilliant library: DropDownList Optgroup MVC 1.0.0

Nuget link

This is how to use it:

Get your list ready:

var ethnicityData = new List<GroupedSelectListItem> {
        new GroupedSelectListItem() { Value="British", Text ="British", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Irish", Text ="Irish", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="White Other", Text ="White Other", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Other Ethin Group", Text ="Other Ethin Group", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Chinese", Text ="Chinese", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Other mixed background", Text ="Other mixed background", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Asian", Text ="White and Asian", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black African", Text ="White and Black African", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black Caribbean", Text ="White and Black Caribbean", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="Other Black background", Text ="Other Black background", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Caribbean", Text ="Caribbean", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="African", Text ="African", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Bangladeshi", Text ="Bangladeshi", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Other Asian background", Text ="Other Asian background", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Indian", Text ="Indian", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Pakistani", Text ="Pakistani", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Not Stated", Text ="Not Stated", GroupName = "Not Stated", GroupKey="3"}

};

Use it like this:

@Html.DropDownGroupListFor(model => model.Ethnicity,ethnicityData, "", new { @class = "form-control" })


来源: stackexchange

问:
Django: Detecting changes of a set of fields when a model is saved

The problem

I have a field in my model that requires some calculation. I want to perform these calculations when the model is saved. However, because it is resource intensive, I want to only perform these calculations when certain fields have changed.

Initial thought

Keep the hash of the 3 fields as a different field in the model. On save, hash the three fields and, if equal to the the one currently saved in the model, continue on saving the instance without further work. Otherwise, perform calculations, save the results of the calculation and save new hash.

My questions:

Is this the best option? If not, please share what would be better and why.

If there isn't a better way: Which kind of hash should I use? And why?

Which kind of Django model field type should I use to save the hash?

答:
I am submitting the implementation of my initial thought as an answer to be critiqued by others:

models.py

```<code>from hashlib import md5

class Stop(models.Model):
    line = models.CharField(max_length=12)
    street = models.CharField(max_length=32, choices=STREET_CHOICES)
    order = models.PositiveIntegerField(blank=True, null=True)
    location_hash = models.CharField(max_length=32, null=True)

    def save(self):
        location_hash = md5('%s@%s' % (self.line, self.street))
        if self.location_hash != location_hash:
            self.order = calculate_order(line=self.line, street=self.street)
            self.location_hash = location_hash
        super(Stop, self).save()
</code>```

If anyone has any suggestions, comments or concerns; please share!

ContentLicense: CC BY-SA 2.5

Body:
I am submitting the implementation of my initial thought as an answer to be critiqued by others:

models.py

from hashlib import md5

class Stop(models.Model):
    line = models.CharField(max_length=12)
    street = models.CharField(max_length=32, choices=STREET_CHOICES)
    order = models.PositiveIntegerField(blank=True, null=True)
    location_hash = models.CharField(max_length=32, null=True)

    def save(self):
        location_hash = md5('%s@%s' % (self.line, self.street))
        if self.location_hash != location_hash:
            self.order = calculate_order(line=self.line, street=self.street)
            self.location_hash = location_hash
        super(Stop, self).save()

If anyone has any suggestions, comments or concerns; please share!


问:
Vegan: Significant axes in RDA
I have a data frame of phytocoenological relevés:

rows represent sites

columns represent species

I run RDA on it using vegan function rda(matrix ~ 1). Now I have the axes of the ordination summary(rda)$sites, but how to find out which of them are significant?

And my further question is, would these approaches differ if I use different ordination methods?

Thank you attention and anwers.

答:
Personally I would say that there is no way. However, some people have suggested ways to find the number of non-significant axes. Some of these are discussed in a vegan github issue. My personal experience is that many of these ways work poorly: if I generate data with a defined number of dimensions + random error, methods fail to find that known number of axes. Many of these methods are easy-ish to implement (although we have not implemented them in vegan), though. See the discussion linked above.

Your title asks about PCoA, but your example uses RDA. However, similar methods apply to both (or fail with both like I think).

ContentLicense: CC BY-SA 3.0

Title: Vegan: Significant axes in RDA


问:
Opening the Settings app from another app
Okay, I know that there are many question about it, but they are all from many time ago.

So. I know that it is possible because the Map app does it.

In the Map app if I turn off the localization for this app, it send me a message, and if I press okay, the "Settings App" will be open.
And my question is, how is this possible?
How can I open the "Setting app" from my own app?

Basically I need to do the same thing, if the user turn off the location for my app, then I'll show him a message saying something that will open the "Setting app"

答:
In Swift 3 / iOS 10+ this now looks like</p>

```<code>if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
    UIApplication.shared.open(url, completionHandler: .none)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Swift 3 / iOS 10+ this now looks like

if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
    UIApplication.shared.open(url, completionHandler: .none)
}


问:
How do I select the top ten scores in a database table full of scores using linq in C#
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

```<code>var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;
</code>```

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

答:
You have to take 10 from the result, not before:</p>

```<code>var TopTen = (from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t).Take(10);
</code>```

Body:
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

Body:
You have to take 10 from the result, not before:

var TopTen = (from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t).Take(10);


问:
How to add Progress bar for mpdf
I have generated pdf through mpdf library , my pdf take 4-5 minutes to generate pdf.
i want add percentage progress bar to show progress at the time of generate pdf.

how can i add javascript or php code for percentage progress bar to show progress

答:
```<code>define('_MPDF_URI','../');     // must be  a relative or absolute URI - not a file system path

$mpdf = new mPDF();

$mpdf->StartProgressBarOutput(2);

$mpdf->WriteHTML('You will hardly have time to see the progress bars!');

$mpdf->Output();
</code>```

From source Link

Title: How to add Progress bar for mpdf

Body:
define('_MPDF_URI','../');     // must be  a relative or absolute URI - not a file system path

$mpdf = new mPDF();

$mpdf->StartProgressBarOutput(2);

$mpdf->WriteHTML('You will hardly have time to see the progress bars!');

$mpdf->Output();

From source Link


答:
Try to use this method:

https://mpdf.github.io/reference/mpdf-functions/startprogressbaroutput.html

At the bottom of page is example.

Title: How to add Progress bar for mpdf

Body:
I have generated pdf through mpdf library , my pdf take 4-5 minutes to generate pdf.
i want add percentage progress bar to show progress at the time of generate pdf.

how can i add javascript or php code for percentage progress bar to show progress


问:
How to remove the border of an image?
I have founded many question like mine on StackOverflow example1  example2 but for a unknown reason I still have some borders displayed around my image:

```<code> .imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border:0;
  border-style: none;

  position: absolute;
  right: 150px;
  top: 5px;
}
</code>```

Someone has a solution ?

[EDIT] with your advices I have this CSS in the browser:

.liMachine {
    list-style-type: none;
    border-style: solid;
    margin-bottom: 5px;
    word-break: break-all;
    position: relative;

}

.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;
  display: block;

  position: absolute;
  right: 250px;
  top: 5px;
}

.whoLock{
  position: absolute;
  right: 15px;
  top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="liMachine switch">
        <div id="nameMachine">
            <h3>My machine</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">running</span>
        </div>
        <div>
            <img class="imgCadenas">
            <p class="whoLock">Locked by: StackOverflow</p>
        </div>
    </li></code>```

答: Does adding !important to your CSS remove the border?</p>

Title: How to remove the border of an image?

Body:
I have founded many question like mine on StackOverflow example1  example2 but for a unknown reason I still have some borders displayed around my image:

 .imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border:0;
  border-style: none;

  position: absolute;
  right: 150px;
  top: 5px;
}

Someone has a solution ?

[EDIT] with your advices I have this CSS in the browser:

.liMachine {
    list-style-type: none;
    border-style: solid;
    margin-bottom: 5px;
    word-break: break-all;
    position: relative;

}

.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;
  display: block;

  position: absolute;
  right: 250px;
  top: 5px;
}

.whoLock{
  position: absolute;
  right: 15px;
  top: 10px;
}

My machine

            State:running

Locked by: StackOverflow


问:
How to find out what form is on top?
In Compact Framework, how can I find out which form is the form that is showing to the user (even if it is not full screen)?

Any ideas?  I will keep looking and post back if I find an answer (and no one responds).

答: Looks like you can p/invoke GetForegroundWindow to find the current window.</p>

Title: How to find out what form is on top?


问:
Desktop Bridge requires .net native tool chain, but how to use it in a runtime component
I try to get a JavaScript UWP app into the Store which uses the Desktop Bridge (some "older" parts). There is a C# UWP Windows runtime component (winmd) as a project in the solution.
Everything works fine and runs as expected, but when I try to get the package into the store I get the following error:

Package acceptance validation error: Apps converted with the Desktop Bridge and that require the .NET Native framework must be pre-compiled by the .NET Native tool chain.

The JavaScript UWP App does already using .net native compiling (AFAIK the this is the default for JS UWP), but how do I configure this for the C# Windows runtime component library project?

答:
I answer my question self, the resolution for this problem was to bundle the package manually after building from visual studio. The relevant information can be find here: Desktop to UWP Bridge: Packaging .NET apps using Visual Studio

Esp. this info:


问:
android FragmentActivity is invisible but onStop() is not called
Does anyone have the problem of a FragmentActivity, when call finish() on itself, it only calls onPause() and doesn't call onStop() and onDestroy(). But the activity is invisible on the device?

I don't see any other error log.

According to the android activity life cycle, If the activity is invisible, then it should call onstop(). But it is not. It is happened on Android 5.0.

I found the cause, but i don't understand why it happened.

A extends FragmentActivity, it is defined launchmode: singleTask.

B extends Activity, it is defined  android:launchMode="singleInstance", android:theme="@android:style/Theme.NoDisplay" in Manifest.

C extends FragmentActivity, it is defined launchmode: singleTask,  android:excludeFromRecents="true", android:taskAffinity="com.xxx.xxxx.xxx" in Manifest.

D is a serviceConnector singleton instance. What handles the event from the binding service callback.

The scenario is:

```<code>Step1 : A calls B with startActivity(intent).
Step2 : B calls serviceConnector to send event to the service process and finish itself. It has no UI. It is set as Theme.NoDisplay.
Step3 : Service callbacks init C if not exist yet and C handle service responses event.
Step4 : In one case, C calls B with startActivity(intent)
Step5 : B calls serviceConnection to send event. No UI. C will onPause and when B finsih itself, C onResume()
Step6: Service callbacks and found C already exist, no create new one. C handle service respsonses.
Step7: user click button on C Fragement activity, C calls finish itself, But only C got onPause(). C couldn't be finish, no onStop(), no onDestroy() is called.
</code>```

I don't understand C calls B, B finsih itself, C resume and C finish itself later has the issue.

答: If you call finish() somewhere within onCreate(), onDestroy() is called directly, without going through onPause() and onStart() methods.

Body:
Does anyone have the problem of a FragmentActivity, when call finish() on itself, it only calls onPause() and doesn't call onStop() and onDestroy(). But the activity is invisible on the device?

I don't see any other error log.

According to the android activity life cycle, If the activity is invisible, then it should call onstop(). But it is not. It is happened on Android 5.0.

I found the cause, but i don't understand why it happened.

A extends FragmentActivity, it is defined launchmode: singleTask.

B extends Activity, it is defined  android:launchMode="singleInstance", android:theme="@android:style/Theme.NoDisplay" in Manifest.

C extends FragmentActivity, it is defined launchmode: singleTask,  android:excludeFromRecents="true", android:taskAffinity="com.xxx.xxxx.xxx" in Manifest.

D is a serviceConnector singleton instance. What handles the event from the binding service callback.

The scenario is:

Step1 : A calls B with startActivity(intent).
Step2 : B calls serviceConnector to send event to the service process and finish itself. It has no UI. It is set as Theme.NoDisplay.
Step3 : Service callbacks init C if not exist yet and C handle service responses event.
Step4 : In one case, C calls B with startActivity(intent)
Step5 : B calls serviceConnection to send event. No UI. C will onPause and when B finsih itself, C onResume()
Step6: Service callbacks and found C already exist, no create new one. C handle service respsonses.
Step7: user click button on C Fragement activity, C calls finish itself, But only C got onPause(). C couldn't be finish, no onStop(), no onDestroy() is called.

I don't understand C calls B, B finsih itself, C resume and C finish itself later has the issue.


问:
Java Solr SolrJ get id value of the newly indexed file
I have an entity, which I want to link to an indexed file uploaded to solr via SolrJ. Preferably it would be a field on the entity with the file's entry id as value. Thing is - I don't know how to get that id after it just being uploaded. Here is the code:</p>

```<code>            //File tempFile;
            //MultipartFile file;
            tempFile = File.createTempFile(prefix, postfix);
            file.transferTo(tempFile);
            ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
            req.addFile(tempFile, file.getContentType());
            req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
            NamedList list = solrClient.request(req);
            System.out.println(list);
            //{responseHeader={status=0,QTime=1328}}
            tempFile.delete();
</code>```

答:
The solution was to create id myself and set it like this:</p>

```<code>req.setParam("literal.id", UUID.randomUUID().toString());
</code>```

Body:
I have an entity, which I want to link to an indexed file uploaded to solr via SolrJ. Preferably it would be a field on the entity with the file's entry id as value. Thing is - I don't know how to get that id after it just being uploaded. Here is the code:

            //File tempFile;
            //MultipartFile file;
            tempFile = File.createTempFile(prefix, postfix);
            file.transferTo(tempFile);
            ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
            req.addFile(tempFile, file.getContentType());
            req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
            NamedList list = solrClient.request(req);
            System.out.println(list);
            //{responseHeader={status=0,QTime=1328}}
            tempFile.delete();

Body:
The solution was to create id myself and set it like this:

req.setParam("literal.id", UUID.randomUUID().toString());


问:
Jqgrid Date sorting issue with day name and date column
In my Jqgrid table I have a column which has dayName, Date as value,
like, Wed, 01-03-217,

But when I add complete data having days as Tue or Thu, jqgrid shows undefined, NaN-NaN-NaN as column values for both days,

I am using Jqgrid versoin 4.6.0

I have also prepare demo at fiddle. http://jsfiddle.net/alpeshjikadra/jss5b43j/1/

Let me know if anyone knows how to solve this

Thanks

答:
The usage of localized format as the input data (texts like "Thu") in the date is bad practice in general. It's better to change the format of data to use ISO 8601 date format. I mean to post the date "Thu, 09-03-2017" like "2017-03-09".

If you really can't change the format of input data, I could suggest you the following workaround: you can include the line

```<code>$.jgrid.formatter.date.parseRe = /[,\s\-]/;
</code>```

in your code. The parseRe be used internally for parsing the dates. The input format which you use, for example, "Thu, 09-03-2017" contains -, spaces and , as separators between the parts of the date. The regex /[,\s\-]/ corresponds the format.

Resulting demo will be http://jsfiddle.net/OlegKi/jss5b43j/6/

Body:
The usage of localized format as the input data (texts like "Thu") in the date is bad practice in general. It's better to change the format of data to use ISO 8601 date format. I mean to post the date "Thu, 09-03-2017" like "2017-03-09".

If you really can't change the format of input data, I could suggest you the following workaround: you can include the line

$.jgrid.formatter.date.parseRe = /[,\s\-]/;

in your code. The parseRe be used internally for parsing the dates. The input format which you use, for example, "Thu, 09-03-2017" contains -, spaces and , as separators between the parts of the date. The regex /[,\s\-]/ corresponds the format.

Resulting demo will be http://jsfiddle.net/OlegKi/jss5b43j/6/


问:
$window.location = pdfLocation; not downloading PDF AngularJs
I am receiving the location of a pdf document in angular, and I cant get it to consistently download.

It works on my home laptop, but not whilst at work.
Code below

```<code>RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    $window.location = pdfLocation;
});
</code>```

Works in Chrome on Ubuntu at home, not on the same set up at work. Does anyone know any reason why the operation of '$window.location' wouldn't be idempotent?

Update:
Also works on FF on my work machine, just not Chrome

答:
This mostly happends if you have some third part software installed or the browser security is configured as to high. Check for addblocker & antivir software on your machine and also check the security configuration in your browser. Ensure that your pdf location is based on HTTPS if your application is running on HTTPS.

For Chrome & Safari try to set your window.location.href property instead of window.location. This should work for all browser so.

```<code>RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    window.location.href = pdfLocation;
    return false;
});
</code>```

Here is a plnkr demo which does run well in chrome.

Body:
I am receiving the location of a pdf document in angular, and I cant get it to consistently download.

It works on my home laptop, but not whilst at work.
Code below

RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    $window.location = pdfLocation;
});

Works in Chrome on Ubuntu at home, not on the same set up at work. Does anyone know any reason why the operation of '$window.location' wouldn't be idempotent?

Update:
Also works on FF on my work machine, just not Chrome

Body:
This mostly happends if you have some third part software installed or the browser security is configured as to high. Check for addblocker & antivir software on your machine and also check the security configuration in your browser. Ensure that your pdf location is based on HTTPS if your application is running on HTTPS.

For Chrome & Safari try to set your window.location.href property instead of window.location. This should work for all browser so.

RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    window.location.href = pdfLocation;
    return false;
});

Here is a plnkr demo which does run well in chrome.


问:
friend vs member functions in Operator Overloading C++
Previously I learnt about overloading Operators in C++ as member functions as well as friend functions of a class. Although, I know how to overload operators in C++ using both techniques. But I am still confused that ** which one is better** ? A member function or a friend function to overload operators, which one should i use and why?
 Please guide me ! Your response will be appreciated greatly. I shall be glad and thankful for your answers.</p>

答:
Member functions and friend are not two opposite among which you need to choose only one. They both can be used, for example to avoid duplicating code by implementing one and making the other calling it.

```<code>struct A
{
    A operator+=(A const & second);
};

A operator+(A const &first, A const &second)
{
    A temp(first);
    temp += second;
    return temp;
}
</code>```

But in case if you want to choose for one function if it needs to be member or not, here is a rule that I follow : to implement a non-member function (friend or not) when I have a binary operator to respect the symmetry we expect. Example : with A and the possibility to convert a int to A implicitly (with a constructor taking a int), if I have a member function, there what will be the result.

```<code>A a1, a2;
a1 + a2; // OK
a1 + 42; // OK
42 + a2; // KO
</code>```

With a free function, there is the result.

```<code>A a1, a2;
a1 + a2; // Ok
a1 + 42; // Ok
42 + a2; // Ok
</code>```

An concrete C++ class that use this possibility is std::string.

```<code>#include <iostream>
#include <string>

int main()
{
    std::string s {"World"};
    // Works with absolutely no problem.
    std::string chaine = "Hello " + s;
    std::cout << chaine << std::endl;
}
</code>```

To conclude, here is a good link on SO to help you.

Body:
Member functions and friend are not two opposite among which you need to choose only one. They both can be used, for example to avoid duplicating code by implementing one and making the other calling it.

struct A
{
    A operator+=(A const & second);
};

A operator+(A const &first, A const &second)
{
    A temp(first);
    temp += second;
    return temp;
}

But in case if you want to choose for one function if it needs to be member or not, here is a rule that I follow : to implement a non-member function (friend or not) when I have a binary operator to respect the symmetry we expect. Example : with A and the possibility to convert a int to A implicitly (with a constructor taking a int), if I have a member function, there what will be the result.

A a1, a2;
a1 + a2; // OK
a1 + 42; // OK
42 + a2; // KO

With a free function, there is the result.

A a1, a2;
a1 + a2; // Ok
a1 + 42; // Ok
42 + a2; // Ok

An concrete C++ class that use this possibility is std::string.

#include <iostream>
#include <string>

int main()
{
    std::string s {"World"};
    // Works with absolutely no problem.
    std::string chaine = "Hello " + s;
    std::cout << chaine << std::endl;
}

To conclude, here is a good link on SO to help you.


问:
Select * from this week
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

```<code>$week = Date('W');
</code>```

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

```<code>$sql = 'SELECT * FROM my_table WHERE week = $week';
</code>```

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

答:
Please use this, it is safer vs SQL injection:

```<code>$week = $mysqli->escape_string($week);

$sql = "SELECT * FROM my_table WHERE week = '" . $week . "'";

$retval = $mysqli->query($sql);
</code>```

You need the mysqli object set as connection to your database for this to work. After that you can fetch the rows from $retval.

Title: Select * from this week

Body:
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

$week = Date('W');

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

$sql = 'SELECT * FROM my_table WHERE week = $week';

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

Body:
Please use this, it is safer vs SQL injection:

$week = $mysqli->escape_string($week);

$sql = "SELECT * FROM my_table WHERE week = '" . $week . "'";

$retval = $mysqli->query($sql);

You need the mysqli object set as connection to your database for this to work. After that you can fetch the rows from $retval.


答:
Try using.</p>

```<code>img {
    border:none;
    outline:none
}
</code>```

Title: How to remove the border of an image?

Body:
Try using.

img {
    border:none;
    outline:none
}


问:
How to automaticlly place the emacs window on the right of the screen at start with GNOME?
I want the Emacs window to be at the right of the screen at start up. I have search a lot and I am close to find but I can't exactly force the window to take exactly the half of the screen, like when you take the windows with the mouse and drop it to the right of the screen.
I can place the window at the right place, set the right size, but it left some tiny pixels that i can't fill.The window is not exactly the same form and do not fill the same pixels.

Thank you for help and sorry for my bad English.

答:
From Emacs Reference Manual:

User Option: frame-resize-pixelwise

If this option is nil, a frame’s size is usually rounded to a multiple of the current values of that frame’s frame-char-height and frame-char-width whenever the frame is resized. If this is non-nil, no rounding occurs, hence frame sizes can increase/decrease by one pixel.

Your problem should be solved by adding (setq frame-resize-pixelwise t) to your settings.


答:
```<code>var TopTen =  datacontext.Scores.OrderByDescending(t => LifetimeScore ).Take(10)
</code>```

Title: How do I select the top ten scores in a database table full of scores using linq in C#


问:
Filtering Posts by User Object Id or Author in Keystone
I'm trying to create an web app where a student can store their notes online. So, if they login they can only see the notes that they posted on the blog.

```<code>    view.on('init', function (next) {
    Post.model.findOne()
          .where('_id', User.id)
          .populate('author')
          .exec(function(err, results) {
              locals.data.posts = results;
      });
});
</code>```

this is the code that I am having problems on

答:
```<code>    view.on('init', function (next) {
    var q = keystone.list('Post').paginate({
        page: req.query.page || 1,
        perPage: 10,
        maxPages: 10,
    })
        .find().where('author', locals.user.id)
        .sort('-publishedDate')
        .populate('author categories');

    if (locals.data.category) {
        q.where('categories').in([locals.data.category]);
    }

    q.exec(function (err, results) {
        locals.data.posts = results;
        next(err);
    });
});
</code>```

This works!

Body:
I'm trying to create an web app where a student can store their notes online. So, if they login they can only see the notes that they posted on the blog.

    view.on('init', function (next) {
    Post.model.findOne()
          .where('_id', User.id)
          .populate('author')
          .exec(function(err, results) {
              locals.data.posts = results;
      });
});

this is the code that I am having problems on

Body:
    view.on('init', function (next) {
    var q = keystone.list('Post').paginate({
        page: req.query.page || 1,
        perPage: 10,
        maxPages: 10,
    })
        .find().where('author', locals.user.id)
        .sort('-publishedDate')
        .populate('author categories');

    if (locals.data.category) {
        q.where('categories').in([locals.data.category]);
    }

    q.exec(function (err, results) {
        locals.data.posts = results;
        next(err);
    });
});

This works!


问:
Create a dictionary of words that are in one document but not in the other
I have the following sample data

```<code>docs_word = ["this is a test", "this is another test"]
docs_txt = ["this is a great test", "this is another test"]
</code>```

What I want to do now is to create two dictionaries of the words in the sample files, compare them and store the words that are in the docs_txt file but not in the docs_word file in a seperate dictionary. Therefore I wrote the following:

```<code>count_txtDoc = Counter()
for file in docs_word:
  words = file.split(" ")
  count_txtDoc.update(words)

count_wrdDoc = Counter()
for file in docs_txt:
  words = file.split(" ")
  count_wrdDoc.update(words)

#Create a list of the dictionary keys
words_worddoc = count_wrdDoc.keys()
words_txtdoc = count_txtDoc.keys()

#Look for values that are in word_doc but not in txt_doc

count_all = Counter()
for val in words_worddoc:
  if val not in words_txtdoc:
   count_all.update(val)
   print(val)
</code>```

The thing now is that the correct values are printed. It shows: "great".

However if I print:

```<code>print(count_all)
</code>```

I get the following output:

```<code>Counter({'a': 1, 'r': 1, 'e': 1, 't': 1, 'g': 1})
</code>```

While I expected

```<code>Counter({'great': 1})
</code>```

Any thoughts on how I can achieve this?
#
print(count_all)

答:
Update the counter using an iterable containing the word, not the word itself (since the word is also iterable):

```<code>count_all.update([val])
#                ^   ^
</code>```

However, you may not need to create a new counter if you only the item. You can take the symmetric difference of the keys:

```<code>words_worddoc = count_wrdDoc.viewkeys() # use .keys() in Py3
words_txtdoc = count_txtDoc.viewkeys()  # use .keys() in Py3

print(words_txtdoc ^ words_worddoc)
# set(['great'])
</code>```

If you want the count also, you can compute the symmetric difference between both counters like so:

```<code>count_all = (count_wrdDoc - count_txtDoc) | (count_txtDoc - count_wrdDoc)

print (count_all)
# Counter({'great': 1})
</code>```

Body:
I have the following sample data

docs_word = ["this is a test", "this is another test"]
docs_txt = ["this is a great test", "this is another test"]

What I want to do now is to create two dictionaries of the words in the sample files, compare them and store the words that are in the docs_txt file but not in the docs_word file in a seperate dictionary. Therefore I wrote the following:

count_txtDoc = Counter()
for file in docs_word:
  words = file.split(" ")
  count_txtDoc.update(words)

count_wrdDoc = Counter()
for file in docs_txt:
  words = file.split(" ")
  count_wrdDoc.update(words)

#Create a list of the dictionary keys
words_worddoc = count_wrdDoc.keys()
words_txtdoc = count_txtDoc.keys()

#Look for values that are in word_doc but not in txt_doc

count_all = Counter()
for val in words_worddoc:
  if val not in words_txtdoc:
   count_all.update(val)
   print(val)

The thing now is that the correct values are printed. It shows: "great".

However if I print:

print(count_all)

I get the following output:

Counter({'a': 1, 'r': 1, 'e': 1, 't': 1, 'g': 1})

While I expected

Counter({'great': 1})

Any thoughts on how I can achieve this?
#
print(count_all)

Body:
Update the counter using an iterable containing the word, not the word itself (since the word is also iterable):

count_all.update([val])
#                ^   ^

However, you may not need to create a new counter if you only the item. You can take the symmetric difference of the keys:

words_worddoc = count_wrdDoc.viewkeys() # use .keys() in Py3
words_txtdoc = count_txtDoc.viewkeys()  # use .keys() in Py3

print(words_txtdoc ^ words_worddoc)
# set(['great'])

If you want the count also, you can compute the symmetric difference between both counters like so:

count_all = (count_wrdDoc - count_txtDoc) | (count_txtDoc - count_wrdDoc)

print (count_all)
# Counter({'great': 1})


问:
Yesod: Non-exhaustive patterns in function isAuthorized
In a Yesod scaffolding project, I have added a new route and a new handler.

My error is the following:

```<code>29/Mar/2017:11:25:22 +0200 [Error#yesod-core] Foundation.hs:(137,5)-(144,45): Non-exhaustive patterns in function isAuthorized
 @(yesod-core-1.4.32-6HthMZNCl0sEMRz6GJ4QO1:Yesod.Core.Class.Yesod ./Yesod/Core/Class/Yesod.hs:693:5)
29/Mar/2017:11:25:22 +0200 [Debug#SQL] SELECT `ident`,`password` FROM `user` WHERE `id`=? ; [PersistInt64 1]
</code>```

How can I solve it?

答:
It is necessary to modify the Foundation.hs file, adding the new route to authorizations:</p>

```<code>-- Routes not requiring authentication.
isAuthorized (AuthR _) _ = return Authorized
isAuthorized CommentR _ = return Authorized
isAuthorized HomeR _ = return Authorized
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
isAuthorized (StaticR _) _ = return Authorized
isAuthorized TestR _ = return Authorized

isAuthorized ProfileR _ = isAuthenticated
</code>```

Body:
In a Yesod scaffolding project, I have added a new route and a new handler.

My error is the following:

29/Mar/2017:11:25:22 +0200 [Error#yesod-core] Foundation.hs:(137,5)-(144,45): Non-exhaustive patterns in function isAuthorized
 @(yesod-core-1.4.32-6HthMZNCl0sEMRz6GJ4QO1:Yesod.Core.Class.Yesod ./Yesod/Core/Class/Yesod.hs:693:5)
29/Mar/2017:11:25:22 +0200 [Debug#SQL] SELECT `ident`,`password` FROM `user` WHERE `id`=? ; [PersistInt64 1]

How can I solve it?

Body:
It is necessary to modify the Foundation.hs file, adding the new route to authorizations:

-- Routes not requiring authentication.
isAuthorized (AuthR _) _ = return Authorized
isAuthorized CommentR _ = return Authorized
isAuthorized HomeR _ = return Authorized
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
isAuthorized (StaticR _) _ = return Authorized
isAuthorized TestR _ = return Authorized

isAuthorized ProfileR _ = isAuthenticated


问:
Jest Mock Function?
Just started using jest and the documentation doesn't seem to be too clear on mocking.

I have a module with the below code. If I want to test the send mail function, but not send an actual email out via mailgun what do I need to do here? I THINK in my test file I need to use the mock behaviour but can't work out how to specifically stop the mail going out, whilst also being able to check the right routes are followed e.g. invalid email address, error thrown, etc. Do I need to break this function down further?

```<code>const Mailgun = require('machinepack-mailgun');
const Emailaddresses = require('machinepack-emailaddresses');
const config = require('../Config');

// Function to send an email
const sendEmail = function (toaddress, toname, sub, msg, cb) {
// Validate the email address is correct and if so send an email. Otherwise log the error and exit.
  Emailaddresses.validate({
    string: toaddress,
  }).exec({
    error(err) {
      return cb(err, null);
    },
    invalid() {
      return cb(new Error('Email address is not valid.'), null);
    },
    success() {
      Mailgun.sendPlaintextEmail({
        apiKey: config.sender.apiKey,
        domain: config.sender.domain,
        toEmail: toaddress,
        toName: toname,
        subject: sub,
        message: msg,
        fromEmail: config.sender.fromEmail,
        fromName: config.sender.fromName,
      }).exec({
        error(err) {
          return cb(err, null);
        },
        success() {
          return cb(null, 'Email Sent.');
        },
      });
    },
  });
};

module.exports.sendEmail = sendEmail;
</code>```

答:
You can mock out Mailgun with your own implementation which:

```<code>const Mailgun = require('machinepack-mailgun');
jest.mock('machinepack-mailgun', () = > ({
  sendPlaintextEmail: jest.fn()
}))
it('sends mail and fail', () = > {
  // no add the way `sendPlaintextEmail` should react.
  // in this case return `exec` which always run the `error` part
  Mailgun.sendPlaintextEmail.mockImplementation(() = > ({
    exec: (arg) = > {
      arg.error('someError')
    }
  }))
  const cb = jest.fn()
  sendEmail ('toaddress', 'toname', 'sub', 'msg', cb)
  expect(Mailgun.sendPlaintextEmail).toHaveBeenCalledWith(...)
  expect(cb).toHaveBeenCalledWith(...)
})
</code>```

In the above example we mock the mailgun module so that sendPlaintextEmail is a spy. Then we import the module into our test so we can set the mock implementation of the spy in every test. In the example we set the behaviour, so that it returns the exec method, which then is called by your code with the error/success object. The mock then just call the error part. After that you can first test that Mailgun.sendPlaintextEmail was called with the correct parameters, then you can test that cb was called with "someError" and null.

In another test you can just set the behaviour of exec so it will call the success method.

Title: Jest Mock Function?

Body:
Just started using jest and the documentation doesn't seem to be too clear on mocking.

I have a module with the below code. If I want to test the send mail function, but not send an actual email out via mailgun what do I need to do here? I THINK in my test file I need to use the mock behaviour but can't work out how to specifically stop the mail going out, whilst also being able to check the right routes are followed e.g. invalid email address, error thrown, etc. Do I need to break this function down further?

const Mailgun = require('machinepack-mailgun');
const Emailaddresses = require('machinepack-emailaddresses');
const config = require('../Config');

// Function to send an email
const sendEmail = function (toaddress, toname, sub, msg, cb) {
// Validate the email address is correct and if so send an email. Otherwise log the error and exit.
  Emailaddresses.validate({
    string: toaddress,
  }).exec({
    error(err) {
      return cb(err, null);
    },
    invalid() {
      return cb(new Error('Email address is not valid.'), null);
    },
    success() {
      Mailgun.sendPlaintextEmail({
        apiKey: config.sender.apiKey,
        domain: config.sender.domain,
        toEmail: toaddress,
        toName: toname,
        subject: sub,
        message: msg,
        fromEmail: config.sender.fromEmail,
        fromName: config.sender.fromName,
      }).exec({
        error(err) {
          return cb(err, null);
        },
        success() {
          return cb(null, 'Email Sent.');
        },
      });
    },
  });
};

module.exports.sendEmail = sendEmail;

Body:
You can mock out Mailgun with your own implementation which:

const Mailgun = require('machinepack-mailgun');
jest.mock('machinepack-mailgun', () = > ({
  sendPlaintextEmail: jest.fn()
}))
it('sends mail and fail', () = > {
  // no add the way `sendPlaintextEmail` should react.
  // in this case return `exec` which always run the `error` part
  Mailgun.sendPlaintextEmail.mockImplementation(() = > ({
    exec: (arg) = > {
      arg.error('someError')
    }
  }))
  const cb = jest.fn()
  sendEmail ('toaddress', 'toname', 'sub', 'msg', cb)
  expect(Mailgun.sendPlaintextEmail).toHaveBeenCalledWith(...)
  expect(cb).toHaveBeenCalledWith(...)
})

In the above example we mock the mailgun module so that sendPlaintextEmail is a spy. Then we import the module into our test so we can set the mock implementation of the spy in every test. In the example we set the behaviour, so that it returns the exec method, which then is called by your code with the error/success object. The mock then just call the error part. After that you can first test that Mailgun.sendPlaintextEmail was called with the correct parameters, then you can test that cb was called with "someError" and null.

In another test you can just set the behaviour of exec so it will call the success method.


问:
How to get as e.target the exact element at which onClick is specified?
I have a React Component and give it onClick event handler:

```<code>function Item(props) {
  return <li onClick={props.onClick}>{props.children}</li>
}
</code>```

Then I use the Component like this:

```<code><Item onClick={ function(e) {console.log(e.target)} }>
  <span>This element is returned as e.target if clicked on it!</span>
</Item>
</code>```

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.

The problem is:

If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...

The question is:

Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li)?

PS. No jQuery for solution if possible.

答:
event.target will always give you the element, which dispatched the event. In order to get the element who's listener is currently processed, you have to use event.currentTarget.

This should help: https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

Here is a simple example to illustrated your issue:

const Inner = () =>
Inner

const Outer = () => {
  const clickHandler = e => {
    console.log('target:', e.target.getAttribute('class'));
    console.log('currentTarget:', e.currentTarget.getAttribute('class'));
  };

  return (
<Inner />
);
};

ReactDOM.render(<Outer/>, document.getElementById('app'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer {
  background: rosybrown;
  padding: 40px;
}

.inner {
  background: cornsilk;
  padding: 20px;
}</code>```

```

Body:
I have a React Component and give it onClick event handler:

function Item(props) {
  return
{props.children}

}

Then I use the Component like this:

<Item onClick={ function(e) {console.log(e.target)} }>
  This element is returned as e.target if clicked on it!
</Item>

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.

The problem is:

If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...

The question is:

Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li)?

PS. No jQuery for solution if possible.

Body:
event.target will always give you the element, which dispatched the event. In order to get the element who's listener is currently processed, you have to use event.currentTarget.

This should help: https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

Here is a simple example to illustrated your issue:

const Inner = () => <div className="inner">Inner</div>

const Outer = () => {
  const clickHandler = e => {
    console.log('target:', e.target.getAttribute('class'));
    console.log('currentTarget:', e.currentTarget.getAttribute('class'));
  };

  return (<div className="outer" onClick={clickHandler}><Inner /></div>);
};

ReactDOM.render(<Outer/>, document.getElementById('app'));

.outer {
  background: rosybrown;
  padding: 40px;
}

.inner {
  background: cornsilk;
  padding: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>


问:
Connection issue while connecting to HANA DB via JDBC
I am connecting HANA DB via ngdbc.jar. Connection is made properly but after running query 3-4 times connection to HANA DB is lost. When I restart my JAVA server again it works for 3-4 times. Can anyone help?

Error Msg-

```<code>WARN  [org.hibernate.util.JDBCExceptionReporter] (http--0.0.0.0-8080-6) SQL Error: -708, SQLState: 08006
 ERROR [org.hibernate.util.JDBCExceptionReporter] (http--0.0.0.0-8080-6) Data receive failed [Connection reset].
 INFO  [com.ultimatix.controller.MetricsController] (http--0.0.0.0-8080-6) context setMonthFreezeDateorg.hibernate.exception.JDBCConnectionException: could not execute query
 ERROR [org.hibernate.transaction.JDBCTransaction] (http--0.0.0.0-8080-6) JDBC rollback failed: com.sap.db.jdbc.exceptions.jdbc40.SQLNonTransientConnectionException: Connection to database server lost; check server and network status [System error: Socket closed]
</code>```

答:
I can see you are using Hibernate based on your log.

Can you elaborate a little bit on your stack?

As @RC said, you should consider connection pooling instead of opening direct connections if this is what you are doing in your "JAVA" server.

May be your are keeping the connection open for too long and it times out.

These are all guesses, until you can share any logs or sample code.

One more thing,  related to the ngjdbc driver only, there is a "reconnect" connection property which by default is set to false.

Regards

Body:
I am connecting HANA DB via ngdbc.jar. Connection is made properly but after running query 3-4 times connection to HANA DB is lost. When I restart my JAVA server again it works for 3-4 times. Can anyone help?

Error Msg-

WARN  [org.hibernate.util.JDBCExceptionReporter] (http--0.0.0.0-8080-6) SQL Error: -708, SQLState: 08006
 ERROR [org.hibernate.util.JDBCExceptionReporter] (http--0.0.0.0-8080-6) Data receive failed [Connection reset].
 INFO  [com.ultimatix.controller.MetricsController] (http--0.0.0.0-8080-6) context setMonthFreezeDateorg.hibernate.exception.JDBCConnectionException: could not execute query
 ERROR [org.hibernate.transaction.JDBCTransaction] (http--0.0.0.0-8080-6) JDBC rollback failed: com.sap.db.jdbc.exceptions.jdbc40.SQLNonTransientConnectionException: Connection to database server lost; check server and network status [System error: Socket closed]


答:
```<code>select user_id
from your_table
group by user_id
having count(distinct year(event_date) * 100 + month(event_date)) > 1
</code>```

Title: Users that returned

Body:
I have a table with [EVENT_DATE] and [USER_ID], I would like to know how to count the users who came back in the same month.

Table_01
-------------------------------------------
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

The answering being 2, because users 0006235012201 & 0006235012203 both came back within the same month.

EDIT: Sorry

I am looking to get the count by month.

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

This is what I have, but it isn't correct as it seems to be listing users.

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016. Compatibility level: SQL Server 2005 (90)


问:
App crashes if Activity starts portrait Mode
I have Android Studio 2.3 bet 3, somehow my application is behaving strangely. If the activity starts in portrait mode it crashes straight a way. But if it starts in landscape mode it does well even if i rotate to portrait mode.

Here are the crash logs.but same XML file line and error comes for all activities.

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.activity.VisitsActivity}: android.view.InflateException: Binary XML file line #43: Error inflating class android.support.v7.widget.ActionBarContextView
</code>```

答: dimen.xml for portrait doesn't have some values which are defined in landscape dimen.xml. that's why it crashes in portrait mode</p>

Body:
I have Android Studio 2.3 bet 3, somehow my application is behaving strangely. If the activity starts in portrait mode it crashes straight a way. But if it starts in landscape mode it does well even if i rotate to portrait mode.

Here are the crash logs.but same XML file line and error comes for all activities.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.activity.VisitsActivity}: android.view.InflateException: Binary XML file line #43: Error inflating class android.support.v7.widget.ActionBarContextView


问:
How do I select the top ten scores in a database table full of scores using linq in C#
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

```<code>var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;
</code>```

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

答:
```<code>var TopTen =  from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t;
TopTen = TopTen.Take(10).ToArray();
</code>```

Last statement will make sure the query is executed.

Body:
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

Body:
var TopTen =  from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t;
TopTen = TopTen.Take(10).ToArray();

Last statement will make sure the query is executed.


问:
Most efficient way to get the highest number from a collection of integers
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

```<code>int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }
</code>```

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

答:
With Java 8 you can find the max using the Stream API but, this does not solve the O(n) problem. However, element access is less computationally expensive than a normal iterator;

```<code>list.stream().mapToInt(i -> i).max().getAsInt();
</code>```

Body:
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

Body:
With Java 8 you can find the max using the Stream API but, this does not solve the O(n) problem. However, element access is less computationally expensive than a normal iterator;

list.stream().mapToInt(i -> i).max().getAsInt();


问:
Why do we need AML - ACPI Machine Language?
As I understand, ACPI defines a generic hardware programming model where operating system relies on the OEM firmware provided AML (ACPI machine language) code to manipulate the hardware.

In order to execute the AML code, operating system has to incorporate an AML interpreter.

So, it looks to me that firmware developers use AML to provide a control interface between platform hardware and operating system.

But do we really need AML?

I think ultimately the hardware can only be configured through the native instruction of the platform. So the AML interpreter must translate the AML into native instructions otherwise it cannot be executed on the platform.

But what's the point of using an intermediate language like AML? I mean though the AML is said to be platform-independent, which means I can use AML to describe my platform in a non-native way.

But the AML is part of the platform firmware in practice. And the entire firmware has already been built into the target platform's native instructions. So what good can it be to make such a little part of the firmware as platform-independent? Why not just use native instructions? There must be some way to let OS use it as well. And this way operating system doesn't need the AML interpreter at all. A lot of complexity can be avoided.

答:
Originally, hardware for "80x86 PC" was cloned from IBM's PC, and this created an effective de-facto standard for hardware to follow. However it didn't take long before manufacturers wanted to add features that didn't previously exist, where there was no (official or de-facto) standard to follow.

This led to a major problem for operating system software (how do you support "non-standard chaos"). Some standards were created for some things (APM, etc) but they didn't really cover everything needed and became out-of-date. ACPI was created to fix this.

Ideally, what was (and still is) needed is standards that allow operating system to detect and use supported features of the motherboard. For example, a "standardised case temperature and fan control" device (with support for detecting how many fans, temperature sensors, etc), or a "standardised CPU speed/power consumption", a "PCI slot IRQ routing for IO APICs" standard, a "hot-plug PCI controller device" standard, etc.

However, ACPI didn't provide useful standards that hardware manufacturers and operating systems can use. Instead, ACPI provided an over-engineered mess (AML) to allow an OS to cope with ACPI's failure to standardise the hardware.

Essentially; we "need" AML now because it's the only viable way for an OS to work-around the "non-standard chaos" problem that ACPI failed to fix.

The problem with providing native code instead of AML is that different operating systems use CPUs in different ways (e.g. native 64-bit 80x86 code in firmware would be useless for an older "32-bit only" OS). AML provides portability between different types of CPUs and between the same CPU/s in different modes.

Also; native code is considered a major security problem (rootkits, etc); and people tend to think an interpreted language mitigates that problem. Of course in practice AML needs far too much access to the underlying hardware and does it in a way that an OS can't check, and there's isn't even a way for an OS to determine if the AML has been maliciously modified before the OS booted. For these reasons AML is still a major security problem despite using interpreted language.


问:
How to rename data frame column by taking only the first value of the splitter string
I have the following data frame:

```<code>df <- structure(list(n.foldchange = c(2, 3, 5), s.foldchange = c(4,
0.2, 100.3)), .Names = c("n.foldchange", "s.foldchange"), row.names = c(NA,
-3L), class = "data.frame")
</code>```

Which looks like this:

```<code>  n.foldchange s.foldchange
1            2          4.0
2            3          0.2
3            5        100.3
</code>```

What I want to do is to rename the column by removing the value after ..
Yielding

```<code>             n            s
1            2          4.0
2            3          0.2
3            5        100.3
</code>```

How can I do that? (with tidyverse possible?)

答:
We can do this with sub to match the . (escape the . (\\.) to get the literal meaning of . as it is a metacharacter which means any character) followed by other characters (.*) and replace it with blanks

```<code>names(df) <- sub("\\..*", "", names(df))
</code>```

Or using substring or substr

```<code>names(df) <- substring(names(df), 1,1)
</code>```

Body:
I have the following data frame:

df <- structure(list(n.foldchange = c(2, 3, 5), s.foldchange = c(4,
0.2, 100.3)), .Names = c("n.foldchange", "s.foldchange"), row.names = c(NA,
-3L), class = "data.frame")

Which looks like this:

  n.foldchange s.foldchange
1            2          4.0
2            3          0.2
3            5        100.3

What I want to do is to rename the column by removing the value after ..
Yielding

             n            s
1            2          4.0
2            3          0.2
3            5        100.3

How can I do that? (with tidyverse possible?)

Body:
We can do this with sub to match the . (escape the . (\\.) to get the literal meaning of . as it is a metacharacter which means any character) followed by other characters (.*) and replace it with blanks

names(df) <- sub("\\..*", "", names(df))

Or using substring or substr

names(df) <- substring(names(df), 1,1)


问:
Auto Create Dimensions in Android
I am developing for android and I am using the Android Studio.I have many XML files and I never used the dimens.xml. Now I want to use it, but I don't want to go through the pains of creating a dimension for each view. I was wondering if there is a programming out there that can automatically do this, or if there is a function in Android Studio to create the dimension for every view that I have. Something simple, as in fewest clicks as possible. Otherwise, I might consider writing a script. </p>

答:
Sorry I know it was too late for the answer...There is no auto create dimension.But there is already dimension are created by a person.

Click this link to Download the dimension

here you can see different types of dimension for different screen size...
you can download individually or all together. Download and paste it in the res folder.

P.S: Please copy the dimens.xml from vlaues(in the site) and paste in your project res > values...

Update:there is also another way. Paste this code in gradle and sync

compile 'com.intuit.sdp:sdp-android:1.0.3

Hope It helps...

Title: Auto Create Dimensions in Android


答:
Assuming your date column is an actual MySQL date column:</p>

```<code>SELECT * FROM my_table WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK);
</code>```

Title: Select * from this week

Body:
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

$week = Date('W');

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

$sql = 'SELECT * FROM my_table WHERE week = $week';

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

Body:
Assuming your date column is an actual MySQL date column:

SELECT * FROM my_table WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK);


问:
How to get the values from HBase table?
I have a table in Hbase with one column family called aand around 30 columns in it. Below is a sample that shows cell values of two row keys-

```<code>ROW                                  COLUMN+CELL
 00:001000574                        column=a:aasbig, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasdel, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasdhq, timestamp=1486493154559, value=false
 00:001000574                        column=a:aasfsc, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasgbm, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasgbr, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasmcu, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasser, timestamp=1486493154559, value=true
 00:001000574                        column=a:aastlp, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasvia, timestamp=1486493154559, value=true
 00:001000707                        column=a:aasbig, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasdel, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasdhq, timestamp=1486493154559, value=true
 00:001000707                        column=a:aasfsc, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasgbm, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasgbr, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasmcu, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasser, timestamp=1486493154559, value=false
 00:001000707                        column=a:aastlp, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasvia, timestamp=1486493154559, value=false
</code>```

Each column has a value with either true or false. These values are subjected to change and week later the values may be different. I would like to capture the old and new values. The result should be stored in a CSV file.

My requirement is, when I run the code for the first time I should see the OLDVALUE as NULL and all the values from the HBase table should be a part of NEWVALUE.

Below is the output I want to see in a CSV file when run for the first time.

```<code>NUM,PRODUCT,OLDVALUE,NEWVALUE
001000574,aasbig,NULL,true
001000574,aasdel,NULL,true
001000574,aasdhq,NULL,false
001000574,aasfsc,NULL,true
001000574,aasgbm,NULL,true
001000574,aasgbr,NULL,true
001000574,aasmcu,NULL,true
001000574,aasser,NULL,true
001000574,aastlp,NULL,true
001000574,aasvia,NULL,true
001000707,aasbig,NULL,false
001000707,aasdel,NULL,false
001000707,aasdhq,NULL,true
001000707,aasfsc,NULL,false
001000707,aasgbm,NULL,false
001000707,aasgbr,NULL,false
001000707,aasmcu,NULL,false
001000707,aasser,NULL,false
001000707,aastlp,NULL,false
001000707,aasvia,NULL,false
</code>```

From Second time on wards when I run the code all the values in NEWVALUES from the previous run should now be under OLDVALUES and the NEWVALUES should get the current values from the HBase table. Like the below sample output

```<code>NUM,PRODUCT,OLDVALUE,NEWVALUE
001000574,aasbig,true,true
001000574,aasdel,true,true
001000574,aasdhq,false,false
001000574,aasfsc,true,true
001000574,aasgbm,true,false
001000574,aasgbr,true,true
001000574,aasmcu,true,false
001000574,aasser,true,false
001000574,aastlp,true,true
001000574,aasvia,true,true
001000707,aasbig,false,true
001000707,aasdel,false,true
001000707,aasdhq,true,true
001000707,aasfsc,false,false
001000707,aasgbm,false,false
001000707,aasgbr,false,false
001000707,aasmcu,false,true
001000707,aasser,false,true
001000707,aastlp,false,false
001000707,aasvia,false,true
</code>```

What I tried:
I created a Hive-on-Hbase table and while querying the table I was only able to get the NUM and the value. I was unable to get the HBase column name. Also I had challenges in getting the Old and New value unless I implement some join operations.

Can we write Pig script to achieve this?

Any help is much appreciated.

答:
This can be easily done programmatically by following steps:

For first time Scan the table and get its output. There are other optimized variants for this too.

Scan scan = new Scan();
ResultScanner scanner = table.getScanner(scan);
for (Result result = scanner.next(); result != null; result =   scanner.next()){

  //Create required format
}

For next time Scan the table using Range filter providing startTime part time in the API. It will fetch all the records updated after a certain time period. Result will contain versions of the updated record. You can use last and recent version details and generate the output.

Scan scan = new Scan();
scan.setTimeRange(startTime, endTime);
ResultScanner scanner = table.getScanner(scan);
for (Result result = scanner.next(); result != null; result =    scanner.next()){
   NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>> allVersions=result.getMap();
   //allVersions map will give all versions of the record.
   //Create required format
}

I am not sure about Hive or Pig process for this. Hope this helps!

Title: How to get the values from HBase table?

Body:
I have a table in Hbase with one column family called aand around 30 columns in it. Below is a sample that shows cell values of two row keys-

ROW                                  COLUMN+CELL
 00:001000574                        column=a:aasbig, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasdel, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasdhq, timestamp=1486493154559, value=false
 00:001000574                        column=a:aasfsc, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasgbm, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasgbr, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasmcu, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasser, timestamp=1486493154559, value=true
 00:001000574                        column=a:aastlp, timestamp=1486493154559, value=true
 00:001000574                        column=a:aasvia, timestamp=1486493154559, value=true
 00:001000707                        column=a:aasbig, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasdel, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasdhq, timestamp=1486493154559, value=true
 00:001000707                        column=a:aasfsc, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasgbm, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasgbr, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasmcu, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasser, timestamp=1486493154559, value=false
 00:001000707                        column=a:aastlp, timestamp=1486493154559, value=false
 00:001000707                        column=a:aasvia, timestamp=1486493154559, value=false

Each column has a value with either true or false. These values are subjected to change and week later the values may be different. I would like to capture the old and new values. The result should be stored in a CSV file.

My requirement is, when I run the code for the first time I should see the OLDVALUE as NULL and all the values from the HBase table should be a part of NEWVALUE.

Below is the output I want to see in a CSV file when run for the first time.

NUM,PRODUCT,OLDVALUE,NEWVALUE
001000574,aasbig,NULL,true
001000574,aasdel,NULL,true
001000574,aasdhq,NULL,false
001000574,aasfsc,NULL,true
001000574,aasgbm,NULL,true
001000574,aasgbr,NULL,true
001000574,aasmcu,NULL,true
001000574,aasser,NULL,true
001000574,aastlp,NULL,true
001000574,aasvia,NULL,true
001000707,aasbig,NULL,false
001000707,aasdel,NULL,false
001000707,aasdhq,NULL,true
001000707,aasfsc,NULL,false
001000707,aasgbm,NULL,false
001000707,aasgbr,NULL,false
001000707,aasmcu,NULL,false
001000707,aasser,NULL,false
001000707,aastlp,NULL,false
001000707,aasvia,NULL,false

From Second time on wards when I run the code all the values in NEWVALUES from the previous run should now be under OLDVALUES and the NEWVALUES should get the current values from the HBase table. Like the below sample output

NUM,PRODUCT,OLDVALUE,NEWVALUE
001000574,aasbig,true,true
001000574,aasdel,true,true
001000574,aasdhq,false,false
001000574,aasfsc,true,true
001000574,aasgbm,true,false
001000574,aasgbr,true,true
001000574,aasmcu,true,false
001000574,aasser,true,false
001000574,aastlp,true,true
001000574,aasvia,true,true
001000707,aasbig,false,true
001000707,aasdel,false,true
001000707,aasdhq,true,true
001000707,aasfsc,false,false
001000707,aasgbm,false,false
001000707,aasgbr,false,false
001000707,aasmcu,false,true
001000707,aasser,false,true
001000707,aastlp,false,false
001000707,aasvia,false,true

What I tried:
I created a Hive-on-Hbase table and while querying the table I was only able to get the NUM and the value. I was unable to get the HBase column name. Also I had challenges in getting the Old and New value unless I implement some join operations.

Can we write Pig script to achieve this?

Any help is much appreciated.


问:
PHPMailer SMTP Error: Could not authenticate Mercury localhost
Currently I'm testing my email format and email send on localhost. I use XAMPP and have 'set up' Mercury mail server. I didn't change anything and made a new user.

Here's a pic of the local users:

Then, I have this in PHP (not all the code but the important part):

```<code>$mailer = new mailer\Mailer();
$mailer->setCustomSettings();
// Some addAddress, From, subject and content variables are set here....
$mailer->send();
</code>```

And then setCustomSettings look like this:

```<code>public function setCustomSettings() {
    $this->CharSet = 'UTF-8';
    $this->isSMTP();
    $this->Host = 'localhost';
    $this->SMTPAuth = true;
    $this->Username = 'Admin';
    $this->Password = '*******';

    //$this->SMTPSecure = 'tls';
    $this->Port = 25;
    $this->imapHost = '127.0.0.1';
}
</code>```

Now, I hoped it'd work but unfortunately it doesn't. I get the following error:

```<code><b>Fatal error</b>:  Uncaught exception 'mailer\phpmailerException' with message 'SMTP Error: Could not authenticate.' in D:\xampp\htdocs\FOLDER\classes\mailer\PHPMailer.php:1352
</code>```

I know my password is correct, you can see the user exists and I can login on Roundcube on my email.

With SMTPDebug I get the following output:

```<code>2017-03-27 07:57:18 SERVER -> CLIENT: 220 localhost ESMTP server ready.
2017-03-27 07:57:18 CLIENT -> SERVER: EHLO SOMENAME.local
2017-03-27 07:57:18 SERVER -> CLIENT: 250-localhost Hello SOMENAME.local; ESMTPs are:
                                  250-TIME
                                  250-SIZE 0
                                  250 HELP
2017-03-27 07:57:18 CLIENT -> SERVER: QUIT
2017-03-27 07:57:18 SERVER -> CLIENT: 221 localhost Service closing channel.
2017-03-27 07:57:18 SMTP Error: Could not authenticate.
</code>```

答:
This shows that there is something missing on your mail server. This is the list of capabilities it says it supports:

```<code>250-TIME
250-SIZE 0
250 HELP
</code>```

Notice that this list does not include the AUTH extension, but you've asked PHPMailer to authenticate, but it can't because your server does not support authentication, so it gives up. To compare, this is what Gmail says (after STARTTLS):

```<code>250-smtp.gmail.com at your service
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
</code>```

You can see that it lists a whole load of AUTH mechanisms.

You should be able to solve this by simply disabling authentication:

```<code>$this->SMTPAuth = false;
</code>```

or by altering the config of your mail server so that it offers authentication.

While I'm here, why don't you put what's in your setCustomSettings() method into a constructor method, so you don't need to call it?

Body:
Currently I'm testing my email format and email send on localhost. I use XAMPP and have 'set up' Mercury mail server. I didn't change anything and made a new user.

Here's a pic of the local users:

Then, I have this in PHP (not all the code but the important part):

$mailer = new mailer\Mailer();
$mailer->setCustomSettings();
// Some addAddress, From, subject and content variables are set here....
$mailer->send();

And then setCustomSettings look like this:

public function setCustomSettings() {
    $this->CharSet = 'UTF-8';
    $this->isSMTP();
    $this->Host = 'localhost';
    $this->SMTPAuth = true;
    $this->Username = 'Admin';
    $this->Password = '*******';

    //$this->SMTPSecure = 'tls';
    $this->Port = 25;
    $this->imapHost = '127.0.0.1';
}

Now, I hoped it'd work but unfortunately it doesn't. I get the following error:

Fatal error:  Uncaught exception 'mailer\phpmailerException' with message 'SMTP Error: Could not authenticate.' in D:\xampp\htdocs\FOLDER\classes\mailer\PHPMailer.php:1352

I know my password is correct, you can see the user exists and I can login on Roundcube on my email.

With SMTPDebug I get the following output:

2017-03-27 07:57:18 SERVER -> CLIENT: 220 localhost ESMTP server ready.
2017-03-27 07:57:18 CLIENT -> SERVER: EHLO SOMENAME.local
2017-03-27 07:57:18 SERVER -> CLIENT: 250-localhost Hello SOMENAME.local; ESMTPs are:
                                  250-TIME
                                  250-SIZE 0
                                  250 HELP
2017-03-27 07:57:18 CLIENT -> SERVER: QUIT
2017-03-27 07:57:18 SERVER -> CLIENT: 221 localhost Service closing channel.
2017-03-27 07:57:18 SMTP Error: Could not authenticate.

Body:
This shows that there is something missing on your mail server. This is the list of capabilities it says it supports:

250-TIME
250-SIZE 0
250 HELP

Notice that this list does not include the AUTH extension, but you've asked PHPMailer to authenticate, but it can't because your server does not support authentication, so it gives up. To compare, this is what Gmail says (after STARTTLS):

250-smtp.gmail.com at your service
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8

You can see that it lists a whole load of AUTH mechanisms.

You should be able to solve this by simply disabling authentication:

$this->SMTPAuth = false;

or by altering the config of your mail server so that it offers authentication.

While I'm here, why don't you put what's in your setCustomSettings() method into a constructor method, so you don't need to call it?


问:
PHP & PDO: Can connect to DB; can't seem to query
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

```<code> private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }
</code>```

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

答:
Array ( [0] => 00000 [1] => 1046 [2] => No database selected ) Array ( )

Nevermind, I guess. It turns out that while migrating from using regular MySQL functions, I wasn't setting $this->sName ($this->sName was null. I'm half surprised it didn't throw an exception. Only half, though)

Fixed.

But thank you guys for the answers :)

Body:
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

 private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?


问:
Queue generated many time for SqlTableDependency C#
For Sql Table Dependency every time new Queue get generated in the service broker Tag in SQL server .

I am getting notification from the SQL using C# language used Sql Table Dependency techniques.

need only one queue in service broker .

thanks in advance .

答:
Newest version fix this problem.
Just try to get latest package.</p>