问:
jQuery Selector From Table
I have a table like below:

```<code><table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button id="getVal">Get</button></td>
<tr>
</table>
</code>```

I want to click 'Get' button then get all td value in tr. I try this code but it's not working.

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('#getVal').click(function () {
         var name    = $(this).find('td:first');
         var surname = $(this).find('td:second');
        });
    });
</script>
</code>```

How can i do that? Please help me!

答:
You can't use the same id multiple times. Give them a class instead.

It would change to this:

```<code><table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table>
</code>```

As long as you know for sure it are always the first and second  you can use the following jQuery (still feels hacky).

```<code>$('.getVal').click(function () {
  var name    = $(this).parent().parent().find('td:first').text();
  var surname = $(this).parent().parent().find('td:nth-child(2)').text();
  console.log(name);
  console.log(surname);
});
</code>```

A working JSFiddle can be found here

Title: jQuery Selector From Table

Body:
I have a table like below:

    james
    sawyer
    <button id="getVal">Get</button>

    kate
    deluna
    <button id="getVal">Get</button>

    tupac
    shakur
    <button id="getVal">Get</button>

I want to click 'Get' button then get all td value in tr. I try this code but it's not working.

How can i do that? Please help me!

Body:
You can't use the same id multiple times. Give them a class instead.

It would change to this:

<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table>

As long as you know for sure it are always the first and second <td> you can use the following jQuery (still feels hacky).

$('.getVal').click(function () {
  var name    = $(this).parent().parent().find('td:first').text();
  var surname = $(this).parent().parent().find('td:nth-child(2)').text();
  console.log(name);
  console.log(surname);
});

A working JSFiddle can be found here


来源: stackexchange

问:
How can cached value be invalidated in single thread?
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

```<code>public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}
</code>```

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;
</code>```

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);
</code>```

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.

答:
Review your IIS application pool recycling options to rule out a recycle event.  Because an application pool recycle, will clear your cache.

Per the App pool recycling settings docs:

You can specify that IIS recycle an application pool at set intervals
  (such as every 180 minutes), at a specific time each day, or after the
  application pool receives a certain number of requests. You can also
  configure the  element to restart the application pool when
  the worker process virtual memory and physical memory usage reaches a
  specific threshold.

Even changing your config can recycle the app pool.

Ensure that no other apps are sharing your app pool and then turn on recycle logging and reproduce the issue.  See if the cache disappearance is correlated with an app pool recycle in the log.  If so, go from there to determine why the recycle is happening and then make a configuration change so app pool doesn't recycle during normal operating hours.

ContentLicense: CC BY-SA 3.0

Body:
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.


问:
Magento not writing to log files
My Magento installation suddenly stopped writing to log files.
If I try to output the following:

```<code>Mage::log('Test', null, 'test.log');
</code>```

Magento creates this file but it's empty.

Logging is activated in settings -> developer.

答:
Try this<br> </p>

```<code>Mage::log('Test', null, 'test.log', true);
</code>```

Title: Magento not writing to log files

Body:
My Magento installation suddenly stopped writing to log files.
If I try to output the following:

Mage::log('Test', null, 'test.log');

Magento creates this file but it's empty.

Logging is activated in settings -> developer.

Body:
Try this

Mage::log('Test', null, 'test.log', true);


问:
Django-registration unique email with hmac backend
I use django-registration package in my app. Is it possible to use unique email while using the (proposed by the documentation) hmac backend?

I have found many posts that answer for the model backend, not the hmac.

Edit: Notice that I am not talking about default or model backend, but HMAC

答:
Answering my own question:

It was a duplicate as mentioned (original answer here by seddonym), sorry for my misunderstanding.

The only thing to do is replace

```<code>from registration.backends.default.views import RegistrationView
</code>```

with

```<code>from registration.backends.hmac.views import RegistrationView
</code>```

Body:
Answering my own question:

It was a duplicate as mentioned (original answer here by seddonym), sorry for my misunderstanding.

The only thing to do is replace

from registration.backends.default.views import RegistrationView

with

from registration.backends.hmac.views import RegistrationView


问:
Copy Row A1 from Sheet 1 into Row A1 Sheet 2
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424</p>

```<code>mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste
</code>```

答:
A small loop code.let me know if it works.</p>

```<code>Sub COPYPASTeHEADER()
Dim K As Integer
For K = 2 To ActiveWorkbook.Sheets.Count
Sheets("All_Data").Range("A1:O1").COPY Sheets(K).Range("A1")
Next
End Sub
</code>```

Body:
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424

mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste

Body:
A small loop code.let me know if it works.

Sub COPYPASTeHEADER()
Dim K As Integer
For K = 2 To ActiveWorkbook.Sheets.Count
Sheets("All_Data").Range("A1:O1").COPY Sheets(K).Range("A1")
Next
End Sub


问:
Is there any way to reduce element locating time in Selenium WebDriver?
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

```<code><div class="col-md-12">
  <label class="mmk-filter-control">Preferred Source City : </label>
     <div class="pull-right refe-link">
     <div class="mmk-filter-control mmk-select-filter pull-right mr5">
     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options
</code>```

And code is:

```<code>if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}
</code>```

Is there any way to overcome and make the test fast?

答:
The issue is likely due to getFirstSelectedOption since the method sends the isSelected command for each option:

https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/support/ui/Select.java#L93

So instead of :

```<code>s.getFirstSelectedOption().getText()
</code>```

, I would use a selector to get the first selected option:

```<code>preferredCity.findElement(By.cssSelector("option[selected]")).getText()
</code>```

Update

The selected attribute is not updated in the DOM when the selection changes.
So an alternative would be to read the selectedIndex property on <select> :

```<code>int selectedIndex = Integer.parseInt(preferredCity.getAttribute("selectedIndex"));

WebElement selectedOption = preferredCity.findElement(By.cssSelector(
    String.format("option:nth-child(%s)", selectedIndex + 1)));

String text = selectedOption.getText();
</code>```

or with executeScript:

```<code>String JS_GET_FIRST_SELECTED_OPTION =
    "var e=arguments[0], i=e.selectedIndex; return i < 0 ? null : e.options[i];";

JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement selectedOption = (WebElement)jse.executeScript(JS_GET_FIRST_SELECTED_OPTION, preferredCity);

if (selectedOption == null)
  throw new NoSuchElementException("No options are selected");)

String text = selectedOption.getText();
</code>```

Body:
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

  Preferred Source City :

     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options

And code is:

if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}

Is there any way to overcome and make the test fast?

Body:
The issue is likely due to getFirstSelectedOption since the method sends the isSelected command for each option:

https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/support/ui/Select.java#L93

So instead of :

s.getFirstSelectedOption().getText()

, I would use a selector to get the first selected option:

preferredCity.findElement(By.cssSelector("option[selected]")).getText()

Update

The selected attribute is not updated in the DOM when the selection changes.
So an alternative would be to read the selectedIndex property on <select> :

int selectedIndex = Integer.parseInt(preferredCity.getAttribute("selectedIndex"));

WebElement selectedOption = preferredCity.findElement(By.cssSelector(
    String.format("option:nth-child(%s)", selectedIndex + 1)));

String text = selectedOption.getText();

or with executeScript:

String JS_GET_FIRST_SELECTED_OPTION =
    "var e=arguments[0], i=e.selectedIndex; return i < 0 ? null : e.options[i];";

JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement selectedOption = (WebElement)jse.executeScript(JS_GET_FIRST_SELECTED_OPTION, preferredCity);

if (selectedOption == null)
  throw new NoSuchElementException("No options are selected");)

String text = selectedOption.getText();


答:
Do this way,

```<code><table>
    <tr>
        <td>james</td>
        <td>sawyer</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>kate</td>
        <td>deluna</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>tupac</td>
        <td>shakur</td>
        <td><button class="get_button">Get</button></td>
    <tr>
</table>
</code>```

And then select your td based on class, like below.

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('.get_button').click(function () {
            var name    = $(this).find('td:first');
            var surname = $(this).find('td:second');
        });
    });
</script>
</code>```

Title: jQuery Selector From Table

Body:
Do this way,

<table>
    <tr>
        <td>james</td>
        <td>sawyer</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>kate</td>
        <td>deluna</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>tupac</td>
        <td>shakur</td>
        <td><button class="get_button">Get</button></td>
    <tr>
</table>

And then select your td based on class, like below.

<script type="text/javascript">
    $(document).ready(function() {
        $('.get_button').click(function () {
            var name    = $(this).find('td:first');
            var surname = $(this).find('td:second');
        });
    });
</script>


问:
Lambda Expression: How to map to a List rather than IEnumerable?
I am using the following code to avoid repetition:

```<code> private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                Actions =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                {
                    incident_ID = z.incident_id,
                    action_ID = z.action_id,
                    action_description = z.action_description

                })
                //actionList = new List<ActionVM>(d => mappingActionVM)

            };
        }
</code>```

Then I can do the following:

List<IncidentVM> incidents = db.Incident_Log.Select(mappingIncidentVM).ToList();

And it maps the Incident_Log entity to my viewModel IncidentVM.
My problem is that I wish I could map directly to a list rather than an IEnumerable.Something like this:

```<code>  private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                actionList =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                    {
                        incident_ID = z.incident_id,
                        action_ID = z.action_id,
                        action_description = z.action_description

                    }).ToList()

            };
        }
</code>```

But that is throwing an error:

LINQ to Entities does not recognize the method System.Collections.Generic.List[ViewModel.ActionVM] ToList[ActionVM](System.Collections.Generic.IEnumerable([ViewModel.ActionVM]) method, and this method cannot be translated into a store expression.

The ToList() is not recognised.

Here is my ViewModel:

```<code> public class IncidentVM
    {

        public int incident_ID { set; get; }

        [Display(Name = "Description*")]
        [Required]
        public string incident_description { get; set; }

        [Display(Name = "Specific Location*")]
        [Required]
        public string location { set; get; }

        public string file_names { set; get; }

//Here is the problem, I 'd like to have only actionList
        public IEnumerable<ActionVM> Actions { get; set; }
        public List<ActionVM> actionList { get; set; }
</code>```

And here is the model for the Action_Log Object:

```<code>public partial class Action_Log
{
    public int action_id { get; set; }
    public int incident_id { get; set; }
    public string action_description { get; set; }

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

Is it possible to map directly to a List in this case?

答: The problem is that LINQ cannot translate ToList so just go for the IEnumerable and then use ToList when working on local data (after you have executed the query) and you should be fine.

Body:
I am using the following code to avoid repetition:

 private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                Actions =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                {
                    incident_ID = z.incident_id,
                    action_ID = z.action_id,
                    action_description = z.action_description

                })
                //actionList = new List<ActionVM>(d => mappingActionVM)

            };
        }

Then I can do the following:

List<IncidentVM> incidents = db.Incident_Log.Select(mappingIncidentVM).ToList();

And it maps the Incident_Log entity to my viewModel IncidentVM.
My problem is that I wish I could map directly to a list rather than an IEnumerable.Something like this:

  private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                actionList =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                    {
                        incident_ID = z.incident_id,
                        action_ID = z.action_id,
                        action_description = z.action_description

                    }).ToList()

            };
        }

But that is throwing an error:

LINQ to Entities does not recognize the method System.Collections.Generic.List[ViewModel.ActionVM] ToList[ActionVM](System.Collections.Generic.IEnumerable([ViewModel.ActionVM]) method, and this method cannot be translated into a store expression.

The ToList() is not recognised.

Here is my ViewModel:

 public class IncidentVM
    {

        public int incident_ID { set; get; }

        [Display(Name = "Description*")]
        [Required]
        public string incident_description { get; set; }

        [Display(Name = "Specific Location*")]
        [Required]
        public string location { set; get; }

        public string file_names { set; get; }

//Here is the problem, I 'd like to have only actionList
        public IEnumerable<ActionVM> Actions { get; set; }
        public List<ActionVM> actionList { get; set; }

And here is the model for the Action_Log Object:

public partial class Action_Log
{
    public int action_id { get; set; }
    public int incident_id { get; set; }
    public string action_description { get; set; }

    public virtual Incident_Log Incident_Log { get; set; }
}

Is it possible to map directly to a List in this case?


问:
How to check if a mouse is over a control
How does one check if the mouse is over a certain HWND? I have tried using the WM_MOUSELEAVE and WM_MOUSEMOVE messages to keep track, but if you click a button and drag the mouse out of the button, it doesn't receive the WM_MOUSELEAVE until the mouse is released, which is too late, because:

When you click a button, the WM_COMMAND message is only sent if:

1. The mouse was originally depressed over the button

2. The mouse is over the button

3. The mouse is released over the button

I need to replicate this functionality.

答: This is built-in to Windows, it is called 'mouse capture', SetCapture(hWnd).  It ensures you get mouse messages even though the mouse has moved outside of the window.  You call it on the WM_LBUTTONDOWN message notification.</p>

ContentLicense: CC BY-SA 2.5


问:
Google Sign In Button does Nothing
I have implemented the Google Sign In exactly as Google states to according to their website. I had it working about a month ago, now it just does nothing. I tried to redo everything by deleting the cocoapod and following their website to a T but nothing is happening still. It is like none of the delegate methods are being called, and I am unsure why. Any help would be appreciative. Thanks!

```<code>import GoogleSignIn
import Google
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //Get Twitter and set Twitter keys for Application
    Twitter.sharedInstance().startWithConsumerKey("uBedaxDuMDgImGbjun1oYf0ay", consumerSecret: "OaKqBZUesX5CypHCwrTvTZE22jrXIuRsUeZzVaMHej11R5Vh3b")
    Fabric.with([Twitter.self])

    // Initialize sign-in GOOGLE
    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    GIDSignIn.sharedInstance().delegate = self

    return true
}

func application(application: UIApplication,
                 openURL url: NSURL, options: [String: AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
                                                annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

func application(application: UIApplication,
                 openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!,
                                        UIApplicationOpenURLOptionsAnnotationKey: annotation!]
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: sourceApplication,
                                                annotation: annotation)
}

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
            withError error: NSError!) {
    print("SIGNING IN")
    if (error == nil) {
        let email = user.profile.email
        print(user.authentication)
        // ...
    } else {
        print("ERROR = \(error.localizedDescription)")
    }
}
</code>```

View Controller

```<code>import GoogleSignIn
class LoginViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate
 override func viewDidLoad() {

    //Default setup for View Controller
    super.viewDidLoad()

    GIDSignIn.sharedInstance().uiDelegate = self
    var error:NSError?
    GGLContext.sharedInstance().configureWithError(&error)
    if(error != nil) {
        print(error)
    }

    var signInButton = GIDSignInButton(frame: CGRect(x: 0, y: 0, width: 150, height: 400))
    view.addSubview(signInButton)

}
</code>```

EDIT

After HOURS, lol, of figuring this out, the Google Sign-In Button works when it is
1)Held down for more than 2 seconds,
2)Swiped left/down/right but not up
I am unsure of this cause and would be open to suggestions! Thanks!

答:
Quick, Easy Solution:

Steps:

Extend to UIGestureRecognizerDelegate

Paste in the following methods

add dismissOnTap() to your view controller

Code:

```<code>class ViewController: UIViewController, UIGestureRecognizerDelegate {

 override func viewDidLoad() {
        super.viewDidLoad()

        // Call dismissOnTap
        dismissOnTap()

 }

 func dismissOnTap() {
        self.view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))
        tap.delegate = self
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
 }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        if touch.view is GIDSignInButton {
            return false
        }
        return true
    }

    func dismissKeyboard() {
        self.view.endEditing(true)
    }

}
</code>```

Title: Google Sign In Button does Nothing

Body:
I have implemented the Google Sign In exactly as Google states to according to their website. I had it working about a month ago, now it just does nothing. I tried to redo everything by deleting the cocoapod and following their website to a T but nothing is happening still. It is like none of the delegate methods are being called, and I am unsure why. Any help would be appreciative. Thanks!

import GoogleSignIn
import Google
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //Get Twitter and set Twitter keys for Application
    Twitter.sharedInstance().startWithConsumerKey("uBedaxDuMDgImGbjun1oYf0ay", consumerSecret: "OaKqBZUesX5CypHCwrTvTZE22jrXIuRsUeZzVaMHej11R5Vh3b")
    Fabric.with([Twitter.self])

    // Initialize sign-in GOOGLE
    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    GIDSignIn.sharedInstance().delegate = self

    return true
}

func application(application: UIApplication,
                 openURL url: NSURL, options: [String: AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
                                                annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

func application(application: UIApplication,
                 openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!,
                                        UIApplicationOpenURLOptionsAnnotationKey: annotation!]
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: sourceApplication,
                                                annotation: annotation)
}

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
            withError error: NSError!) {
    print("SIGNING IN")
    if (error == nil) {
        let email = user.profile.email
        print(user.authentication)
        // ...
    } else {
        print("ERROR = \(error.localizedDescription)")
    }
}

View Controller

import GoogleSignIn
class LoginViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate
 override func viewDidLoad() {

    //Default setup for View Controller
    super.viewDidLoad()

    GIDSignIn.sharedInstance().uiDelegate = self
    var error:NSError?
    GGLContext.sharedInstance().configureWithError(&error)
    if(error != nil) {
        print(error)
    }

    var signInButton = GIDSignInButton(frame: CGRect(x: 0, y: 0, width: 150, height: 400))
    view.addSubview(signInButton)

}

EDIT

After HOURS, lol, of figuring this out, the Google Sign-In Button works when it is
1)Held down for more than 2 seconds,
2)Swiped left/down/right but not up
I am unsure of this cause and would be open to suggestions! Thanks!

Body:
Quick, Easy Solution:

Steps:

Extend to UIGestureRecognizerDelegate

Paste in the following methods

add dismissOnTap() to your view controller

Code:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

 override func viewDidLoad() {
        super.viewDidLoad()

        // Call dismissOnTap
        dismissOnTap()

 }

 func dismissOnTap() {
        self.view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))
        tap.delegate = self
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
 }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        if touch.view is GIDSignInButton {
            return false
        }
        return true
    }

    func dismissKeyboard() {
        self.view.endEditing(true)
    }

}


问:
Kruskal Algorithm implemenation
I found a tutorial that created the makes and finds methods as such

```<code>public void makeSet(long data) {
        Node node = new Node();
        node.data = data;
        node.parent = node;
        node.rank = 0;
        map.put(data, node);
    }

private Node findSet(Node node) {
        Node parent = node.parent;
        if (parent == node) {
            return parent;
        }
        node.parent = findSet(node.parent);
        return node.parent;
    }
</code>```

Here is the link to the full code to
Here is the link to the Kruskal Algorithm

I'm confused on why they are returning a node who's parent is itself instead of the different node and what the rank is used for when implementing Union when the rank is set to 0. I've tried finding other Kruskal Algorithm code and explanations but there are very few sources that go over the implementation.

答:
Kruskal's algorithm works like this:

Put each node is in its own subtree

Sort edges by their weight

Find first node that connects two nodes that are in different subtrees

Join subtrees that the edge connects

Repeat steps 3 and 4 until there are no more edges to test or the tree is complete

In this particular implementation, each node can be in one of two states:

It's subtree's "master" node (if node.parent == node)

Is's a non-master not and has a link to another node in the same subtree (if node.parent != node)

When you test whether an edge connects two separate subtrees, you compare the master of the first node to the master of 2nd node. If they are equal, then the nodes are in the same subtree and you can ignore the edge.

If the master of 1st node is not equal to the master of 2nd node, you join those subtrees: set the parent of "master of 2nd node" to the master of 1st node.

When you end up with a single master node that has (node.parent == node) then you have a full tree. Of course, it's easier to simply count the edges, as you expect N-1 edges for a tree.

Title: Kruskal Algorithm implemenation

Body:
I found a tutorial that created the makes and finds methods as such

public void makeSet(long data) {
        Node node = new Node();
        node.data = data;
        node.parent = node;
        node.rank = 0;
        map.put(data, node);
    }

private Node findSet(Node node) {
        Node parent = node.parent;
        if (parent == node) {
            return parent;
        }
        node.parent = findSet(node.parent);
        return node.parent;
    }

Here is the link to the full code to
Here is the link to the Kruskal Algorithm

I'm confused on why they are returning a node who's parent is itself instead of the different node and what the rank is used for when implementing Union when the rank is set to 0. I've tried finding other Kruskal Algorithm code and explanations but there are very few sources that go over the implementation.


问:
How do I include a date column in a google visualisation datatable column taken from a spreadsheet
I have a Google sheet that look like this:

```<code>   Date     Sales
31/03/2017  1000
30/06/2017  2000
30/09/2017  1500
31/12/2017  2500
31/03/2018  4000
</code>```

If I import this using .arrayToDataTable in Google charts and set the type of column 0 to 'date' or 'string' -  it doesn't like it, because the date is only a formatted number i.e 43190 = 31/3/2018.  so the type has to be 'number' which then only displays the underlying number on the chart and not the date

I can loop through each of the row values and I've tried changing them with this

```<code>function formatDate(date) {
   var d = new Date((date - 25569)*86400*1000),
   locale = "en-us",
   month = d.toLocaleString(locale, { month: "short" });
   var formattedDate = d.getDay() + "/" + month + "/" + d.getFullYear();
   return formattedDate
}
</code>```

this converts the number to a date string - so with an input of, say,  43190 it returns 31/Mar/2018 but I still can't change the column type to 'date'

I could output the dates as strings but they don't sort in chronological order but alphabetical - I want them chronological.

can anybody show me where I'm going wrong?

EDIT:

If I change the function to

```<code>function formatDate(date) {
  var d = new Date((date - 25569)*86400*1000)
  return d
}
</code>```

this now sets the column values to the full date object

but I get an error a saying "Value Sun Jun 30 2013 01:00:00 GMT+0100 (GMT Summer Time) does not match type number in column index 0"

Now this must be referring to the datatable column zero, which in the original table, is a date number.  I've tried adding:

```<code>data.setColumnProperty(0, 'type' , 'date')
</code>```

but seem to get the same error.

perhaps I'm not changing the type at the correct point in the code.

to clarify:  I'm getting the original values from a range in the google sheet then converting that range to a datatable using .arrayToDataTable.  So I'm not sure I can define the column type at the point of making the datatable hence the separate attempt with:

```<code>data.setColumnProperty(0, 'type' , 'date')
</code>```

答:
You have to supply the complete date object in the date-type column.

Good documentation about dates can be found here
https://developers.google.com/chart/interactive/docs/datesandtimes#axesgridlinesticks

An example of dates and sales could be

```<code>var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Sales');

        data.addRows([
          [new Date(2015, 0, 1), 5],  [new Date(2015, 0, 2), 7],  [new Date(2015, 0, 3), 3],
          [new Date(2015, 0, 4), 1],  [new Date(2015, 0, 5), 3],  [new Date(2015, 0, 6), 4],
          [new Date(2015, 0, 7), 3],  [new Date(2015, 0, 8), 4],  [new Date(2015, 0, 9), 2],
          [new Date(2015, 0, 10), 5], [new Date(2015, 0, 11), 8], [new Date(2015, 0, 12), 6],
          [new Date(2015, 0, 13), 3], [new Date(2015, 0, 14), 3], [new Date(2015, 0, 15), 5],
          [new Date(2015, 0, 16), 7], [new Date(2015, 0, 17), 6], [new Date(2015, 0, 18), 6],
          [new Date(2015, 0, 19), 3], [new Date(2015, 0, 20), 1], [new Date(2015, 0, 21), 2],
          [new Date(2015, 0, 22), 4], [new Date(2015, 0, 23), 6], [new Date(2015, 0, 24), 5],
          [new Date(2015, 0, 25), 9], [new Date(2015, 0, 26), 4], [new Date(2015, 0, 27), 9],
          [new Date(2015, 0, 28), 8], [new Date(2015, 0, 29), 6], [new Date(2015, 0, 30), 4],
          [new Date(2015, 0, 31), 6], [new Date(2015, 1, 1), 7],  [new Date(2015, 1, 2), 9]
        ]);
</code>```

You could than add the following to options to format your date

```<code>hAxis: {
    format: 'MM/dd/yyyy'
}
</code>```

Body:
I have a Google sheet that look like this:

   Date     Sales
31/03/2017  1000
30/06/2017  2000
30/09/2017  1500
31/12/2017  2500
31/03/2018  4000

If I import this using .arrayToDataTable in Google charts and set the type of column 0 to 'date' or 'string' -  it doesn't like it, because the date is only a formatted number i.e 43190 = 31/3/2018.  so the type has to be 'number' which then only displays the underlying number on the chart and not the date

I can loop through each of the row values and I've tried changing them with this

function formatDate(date) {
   var d = new Date((date - 25569)*86400*1000),
   locale = "en-us",
   month = d.toLocaleString(locale, { month: "short" });
   var formattedDate = d.getDay() + "/" + month + "/" + d.getFullYear();
   return formattedDate
}

this converts the number to a date string - so with an input of, say,  43190 it returns 31/Mar/2018 but I still can't change the column type to 'date'

I could output the dates as strings but they don't sort in chronological order but alphabetical - I want them chronological.

can anybody show me where I'm going wrong?

EDIT:

If I change the function to

function formatDate(date) {
  var d = new Date((date - 25569)*86400*1000)
  return d
}

this now sets the column values to the full date object

but I get an error a saying "Value Sun Jun 30 2013 01:00:00 GMT+0100 (GMT Summer Time) does not match type number in column index 0"

Now this must be referring to the datatable column zero, which in the original table, is a date number.  I've tried adding:

data.setColumnProperty(0, 'type' , 'date')

but seem to get the same error.

perhaps I'm not changing the type at the correct point in the code.

to clarify:  I'm getting the original values from a range in the google sheet then converting that range to a datatable using .arrayToDataTable.  So I'm not sure I can define the column type at the point of making the datatable hence the separate attempt with:

data.setColumnProperty(0, 'type' , 'date')

Body:
You have to supply the complete date object in the date-type column.

Good documentation about dates can be found here
https://developers.google.com/chart/interactive/docs/datesandtimes#axesgridlinesticks

An example of dates and sales could be

var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Sales');

        data.addRows([
          [new Date(2015, 0, 1), 5],  [new Date(2015, 0, 2), 7],  [new Date(2015, 0, 3), 3],
          [new Date(2015, 0, 4), 1],  [new Date(2015, 0, 5), 3],  [new Date(2015, 0, 6), 4],
          [new Date(2015, 0, 7), 3],  [new Date(2015, 0, 8), 4],  [new Date(2015, 0, 9), 2],
          [new Date(2015, 0, 10), 5], [new Date(2015, 0, 11), 8], [new Date(2015, 0, 12), 6],
          [new Date(2015, 0, 13), 3], [new Date(2015, 0, 14), 3], [new Date(2015, 0, 15), 5],
          [new Date(2015, 0, 16), 7], [new Date(2015, 0, 17), 6], [new Date(2015, 0, 18), 6],
          [new Date(2015, 0, 19), 3], [new Date(2015, 0, 20), 1], [new Date(2015, 0, 21), 2],
          [new Date(2015, 0, 22), 4], [new Date(2015, 0, 23), 6], [new Date(2015, 0, 24), 5],
          [new Date(2015, 0, 25), 9], [new Date(2015, 0, 26), 4], [new Date(2015, 0, 27), 9],
          [new Date(2015, 0, 28), 8], [new Date(2015, 0, 29), 6], [new Date(2015, 0, 30), 4],
          [new Date(2015, 0, 31), 6], [new Date(2015, 1, 1), 7],  [new Date(2015, 1, 2), 9]
        ]);

You could than add the following to options to format your date

hAxis: {
    format: 'MM/dd/yyyy'
}


问:
Fixing my background image and website layout on Blogger using CSS or HTML
Heres my website: www.ChrisStephensMusic.net

As you can see the background image is not full size and moves when the page is scrolled. I'd like it to be full size and remain still while the content scrolls. I've tried the CSS suggestions I could find when searching this topic here but they do nothing when I add them to the "Custom CSS" on Blogger. Is there a better way to fix this using HTML or is there something else I need to do to get the custom CSS to be recognized?

答:
Try using this code in your css file for the background image:</p>

```<code>    width: 100%;
    background-size: cover;
    background-attachment: fixed;
</code>```

Body:
Try using this code in your css file for the background image:

    width: 100%;
    background-size: cover;
    background-attachment: fixed;


问:
Access non-type template parameters in constructor
I have a class that looks like this

```<code>#ifndef UNTITLED_FIXEDVECTOR_H
#define UNTITLED_FIXEDVECTOR_H

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector();

private:
    T data[];
};

#endif //UNTITLED_FIXEDVECTOR_H
</code>```

But I can't in any way access length from its constructor:

```<code>#include "FixedVector.h"

FixedVector::FixedVector() {
    T[] data = new T[length]; //**NO LENGTH HERE!!!**
}
</code>```

How can I access non-type template parameter from the constructor so that I can allocate data?

答:
You can implement the body of your constructor in your header file :

```<code>template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector()
    {
      data = new T[length];
    }

private:
    T* data;
};
</code>```

Better yet, use std::array and not dynamic allocation if the length is known at compile time anyway, otherwise use std::vector.

Body:
I have a class that looks like this

#ifndef UNTITLED_FIXEDVECTOR_H
#define UNTITLED_FIXEDVECTOR_H

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector();

private:
    T data[];
};

#endif //UNTITLED_FIXEDVECTOR_H

But I can't in any way access length from its constructor:

#include "FixedVector.h"

FixedVector::FixedVector() {
    T[] data = new T[length]; //**NO LENGTH HERE!!!**
}

How can I access non-type template parameter from the constructor so that I can allocate data?

Body:
You can implement the body of your constructor in your header file :

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector()
    {
      data = new T[length];
    }

private:
    T* data;
};

Better yet, use std::array and not dynamic allocation if the length is known at compile time anyway, otherwise use std::vector.


问:
How Ember does Ember.version() from browser console?
I was studying Javascript / Ember and I was looking into its source codes.
https://github.com/emberjs/ember.js/

While I was studying, I found something interesting and I wonder how it works. As you may know, you can get version number of Ember if you type Ember.VERSION in the browser console. I wanted to do in my project so I started searching codes how Ember did it.

I could find

```<code>// in packages/ember/lib/index.js
Ember.VERSION = VERSION;
...
// Later exports Ember object
</code>```

However I can't find how Ember makes it available in window (from browser). I expected they did like... window['Ember'] = Ember or something like that but I couldn't find any similar codes.

I wonder if there is anyone knows how they make Ember object available throughout window. Thank you so much!

答:
ember-cli-app-version addon can expose your application's name and version info. So you can put your version in your templates via an helper.

The addon also registers the infos to the Ember.libraries so that ember-inspector can understand. You can access the Ember.libraries in a such way:

```<code>Ember.libraries._registry.filter(item=>{return item.name==='my-app-name';})[0].version
</code>```

The addon can give you both package.json information or git describe result.

Body:
I was studying Javascript / Ember and I was looking into its source codes.
https://github.com/emberjs/ember.js/

While I was studying, I found something interesting and I wonder how it works. As you may know, you can get version number of Ember if you type Ember.VERSION in the browser console. I wanted to do in my project so I started searching codes how Ember did it.

I could find

// in packages/ember/lib/index.js
Ember.VERSION = VERSION;
...
// Later exports Ember object

However I can't find how Ember makes it available in window (from browser). I expected they did like... window['Ember'] = Ember or something like that but I couldn't find any similar codes.

I wonder if there is anyone knows how they make Ember object available throughout window. Thank you so much!

Body:
ember-cli-app-version addon can expose your application's name and version info. So you can put your version in your templates via an helper.

The addon also registers the infos to the Ember.libraries so that ember-inspector can understand. You can access the Ember.libraries in a such way:

Ember.libraries._registry.filter(item=>{return item.name==='my-app-name';})[0].version

The addon can give you both package.json information or git describe result.


问:
Go installing package /usr/bin/go not a directory
Im trying to install a Go package but having the following error.

Here is my GOPATH

```<code>p@p-ubuntu:~/ba/docker-lvm-plugin$ echo $GOPATH
/usr/bin/go
</code>```

Package install

```<code>p@p-ubuntu:~/ba/docker-lvm-plugin$ go get github.com/Sirupsen/logrus
    package github.com/Sirupsen/logrus: mkdir /usr/bin/go: not a directory
</code>```

答: Your GOPATH is wrong. It should not be the path to the go binary, it should be the path to the root of your go project directory, which should contain src, pkg, and bin subdirectories. See what should be the values of GOPATH and GOROOT?

Body:
Im trying to install a Go package but having the following error.

Here is my GOPATH

p@p-ubuntu:~/ba/docker-lvm-plugin$ echo $GOPATH
/usr/bin/go

Package install

p@p-ubuntu:~/ba/docker-lvm-plugin$ go get github.com/Sirupsen/logrus
    package github.com/Sirupsen/logrus: mkdir /usr/bin/go: not a directory


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答:
I prefer to regard an interface as a description of a role to be fulfilled by each instance of an implementing class, independent of any implementation inheritance hierarchy.

By way of analogy, you can describe a "screen pass" football play in terms of how certain positions on the team interact. That description, in terms of position (or role or interface) is independent of which player happens to be playing the position at a given time. It's also independent of whether the team happens to have some talented players who can play more than one position.

The advantage of interface-oriented thinking is that it puts the focus on the role that an object fulfills in a given interaction with other objects, without concern for any other roles the object may play in other kinds of interactions. It also allows testing to focus on scenarios that are relevant to a role (and to mock or fake roles in a test scenario).

OwnerDisplayName: koldfyre

Title: Interesting Applications of Interfaces


问:
jQuery changing the name of a field
im trying to change the name of a field on the change state of a select list.

I have the following code

```<code><script>
$('#selectintrole').change(function(){
    $('#proven_keyname').val($(this).val());
};
</script>

<select name="item_options" id="selectintrole">
<option value="20030">Universal (20030)</option>
<option value="4545456">Medium (4545456)</option>
<option value="15447">Large (15447)</option>
</select>

<input name="proven" value="1" type="checkbox" id="proven_keyname" />
</code>```

It doesnt seem to be doing anything though ... when i check the generated source, nothing has changed .... am i missing something?

答:
Your code is running before the elements exist.

Move the script below the HTML, or wrap it in $(function() { ... }), which will run it when the page loads.

EDIT: Demo

Title: jQuery changing the name of a field

Body:
im trying to change the name of a field on the change state of a select list.

I have the following code

<select name="item_options" id="selectintrole">
<option value="20030">Universal (20030)</option>
<option value="4545456">Medium (4545456)</option>
<option value="15447">Large (15447)</option>
</select>

<input name="proven" value="1" type="checkbox" id="proven_keyname" />

It doesnt seem to be doing anything though ... when i check the generated source, nothing has changed .... am i missing something?


问:
Android Instant Apps not running on Pixel
Recently my Pixel started showing the following message:

```<code>Development Mode Active -
URLs will be routed to Dev Manager in order to launch Instant Apps locally.
</code>```

Also, in settings -> apps I can see Google play services for Instant apps.

Now, when I tried wish and buzzfeed tasty so that I can run their Instant apps I was taken to their site and not in the Instant app.

I built an Instant app in Android Studio 3.0 Canary 4.

It is working fine on the emulator but when I connected my Pixel running on android 7 it shows the following error -

Side loading instant app failed: Reading bundle timed out.

and when I retry some more times it shows this -

```<code>Side loading instant app failed: Failure when trying to read bundle.
Unable to connect to Google Play Service ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
</code>```

A same question has been asked here but in this case the problem is with the emulator not a real device.

CompiledSdkVersion  25
  targetSdkVersion  25
buildToolsVersion   25.0.3

Any help would be appreciated and also a list of some already published instant apps I can try.

答:
In your instant App run configuration.
Try To enable Instant APP Provision and "Clear Provisioned Devices Cache"

Body:
Recently my Pixel started showing the following message:

Development Mode Active -
URLs will be routed to Dev Manager in order to launch Instant Apps locally.

Also, in settings -> apps I can see Google play services for Instant apps.

Now, when I tried wish and buzzfeed tasty so that I can run their Instant apps I was taken to their site and not in the Instant app.

I built an Instant app in Android Studio 3.0 Canary 4.

It is working fine on the emulator but when I connected my Pixel running on android 7 it shows the following error -

Side loading instant app failed: Reading bundle timed out.

and when I retry some more times it shows this -

Side loading instant app failed: Failure when trying to read bundle.
Unable to connect to Google Play Service ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}

A same question has been asked here but in this case the problem is with the emulator not a real device.

CompiledSdkVersion  25
  targetSdkVersion  25
buildToolsVersion   25.0.3

Any help would be appreciated and also a list of some already published instant apps I can try.


问:
Min and max properties in scene builder JavaFX do not work
I set min and max properties so that to make my window not resizable. But when I try it out it does not work. What is wrong?

答:
You can try:

```<code>primaryStage.setMaxHeight(A);
primaryStage.setMaxWidth(B);
primaryStage.setMinHeight(A);
primaryStage.setMinWidth(B);
</code>```

Where A and B are doubles.

Body:
You can try:

primaryStage.setMaxHeight(A);
primaryStage.setMaxWidth(B);
primaryStage.setMinHeight(A);
primaryStage.setMinWidth(B);

Where A and B are doubles.


问:
Different child nodes in the same XML
In SQL Server 2008 there is a table with XML column to be queried and there is a need to get the name of the node that is the child of the "Inc" node - in the example below "Architect" and "Professor". We do not know all of the child nodes (Professor, Architect, etc.) so we cannot just outer apply all of the potential child nodes names, but we need to extract their values for every row.
First row:

```<code>  <Inc>
    <Architect>
        <ArchitectLevel>
          <Average>100000</Average>
        </ArchitectLevel>
    </Architect>
  </Inc>
</code>```

Second row:

```<code>    <Inc>
        <Professor>
            <ProfessorLevel>
                <Maximum>100000</Maximum>
                <Minimum>1000</Minimum>
            </ProfessorLevel>
        </Professor>
    </Inc>
</code>```

Does someone now how to do it?

答:
Use local-name() Demo

```<code>declare @x xml =
'<Inc>
  <Architect>
        <ArchitectLevel>
          <Average>100000</Average>
        </ArchitectLevel>
    </Architect>
</Inc>
<Inc>
    <Professor>
        <ProfessorLevel>
            <Maximum>100000</Maximum>
            <Minimum>1000</Minimum>
        </ProfessorLevel>
    </Professor>
</Inc>';

select t.n.value('local-name(.)[1]','varchar(100)')
from @x.nodes('Inc/*') t(n)
</code>```

Title: Different child nodes in the same XML

Body:
In SQL Server 2008 there is a table with XML column to be queried and there is a need to get the name of the node that is the child of the "Inc" node - in the example below "Architect" and "Professor". We do not know all of the child nodes (Professor, Architect, etc.) so we cannot just outer apply all of the potential child nodes names, but we need to extract their values for every row.
First row:

  <Inc>
    <Architect>
        <ArchitectLevel>
          <Average>100000</Average>
        </ArchitectLevel>
    </Architect>
  </Inc>

Second row:

    <Inc>
        <Professor>
            <ProfessorLevel>
                <Maximum>100000</Maximum>
                <Minimum>1000</Minimum>
            </ProfessorLevel>
        </Professor>
    </Inc>

Does someone now how to do it?

Body:
Use local-name() Demo

declare @x xml =
'<Inc>
  <Architect>
        <ArchitectLevel>
          <Average>100000</Average>
        </ArchitectLevel>
    </Architect>
</Inc>
<Inc>
    <Professor>
        <ProfessorLevel>
            <Maximum>100000</Maximum>
            <Minimum>1000</Minimum>
        </ProfessorLevel>
    </Professor>
</Inc>';

select t.n.value('local-name(.)[1]','varchar(100)')
from @x.nodes('Inc/*') t(n)


问:
SQL*Loader: Multiple row delimeter
I have a flat file that needs to be load into a table via SQL*Loader.

The content of the flat file is like:

AAA|BBB

CCC|DDD

EEE|FFF

Below is my expected result after loaded into the table:

AAA

BBB

CCC

DDD

EEE

FFF

So far, I am just able to put "|" as the row delimiter and the control file is like:

```<code>LOAD DATA
INFILE 'TEST.dat' "STR '|'"
TRUNCATE
INTO TABLE TBL_TEST
FIELDS TERMINATED BY '\n'
(TEXT)
</code>```

The output for above are:

AAA

BBB

DDD

FFF

Where CCC and EEE are missing due to the new line.

Is there a way to specify multiple row delimiters?
In my case, the row delimiters are "|" and "\n".

Thanks in advance.

答: Even if you could, it would be real complicated.  First make the data source give you the data in the right format.  Failing that, preprocess the file with a script to replace the pipe characters with a carriage return. Or, load as-is into a staging table, then manipulate from there with standard SQL or PL/SQL.</p>

Title: SQL*Loader: Multiple row delimeter

Body:
I have a flat file that needs to be load into a table via SQL*Loader.

The content of the flat file is like:

AAA|BBB

CCC|DDD

EEE|FFF

Below is my expected result after loaded into the table:

AAA

BBB

CCC

DDD

EEE

FFF

So far, I am just able to put "|" as the row delimiter and the control file is like:

LOAD DATA
INFILE 'TEST.dat' "STR '|'"
TRUNCATE
INTO TABLE TBL_TEST
FIELDS TERMINATED BY '\n'
(TEXT)

The output for above are:

AAA

BBB

DDD

FFF

Where CCC and EEE are missing due to the new line.

Is there a way to specify multiple row delimiters?
In my case, the row delimiters are "|" and "\n".

Thanks in advance.


问:
Change height of element on resize
Hello guys I'm trying to change height of my element dynamically.
These are my variables.

```<code>var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
</code>```

Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.

```<code>$( window ).bind("resize", function(){
    if((windowWidth - currentWidth)<6) {
        $("#line4").css('height', elementHeight-14);
    }
});
</code>```

It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.

答:
You need to measure the current width of the window on every resize event, since it's changing too.</p>

```<code>var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();

$( window ).bind("resize", function(){
  currentWidth = $(window).width()
  if((windowWidth - currentWidth)<6) {
    $("#line4").css('height', elementHeight-14);
  }
});
</code>```

Title: Change height of element on resize

Body:
Hello guys I'm trying to change height of my element dynamically.
These are my variables.

var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();

Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.

$( window ).bind("resize", function(){
    if((windowWidth - currentWidth)<6) {
        $("#line4").css('height', elementHeight-14);
    }
});

It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.

Body:
You need to measure the current width of the window on every resize event, since it's changing too.

var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();

$( window ).bind("resize", function(){
  currentWidth = $(window).width()
  if((windowWidth - currentWidth)<6) {
    $("#line4").css('height', elementHeight-14);
  }
});


问:
Python internal string format indexing with range
I would like to use segment of the same string in a formatted string.

input_string = 'abcdefhijk'
result_string = "A's name is abcd-defh; he does hijk"
```

<p>The intuitive solution is</p>

<pre class="lang-python prettyprint-override"><code>"A's name is {0[0:4]}-{0{[3:7]}; he does {0[6:10]}".format(input_string)
</code>```

And this obviously doesn't work.
What works is the round-about way

"A's name is {0}-{1}; he does {2}".format(input_string[0:4], input_string[3:7], input_string[6:10])
```

Is there any easy way to specify the index range in the formatting string?

答:
Have you tried the below</p>

```<code>result_string = "A's name is %s-%s; he does %s" %(input_string[:4], input_string[3:7], input_string[6:10])
</code>```

Body:
I would like to use segment of the same string in a formatted string.

input_string = 'abcdefhijk'
result_string = "A's name is abcd-defh; he does hijk"

The intuitive solution is

"A's name is {0[0:4]}-{0{[3:7]}; he does {0[6:10]}".format(input_string)

And this obviously doesn't work.
What works is the round-about way

"A's name is {0}-{1}; he does {2}".format(input_string[0:4], input_string[3:7], input_string[6:10])

Is there any easy way to specify the index range in the formatting string?

Body:
Have you tried the below

result_string = "A's name is %s-%s; he does %s" %(input_string[:4], input_string[3:7], input_string[6:10])


答:
CSS

```<code>html {
  background: url(image.png) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</code>```

source: https://css-tricks.com/perfect-full-page-background-image/

Title: Fixing my background image and website layout on Blogger using CSS or HTML

Body:
Heres my website: www.ChrisStephensMusic.net

As you can see the background image is not full size and moves when the page is scrolled. I'd like it to be full size and remain still while the content scrolls. I've tried the CSS suggestions I could find when searching this topic here but they do nothing when I add them to the "Custom CSS" on Blogger. Is there a better way to fix this using HTML or is there something else I need to do to get the custom CSS to be recognized?

Body:
CSS

html {
  background: url(image.png) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

source: https://css-tricks.com/perfect-full-page-background-image/


答:
You need to re-specify the template parameters</p>

```<code>template <typename T, unsigned length>
FixedVector<T,length>::FixedVector() {
   data = new T[length];
}
</code>```

Title: Access non-type template parameters in constructor

Body:
I have a class that looks like this

#ifndef UNTITLED_FIXEDVECTOR_H
#define UNTITLED_FIXEDVECTOR_H

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector();

private:
    T data[];
};

#endif //UNTITLED_FIXEDVECTOR_H

But I can't in any way access length from its constructor:

#include "FixedVector.h"

FixedVector::FixedVector() {
    T[] data = new T[length]; //**NO LENGTH HERE!!!**
}

How can I access non-type template parameter from the constructor so that I can allocate data?

Body:
You need to re-specify the template parameters

template <typename T, unsigned length>
FixedVector<T,length>::FixedVector() {
   data = new T[length];
}


问:
Unable to run project with Jack compiler
I updated my project to use Java 8 and the Jack compiler. The project compiles successfully but whenever I try to run it on a device I get the following error:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformJackWithJackForDebug'.
> java.lang.UnsupportedOperationException

* Try:
Run with --info or --debug option to get more log output.
</code>```

The full log is as follows:

```<code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformJackWithJackForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: java.lang.UnsupportedOperationException
    at com.android.sched.util.config.ReflectFactory.create(ReflectFactory.java:98)
    at com.android.jack.ir.ast.JSession.reset(JSession.java:144)
    at com.android.jack.frontend.java.JAstBuilder.compile(JAstBuilder.java:265)
    at com.android.jack.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:452)
    at com.android.jack.frontend.java.JAstBuilder.compile(JAstBuilder.java:269)
    at com.android.jack.frontend.java.JackBatchCompiler.performCompilation(JackBatchCompiler.java:219)
    at com.android.jack.eclipse.jdt.internal.compiler.batch.Main.compile(Main.java:1712)
    at com.android.jack.frontend.java.JackBatchCompiler.compile(JackBatchCompiler.java:184)
    at com.android.jack.Jack.buildSession(Jack.java:1052)
    at com.android.jack.Jack.run(Jack.java:540)
    at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:124)
    at com.android.builder.core.JackToolchain.convertUsingJackApis(JackToolchain.java:310)
    at com.android.builder.core.JackToolchain.convertUsingApis(JackToolchain.java:189)
    at com.android.builder.core.JackToolchain.convert(JackToolchain.java:170)
    at com.android.build.gradle.internal.transforms.JackTransform.runJack(JackTransform.java:230)
    at com.android.build.gradle.internal.transforms.JackTransform.transform(JackTransform.java:198)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:185)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:181)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:176)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 78 more
Caused by: java.lang.UnsupportedOperationException
    at com.android.sched.vfs.ReadZipFS.createVDir(ReadZipFS.java:263)
    at com.android.sched.vfs.ReadZipFS.createVDir(ReadZipFS.java:53)
    at com.android.sched.vfs.ReadZipFS$ZipVDir.createVDir(ReadZipFS.java:100)
    at com.android.sched.vfs.BaseVDir.createVDir(BaseVDir.java:98)
    at com.android.sched.vfs.PrefixedFS.<init>(PrefixedFS.java:56)
    at com.android.jack.library.v0003.InputJackLibraryImpl.getSectionVFS(InputJackLibraryImpl.java:174)
    at com.android.jack.library.v0003.InputJackLibraryImpl.getDir(InputJackLibraryImpl.java:145)
    at com.android.jack.jayce.TypePackageLoader.<init>(TypePackageLoader.java:34)
    at com.android.sched.util.config.ReflectFactory.create(ReflectFactory.java:90)
    ... 103 more

BUILD FAILED

Total time: 13.033 secs
</code>```

Prior to using the Jack compiler, everything was fine. What could be the problem?

答:
Jack is now deprecated, see this post.

You have to upgrade your Android Studio to 3.0 preview 1, to be able to use Java 8.

If you can't upgrade it (conflict with other lib), or you want to wait for a release version, you can try this workaround solution :

Add the retrolamba lib, follow instructions here.

Remove this lines if exists from your build.gradle :

```<code>jackOptions {
    enabled true
}
</code>```

Sync Project with Gradle files.

Body:
I updated my project to use Java 8 and the Jack compiler. The project compiles successfully but whenever I try to run it on a device I get the following error:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformJackWithJackForDebug'.
> java.lang.UnsupportedOperationException

* Try:
Run with --info or --debug option to get more log output.

The full log is as follows:

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformJackWithJackForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: java.lang.UnsupportedOperationException
    at com.android.sched.util.config.ReflectFactory.create(ReflectFactory.java:98)
    at com.android.jack.ir.ast.JSession.reset(JSession.java:144)
    at com.android.jack.frontend.java.JAstBuilder.compile(JAstBuilder.java:265)
    at com.android.jack.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:452)
    at com.android.jack.frontend.java.JAstBuilder.compile(JAstBuilder.java:269)
    at com.android.jack.frontend.java.JackBatchCompiler.performCompilation(JackBatchCompiler.java:219)
    at com.android.jack.eclipse.jdt.internal.compiler.batch.Main.compile(Main.java:1712)
    at com.android.jack.frontend.java.JackBatchCompiler.compile(JackBatchCompiler.java:184)
    at com.android.jack.Jack.buildSession(Jack.java:1052)
    at com.android.jack.Jack.run(Jack.java:540)
    at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:124)
    at com.android.builder.core.JackToolchain.convertUsingJackApis(JackToolchain.java:310)
    at com.android.builder.core.JackToolchain.convertUsingApis(JackToolchain.java:189)
    at com.android.builder.core.JackToolchain.convert(JackToolchain.java:170)
    at com.android.build.gradle.internal.transforms.JackTransform.runJack(JackTransform.java:230)
    at com.android.build.gradle.internal.transforms.JackTransform.transform(JackTransform.java:198)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:185)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:181)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:176)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 78 more
Caused by: java.lang.UnsupportedOperationException
    at com.android.sched.vfs.ReadZipFS.createVDir(ReadZipFS.java:263)
    at com.android.sched.vfs.ReadZipFS.createVDir(ReadZipFS.java:53)
    at com.android.sched.vfs.ReadZipFS$ZipVDir.createVDir(ReadZipFS.java:100)
    at com.android.sched.vfs.BaseVDir.createVDir(BaseVDir.java:98)
    at com.android.sched.vfs.PrefixedFS.<init>(PrefixedFS.java:56)
    at com.android.jack.library.v0003.InputJackLibraryImpl.getSectionVFS(InputJackLibraryImpl.java:174)
    at com.android.jack.library.v0003.InputJackLibraryImpl.getDir(InputJackLibraryImpl.java:145)
    at com.android.jack.jayce.TypePackageLoader.<init>(TypePackageLoader.java:34)
    at com.android.sched.util.config.ReflectFactory.create(ReflectFactory.java:90)
    ... 103 more

BUILD FAILED

Total time: 13.033 secs

Prior to using the Jack compiler, everything was fine. What could be the problem?

Body:
Jack is now deprecated, see this post.

You have to upgrade your Android Studio to 3.0 preview 1, to be able to use Java 8.

If you can't upgrade it (conflict with other lib), or you want to wait for a release version, you can try this workaround solution :

Add the retrolamba lib, follow instructions here.

Remove this lines if exists from your build.gradle :

jackOptions {
    enabled true
}

Sync Project with Gradle files.