Q:

Why do I keep getting a NoSuchElementException?

This is the code I currently have. For some reason, I keep getting and error called: NoSuchElementException: No line found. The exception occurs at the line:
"String number = scanPhone.nextLine();"  and in the Provider class and at the line:"provObj.readCellPhoneFile(fileNameIn);"in the CellPhonesPart2 class. Does anyone know what's wrong with it?
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.io.IOException;

public class Provider {
   private String name;
   private CellPhone[] phones;
   private String[] excludedRecords;

   /**
    * Constructor for Provider class.
    */
   public Provider() {
      name = "not yet assigned";
      phones = new CellPhone[0];
      excludedRecords = new String[0];
   }

   /**
    * Reads in file name and assigns data.
    *
    * @param fileNameIn Input for file name from main
    * @throws IOException from scanning file name
    */
   public void readCellPhoneFile(String fileNameIn) throws IOException {
      //Reads in file name and creates Scanner object
      File fileIn = new File(fileNameIn);
      Scanner scanFile = new Scanner(fileIn);
      //Assigns name from first line
      name = scanFile.nextLine();
      //Assigns data from file to different categories
      while (scanFile.hasNext()) {
         Scanner scanPhone = new Scanner(scanFile.nextLine());
         scanPhone.useDelimiter(", *");

         String phoneType = scanPhone.nextLine();
         char phoneChar = phoneType.toUpperCase().charAt(0);

         //Assigns phone to different category
         switch (phoneChar) {
            case 'F':
               String number = scanPhone.nextLine();
               int texts = Integer.parseInt(scanPhone.nextLine());
               int minutes = Integer.parseInt(scanPhone.nextLine());
               FlipPhone flip1 = new FlipPhone(number, texts, minutes);
               addPhone(flip1);
               break;
            case 'S':
               number = scanPhone.nextLine();
               texts = Integer.parseInt(scanPhone.nextLine());
               minutes = Integer.parseInt(scanPhone.nextLine());
               int data = Integer.parseInt(scanPhone.nextLine());
               SmartPhone smart1 = new SmartPhone(number, texts, minutes, data);
               addPhone(smart1);
               break;
            case 'I':
               number = scanPhone.nextLine();
               texts = Integer.parseInt(scanPhone.nextLine());
               minutes = Integer.parseInt(scanPhone.nextLine());
               data = Integer.parseInt(scanPhone.nextLine());
               int iMessages = Integer.parseInt(scanPhone.nextLine());
               IPhone iPhone1 = new IPhone(number, texts,
                  minutes, data, iMessages);
               addPhone(iPhone1);
               break;
            case 'A':
               number = scanPhone.nextLine();
               texts = Integer.parseInt(scanPhone.nextLine());
               minutes = Integer.parseInt(scanPhone.nextLine());
               data = Integer.parseInt(scanPhone.nextLine());
               int hotspotMin = Integer.parseInt(scanPhone.nextLine());
               Android android1 = new Android(number, texts,
                  minutes, data, hotspotMin);
               addPhone(android1);
               break;
            default:
               String unrecognized = scanPhone.nextLine();
               addExcludedRecord(unrecognized);
         }
      }
   }

   /**
    * Returns string for provider name.
    *
    * @return String
    */
   public String getName() {
      return name;
   }

   /**
    * Assigns a name input as provider name.
    *
    * @param nameIn Input for provider name
    */
   public void setName(String nameIn) {
      name = nameIn;
   }

   /**
    * Returns CellPhone array for phones.
    *
    * @return CellPhone[]
    */
   public CellPhone[] getPhones() {
      return phones;
   }

   /**
    * Returns string array for excluded records.
    *
    * @return String[]
    */
   public String[] getExcludedRecords() {
      return excludedRecords;
   }

   /**
    * Adds phone to array of phones.
    *
    * @param newPhoneIn Input for phone object
    */
   public void addPhone(CellPhone newPhoneIn) {
      //Increases size of phones array
      CellPhone[] newPhones = new CellPhone[phones.length + 1];
      for (int i = 0; i < phones.length; i++) {
         newPhones[i] = phones[i];
      }
      phones = newPhones;
      //Adds CellPhone object to phones array
      phones[phones.length] = newPhoneIn;
   }

   /**
    * Determines if phone number is found and deleted.
    *
    * @return boolean
    * @param numberIn Input for phone number
    */
   public boolean deletePhone(String numberIn) {
      boolean delete = false;
      int deleteIndex = -1;
      //Searches for phone number match
      for (int i = 0; i < phones.length; i++) {
         if (numberIn == phones[i].getNumber()) {
            deleteIndex = i;
            //Decreases size of phones array
            CellPhone[] newPhones = new CellPhone[phones.length - 1];
            for (i = 0; i < phones.length; i++) {
               newPhones[i] = phones[i];
            }
            phones = newPhones;
         }
      }
      if (deleteIndex > -1) {
         for (int i = deleteIndex; i < phones.length - 1; i++) {
            phones[i] = phones[i + 1];
         }
         return true;
      }
      else {
         return false;
      }
   }

   /**
    * Adds unrecognized phone to excluded records.
    *
    * @param excRecIn Input for unrecognized phone
    */
   public void addExcludedRecord(String excRecIn) {
      //Increases capacity of excludedRecords
      String[] newExcRecords = new String[excludedRecords.length + 1];
      for (int i = 0; i < excludedRecords.length; i++) {
         newExcRecords[i] = excludedRecords[i];
      }
      excludedRecords = newExcRecords;
      //Adds excRecIn to array
      excludedRecords[excludedRecords.length] = excRecIn;
   }

   /**
    * Returns list of cell phones in phones array.
    *
    * @return String
    */
   public String toString() {
      String result = "";
      for (CellPhone phone : phones) {
         result += phone;
      }
      return result;
   }

   /**
    * Calculates total bill for all phones.
    *
    * @return double
    */
   public double calculateTotalBill() {
      double totalBill = 0;
      for (int i = 0; i < phones.length; i++) {
         totalBill += phones[i].calculateBill();
      }
      return totalBill;
   }

   /**
    * Calculates total number of texts for all phones.
    *
    * @return int
    */
   public int calculateTotalTexts() {
      int totalTexts = 0;
      for (int i = 0; i < phones.length; i++) {
         totalTexts += phones[i].getTexts();
      }
      return totalTexts;
   }

   /**
    * Calculates total number of minutes for all phones.
    *
    * @return int
    */
   public int calculateTotalMinutes() {
      int totalMinutes = 0;
      for (int i = 0; i < phones.length; i++) {
         totalMinutes += phones[i].getMinutes();
      }
      return totalMinutes;
   }

   /**
    * Calculates total data for smartphones.
    *
    * @return int
    */
   public int calculateTotalData() {
      int totalData = 0;
      for (int i = 0; i < phones.length; i++) {
         if (phones[i] instanceof SmartPhone) {
            totalData += ((SmartPhone) phones[i]).getData();
         }
      }
      return totalData;
   }

   /**
    * Calculates total hotspot minutes for Androids.
    *
    * @return int
    */
   public int calculateTotalHotspotMin() {
      int totalHotspotMin = 0;
      for (int i = 0; i < phones.length; i++) {
         if (phones[i] instanceof Android) {
            totalHotspotMin += ((Android) phones[i]).getHotspotMin();
         }
      }
      return totalHotspotMin;
   }

   /**
    * Calculates total iMessage count for iPhones.
    *
    * @return int
    */
   public int calculateTotalIMessages() {
      int totalIMessages = 0;
      for (int i = 0; i < phones.length; i++) {
         if (phones[i] instanceof IPhone) {
            totalIMessages += ((IPhone) phones[i]).getIMessages();
         }
      }
      return totalIMessages;
   }

   /**
    * Returns string for summary report.
    *
    * @return String
    */
   public String summary() {
      String summary = "------------------------------"
         + "\nSummary for " + getName()
         + "\n------------------------------"
         + "\nNumber of cell phones: " + getPhones()
         + "Texts: " + calculateTotalTexts()
         + "Talk Minutes: " + calculateTotalMinutes()
         + "Data: " + calculateTotalData()
         + "Hotspot Minutes: " + calculateTotalHotspotMin()
         + "iMessages: " + calculateTotalIMessages()
         + "Bill Total: $" + calculateTotalBill()
         + "\n\n------------------------------"
         + "\nRates for " + getName()
         + "\n------------------------------"
         + rates()
         + "\n------------------------------"
         + "\nCell Phones by Number"
         + "\n------------------------------\n"
         + listByNumber()
         + "\n------------------------------"
         + "\nCell Phones by Billing Amount"
         + "\n------------------------------\n"
         + listByBill()
         + "\n------------------------------"
         + "\nExcluded Records"
         + "\n------------------------------\n"
         + excludedRecordsList();
      return summary;
   }

   /**
    * Returns string for different rates.
    *
    * @return String
    */
   public String rates() {
      String rates = "FlipPhone Talk Rate: $" + FlipPhone.TALK_RATE
         + "\tText Rate: $" + FlipPhone.TEXT_RATE
         + "SmartPhone Talk Rate: $" + SmartPhone.TALK_RATE
         + "\tText Rate: $" + SmartPhone.TEXT_RATE
         + "\tMax Talk Time: " + SmartPhone.MAX_TALK_TIME
         + "\n\tiPhone iMessage Rate: $" + IPhone.IMESSAGE_RATE
         + "\n\tAndroid HotspotRate: $" + Android.HOTSPOT_RATE;
      return rates;
   }

   /**
    * Returns string of phones sorted by number.
    *
    * @return String
    */
   public String listByNumber() {
      String listByNumber = "";
      for (CellPhone phone : phones) {
         listByNumber += phone.toString();
      }
      Arrays.sort(phones);
      return listByNumber;
   }

   /**
    * Returns string of phones sorted by bill.
    *
    * @return String
    */
   public String listByBill() {
      String listByBill = "";
      for (CellPhone phone : phones) {
         listByBill += phone.toString();
      }
      Arrays.sort(phones, new CellPhoneBillComparator());
      return listByBill;
   }

   /**
    * Returns string excluded records.
    *
    * @return String
    */
   public String excludedRecordsList() {
      String excRecList = "";
      for (String phone : excludedRecords) {
         excRecList += phone;
      }
      return excRecList;
   }
}

It reads in the file from this class:
public class CellPhonesPart2 {

   /**
    * Creates objects from different classes and prints objects.
    *
    * @param args Reads in file
    * @throws IOException from scanning input file
    */
   public static void main(String[] args) throws IOException {
      String fileNameIn = args[0];
      Provider provObj = new Provider();
      provObj.readCellPhoneFile(fileNameIn);

      System.out.println(provObj.summary());
   }
}

A:

Scanner scanPhone = new Scanner(scanFile.nextLine());
// this is causing your error. scanPhone is ultimately just a one line String

// this line will be found
String phoneType = scanPhone.nextLine();

// this line won't because scanPhone is only one line
String number = scanPhone.nextLine();

Edit: possible Solution
 while (scanFile.hasNextLine()) {
     Scanner scanPhone = new Scanner(scanFile.nextLine());
     scanPhone.useDelimiter(", *");

     String phoneType = scanPhone.next();
     char phoneChar = phoneType.toUpperCase().charAt(0);

     //Assigns phone to different category
     switch (phoneChar) {
        case 'F':
           String number = scanPhone.next();
           int texts = Integer.parseInt(scanePhone.next());
           int minutes = Integer.parseInt(scanPhone.next());
           FlipPhone flip1 = new FlipPhone(number, texts, minutes);
           addPhone(flip1);
           break;

Changed all the scanPhone.nextLine()'s to scanPhone.next()
Also, try using while (scanFile.hasNextLine()); instead of hasNext()


Q:

SQL - timestamp Query

I am trying to create a condition within a GP database whereby I must only be able to insert appointments which are equal to or greater than todays date.
Query:
CREATE TABLE Appointment_Table(
AppointmentID Number(6) NOT NULL Primary Key,
DateAndTime Timestamp(0) NOT NULL,
Check (DateAndTime >= (SYSDATE, 'MM-DD-YYYY HH24:MI:SS')));

This is the error I am getting:

ORA-01797: this operator must be followed by ANY or ALL

Would really appreciate any help :)

A:

Data type date is enough to store day, hour, minute and seconds. No need for timestamp. Also, primary key gives you not null for free, so no need to specify that.
Use a trigger, not a check constraint, since Oracle don't allow sysdate (time now) in check.
create table a (
  id    number(6) primary key,
  d     date      not null
);

create or replace trigger t_a_ins before insert on a
for each row when ( new.d < sysdate )
begin raise_application_error( -20000, 'Forbidden!'); end;
/

insert into a values (1, sysdate+1);
insert into a values (2, sysdate-1);

The first insert is ok.
The second results in error ORA-20000: Forbidden!. Choose numbers between -20000 and -20999 to define your own ORA-errors.


Q:

Assign values to map

I have below code where i am trying to assign values to a map.
Code
List<territory> obj = database.query(soql1);
        system.debug('obj@@assign'+obj);
        Map<Id, territory> terrMap = new Map<Id,Territory>(); // [Select Id,Category_ID_abv__c,ParentTerritoryId,Name from Territory]);  // where ID not in: excludeterrId
        for(territory objCS : obj)
        terrMap.put(objCS.ID, objCS);
        system.debug('terrmap@@assign'+terrmap);

As from debug, i get terrmap value is populated fine with above code inside constructor. But in another method as below [Line - system.debug('terrmap@@check'+terrmap); ] it shows null in debug statement. What could be the reason? Please let me know.
Method
public Integer prepareInScopeUserList(Territory t, String curHierString)
    {    List<Id> childTerrs = new list<Id>();

         system.debug('userterrsIds@@Hi'+userterrsIds);
         for(Id s : terrHierTopDownMap.get(t.Id)) {
    if(userterrsIds.contains(s))
      childTerrs.add(s);
       }

      /*   if(l.contains(terrHierTopDownMap.get(t.Id)))
         childTerrs = terrHierTopDownMap.get(t.Id);*/
        Integer childCount = 0;

        if(childTerrs == null)
            return 0;

        for(Id childTerr: childTerrs)
        { Territory nt;
        system.debug('terrmap@@check'+terrmap);
        if(terrmap!=null)
           { nt = terrMap.get(childTerr);
            if(!excludedNodes.contains(nt.Name) ) //&& userterrsIds.contains(childterr)
            {
                childCount ++;
                hierarchyNode hn;
                if(TerrUserMap.get(childTerr) == null && (t.Name != 'iRep'  && t.Category_ID_abv__c !='PM'))
                {
                    terrHierIdMap.put(childTerr,terrHierIdMap.get(t.Id));
                }
                else
                {
                    Integer hierId = terrHierIdMap.keySet().size()+1;
                    terrHierIdMap.put(childTerr,hierId);
                }

                Boolean userAssocTerr = False;
                if(TerrUserMap.get(childTerr) != null)
                {   //TerrUserMap.get(childTerr)  Need change here. @Saikat
                  If(resultids.contains(TerrUserMap.get(childTerr)))
                    inScopeUsers.add(TerrUserMap.get(childTerr));
                    hn = new hierarchyNode(terrHierIdMap.get(childTerr),terrHierIdMap.get(t.Id),'User',terrMap.get(childTerr).Name,TerrUserMap.get(childTerr));
                    userAssocTerr = True;
                }
               else
                {
                    if((t.Name == 'iRep' && terrMap.get(childTerr).Category_ID_abv__c != 'PM') || t.Category_ID_abv__c == 'PM')
                    hn = new hierarchyNode(terrHierIdMap.get(childTerr),terrHierIdMap.get(t.Id),'Terr','<' + terrMap.get(childTerr).Name +'>',null);
                    userAssocTerr = False;
                }

                //String hierString = curHierString + '->' + nt.Name;
                String hierString =  nt.Name;
                terrHierMap.put(nt.Id,hierString);
                Integer grandChildCount = prepareInScopeUserList(nt, hierString );
                List<hierarchyNode> hierSubList = hier[hier.size()-1];
                if(hierSubList.size() >= 1000)
                {
                    hierSubList = new List<hierarchyNode>();
                    hier.add(hierSubList);
                }
                if(grandChildCount > 0 || userAssocTerr )
                {
                    if(hn != null)
                    hierSubList.add(hn);
                }
                else
                    childCount --;
            }
          }
        }
        return childCount;
    }

Please note terrmap is transient type map.
  Transient Map<Id,Territory> terrMap{get;set;}

A:

You say that terrMap has the transient keyword applied. That is likely the reason it is null after a round trip to the server.
While it was populated in the constructor, if the prepareInScopeUserList method was invoked via a subsequent server request the map wouldn't have been transmitted via viewstate to maintain the value.
You could either remove the transient keyword, or if the viewstate size is a concern, check if it is null before using it and repopulate it from the SOQL query as required.


Q:

Preselect items in h:selectManyCheckbox

How do I preselect the elements in a h:selectManyCheckbox component? I've searched through the properties of the f:selectItem tag but not yet have found how to pre-select this item (i.e. it is ticked already when the site is called).

A:

The value attribute of h:selectManyCheckbox can accept an array of string from the managed bean. You can directly set the default values to this array when the managed bean is initialized.
For example , in the view :
<h:selectManyCheckbox value="#{MBean.choice}">
    <f:selectItem itemValue="A" itemLabel="Choice A" />
    <f:selectItem itemValue="B" itemLabel="Choice B" />
    <f:selectItem itemValue="C" itemLabel="Choice C"/>
    <f:selectItem itemValue="D" itemLabel="Choice D" />
</h:selectManyCheckbox>

Then in the MBean :
public class MBean{

    //Preselect the "Choice A" and "Choice C"
    private String[] choice= {"A","C"};

    //Getter and setter of choice

}


Q:

To generate scatter xy graph in excel using macro

I have written a macro to generate graph in excel but i want that graph to be generated in the next sheet not in the same sheet.i have pasted my macro below its working properly i just want it to be in the next sheet. please provide me some solution*
Sub LumData1()

    If IsEmpty(Range("B2,D2")) = False Then
        Range("B:B,D:D,H:H,I:I,J:J,M:M").Select
        Range("M1").Activate
        ActiveSheet.Shapes.AddChart.Select
        ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
        ActiveChart.SetSourceData Source:=Sheets(ActiveSheet.Name).Range( _
            "$B:$B,$D:$D,$H:$H,$I:$I,$J:$J,$M:$M" _
            )
        ActiveChart.Location Where:=xlLocationAsObject, Name:=ActiveSheet.Name

        With ActiveChart.ChartArea
            .Width = 1060
            .Height = 420
            .Left = 0
        End With

        ActiveChart.SeriesCollection(1).Select
        ActiveChart.SeriesCollection(1).AxisGroup = 2
        ActiveChart.SeriesCollection(5).Select
        ActiveChart.SeriesCollection(5).AxisGroup = 2
        ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
        ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
        ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
        ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Value"
        ActiveChart.Axes(xlCategory).TickLabels.Orientation = 45
    End If

End Sub

A:

My answer covers not only how to solve your question in your post, but how to automatically define and set-up charts in VBA in a “cleaner” and safer way.
It's better if you avoid using ActiveSheet, Select, and ActiveChart. Instead always use referenced objects, in this case Worksheets and ChartObject. E.g Dim ChtObj As ChartObject , and later set it with Set ChtObj = ShtCht.ChartObjects.Add(100, 100, 500, 500) , where ShtCht is the worksheet where you create your chart.
Once you defined and set your ChartObject, its quite easy to modify its properties by using the With ChtObj , and also nested properties, by adding With .Chart.ChartArea under the first With statement.
Code
Option Explicit

Sub LumData1()

Dim ChtObj As ChartObject
Dim ShtSrc  As Worksheet
Dim ShtCht  As Worksheet

' change "Sheet1" to your sheet's name (where you have your chart's data)
Set ShtSrc = Worksheets("Sheet1") ' <-- I preffer not to work with ActiveSheet

'Set ShtCht = Worksheets("Sheet2") ' <-- set the chart's destination worksheet
Set ShtCht = Worksheets.Add ' <-- create a new worksheet to place the chart
ShtCht.Name = "Chart"

If Not IsEmpty(ShtSrc.Range("B2,D2")) Then

    Set ChtObj = ShtCht.ChartObjects.Add(100, 100, 500, 500)

    With ChtObj
        .Chart.ChartType = xlXYScatterSmoothNoMarkers
        .Chart.SetSourceData ShtSrc.Range("$B:$B,$D:$D,$H:$H,$I:$I,$J:$J,$M:$M")

        ' set position of the chart to Cell M1
        .Top = ShtCht.Range("M1").Top
        .Left = ShtCht.Range("M1").Left

        ' modify chart position and dimensions
        With .Chart.ChartArea
            .Width = 1060
            .Height = 420
            .Left = 0
        End With

        With .Chart
            .SeriesCollection(1).AxisGroup = 2
            .SeriesCollection(5).AxisGroup = 2

            .Axes(xlCategory, xlPrimary).HasTitle = True
            .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
            .Axes(xlValue, xlPrimary).HasTitle = True
            .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Value"
            .Axes(xlCategory).TickLabels.Orientation = 45
        End With

    End With

End If

End Sub


Q:

How to configure KnpPaginatorBundle for Symfony 4

I’m looking to implement  KnpPaginatorBundle into symfony4.
My issue here is that , in their documentation (meant for S3) they recommend using the following parameters i config.yml.
knp_paginator:
page_range: 5                       # number of links showed in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links to page 4, 5, 6)
default_options:
    page_name: page                 # page query parameter name
    sort_field_name: sort           # sort field query parameter name
    sort_direction_name: direction  # sort direction query parameter name
    distinct: true                  # ensure distinct results, useful when ORM queries are using GROUP BY statements
    filter_field_name: filterField  # filter field query parameter name
    filter_value_name: filterValue  # filter value query parameter name
template:
    pagination: '@KnpPaginator/Pagination/sliding.html.twig'     # sliding pagination controls template
    sortable: '@KnpPaginator/Pagination/sortable_link.html.twig' # sort link template
    filtration: '@KnpPaginator/Pagination/filtration.html.twig'  # filters template

I am not sure where to use these parameters as S4 does not come with a config.yml file.
I couldn’t find any documentation concerning KNP Bundle and S4. Any help is much appreciated! Thanks!

A:

Following the issue here where the discuss about symfony4 problem, the configuration seems to be the same:
he places the config in "config/packages/paginator.yaml"
# config/packages/paginator.yaml
knp_paginator:
    page_range: 5                       # number of links showed in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links to page 4, 5, 6)
    default_options:
        page_name: page                 # page query parameter name
        sort_field_name: sort           # sort field query parameter name
        sort_direction_name: direction  # sort direction query parameter name
        distinct: true                  # ensure distinct results, useful when ORM queries are using GROUP BY statements
        filter_field_name: filterField  # filter field query parameter name
        filter_value_name: filterValue  # filter value query paameter name
    template:
        pagination: '@KnpPaginator/Pagination/sliding.html.twig'     # sliding pagination controls template
        sortable: '@KnpPaginator/Pagination/sortable_link.html.twig' # sort link template
        filtration: '@KnpPaginator/Pagination/filtration.html.twig'  # filters template


Q:

"The likeliest problem" vs. "the most likely problem"

The likeliest problem vs. the most likely problem:

are they both correct?
do they mean the same thing?
is one preferable over another?

A:

They're both equally understandable and clear, they both mean the same thing, and they're both grammatically correct, but one is stylistically better (and, therefore, preferable). This is a style choice (personal judgment and preference prevail, in other words). My style is generally formal, so I prefer "the most likely problem"; "the likeliest problem" is casual and more appropriate for spoken English or for a letter to a friend. Superlatives with two-syllable words such as "likely" usually give the writer/speaker the choice of adding the /-est/ suffix or using "the most..." structure. One wouldn't say "the most big" (one-syllable word) but "the biggest", and one wouldn't say "the interestingest" (three-syllable word) but "the most interesting".

A:

At first, comparison of disyllabic adjectives is a very tricky thing - cf. Palmer, Huddleston, and Pullum 2002: 1584 "there is no hard and fast boundary between those that can inflect and those that can't: speaker judgements are by no means wholly uniform." A good rule of thumb for disyllabic adjectives is that the analytic forms (with more and most) are always possible,  unlike the inflectional ones (with -er and -est).
However, adjectives ending in "-ly" generally permit inflection (PHP 2002: 1583). The authors of the "Longman Grammar of Spoken and Written English" (LGSWE) make a very important addition to that statement, "with varying degrees of frequency" (Biber et al. 1999: 523). Quite often it's a matter of style/register (Weiner and Delahunty 1994).
To answer your specific question, Biber et al. argue that with the adjective "likely," the analytic forms ("more likely") are much more common that the inflectional ones ("likelier"), esp. in academic prose and in news, where you're more likely to encounter the analytic forms in general.


Q:

Research on impact of display ads on UX?

Is there any research on how the kind and amount of display advertisement affects UX and or usability of the site?

A:

I recommend looking at this smashing magazine article which states that while loud ads are usually ignored by users due to Banner blindness text based and static ads are generally better received. To quote the article

The state of online ad delivery methods leaves much to be desired. The
  only universally well-received options are static text-based ads and
  static banner advertisements. Banner ads are good because they’re
  usually discrete, but they’re also bad because readers usually ignore
  them. This well-documented phenomenon is known as banner blindness.
  Web usability professional Jakob Neilsen confirms that “Users almost
  never look at anything that looks like an advertisement.”

I also found this interesting study which states that text based ads are the most effective way to avoid banner blindness.To quote the article

According to a recent survey by a leading market research firm, it was
  found that 25% of web site visitors are more likely to click on a
  text-only ad when they visit a web site, a preference that beat out
  every other ad format.

I also recommend looking at this interesting article which did heat map studies of sites having banners to see the best positioning and see which are the areas banner blindness was the most prevalent.
The study showed that if it looks like banner ad or an add,users are more likely to ignore it but  if its well integrated into the site and seems like part of the site it might have greater success.

To quote the article

With two of the sites when users had a specific task in mind, the main
  banners were ignored – even the animated one. This could suggest that
  the central real estate of many websites is ‘wasted’, dead space,
  because users don’t perceive the messages or offers promoted there.
However, the ASOS central banner managed to capture participants’
  attention better. In comparing task-based and free-roam behaviour, we
  could see that the users’ pattern of perception was not as strongly
  influenced by the task as on the other homepages.
What does the ASOS banner have that the others don’t? Our
  interpretation:

The ASOS central banner doesn’t look like a banner. It’s much more integrated into the page than the others we tested. The Kiwibank
  and RaboDirect banners clearly carry the brand style, but could be
  seen as less connected to the rest of the homepage design.
The ASOS banner not only advertises the current sales theme, but provides access to the main sections of the website (shop for women
  and shop for men). It has some practical value and is in effect a
  key part of the navigation.
The RaboDirect banner is merely a ‘welcome’ – we often see users skip over introductions and welcomes ( ‘Blah, blah, blah
  blindness’). The Kiwibank message may be relevant to the users, but it
  takes some interpretation: ‘What is free?’ Conversely, the text of the
  ASOS banner is integrated in the image and its message is simple –
  ‘It’s spring season’ – no further interpretation is needed. Plus, the
  message is likely to be relevant to a large group of users.


Q:

Commit ok, but sync reverted everything to previous state

I used github for mac this morning. did a commit locally of a massive number of changes, worked ok. Then tried to sync that's where something went wrong
My unsynced commit didn't show in the list anymore, but the online repository wasn't updated  and my local files have been reverted to the previous online repository's state
Did I just loose days of work with a simple click? Or can I actually restore what I did because the local commit worked! But it looks like it disappeared, it doesn't appear anywhere in the software
It's like all the work I put up never happened, vanished

A:

I don't think you lost all your work. If you committed locally your work should remain in the git repo. Please refer to the git log command.
Try something like
git log --full-history

or
git log --sparse

If you found the SHA1 ID you can try git cherry-pick to grab this commit and put it on top of your actual state.


Q:

How to check if a mining pool runs the forking client or not? [The DAO]

As Geth and Parity forking version are out, the switch to a soft fork related to The DAO is said to happend on block 1800000 if block gas limit is below or equal to 4M. We can see global gas limit on sites like https://ethstats.net/ but they don't represent the whole Ethereum system.
But how to check a particular pool (Ethermine on which I mine is 0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8) gas limit to see if it runs the client in this particular fork mode ?

A:

The block gasLimit is in each block.  Example:

eth.getBlock(1500000)

{
  difficulty: 34982465665323,
  extraData: "0xd783010305844765746887676f312e352e31856c696e7578",
  gasLimit: 4712388,
  miner: ...
  ...
}

If the gasLimit of the next block decreases, it suggests that the client is running the fork mode to try to bring the gasLimit below 4M.
The extraData and miner in the block can provide clues on which mining pool it is.  (Note that miners don't have to set extraData and can change their miner address.)


Q:

CakePHP2 file upload plugin

I use paperclip plugin for Ruby on Rails app.
What is the defacto standard file upload plugin like paperclip for CakePHP2?
https://github.com/davidpersson/media supports only CakePHP1.3?

A:

There is no default plugin defined, a suggestion would be to use the Uppy Plugin with ajax request, for more information go to:
[1]: https://uppy.io/docs/plugins/

I hope this helps.


Q:

How to mount a CD/DVD in DOSBOX?

I'm using DOSBox 0.74, which works properly and can successfully mount a "c" drive.  However, I don't know how to mount a dvd drive.  I'm trying to install Star Control 3 from a disk so that I can play it with DOSBox, but I can't mount the "d" drive.  I've tried mount d /media/cdrom0 -t cdrom which http://www.ubuntugeek.com/howto-auto-mount-a-drive-in-dosbox.html claimed would work.  I've looked at http://www.dosbox.com/wiki/MOUNT#Linux but I didn't understand what exactly it was saying.
So I guess what I'm really asking is does anyone know what commands to use to mount a CD/DVD using DOSBox in Ubuntu 12.04?

A:

Check that you really have the CD/DVD mounted on that location, as usually the CD label is used instead, then run:
mount d /media/LABEL -t cdrom -label LABEL -ioctl -usecd 0

Just replace LABEL with whatever you have.
Tested it on Dosbox 0.74 on Ubuntu 12.04.


Q:

Distribution of five people in a car where exactly two can drive

In how many ways can we distribute five people in a car if exactly two of them are can drive?

A:

We can have two people at the driver's seat, and others can have a seat wherever they want.

For the driver's seat (S1), there are two possibilities.
For the next seat (we'll label it as S2), there are $4$ possibilities.
For the next seat (S3), there are $3$ possibilities.
For the next seat (S4), there are $2$ possibilities.
For the next seat (S5), there is only one possibility.

Simply multiply the possibilities for S1, S2, S3, S4 and S5 which yields $2\cdot 4 \cdot 3\cdot 2 \cdot 1$.


Q:

C# calculation errors

I have a c# code which calculates (304/1000)*100, which equals 30.4, however when I run the code in c# every single time I get 0.
decimal width = (maxSize.Width/ maxValue) * value; //304, 1000, 100 respectively
Console.WriteLine(width); //Returns 0

I don't understand what the hell is going on?

A:

It seems as if you are using ints for the operands.
With int division, you must remember that the decimal part of the result gets truncated.
I.e., for the line (304/1000)*100 (replacing the variables with their values for simplicity), the following is calculated:
304 is divided by 1000, which results in 0.304.  Then, the decimal is truncated, since this is integer division, resulting in 0 being the end result.
Then, 0 is multiplied by 100, which gives 0 as the result.
Solution:
Make the operands decimals, floats, or doubles. (100m, 100f, and 100d, respectively, for an example of each type)
These three types support decimals, so if you use them, you will get the correct result of 30.4.
Either that, or you can multiply one of the values in the parentheses by 1.0 of any of the three above types:
(1.0f * 304 / 1000) * 100


Q:

React Component State issue with duplicate components

I've recently started learning React and I'm a little bit confused.
Please see the following codepen or the code snippet below.
class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      sessions: [],
      sessionSelected: null
    }
    this.addSession = this.addSession.bind(this);
    this.switchSession = this.switchSession.bind(this);
  }

  addSession() {
    let sessions = this.state.sessions;
    let id = (sessions.length)
    let title = "Session " + id;
    let session = <Session title={title} index={id + 1} />;
    sessions.push(session);
    this.setState({
      sessions: sessions,
      sessionSelected: id
    });
  }

  switchSession(id) {
    this.setState({
      sessionSelected: id
    });
  }

  render() {
    return (

        <button onClick={this.addSession} >+ Add Session</button>

{this.state.sessions[this.state.sessionSelected]}

          {this.state.sessions.map((x, i) => {
            return <SessionSwitcher index={i + 1} onClick={() => { this.switchSession(i) }} />;
          })}

    );
  }
}

class Session extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
    this.startTimer = this.startTimer.bind(this);
    this.count = this.count.bind(this);
  }
  startTimer() {
    setInterval(this.count, 1000);
  }
  count() {
    this.setState({
      count: this.state.count + 1
    });
  }
  render() {
    return (

{this.props.title}

{this.state.count}

        <button onClick={this.startTimer}>Start Timer</button>

    )
  }
}

class SessionSwitcher extends React.Component {
  render() {
    return (

        {this.props.index}

    )
  }
}

ReactDOM.render(
  <App />,
  document.querySelector('#app')
);

I want to be able to trigger multiple timers within multiple components.
For some reason when I click the start timer in one component, it triggers it for the other components too.
Can someone explain to me what I am doing wrong?

A:

Here are a couple of things you could change to get a more predictable experience:

Rather than storing JSX in state, which is a complex object, store just the id, and render JSX according to that id.
Try not to mutate state in place (as with pushing onto an array that's already in state).
If you want to have persistent timers across components, regardless of which ones are currently selected, be sure not to unmount them when they're deselected.

Here are the relevant updated parts of your <App/> component (note that these are more quick fixes than best practices):
  addSession() {
    const id = this.state.sessions.length;
    this.setState( state => ({
      // treat your state as immutable
      sessions: state.sessions.concat( id ),
      sessionSelected: id
    }));
  }

  // don't unmount when switching components, just hide
  render() {
    return (

        <button onClick={this.addSession} >+ Add Session</button>

          { this.state.sessions.map( session =>

              <Session title={"Session " + session} />

          )}

          {this.state.sessions.map((x, i) => {
            return <SessionSwitcher index={i + 1} onClick={() => { this.switchSession(i) }} />;
          })}

    );
  }

Try it here: https://codepen.io/glortho/pen/ZrLMda?editors=0011


Q:

Website for Android: what to do with low devicePixelRatio devices: tablets, smartphones, etc.?

I'm struggling with this for a while now.
I did a responsive website for a client, but then it turns out that his tablet (Panasonic FZ-A1) has 0.75 devicePixelRatio, which means, that it sais it has 1024x768 pixels, but actually displays less.
While I find it difficult to understand, what is the point in creating devices which say they can display a webpage properly, when they obviously will fail at doing that, I'm trying hard to find the proper way to handle this.

Here is the problem: 1px borders on elements randomly don't appear.
  Obviously, they don't appear on screen, because of the 0.75 pixel
  scale. My site is responsive, but the browser 'lies' about the screen size - it returns 1024x768, so media queries in CSS are working as if it would actually be that big.

The meta tag in the header <meta content="width=device-width, initial-scale=1.33" name="viewport"/> shouldn't be the answer, because it does not affect what the browser sais about the screen size, so CSS responsivity will not work properly.
I can't find anything in 'Settings' regarding screen pixel ratio.
Any help would be greatly appreciated. Even some explanation, why would anyone product a device with <1 screen pixel ratio.

Update:
In the native Android browser, there is a thing under 'Special' settings, which I just found, and it makes it work. It is called 'default scale', with 'far','normal' and 'close' options. Selecting 'close' fixes the problem. But then again, default browser in Android 4.03 does not support some of the html5 features, and it would be nice if we could find a more generic solutions.

A:

I had this issue with the exact same tablet, and this is what I did in the end.
I had tried to use media selectors for low-dpi screens, and do html { zoom: 120% } which looked pretty good but was still missing a few pixels off inputs.
In the end I did this, which works great, basically it ends up setting the width of the viewport to 1024 which is the actual native resolution of those toughpads.
Note I still did user-scaleable=no as soon I think it's going to help prevent the click delay on mobile devices.
<meta id="viewport" name="viewport" content="width=device-width, user-scalable=no">
<script type="text/javascript">
    // Try and show the page nicer if we have a low dpi screen
    if(window.devicePixelRatio < 1.0) {
        var newWidth = Math.floor(screen.width * window.devicePixelRatio);
        var viewportContent = "user-scalable=no, width=" + newWidth;
        document.getElementById('viewport').setAttribute('content', viewportContent);

    }
</script>

I just wish I didn't have to use javascript :(


Q:

DOMException 105 only during UI Tests

I am intermittently getting an unhandled DOMException 105. It only happens when running my UI tests.
If I comment out the use of loadHTMLString:baseURL call of UIWebView, then the exception no longer happens.
This is making my tests very unreliable. Any suggestions on how to work around this?
Stack trace:
2017-01-05 16:57:01.431 Allhomes[64245:4871703] *** Terminating app due to uncaught exception 'DOMException', reason: '*** DOMException 105'
*** First throw call stack:
(

0   CoreFoundation                      0x0000000110e4dd4b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x00000001104b721e objc_exception_throw + 48
2   CoreFoundation                      0x0000000110e4dc99 -[NSException raise] + 9
3   WebCore                             0x000000011785a542 _ZN7WebCore17raiseDOMExceptionEi + 370
4   WebCore                             0x000000011785a55e _ZN7WebCore23raiseTypeErrorExceptionEv + 14
5   WebCore                             0x00000001177e311e -[DOMRange setStart:offset:] + 158
6   UIKit                               0x000000010d92edab -[UIWebDocumentView text] + 292
7   UIKit                               0x000000010d6afcde _UIViewDescriptionAppendTextIfApplicable + 96
8   UIKit                               0x000000010d6afe91 -[UIView(UIDebugging) description] + 147
9   CoreFoundation                      0x0000000110e2374a -[NSArray descriptionWithLocale:indent:] + 362
10  Foundation                          0x000000010ff80a9e _NSDescriptionWithLocaleFunc + 66
11  CoreFoundation                      0x0000000110d8b7d7 __CFStringAppendFormatCore + 10983
12  CoreFoundation                      0x0000000110d88cc7 _CFStringCreateWithFormatAndArgumentsAux2 + 263
13  AccessibilityUtilities              0x000000012544e38f _AXStringForArgs + 333
14  UIAccessibility                     0x0000000125f29fe2 -[UIView(UIAccessibilityElementTraversal) _accessibilitySubviewsForGettingElementsWithOptions:] + 199
15  UIAccessibility                     0x0000000125f2ae3b -[UIView(UIAccessibilityElementTraversal) _addAccessibilityElementsAndOrderedContainersWithOptions:toCollection:] + 743
16  UIAccessibility                     0x0000000125f2aec6 -[UIView(UIAccessibilityElementTraversal) _addAccessibilityElementsAndOrderedContainersWithOptions:toCollection:] + 882
17  UIAccessibility                     0x0000000125f2aec6 -[UIView(UIAccessibilityElementTraversal) _addAccessibilityElementsAndOrderedContainersWithOptions:toCollection:] + 882
18  UIAccessibility                     0x0000000125f2aec6 -[UIView(UIAccessibilityElementTraversal) _addAccessibilityElementsAndOrderedContainersWithOptions:toCollection:] + 882
19  UIAccessibility                     0x0000000125f2b3e4 +[UIView(UIAccessibilityElementTraversal) _accessibilityElementsAndContainersDescendingFromViews:options:sorted:] + 472
20  UIAccessibility                     0x0000000125f2b599 -[UIView(UIAccessibilityElementTraversal) _accessibilityViewChildrenWithOptions:] + 186
21  UIKit                               0x0000000125db20ab -[UITableViewCellAccessibility _accessibilityRetrieveTableViewCellText] + 1551
22  UIKit                               0x0000000125db2ed1 -[UITableViewCellAccessibility _accessibilityChildren] + 1534
23  UIKit                               0x0000000125dac175 -[UITableViewCellAccessibility _accessibilityUserTestingChildren] + 82
24  UIKit                               0x0000000125dac0f7 -[UITableViewCellAccessibility _accessibilityUserTestingChildrenCount] + 24
25  UIKit                               0x0000000125dc0d24 -[UITableViewCellAccessibilityElement _accessibilityUserTestingChildrenCount] + 48
26  UIAccessibility                     0x0000000125f3890b -[NSObject(AXPrivCategory) accessibilityAttributeValue:] + 5720
27  UIAccessibility                     0x0000000125f53636 -[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotDescendantsWithAttributes:maxDepth:maxChildren:maxArrayCount:] + 1814
28  UIAccessibility                     0x0000000125f54f96 -[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotWithOptions:] + 557
29  UIAccessibility                     0x0000000125f36c0a -[NSObject(AXPrivCategory) accessibilityAttributeValue:forParameter:] + 7903
30  UIAccessibility                     0x0000000125f20856 _copyParameterizedAttributeValueCallback + 211
31  AXRuntime                           0x000000012558f532 _AXXMIGCopyParameterizedAttributeValue + 216
32  AXRuntime                           0x0000000125589f1c _XCopyParameterizedAttributeValue + 440
33  AXRuntime                           0x0000000125598de5 mshMIGPerform + 266
34  CoreFoundation                      0x0000000110ddf3d9 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
35  CoreFoundation                      0x0000000110ddf351 __CFRunLoopDoSource1 + 465
36  CoreFoundation                      0x0000000110dd7435 __CFRunLoopRun + 2389
37  CoreFoundation                      0x0000000110dd6884 CFRunLoopRunSpecific + 420
38  GraphicsServices                    0x00000001151ada6f GSEventRunModal + 161
39  UIKit                               0x000000010d5e8c68 UIApplicationMain + 159
40  Appname                             0x000000010c127a33 main + 99
41  libdyld.dylib                       0x000000011261068d start + 1
)
 libc++abi.dylib: terminating with uncaught exception of type NSException

A:

Same problem here using an UIWebView with voiceover. I've added my view controller as the delegate of the webview and added the following code (to indicate that the tree has changed) and I don't have the bug anymore:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);
}

Does it work for you as well ?
UPDATE 1
The bug appears less often, but still appears sometimes ...
UPDATE 2
Making the webview not visible by voiceover  while it is loading its content seems to work so far ... :
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    self.webView.accessibilityElementsHidden  = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.webView.accessibilityElementsHidden  = NO;
}

A:

Swift 3 version: Add these lines in UIWebViewDelegate:
// Prevent Accessibility Crash
func webViewDidStartLoad(_ webView: UIWebView) {
    self.webView.accessibilityElementsHidden = true
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    self.webView.accessibilityElementsHidden = false
}

Note : Considering use a WKWebview instead of a UIWebView.


Q:

Safe/good way to wrap c++ new/delete for multi-threaded environment

I was having some issues with new/deletes occurring on different threads (TI F28379D) that were causing the program to lock if an interrupt occurred in the middle of allocating or deleting. I didn't want to wrap every instance of new/delete with a macro that disables and enables interrupts, as it felt like a lot of duplicate code. My solution was to create two functions that have the appropriate macros around the new/delete.
void *create_array_pointer(uint16_t count, size_t size, char *variable_name) {
    //create the array (inside where interrupts are disabled
    uint16_t interrupt_settings = __disable_interrupts();
    void *ptr = new uint16_t[count*size];
    __restore_interrupts(interrupt_settings);
    check_allocation_throw_error(ptr, variable_name);
    return ptr;
}

void delete_array_pointer(void *ptr) {
    uint16_t interrupt_settings = __disable_interrupts();
    delete[] ptr;
    ptr = NULL;
    __restore_interrupts(interrupt_settings);
}

This works for primitive types. However, I realized today that this is a bad solution for c++ classes that have default constructors/destructors, as the constructor or destructor will never be called automatically.
Is there some way to make sure the constructors/destructors are called, without going back to wrapping every call?

A:

I am assuming you are in an environment where you can't use containers or  smart pointers. Otherwise I would recommend returning std::vector or std::unique_ptr.
You can use templates to retain the type of the objects you are creating whilst still being generic.
Also you may want to consider a RAII way to manage your interrupts as they will be exception safe as well as being generally safer and easier:
template<typename T>
void check_allocation_throw_error(T*, char const*) {}

// This will disable interrupts on creation and re-enable them
// when it goes out of cope. This means if you reach the end
// of the function OR if an exception is thrown the interrupts
// will be re-enabled regardless.
class interrupt_disabler
{
public:
    interrupt_disabler(): settings(__disable_interrupts()) {}
    ~interrupt_disabler() { __restore_interrupts(settings); }

private:
    interrupt_disabler(interrupt_disabler const&) {}
    interrupt_disabler& operator=(interrupt_disabler const&) { return *this; }

    uint16_t settings;
};

template<typename T>
T* create_array_of(uint16_t count, char const* variable_name)
{
    T* ptr = 0;

    // create a scope where interrupts are disabled
    {
        interrupt_disabler lock(); // enabled at end of scope OR if new throws
        ptr = new T[count];
    }
    // interrupts enabled automatically here

    check_allocation_throw_error(ptr, variable_name);

    return ptr;
}

template<typename T>
void delete_array(T* ptr)
{
    interrupt_disabler lock(); // enabled at end of scope
    delete[] ptr;
}

struct MyType {}; // any old type

int main()
{
    MyType* mytype = create_array_of<MyType>(10, "wibble");

    delete_array(mytype);
}


Q:

what is the right way to delete all features from featureLayer

I have a featureLayer and I don't want to kill it and create another one. I want to delete all features from the current featureLayer. I found that I can use applyEdits method but in order to use it I need to have all features I want to delete. Whilst I don't want to store them separately. Do you know a better way to empty my featureLayer when using the ArcGIS Javascript API?

A:

Try making a REST delete features call with a where clause "1 = 1" or something similar.

A:

Use featureLayer.selectFeatures() with, as Kirk suggested, a where clause that will return all your features. Once you have all your features, pass them to applyEdits() as the deletes.


Q:

Prevent VS C# Unit Testing breaking on exceptions

I want to write a unit test for detecting a thrown exception. Using ExpectedExceptionAttribute, I run the test from inside MSVS and when the TestMethod hits the exception, the debugger breaks to the exception but the TestMethod correctly skips over and reports Passed.
Is there a flag to tell VS not to break during unit testing?

A:

Do not run the tests in a debug session. You have the option to 'Run Selection' or 'Debug selection', choose the first and you should be fine.

A:

If you press CTRL + ALT + E you can configure whether the debugger will break when different types of exceptions are thrown and/or not handled.
I have found using these settings to be very handy at times.


Q:

Handling loads of different message-types at runtime in an elegant way

In order to be able to handle large amounts of different request types I created a .proto file like this:
message Message
{
   string typeId = 1;
   bytes message = 2;
}

I added the typeId so that one knows what actual protobuf bytes represents. (Self-describing)
Now my problem is handling that different "concrete types" in an elegant way. (Note: All works fine if I simple use a switch-case-like approach!)
I thought about a solution like this:
1) Have a trait the different handlers have to implement, e.g.:
trait Handler[T]
{
  def handle(req: T): Any
}

object TestHandler extends Handler[Test]
{
  override def handle(req: Test): String =
  {
    s"A success, $req has been handled by TestHandler
  }
}

object OtherHandler extends Handler[Other]
{
  override def handle(req: Other): String =
  {
    s"A success, $req has been handled by OtherHandler
  }
}

2) provide some kind of registry to query the right handler for a given message:
val handlers = Map(
    Test -> TestHandler,
    Other -> OtherHandler
  )

3) If a request comes in it identifies itself, so we need another Mapper:
val reqMapper = Map(
  "Test" -> Test
  "Other" -> Other
)

4) If a request comes in, handle it:
val request ...
// Determine the requestType
val requestType = reqMapper(request.type)
// Find the correct handler for the requestType
val handler = handlers(requestType)
// Parse the actual request
val actualRequest = requestType.parse(...) // type of actualRequest can only be Test or Other in our little example

Now, until here everything looks fine and dandy, but then this line breaks my whole world:
handler.handle(actualRequest)

It leads to:

type mismatch; found : com.trueaccord.scalapb.GeneratedMessage with Product with com.trueaccord.scalapb.Message[_ >: tld.test.proto.Message.Test with tld.test.proto.Message.Other <: com.trueaccord.scalapb.GeneratedMessage with Product] with com.trueaccord.lenses.Updatable[_ >: tld.test.proto.Message.Other with tld.test.proto.Message.Test <: com.trueaccord.scalapb.GeneratedMessage with Product]{def companion: Serializable} required: _1

As far as I understand - PLEASE CORRECT ME HERE IF AM WRONG - the compiler cannot be sure here, that actualRequest is "handable" by a handler. That means it lacks the knowledge that the actualRequest is definitely somewhere in that mapper AND ALSO that there is a handler for it.
It's basically implicit knowledge a human would get, but the compiler cannot infer.
So, that being said, how can I overcome that situation elegantly?

A:

I settled for this solution for now (basically thesamet's, a bit adapted for my particular use-case)
trait Handler[T <: GeneratedMessage with Message[T], R]
{
    implicit val cmp: GeneratedMessageCompanion[T]
    def handle(bytes: ByteString): R = {
        val msg: T = cmp.parseFrom(bytes.newInput())
        handler(msg)
    }

    def apply(t: T): R
}

object Test extends Handler[Test, String]
{
    override def apply(t: Test): String = s"$t received and handled"

    override implicit val cmp: GeneratedMessageCompanion[Test] = Test.messageCompanion
}


Q:

Why is my Django URL Dispatcher not working?

I'm really confused as to why my URL dispatcher is not matching this url
http://127.0.0.1:8000/2011/jun/26/third-entry/

This is what my main url dispatcher looks like
urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^blog/', include('djangoblog.blog.urls')),
)

And inside my blog folder I have another url dispatcher
urlpatterns = patterns('django.views.generic.date_based',
    #regex is passed to object_detail which is the name of the generic view that will pull out a single entry
    (r'^(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='blog/detail.html')),
)

I also tried this url with no luck
http://127.0.0.1:8000/blog/2011/jun/26/third-entry/

I must be missing something really simple...

A:

Your regexp is wrong.
(?P<year>d{4}) should be (?P<year>\d{4})
The same applies to the other parts of the URI:

(?P<day>\d{1,2})
(?P<slug>[-\w]+)


Q:

Illustrator: how to select or delete all raster objects

I'm about to submit some illustrations and they should not contain any raster effect or image and the illustration objects are too complex. I don't know where I used the effects or raster objects.
Is there a way to find all objects with that specifics in artboard and within clipping masks, groups and such and delete them?

A:

I've found that raster images appear in "Links panel", could be selected from there, then by clicking "Goto link" the raster object will selected in artboard and then could be deleted.


Q:

how to create toast in java to show value of a computation

I am trying to create a calculator that shows the result using a toast.
my code is
Button addBtn=(Button)findViewById(R.id.additionBtn);
    addBtn.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
        EditText inputFirst = (EditText)findViewById (R.id.inputTextFirst);
        String message= inputFirst.getText().toString();

        EditText inputSecond = (EditText)findViewById     (R.id.inputTextSecond);
        String message2= inputSecond.getText().toString();

            int first = Integer.parseInt(message);
            int second = Integer.parseInt(message2);

            int sum = first + second;
            TextView resTxt = (TextView)findViewById(R.id.viewResult);
            resTxt.setText("Result is  " +sum);

 Toast.makeText(this,message, Toast.LENGTH_LONG).show();
            TextView ResTxt=(TextView)findViewbyId(R.id.viewResult);
            resTxt.setText("answer is" + sum);

        }       });

}

it manages to show the result in a label. but with the toast, it is giving me notification that makeText not applicable to arguments.

A:

Change
Toast.makeText(this,message, Toast.LENGTH_LONG).show();

to
Toast.makeText(ActivityName.this ,message, Toast.LENGTH_LONG).show();

makeText takes as first parameter a Context object, but this, in your case, refers to the object of the inner anonymous class new View.OnClickListener


Q:

check if twilio client is busy in a call or available

I have 2 problems, 1st and most importantly i want to check if a client is busy in a call or available, 2nd i want to  check current queue Size and notify a user when they click pick a call from queue.
If client is not busy and there are no calls in a queue i want to allow an incoming call but if a client is still not busy while there are calls in a queue i don't want to allow an incoming call, all incoming calls should go to queue.
At the end i want to be able to update client status or if my client are online i should be able to indicate, maby in the database i store client and status, when the clients are online i allow them to handle calls.
currently i can enqueue and pick a call from queue.
Enqueue:
<Response>
    <Say>Please wait while we connect you to our available agent</Say>
    <Enqueue waitUrl="waiting.php">support_en</Enqueue>
</Response>

Queue:
<Response>
        <Dial>
            <Queue url="about_to_connect.php">support_en</Queue>
        </Dial>
    </Response>

Please help.
Thanks in advance.

A:

You will want to use Twilio Task Router to architect a solutuion like this. Take a look at this blog as a starting off point.
How to Customize Phone Call Workflows with Twilio Studio and TaskRouter


Q:

Flutter - change appbar icon when receiving notification

I am using FirebaseMessaging to push notifications on my app.
So I can handle these notification with this code :
firebaseMessaging.configure(
    onLaunch: (Map<String, dynamic> msg) {
  print("onLaunch called");
}, onResume: (Map<String, dynamic> msg) {
  print("onResume called");
}, onMessage: (Map<String, dynamic> msg) {
  print("onMessage called : " + msg.toString());
});

When I receive a notification, I want to display this little '1' on my icon in my appbar

My problem is : I don't know how to change my bell icon dynamically on my appbar for all pages (and I can't call setState in my appbar)

A:

I think is pretty simple to solve your problem you only need to use a Stateful class and a custom icon as below snippet:
Widget myAppBarIcon(){
return Container(
  width: 30,
  height: 30,
  child: Stack(
    children: [
      Icon(
        Icons.notifications,
        color: Colors.black,
        size: 30,
      ),
      Container(
        width: 30,
        height: 30,
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(top: 5),
        child: Container(
          width: 15,
          height: 15,
          decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Color(0xffc32c37),
              border: Border.all(color: Colors.white, width: 1)),
          child: Padding(
            padding: const EdgeInsets.all(0.0),
            child: Center(
              child: Text(
                _counter.toString(),
                style: TextStyle(fontSize: 10),
              ),
            ),
          ),
        ),
      ),
    ],
  ),
);
}

and later you can include this icon on your app bar(leading or action). As you can see the Text value change with any touch I used as base the example code when you start a new Flutter project it contains a method to count how many times you touch the floating button and change the state:
void _incrementCounter() {
setState(() {
  _counter++;
});
}

I hope this helps you
this is my example


Q:

Android IAB testing: app in draft state but in alpha slot, cannot retrieve active product

I am testing in-app purchase functionality for my app.
The app is in alpha slot, product is active but I get errors saying "item not available" or similar when I test the functionality with release apk on real device (with gmail account in "license test response" list).
I see that the app is in draft state, is it the cause? I know draft state is not good for testing IAB but I followed the instructions about the alpha slot so I think I made no mistake.

A:

I had the same problem, actually got here in search for a solution.
The reason was because the app was in "Draft" status due to some details in the configuration missing, especially the screenshots.
At the top right side of the page of the settings for the APK it must show Published, otherwise if it shows "Draft" it will give an option to see what's missing to publish.


Q:

Proof using boolean algebra properties

I need to prove that
$$ x + y = y ~~~\iff~~~ xy = x $$
also need to prove that:
$$ x + y = x ~~~->~~~ x + not(y) = 1 $$
Using algebra boolean properties.
But I have no idea how to solve this problem.
Any ideas? Thanks

A:

Here's a useful principle for the first problem:
Absorption
$x + xy = x$
$x(x+y) = x$
Applied to your problem 1, going from left to right:
Assume $x + y = y$.  Then $xy = x(x+y) = x$
Can you go from right to left?
For the second problem, use:
Complement
$x + x' = 1$
$xx'=0$
and
Annihilation
$x + 1 = 1$
$x0=0$


Q:

Track external site with socket.io?

Is there any way to track an external site with socket.io? So whenever the website changes then it would automatically send an event to my server?
For example:
socket.on("newconnectionfromxxxxxxxxxxxxxxx", function (websiteChange)  {  //websiteChange would be the contents of the updated website.
});

Sorry if this questions is obvious because I couldn't find anything online.
EDIT: The site that I want to be tracking is a JSON file.

A:

socket.io works between two cooperating sites.  So, it would only help you here if the site you want to monitor specifically supports an incoming socket.io connection AND it supports sending a notification message over that connection whenever the specific file you are interested in changes.
If the site you want to monitor does not have such specific monitoring features, then the best you could do is to regularly download the file of interest and see for yourself if it has changed.


Q:

Writing to stdout except for output redirection C

I have to make a simple app for school.
I have to write arguments one per line on the terminal, and return on stdout the user choices.
For example, I write cat my_app main.c main.h, if the user choose main.c, then I return main.c to cat. The problem is that if I write the menu on the standard output (aka STDOUT_FILENO), I return it to cat. I could write my menu on STDERR, but it's a little ugly.
I don't really know how to use devices/files like /dev/tty* or /dev/pty*, but I feel I could use them to write something on the terminal without having to write it on STDOUT or STDERR.
Basically, I want to open a new output, which would be shown by the terminal (STDOUT, STDERR, MYOUT).
I don't know if I explained it correctly.

A:

To build an interactive application you can open /dev/tty, it will return a file descriptor to the controlling terminal:
int ttyfd = open("/dev/tty", O_RDWR);

You can use it instead of STDIN_FILENO or STDOUT_FILENO (those could be redirected to something different than the terminal when the program is started).

Here is some example:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() {
  int ttyfd = open("/dev/tty", O_RDWR);
  printf("fd: %d\n", ttyfd);
  write(ttyfd, "hello tty!\n", 11);
  return 0;
}

When invoked with ./test >out, it should print the hello message on the terminal and something like fd: 3 in the out file.


Q:

Serving tomcat6 app in document root using apache2

I have a server running apache2 that is currently serving several apps on a tomcat6 instance. Those are already configured and working and there is a rewrite rule, like this:
RewriteCond %{REQUEST_URI} ^/app1 [NC,OR]
RewriteCond %{REQUEST_URI} ^/app2 [NC,OR]
RewriteCond %{REQUEST_URI} ^/app3 [NC,OR]
RewriteCond %{REQUEST_URI} ^/aap4 [NC,OR]
RewriteCond %{REQUEST_URI} ^/app5 [NC,OR]
RewriteCond %{REQUEST_URI} ^/app6 [NC]
RewriteCond %{SERVER_PORT} !443
RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [R,L]

then it has the JKMounts:
JkMount /app1/*.jsp tomcat.web
JkMount /app2* tomcat.web
JkMount /app3* tomcat.web
JkMount /app6* tomcat.web
JkMount /app6* tomcat.web
JkMount /app6* tomcat.web

And the workers.properties looks like this:
workers.tomcat_home=/usr/local/tomcat
workers.java_home=/usr/local/java
ps=\

worker.list=tomcat.web

# Set properties for worker 'tomcat.web' (ajp13)
worker.tomcat.web.type=ajp13
worker.tomcat.web.host=localhost
worker.tomcat.web.port=8009
worker.tomcat.web.cachesize=10
worker.tomcat.web.cache_timeout=600
worker.tomcat.web.socket_keepalive=1
worker.tomcat.web.connection_pool_size=150
worker.tomcat.web.connection_pool_minsize=75
worker.tomcat.web.connection_pool_timeout=10000

I had added a new tomcat installation and there I have running a new app, called 'online'. So I added a new worker, like this (also appended the worker name into worker.list):
# Set properties for worker 'tomcatb.web' (ajp13)
worker.tomcatb.web.type=ajp13
worker.tomcatb.web.host=localhost
worker.tomcatb.web.port=8109
worker.tomcatb.web.cachesize=10
worker.tomcatb.web.cache_timeout=600
worker.tomcatb.web.socket_keepalive=1
worker.tomcatb.web.connection_pool_size=150
worker.tomcatb.web.connection_pool_minsize=75
worker.tomcatb.web.connection_pool_timeout=10000

and then I just added a new COND on top of all other CONDs
RewriteCond %{REQUEST_URI} ^/online [NC,OR]

and a new JKMount like this:
JkMount /online* tomcatb.web

Here things work fine. I can access my app in
http://MYSERVER/online

and it works ok.  Now I need to be able to serve that app just by accesing
http://MYSERVER/

but I have not been able to accomplish that. I've been trying to write a rewrite rule like this (removing the previous COND, and adding this):
RewriteCond %{REQUEST_URI} ^/online [NC,OR]
RewriteCond %{SERVER_PORT} !443
RewriteRule ^online(.*)$ / [PT,QSA,L]

but that doesn't work, and when I go to
http://MYSERVER/

I get the error:
Forbidden
You don't have permission to access / on this server.

Can someone point me in the right direction on how to configure apache to server my app the way I need it?

A:

I solved this, not sure if I did it using the best approach, but this I what I did in the end (which accomplish my requirement, so by now it's good enough)
I added a new rewrite condition, like this:
RewriteCond %{REQUEST_URI} ^/ [NC,OR]

Then this JKMount
JkMount /* tomcatb.web

And since the app I need to server run in a separate tomcat instance, I removed all webapps and deployed the war as ROOT.war.
Restart everything and now if I go to
http://MYSERVER/

it displays the content that I am expecting


Q:

'AssemblyTitle' attribute in the .NET Framework

What is the practical use of the AssemblyTitle attribute? MSDN says that it specifies a description for an assembly and that the assembly title is a friendly name which can include spaces.
Visual Studio asks for the assembly name in the properties window of the project along with the default namespace. There is an AssemblyName attribute but it describes an assembly's unique identity in full (i.e., culture, etc.). I don't see how AssemblyTitle differs from AssemblyProduct.
I used the IL Disassembler to see how Microsoft uses AssemblyTitle. I discovered that in mscorlib.dll, AssemblyTitle, AssemblyProduct and AssemblyDefaultAlias are all set to "mscorlib.dll".
In conclusion, what I really would like to see are practical examples of the use of AssemblyTitle.

A:

[AssemblyTitle] is a pretty big deal, it is directly visible when you right-click on the assembly and use Properties + Details.
An example to make it more visible.  Let's start with this AssemblyInfo.cs file:
[assembly: AssemblyTitle("AssemblyTitle")]
[assembly: AssemblyDescription("AssemblyDescription")]
[assembly: AssemblyConfiguration("AssemblyConfiguration")]
[assembly: AssemblyCompany("AssemblyCompany")]
[assembly: AssemblyProduct("AssemblyProduct")]
[assembly: AssemblyCopyright("AssemblyCopyright")]
[assembly: AssemblyTrademark("AssemblyTrademark")]
[assembly: AssemblyCulture("")]
[assembly: Guid("7da36bdf-39fb-4a4d-b98c-ecefd99b155a")]
[assembly: AssemblyVersion("1.2.3.4")]
[assembly: AssemblyFileVersion("5.6.7.8")]

And look at the properties of the file:

Some annotations to this:

Note how [AssemblyDescription] is misleading, it is actually the Title you see in the property sheet.
Description, Configuration and Company are not displayed.  You probably want to merge the company name into the visible Copyright.  Description and Company are actually present in the unmanaged version resource but Windows just doesn't display it.
[AssemblyCulture] is special, it is used by satellite assemblies for localization
[Guid] is special, it sets the type library guid if you create a [ComVisible] assembly
[AssemblyVersion] is extraordinary special, a really big deal in the .NET Framework.  That it is not displayed is a major hangup.  You can see it in XP, not in later Windows versions.  A strong consideration is to make the [AssemblyFileVersion] the same value.
The displayed "Product version" is the same as the "File version".  That's not great either, you want to add the [AssemblyInformationalVersion] attribute to fix that.

It is quirky, the Windows group and DevDiv didn't always work together well.

A:

Your Product can comprise of several assemblies.
All of the assemblies will have a single product name and individual assemblies will have their own titles.
AssemblyProduct = "MyProduct"
AssemblyTitle = "MyProduct.Utilities"
and for another assembly
AssemblyTitle = "MyProduct.Security"
the assembly title is also used in the explorer file properties etc. File > Properties > Details tab
File Description = AssemblyTitle
Product name = AssemblyProduct

A:

The AssemblyTitle also appears as an application's name in the task manager (Windows 10), e.g. in the "Processes" tab or the "Fewer details" view.


Q:

determine efficiently which rectangle a point is in 2d space

I have a large set of rectangles that are drawn on html5 canvas.

I would like to be able to interact with this image using mouse tracking (I cannot use SVG because it does not scale to 10-100k rectangles). Is there any data structure/algo that, given the mouse x,y coordinates would be able to tell you which box the mouse was over (using the computed locations of the rectangles)? I was thinking something like a k-d tree but was not sure.

A:

If your data is always of the form shown I think you should be able to do better than a spatial tree data structure.
Since the data is structured in y you should be able to calculate which 'strip' of rectangles the points is in based on offsets in O(1) time.
If you store the individual rectangles within each 'strip' in sorted order (using xmax say) you should then be able to locate the specific rectangle within the strip using a binary search (in O(log(n))).
Hope this helps.


Q:

Looking for a synonym, when something is dedicated to something, like a movie

To elaborate, when a movie for example borrows heavily from something, when you could call it a love letter to that something. It's on the tip of my tongue, and been killing me for a while now. Thanks in advance.

A:

"an ode to..." comes to mind.  It originally referred to any lyric poem dedicated to someone or something. It can also refer to a film or a piece of music, though.   Beethoven's Symphony nº9, for instance, is also known as "Ode to Joy".

ode (noun) - "a poem in which a person expresses a strong feeling of love or respect for someone or something."

A:

I think you are looking for the word hommage.  It's the French word for "homage", but in English, it means something specific:

A homage, especially something in an artwork which has been done in respectful imitation of another artist.

It's pronounced in that Frenchified way (/oʊˈmɒːʒ/ instead of /ˈhɑmɪdʒ/) and usually italicized in print.

Fan: Was the scene between you and Sandy Bates at the wax museum a hommage to Vincent Price's horror movie, The House of Wax?
Tony: An hommage? Not exactly. We just stole the idea outright.


Q:

IIS overriding custom 404 error page in ASP.NET

I am trying to create a 404 error page and currently I have all of the following/tried all of the following to try and accomplish this.  When the user types in :
http://name/something.aspx
It works just as its supposed to.  But if the user types in:
http://name/NotAFile
with no .aspx then IIS7 takes matters into its own hands and I get the lovely error page that IIS7 comes with.  The goal is that the site redirects with only a 404 status code (so not a 200, or a 302 redirect).  I have tried in both the web config with:
<customErrors mode="On" defaultRedirect="~/error/Default.aspx redirectMode="ResponseRewrite">
     <error statusCode="404" redirect="~/error/NotFound.aspx" />
</customErrors>

This works for the url with a .aspx file extension but not for no extension.  Same with this approach in the global.asax
void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;

    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Server.Transfer("~/error/NotFound.aspx");
        }

        Server.Transfer("~/error/Default.aspx");
    }
}

The same results are present for this :(  My final attempt was to apply this to the web config:
<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>

With this I just get a plain white screen with nothing on it...
Any thoughts or comments would be greatly appreciated!! Thanks in advance!

A:

The following codes works with both .aspx and other file types:
Global.asax
void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;
    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Response.Redirect("~/NotFound.aspx?URL=" + Request.Url.ToString());
        }
        Response.Redirect("~/Default.aspx");
    }
}

Web.config
<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>

A:

It seems that your application is running in classic pipeline mode. Change it to integrated and your problem will be fixed. Here is an article about pipeline modes and their differences - http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/


Q:

excel - separate email and url from same cell

I have a list in Excel that looks like this:
Column A
skfjkdf@kasldfj.com
fjls@fdkjd.comhttp://www.kdfj.com
dfkjdf@kdlfj.eshttp://djfkdsf
dkfjs@kljf.com
kjsfld@klfjlf.cahttp://www...

there are cells with just the email address
and there are cells with email and url together (always without space)
I would like the single emails to stay in Column A
and the ones together separated: Email Column A, URL Column B
I've tried with TRIM, LEFT, RIGHT and SUBSTITUTE but I couldn't figure it out.
Thanks very much for your help!

A:

I found two ways to do this.. One without formulas and one with

In Excel push Ctrl+H to bring up the Find and Replace dialog.
Replace "http" with " http" (note the space)
Then select the cells you want to split and go to Data > Texts to
Columns. Make sure to have it delimit on the space.
To extract just the E-mail use
=LEFT(A1,SEARCH("http",A1,1)-1)

To extract just the site use
=RIGHT(A1,LEN(A1)-SEARCH("http",A1,1)+1)

This assumes all your sites start with "http"

Now the email and URL should be split.


Q:

Maxing out gear with maxed out smithing, enchanting and alchemy

I have level 100 smithing, enchanting and alchemy. I also have some nice enchanted gear, fortify smithing and alchemy.
How high should I be able to get my fortified equipment?
Currently I'm around 29% for alchemy and smithing.
How high can I get fortify smithing and fortify enchanting potions without using the console (cheating)? And how?
Currently I get +147% and +32% respectively.
Is something like this possible without using the console(or photoshop)?

A:

29% is the max cap you can get per piece of armor via the in game fortify loop.  I've tried using the falmer helmet glitch to see if I can boost my enchanting up some more, but it does not.  The only way you can make that armor with a fully patched game is using the console.
However, there used to be a glitch with fortify restoration that can turbo boost your skills to insane levels, and with that it was possible to make armor as shown in the picture.

A:

That glitch you used is still available and can be used...but what you should do is wear fortify alchemy equipment, make the fortify restoration potion, drink, unequip/equip clothing, repeat till your gear is ridiculously high, fortify alchemy, then make a fortify enchanting potion and set enchantments on other equipment.


Q:

ASP.net Web page error Use of unassigned local variable 'some'

I have razor code like this
bool some;

if (IsPost == false)
{

 some = True

}

then html
<h1>@some.ToString()</h1>

and when i run it it get's me error
 Use of unassigned local variable 'some'
could anyone explain why? doesn't razor code executes first and then html?

A:

Assign your variable some value.
bool some  = false;

could anyone explain why? doesn't razor code executes first and then
  html?

It doesn't has anything to do with Razor or HTML execution priority. Consider the following simple C# example:
bool some;
Console.WriteLine(some);

You are trying to write some which hasn't been assign any value. Similar is the case with @some.ToString(), you haven't assign it any value and the compiler can't determine whether it will get the value inside the if statement.
You can also do:
bool some = default(bool); //same as false for bool

You can also assign some, a value in else part like:
bool some;
bool IsPost = true;
if (IsPost == false)
{
    some = true;
}
else
{
    some = false;
}

Now the compiler knows that some will be assigned some value and your error would go away.
Not really sure but it appears you are trying to toggle the value of IsPost to some you can do:
some = !IsPost;


Q:

h:link in JSF gets called automatically

I am creating a user authentification in JSF2, and my header displayed on every page contains this:
<c:if test="#{user.loggedIn}">

<h:link value="Log out" outcome="#{user.logout}"/>

</c:if>

User refers to the userBean, and logout() simply invalidates the session, and issues a redirect to the login page. So when the user logs in, user.loggedIn becomes true, and logout link gets displayed, but it somehow immediately gets called, and the user is immediately logged out.
Does anyone have an idea why is this happening? I thought of using h:commandLink, but it requires a form, and I'm trying to avoid it.
Edit:
I copied the wrong code... just my luck after spending an hour figuring out why the user cannot login. You can look at the previous revision to see miscopied code.

A:

That can happen when the JSF tags are not recognized and parsed as such and it effectively get rendered as plain text wherein all EL expressions are evaluated as value expressions. It would in your case basically print the returned value of #{user.logout()}. But while EL does that, the method's logic is of course invoked.
If you remove the action attribute and open the page in browser and do a View Source, then you'll see an unparsed <h:commandLink> tag instead of the generated HTML  element.
Make sure that you have the h: XML namespace definied on the right URI in the root tag of the view file.
xmlns:h="http://java.sun.com/jsf/html"

Update: the <h:link> isn't intented to invoke bean actions. It's intented as a pure GET link. The outcome is per specification evaluated as a value expression, not as a method expression. The outcome must represent a view ID where the link has to navigate to. When the EL evaluates your method as a value expression, it's of course immediately invoked. Just keep using <h:commandLink> in combination with a redirect. Additional advantage is that this isn't bookmarkable nor searchbot-crawlable.


Q:

list of pages and categories

I've a question.
My wordpress theme, prints a list of pages in
 tag.
My pages name:

page1, page2, page3

OK ... Now can I prints my categories names inside the pages list? for example:

page1

page2

category1

page3

If I can, how I can?
Thanks a lot ...

A:

If you user Wordpress 3.0, use the Custom Menu under Appereance -> Menus.
It let you build a menu with pages, categories, links !


Q:

Elasticsearch Error: MapperParsingException: failed to parse

I want to add an entry to Elasticsearch using Apache HttpClient in Java.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:9200/index/entries/");

List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("title", "Title123"));
params.add(new BasicNameValuePair("content", "Content123"));

httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);

After sending the request Elasticsearch responds with the following error:

org.elasticsearch.index.mapper.MapperParsingException: failed to parse
Caused by: org.elasticsearch.ElasticsearchParseException: Failed to derive xcontent from (offset=0, length=33): [...]

It seems that my request is invalid but I have no idea why.
Here is the full Trace from Elasticsearch:
[index][0], node[LomlwFXNQl2w_hBrHGKU0Q], [P], s[STARTED]: Failed to execute [index {[index][entries][AUzTUAj4AmLRyNLK73dO], source[_na_]}]
org.elasticsearch.index.mapper.MapperParsingException: failed to parse
  at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:565)
  at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:493)
  at org.elasticsearch.index.shard.IndexShard.prepareCreate(IndexShard.java:453)
  at org.elasticsearch.action.index.TransportIndexAction.shardOperationOnPrimary(TransportIndexAction.java:201)
  at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.performOnPrimary(TransportShardReplicationOperationAction.java:515)
  at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction$1.run(TransportShardReplicationOperationAction.java:422)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
Caused by: org.elasticsearch.ElasticsearchParseException: Failed to derive xcontent from (offset=0, length=33): [116, 105, 116, 108, 101, 61, 84, 105, 116, 108, 101, 49, 50, 51, 38, 99, 111, 110, 116, 101, 110, 116, 61, 67, 111, 110, 116, 101, 110, 116, 49, 50, 51]
  at org.elasticsearch.common.xcontent.XContentFactory.xContent(XContentFactory.java:195)
  at org.elasticsearch.common.xcontent.XContentHelper.createParser(XContentHelper.java:73)
  at org.elasticsearch.common.xcontent.XContentHelper.createParser(XContentHelper.java:51)
  at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:507)
  ... 8 more

And the Apache log:
2015/04/19 22:12:59:959 CEST [DEBUG] wire - http-outgoing-0 >> "POST /index/entries/ HTTP/1.1[\r][\n]"
2015/04/19 22:12:59:962 CEST [DEBUG] wire - http-outgoing-0 >> "Content-Length: 33[\r][\n]"
2015/04/19 22:12:59:962 CEST [DEBUG] wire - http-outgoing-0 >> "Content-Type: application/x-www-form-urlencoded; charset=UTF-8[\r][\n]"
2015/04/19 22:12:59:962 CEST [DEBUG] wire - http-outgoing-0 >> "Host: localhost:9200[\r][\n]"
2015/04/19 22:12:59:963 CEST [DEBUG] wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
2015/04/19 22:12:59:963 CEST [DEBUG] wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.4.1 (Java/1.8.0_40)[\r][\n]"
2015/04/19 22:12:59:963 CEST [DEBUG] wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
2015/04/19 22:12:59:963 CEST [DEBUG] wire - http-outgoing-0 >> "[\r][\n]"
2015/04/19 22:12:59:963 CEST [DEBUG] wire - http-outgoing-0 >> "title=Title123&content=Content123"
2015/04/19 22:13:00:051 CEST [DEBUG] wire - http-outgoing-0 << "HTTP/1.1 400 Bad Request[\r][\n]"
2015/04/19 22:13:00:051 CEST [DEBUG] wire - http-outgoing-0 << "Content-Type: application/json; charset=UTF-8[\r][\n]"
2015/04/19 22:13:00:051 CEST [DEBUG] wire - http-outgoing-0 << "Content-Length: 312[\r][\n]"
2015/04/19 22:13:00:052 CEST [DEBUG] wire - http-outgoing-0 << "[\r][\n]"
2015/04/19 22:13:00:052 CEST [DEBUG] wire - http-outgoing-0 << "{"error":"MapperParsingException[failed to parse]; nested: ElasticsearchParseException[Failed to derive xcontent from (offset=0, length=33): [116, 105, 116, 108, 101, 61, 84, 105, 116, 108, 101, 49, 50, 51, 38, 99, 111, 110, 116, 101, 110, 116, 61, 67, 111, 110, 116, 101, 110, 116, 49, 50, 51]]; ","status":400}"

A:

Ok I found my mistake.
My entity gets not handled as JSON. Using a StringEntity worked:
StringEntity params = new StringEntity("{your JSON String}");
params.setContentType("application/json");
httppost.setEntity(params);
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);


Q:

How do I use chrome.tabs.onUpdated.addListener?

I am creating an extension for Chrome. I want to show an alert() with the page URL whenever the user moves from one tab to another, or when the user enters a new URL in a tab.
This is not working:
chrome.tabs.onUpdated.addListener(function(integer tabId, object changeInfo, Tab tab) {
    alert(changeInfo.url);
});

chrome.tabs.onActivated.addListener(function(object activeInfo) {
    // also please post how to fetch tab url using activeInfo.tabid
});

A:

Remove integer, object and Tab in the functions signature. Also change .onUpdated to .onActivated
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
   alert(changeInfo.url);
});

chrome.tabs.onActivated.addListener(function(activeInfo) {
  // how to fetch tab url using activeInfo.tabid
  chrome.tabs.get(activeInfo.tabId, function(tab){
     console.log(tab.url);
  });
});


Q:

Firing onchange event when Ember.Select option is changed

I have been trying to bind an event to select element generated via Ember.Select but I am having no luck. I have bunch of selects in my page and I wanted to populate the options of a select based on the value of another. I created a select view like :
AS.ClientSelectView = Ember.Select.extend({
    contentBinding:"AS.customerController",
    selectionBinding:"AS.SelectedClient.client",
    optionLabelPath : "content.name",
    optionValuePath : "content.id",
    change: function () {
          console.log(AS.SelectedClient.client.get('name'));
    }
});

but when the change event fires, it does not show the currently selected element's value but it shows the prior selected options value.
Here is the jsbin link : http://jsbin.com/iSiCUmU/2

A:

you need to create an object of type AS.SelectedClient and then use that object in you select:
AS.selectedClient = AS.SelectedClient.create();

AS.ClientSelectView = Ember.Select.extend({
  contentBinding: "AS.customerController",
  selectionBinding: "AS.selectedClient.client",
  optionLabelPath : "content.name",
  optionValuePath : "content.id"
});


Q:

how do I design an alien planet without deep speculative evolution?

I've been wanting to make an alien planet for a while, and though I don't want it to just be an 'earth but everything is wacky colored' type thing, I honestly do not have the patience to simulate millions of years of evolution. yes, this planet will have special circumstances that the animals will 'evolve' to live in, but how do I design these creatures without spending weeks on speculative evolution, and still have them fit where they are?

A:

Design the creatures how you want them to be first, and then bother yourself with how they evolved later - if you bother yourself at all with that.
A seminal work in sci-fi is The Forever War. It features a species of psionic, green, tripod "teddy bears". Why are they tripods? Why are they green? How are they psionic? Joe Haldeman never elaborated on that. The creatures appear for two or three pages, and even then only briefly.
The Forever War won the Hugo, Nebula and Locus awards. Each of these is to sci-fi books what oscars are for movies.

If you really must explain stuff, then dark planets make for good hearing, low gravity gives you good jumpers yada-yada. If you really, really want to go into speculative evolution, then probably the story you want to write is the speculation itself. This is a niche of sci-fi with its own cult followers.

A:

Your best option seems to be to identify which main unique traits you want for each creature, determine where they live, then research our own animals which live in a similar habitat to have a better idea on how they'd look like.
This might seem like your "earth but everything is whacky colored" problem, but here's the problem regarding biology: there's no such thing as copyright in nature, so a specific trait or body plan which is advantageous for a creature can and likely will evolve multiple times in species which originally had very little in common. This occurrence is called "convergent evolution" and has happened several times here on earth throughout history, with flying squirrels and sugar gliders being a very good example (both look very similar, but one is a marsupial mammal while the other is a placentary mammal).

So in essence, it's all about identifying the similarities between your world's habitats and those found here on earth, thus seeing what would likely be similar in your own creatures and then determine traits which evolved differently from creatures on earth. Of course, you can still have creatures completely unlike anything that's ever walked on our planet, but know that the existence of creatures which look similar on the outside is far from unrealistic or a sign of a lazy job, and the sheer amount of different creatures and traits on our own planet just shows how you don't have to worry about creating an entire evolutionary graph for them to look real (without genetics and the studies in biology, I doubt anyone would ever believe you, a cat, an ostrich and a dinosaur all came from a fish with stumpy leg-like fins).
Regarding reference for what you might be looking for, "subnautica" and "james Cameron's avatar" are both good examples of this process, having many creatures which look a lot like some of our own animals, but they're not quite the same due to a vastly different ancestor and due to having unique traits which their own variations in the environment selected as more advantageous. The game "the Outer worlds" are also good reference on how to combine different traits of creatures we have on earth to create something that looks pretty unique and alien-like.


Q:

I get a 403 error when submitting "http://www." via GET. Even if it's encoded beforehand. Is there a solution for this?

It seems like my shared host provider is detecting the presence of "http://www" or "http%3A%2F%2Fwww" in any get request and serving up a 403 page.
I also get an 'in addition' error...
"Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request."
This only happens with this string. If I change it to something else the get is successfully submitted and the target page successfully returned.
If it helps I'm writing a QR code getter, so the ability to submit urls is quite important.
Also,  strangely I can submit a url as long as it doesn't have 'www' in it.  I can also submit 'www' as long as it isn't preceded by 'http://' (or the encoded version)
edit:  Just to confirm this wasn't a specific problem with the page I was writing, I went to another page on my website that uses get request and manually inserted the string.  This also generates the 403 error.

A:

Yes -- there are two solutions:

Request to remove this strange security feature for your account from your provider.
Don't send urls with http://www in them. For example replace this scting in javascript before sending data to some "%htpwwwashere:(%", that will be replaced by you back in PHP.


Q:

Construct group $G=Q\ltimes Z_{7}$

I read a example. i have problem.
Let $Q=\langle x, y| x^{9}=y^{3}=1, x^{y}=x^{4}\rangle$ and $Z_{7}$ be a group of order $7$.
I know $\Omega_{1}(Q):=\Omega$ is an abelian group of order $9$. Since
$Q/\Omega$ is isomorphic to the subgroup $Z_{3}$ of order $3$ of the automorphism group $Aut(Z_{7})$. we may form $G=Q\ltimes Z_{7}$.
Do you need $\Omega_{1}$ for construct G ?
$\Omega_{i}=$ the subgroup of $G$ generated by its elements of order dividing $p^{i}$

A:

If you use $\Omega_1$ this way you will miss some possibilities for $G=Q\ltimes Z_7$. The way you describe gives one of the four possibilities. So if you want to specify that one possibility, then yes, use $\Omega_1$. If you want all possibilities, then no, do not use it.
Since the Sylow 3-subgroup of $\operatorname{Aut}(Z_7)$ has order 3, you know that $x^3$ acts as the identity on $Z_7$ for all $x \in Q$. Hence you get an action of $Q/\mho(Q)$ where $\mho_1(Q) = \mho(Q) = \langle x^3 : x \in Q \rangle$.  However, $G/\mho(Q) \cong C_3 \times C_3$ has many homomorphisms to $\operatorname{Aut}(Z_7)$.
In particular, there are four distinct semidirect products $G$ (one of them direct). You can specify one of them by requiring that $\Omega(Q)$ is the kernel of $Q \to \operatorname{Aut}(Z_7)$.
$Q$ has 2 $\operatorname{Aut}(Q)$-orbits of subgroups of order 9. One is $\{ \Omega_1(Q) \}$ and the other, $\{ \langle x \rangle, \langle yx \rangle, \langle y^2x \rangle \}$, consists of 3 cyclic subgroups of order 9. The semidirect products with kernel $\Omega_1(Q)$ are all isomorphic, but if the kernel is in the other orbit, then there are two possible actions, $z^y = z^2$ or $z^y = z^4$, giving two more semidirect products. Also the kernel could be order 27, giving the direct product as a fourth possibility.


Q:

JQuery slider event triggered on individual handle (slider range)

Is there a way to trigger events based on the movement of individual slider handles?
It would be interesting as I need to update a datepicker depending of the handle moved. The problem is that I don't know if there's actually a way:

To specify an event on a specific handle
Or to retrieve the id of the moved handle via a listener...

Here's how my events are currently triggered.
$(function() {
      var evt = this.timelineDiv
        .children(".slider")
        .slider({
          min: this.dates.start,
          max: this.dates.end,
          step: 1,
          change: function(event, ui) {
            conditionnalDatePickersUpdate();
            },
          slide: function(event, ui) {
            conditionnalDatePickersUpdate();
            }
          })
          .slider("pips", {
            rest: "label",
            step: 1
            })
    });

A:

Firstly;
your setup indicates only a single handle. For multiple handles you'd need to have values: Array set as an option.
Secondly;
You may use the built-in ui object to check the handleIndex, and the value.
$(function(){
  var values = [1,10];
  var $slider = $(".slider").slider({
    values: values,
    change: handleChanged
  }).slider("pips");

  // fill in the rest of your setup

});

And then after the change event triggers you may compare the values to the original with the following method;
var handleChanged = function( evt, ui ) {
  switch ( ui.handleIndex ) {
    case 0:
      // do something for first handle
      break;
    case 1:
      // do something for second handle
      break;
    case 2:
      // do something for third handle
      break;
  }
};