text:
Q: Django Foreign Key I am trying to generate a report across 2 models/ tables. Here they are:
class Members(models.Model):
    username          = models.CharField(max_length=30,null=True, unique=True)
    email             = models.CharField(max_length=100,null=True, unique=True)
    name              = models.CharField(max_length=30,null=True)
    phone             = models.CharField(max_length=30,null=True)

and
class Report(models.Model):
    report_text    = models.CharField(max_length=500)
    reporter_id    = models.IntegerField(db_index=True)
    reported_id    = models.IntegerField(db_index=True)
    date_created   = models.DateTimeField(null=True)
    date_read      = models.DateTimeField(null=True)

The 2 tables obviously have auto increment IDs as the primary key.
The report will look like this:
Reported Phone | Reported Name | Report | Date Reported | Date Report Read

Everyone reported on will be in the member table. The reporter ID is the ID of the member who logged the report. The reported_id is the ID of the person the report is on. I need to do a join across the 2 models to get the members name and their phone number. I can't quite work it out form the doc. I believe I should make the reported_id and reporter_id both foreign keys to the Members table primary key ID field. How do I do that and what code will extract the report for all entries submitted by a specific reporter?
Do I user reported_id = models.ForeignKey(Members) and do the same for reporter_id. It seems odd as I don't specify the field that the field is foreign to. The ORM is supposed to make it easier (and it usually does!). I could do it with a join in SQL but this has got me stumped.
I hope the question makes sense.
Thanks in advance
Rich

A:
How do I do that and what code will
  extract the report for all entries
  submitted by a specific reporter?

Yes, do reported_id = models.ForeignKey(Members)
The field will be the target models primary key, which is in your case id since you haven't specified one.
You will need to specify a related_name for one of these fields to prevent a name clash for the reverse foreign key accessor.
After setting up the foreign key field, to get all objects related via that foreign key, use the related_name to query the related model.
http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
For example, if you set up your model as:
reporter = models.ForeignKey(Members, related_name="reports_by_me")
reported = models.ForeignKey(Members, related_name="reports_by_others")

You could access all related Report models via that foreign key by
member_instance.reports_by_me.all()
member_instance.reports_by_others.all()


text:
Q: getting error in using the newsapi php script $json = file_get_contents("https://newsapi.org/v2/top-headlines?country=us&apiKey=a1075eab1cfa4e129cb60c7dd8622322");
$news = json_decode($json, true);

foreach ($news["articles"] as $i => $article) {
    echo '
' . $article['title'] . '
';
    echo '';
    echo '
Published on ' . $article['publishedAt'] . '
';
    echo '
' . $article['description'] . '
';
    echo 'Read more';
}

*

*i am using this code & it used to work till few days back.
but now its returning error PHP Warning:  Invalid argument supplied for foreach() in /home/asdfgh/public_html/test.php on line 5
Requesting to guide me to understand and resolve the error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting element id with jquery The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML

         <button onclick="return add_row();" style="width:100%;">Add Row</button>

Javascript
$(document).ready(function() {
    $('#form_area div').click(function(e) {
        console.log($(this).attr('id'));
    });
});

function add_row() {
    var random_id = Math.floor((Math.random() * 1000) + 1);
    $('#form_area').prepend('

');
}

A: Ok, I think I understand what you are missing. You are trying to log the ID after adding a row using add_row function,
.form_row is added dynamically to the DOM. So when executing $('.form_row').click(, there is no .form_row to bind the handler. The below way of using .on method binds the handler to #form_area and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
   console.log(this.id);
});

$('#form_area div') selects the div inside the div #form_area which doesn't have an ID
Below comment in html shows which div is selected,

      <button onclick="return add_row();" style="width:100%;">Add Row</button>

A: To access id use 'on' as your div is dynamically generated:
$(document).ready(function() {
   $('#form_area').on('click', '.form_row', function () {
        console.log(this.id);
    });
});

A: Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.
Secondly, your button handler is inside #formarea and so is also triggering the click handler since the button's parent has no ID.  This is probably not desired.
Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.
So, remove the onclick attribute and add this:
$('#formarea button').on('click', addRow);

$('#formarea').on('click', '.form_row', function() {  // delegated, for dynamic rows
    console.log(this.id);                            // NB: not $(this).attr('id') !!
});

function addRow(ev) {
    // unmodified
}

See http://jsfiddle.net/alnitak/aZTbA/

A: Try console.log($('#form_area div').attr('id'));


text:
Q: Form Validation event issue So I'm trying to write an interactive form, where clicking a radio button will unhide another field in the form. It is for display purpose, so I'm not submitting anything. I'm attempting to use Javascript to validate, but needless to say, it's not working very well. A run through of my code would be appreciated.
Since it's so much code, I'll pastie it to you for convenience...
http://pastie.org/3615669
Thanks :)

A: Your code:
function getShrimpa(radio, name, ext){
    //Use of form 'shrimpa'.
    var form = document.shrimpa;

    document.form.name.style.display = 'block'; // <---- this is not valid
    document.getElementById('shrimpa').innerHTML = ext;
}

You cannot use the variable name like that. It's a string and it will not get "replaced" or whatever you were hoping would happen. You'll need to use document.getElementsByName(name) to select that element. But that will give you a node list so you probably want to use ids instead there.


text:
Q: How to prove that a subspace is a proper subspace? How to prove that a subspace $X \subset V$ ($V$ is vector space) is a proper subspace?
I've read that:

A subspace $X$ is called a proper subspace of $V$ if it is neither the whole space $V$ nor the zero subspace $\{0\}$.

But am unsure about how to display this?

A: If we are working with finite dimensional vector spaces (which I assume we are) then there are a few ways to do this. If $X\subseteq V$ is our vector subspace then we can simply determine what $\dim X$ is. If $0<\dim X<\dim V$ then we know that $X$ is a proper subspace. The easiest way to check this is to find a basis for the subspace and check its length.
Another more manual way to do this is to check that there is a nonzero vector in $X$, and also that $V$ contains a vector that is not in $X$.


text:
Q: Custom Formula to look at a different GSheet I am still trying to wrap my head around using script, so my apologies if this is basic.
I have a summary Spreadsheet that pulls values from hundreds of other documents.  This used (too many) importrange formulas, but many of these are now #REF or ...Loading.
I am trying to create a custom formula that will mimic the importrange function and return the values.
I thought the hard part would be getting the formulas to update when another document was updated, but I have fallen right at the start.
This is my code.
function GetRngValue(ShtURL, GetRng) {
// find id from shtURL? - check if the workbook was updated in the last minute
Logger.log(ShtURL);
var Source = SpreadsheetApp.openByUrl(ShtURL);
// IF Source lastupdated > ThisSht lastupdated then  [ Ensure update runs at startup though ]
if (DriveApp.getFileById(Source.getId()).getLastUpdated() > DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getLastUpdated()) {

  var shtNm = GetRng.substring(1,find("!")-1);
  Logger.log(shtNm);
  var myRng = GetRng.substring(find("!")+1,len(GetRng));
  Logger.log(myRng);
  TargetRng =  Source.getSheetByName(shtNm)
  var TargetRng = Source.getSheetByName(shtNm).getRange("'"+myRng+"'").getValues;
  Logger.log(TargetRng);
  return TargetRng;
 };
 Logger.log("First - "+DriveApp.getFileById(Source.getId()).getLastUpdated()+" meets last - "+DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getLastUpdated());
Logger.log("Ending");

}

I am getting the error:
Exception: You do not have permission to call SpreadsheetApp.openByUrl. Required permissions: https://www.googleapis.com/auth/spreadsheets (line 4).
The formula in the cell is: =GetRngValue("""https://docs.google.com/spreadsheets/d/1axNelBTg4j..etc..7xJx2lSk/edit""", """Summary!B32""")
Can anyone point me in the right direction?  Can I not reference another GSheet from a custom formula?

A: As mentioned by TheMaster, you're better off without custom functions here. They place a lot more restrictions and are slower than if your spreadsheet were updated via script–replacing your IMPORTRANGE() functions with GetRngValue() wouldn't help you much if it were even possible. If you're pulling "values from hundreds of other documents", then it's likely you're well due for an overhaul anyway.
In the documentation for custom functions, it's stated that "custom functions never ask users to authorize access to personal data". This includes spreadsheet data and is later made more explicit:

Cannot open other spreadsheets (SpreadsheetApp.openById() or SpreadsheetApp.openByUrl()).


text:
Q: Database relationships using phpmyAdmin (composite keys) I am bit confused on making a good relational database. I am using phpmyAdmin to create a database. I have the following four tables. Don't worry about that fact place and price are optional they just are.

*

*Person (Mandatory)

*Item (Mandatory)

*Place (Optional)

*Price (Optional)

Item is the main table. It will always have person linked.
* I know you do joins in mysql for the tables.
If I want to link the tables together I could use composite keys (using the ids from each table), however is this the most correct way to link the tables? It also means item will have 5 ids including its own. This all cause null values (apparently a big no no, which I can understand) because if place and price are optional and are not used on one entry to the items table I will have a null value there. Please help!
Thanks in advance. I hope this makes sense.

A: NULL values

It also means item will have 5 ids including its own. This all cause null values (apparently a big no no, which I can understand) because if place and price are optional and are not used on one entry to the items table I will have a null value there

Personally I think this is one situation where NULL values are perfect, and I certainly wouldn't have any doubts about putting this into my database design.
One way I've seen others achieve the same thing without NULL values is to create a record in the optional tables (place and price in your example) with an ID of 0 that signifies there's no related record - but this just makes 10 times more work for the developer of the application to filter these records out - it's FAR easier to do a join and if you don't get any records back, there are no related records in the optional table.
Just remember to do a LEFT or RIGHT OUTER join if you want to return Items regardless of whether they have a Place or Price associated (you'll get NULL values in the optional table columns for Items that don't have associated records) and an INNER join if you only want the Items that do have an associated optional record.
Composite Keys
A composite key is a key in a table that's made up of more than one column.  If each of your Person, Item, Place and Price all have an ID (even if it's just an auto-incrementing number) you won't need a composite key - just a primary key column in each table, and a foreign key column in the Item table for each related table - e.g. item_id, person_id, place_id, price_id.  You state that Item has its own ID, so you shouldn't need a composite key - just a primary key on the item_id column.


text:
Q: create insertion rule on view returning id I have a table private.products and a view public.products representing that table. And I want to create entries in private.products while inserting into view, it all works right, except that I also what to return the inserted id:
CREATE RULE insert_product
AS ON INSERT TO public.products DO INSTEAD
INSERT INTO private.products (name) VALUES (new.name) RETURNING products.id;
ERROR:  RETURNING list has too few entries

What am I doing wrong?

A: Without knowing your table and view structure, I created a test case for myself:
CREATE TABLE private_table (
    id serial,
    col1 text
);

CREATE OR REPLACE VIEW public_view AS
    SELECT id, col1
      FROM private;

CREATE OR REPLACE RULE insert_private AS
    ON INSERT TO public_view DO INSTEAD
        INSERT INTO private_table (col1)
        VALUES (new.col1)
        RETURNING id, col1; -- apparently, this does not work with fewer columns
                            -- or different ordering

So far, everything works fine, and there is an answer for your question: you have to add all columns of the view in the RETURNING clause of the rule.
What this does not achieve, though, is turning the INSERT into the view into something that returns the id:
INSERT INTO public_view (col1)
    VALUES ('blah');

INSERT 0 1
-- no id returned!

This absolutely makes sense, and can be avoided by adding the RETURNING clause to the actual INSERT, as usual:
INSERT INTO public_view (col1)
    VALUES ('blah2')
    RETURNING id;

 id
────
  2
(1 row)

INSERT 0 1


text:
Q: how to make a Jbutton do multiple things I'm trying to creating an Interface that work like a Terminale in Linux
so I have a TextArea where I print and a TextField where I write and a Button that When I press should send data from TextField to TextArea
the problem now is each time I should do somthing different with what I got from My JTextField. and one listener doesn't help me like for exemple this:
public void actionPerformed(ActionEvent e) {

    Object o = e.getSource();

    if (o == ButtonCharger){
         // have multiple tests here and the "o" is diffrent each time

    }
}

I did many test but never works like I want I cauldn't make one JButton do multiple taches
I apologize about My English

A: What if you base your actions on the value you get from your JTextField,
private JTextField tField = new JTextField();

public void actionPerformed(ActionEvent e) {

    Object o = e.getSource();

    if(jField.getText().equals("YOUR STRING 1")) {

        //do something
    }
    else if(jField.getText().equals("YOUR STRING 2")) {

        //do somehting else
    }
    else {

        //don't do anything
    }
}


text:
Q: I want to make a parent nav link sidebar active when its child is active (current page) Here's my code:
I want it in a way that when i click on a child link, it becomes active and the parent link is active too. I utilize the css class .active for my active classes for both the main and sub-menu.
The below JS snippet works but only for the menus without sub-menus

$(document).ready(function($) {
  var url = window.location.href;
  var activePage = url;
  $('.menu li a').each(function() {
    var linkPage = this.href;

    if (activePage == linkPage) {
      $(this).closest("li").addClass("active");
    }
  });
});

MAIN NAVIGATION

        home
        Dashboard

        receipt
        Sell

        show_chart
        Reporting

        apps
        Products

          Add Product

          All Products

          Add Category

          All Categories

A: Implement an on mousedown event listener for your anchor tags, passing in the id for each anchor tag and use the parentElement property to get the element's parent.
document.getElementById("myLI").parentElement.nodeName;

A: you can try this JS code:
$(document).ready(function () {
        $('a').click(function () {
            //removing the previous selected menu state
            $('.menu').find('li.active').removeClass('active');
            //adding the state for this parent menu
            $(this).parents("li").addClass('active');

        });
    });

And the css for Active link:
.active > a {
    color:red;
}

hope it helps...


text:
Q: Understanding the proof to selecting $p−1$ integers from a set of $p+1$ integers, so that their weighted sum is divisible by $p$ . Could someone translate this proof to a simpler one or could you explain it to me, to more specific I am not expert in modular arithmetics?

For every choice of $p$ elements $x_0,\ldots,x_{p-1}\in S$ you have
$$k\sum x_i+\sum ix_i=\sum(i+k)x_i\equiv\sum ix_{i-k}\pmod{p},$$
if you consider the indices mod $p$. So it suffices to find $p$ such elements such that their sum is not divisible by $p$, i.e. their sum is a unit mod $p$, so that there exists an integer $k$ such that
$$k\sum x_i+\sum ix_i\equiv0\pmod{p}.$$
If the sum of every choice of $p$ elements is divisible by $p$, then all elements of $S$ are pairwise congruent mod $p$, so any choice of $p-1$ elements from $S$ will do as then
$$\sum ix_i\equiv x_1\sum i=x_1\frac{p(p+1)}{2}\equiv0\pmod{p}.$$


text:
Q: How to implement double indexing in a 2D sparse scipy matrix? Suppose I have a 2D sparse matrix M representing the results of 2-on-2 basketball matches.
I want to use address the elements of the matrix using double-indexing :
Element M[i,j][k,l] will represent the score of the game played by a team of players i and j against team  k and l. Thus, each column/row is specified by two numbers instead of one.
Note that this is not a 4D matrix.
I'm looking for a way to do this with a sparse SciPy matrix in order to be able to perform various matrix-related calculations (eigenvalues/vectors, etc).


text:
Q: asymptotic behaviour of inverse hyperbolic sine function Good evening everyone,
I'm solving a physics problem and I would like to approximate the funcion arcsinh(ax)/x to a easier to work with function in the x>> region.
I did a Taylor series to approximate the x<< region, but now I don't know what to do

A: As you inverse hyperbolic functions are logarithmic functions.
for example,  $$ \sinh^{-1} ax = \ln|ax+\sqrt {a^2x^2 +1}|$$
so you may use that function instead.

A: Ais said in comments and answer, assuming $a>0$, let $y=ax$ to make
$$\frac{\sinh ^{-1}(a x)}{x}=\frac a y \frac{\sinh ^{-1}(y)}{y}=\frac a y\log\left(y+\sqrt{1+y^2}\right)$$
Now $$\log\left(y+\sqrt{1+y^2}\right)=\log(y)+\log \left(1+\sqrt{1+\frac{1}{y^2}}\right)$$ and use Taylor
$$\sqrt{1+t}=1+\frac{t}{2}-\frac{t^2}{8}+\frac{t^3}{16}-\frac{5 t^4}{128}+O\left(t^5\right)$$
$$1+\sqrt{1+t}=2+\frac{t}{2}-\frac{t^2}{8}+\frac{t^3}{16}-\frac{5 t^4}{128}+O\left(t^5\right)$$
$$\log \left(1+\sqrt{1+t}\right)=\log (2)+\frac{t}{4}-\frac{3 t^2}{32}+\frac{5 t^3}{96}-\frac{35
   t^4}{1024}+O\left(t^5\right)$$ Make $t=\frac 1{y^2}=\frac 1{a^2x^2}$ to get the desired result.


text:
Q: How does dependency injection work in EJB's following polymorphism Suppose I have an interface, let's call it A and there are two classes that implement this interface. Now, when I'll be doing dependency injection, how do I mention which specific implementation to call.
@Local
interface SortAlgo{
   void sort();
}

class bubbleSort implements SortAlgo{
   void sort(){
     // logic
   }
}

class insertionSort implements SortAlgo{
   void sort(){
     // logic
   }
}

Now dependency injection
class SortArray{
  @EJB
  SortAlgo sortAlgo;
  System.out.println(sortAlgo.sort());
}

At this point how I'll mention which implementation to pick.

A: For example, if you have SMS EJB which sends SMS via Verizon or T-Mobile Gateway, then:
@Local
public interface SmsProvider {
    public void sendSms(Sms sms);
}

T-Mobile:
@Stateless(name = "SmsProviderTMobile")
public class SmsProviderTMobile implements SmsProvider {
...
}

Verizon:
@Stateless(name = "SmsProviderVerizon")
public class SmsProviderVerizon implements SmsProvider {
...
}

Then you can inject specific implementation like this:
@EJB(beanName = "SmsProviderTMobile")
SmsProvider smsProviderTMobile;


text:
Q: Java - error after initialising game - minesweeper I am having this weird problem but I can't seem to figure it out.
I have a button that says "new game". After I play the game once, and then press "new game" which goes back into to initGame(), I face a problem as I cannot right-click on cells that was the previous game's mines. I can left-click with no problem hence I am lost.
(p.s. if you want to advice me on how to shorten/simplify my code, feel free to do so too!)
Please advice, this is part of my code(everything else works fine):
private void initGame() {
    minesFlagged=10;
    tfFlag.setText(minesFlagged + "");
    CellMouseListener listener = new CellMouseListener();
   // Reset cells, mines, and flags
   for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
         // Set all cells to un-revealed
         btnCells[row][col].setEnabled(true);  // enable button
         btnCells[row][col].setForeground(FGCOLOR_NOT_REVEALED);
         btnCells[row][col].setBackground(BGCOLOR_NOT_REVEALED);
         btnCells[row][col].setFont(FONT_NUMBERS);
         btnCells[row][col].setText("");       // display blank
         mines[row][col] = false;   // clear all the mines
         flags[row][col] = false;   // clear all the flags
         zeroesVisit[row][col] = false;
         btnCells[row][col].setIcon(null);
         btnCells[row][col].addMouseListener(listener);
      }
   }

   for (int row = 0; row <= ROWS; row++) {
      for (int col = 0; col <= COLS; col++) {
         sol[row][col]=-1;
       }
    }

// Set the number of mines and the mines' location
   numMines = 10; //rmb the array starts from zero and ends at index 9
   for(int i=0;i<numMines;i++){
       Random rand = new Random();
       //get random position for next mine
       int row = rand.nextInt(ROWS);
       int col = rand.nextInt(COLS);
       while(mines[row][col]||mines[0][0]){//if this position is a mine
           //we get new position
           row = rand.nextInt(ROWS);
           col = rand.nextInt(COLS);
       }
       mines[row][col]=true;
   }
}
private void findSol(int rowSelected,int colSelected){
    for (int rr = rowSelected - 1; rr<= rowSelected + 1; rr++){//finding how many surrounding mines
        for (int cc = colSelected - 1; cc <= colSelected + 1; cc++){
            if(rr>=0 && cc>=0 && rr<ROWS && cc<COLS){
               if (mines[rr][cc]){
                   sol[rowSelected][colSelected]++;
                }
            }
        }
    }
}
    private class CellMouseListener extends MouseAdapter {
   @Override
   public void mouseClicked(MouseEvent e) {
      // Determine the (row, col) of the JButton that triggered the event
      int rowSelected = -1,colSelected = -1;

      // Get the source object that fired the Event
      JButton source = (JButton)e.getSource();
      // Scan all rows and columns, and match with the source object
      boolean found = false;
      boolean done = true;
      for (int row = 0; row < ROWS && !found; ++row) {
         for (int col = 0; col < COLS && !found; ++col) {
            if (source == btnCells[row][col]) {
               rowSelected = row;
               colSelected = col;
               found = true;   // break both inner/outer loops
            }
         }
      }

      // Left-click to reveal a cell; Right-click to plant/remove the flag.
      if (e.getButton() == MouseEvent.BUTTON1 && (!flags[rowSelected][colSelected])) {  // Left-button clicked
         //If you hit a mine, game over - OKAY
         //Otherwise, reveal the cell and display the number of surrounding mines - okay
          if (mines[rowSelected][colSelected]){
             btnCells[rowSelected][colSelected].setBackground(BGCOLOR_REVEALED);
             imgMines = new ImageIcon(getClass().getResource("Bombicon.png"));
             btnCells[rowSelected][colSelected].setIcon(imgMines);
             JOptionPane.showMessageDialog(null, "Game Over! Try to complete the game~");
         }else{
             btnCells[rowSelected][colSelected].setBackground(FGCOLOR_REVEALED); //though foreground is text color
             btnCells[rowSelected][colSelected].setIcon(null);
             sol[rowSelected][colSelected]=0;
             findSol(rowSelected,colSelected);

             if(sol[rowSelected][colSelected]>0){
                 btnCells[rowSelected][colSelected].setText(""+sol[rowSelected][colSelected]);
                 btnCells[rowSelected][colSelected].removeMouseListener(this);
                 colorCell(rowSelected,colSelected);
             }
             else if(sol[rowSelected][colSelected]==0){
                 do{
                     done = true;
                     for(int r=0;r<ROWS;r++){//scanning through whole board
                         for(int c=0;c<COLS;c++){
                             if(sol[r][c]==0 && !zeroesVisit[r][c]){
                                 zeroesVisit[r][c]=true;
                                 for(int row=r-1;row<=r+1;row++){//open the 8 surrounding cells
                                     for(int col=c-1;col<=c+1;col++){
                                         if(row>=0 && col>=0 && row<ROWS && col<COLS){//make sure not out of bounds
                                             btnCells[row][col].setBackground(FGCOLOR_REVEALED);
                                             btnCells[row][col].setIcon(null);
                                             sol[row][col]=0;
                                             findSol(row,col);
                                             btnCells[row][col].removeMouseListener(this);
                                             if(sol[row][col]>0){
                                                 btnCells[row][col].setText(""+sol[row][col]);
                                                 colorCell(row,col);
                                             }
                                             else if(sol[row][col]==0){
                                                 btnCells[row][col].setText("");
                                                 done=false;//to prompt looping again
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }while(!done);//scan again to find all/any the zero cells
             }
         }

      }else if (e.getButton() == MouseEvent.BUTTON3) { // right-button clicked
         //If the location is flagged, remove the flag
         // Otherwise, plant a flag. - COMPLETED
          if(flags[rowSelected][colSelected]){
              flags[rowSelected][colSelected]=false;
              btnCells[rowSelected][colSelected].setBackground(BGCOLOR_NOT_REVEALED);
              btnCells[rowSelected][colSelected].setIcon(null);
              minesFlagged++;
              tfFlag.setText(minesFlagged + "");
          }else{
              flags[rowSelected][colSelected]=true;
              btnCells[rowSelected][colSelected].setBackground(FGCOLOR_NOT_REVEALED);
              imgFlags = new ImageIcon(getClass().getResource("whiteflag.png"));
              btnCells[rowSelected][colSelected].setIcon(imgFlags);
              minesFlagged--;
              tfFlag.setText(minesFlagged + "");
          }
      }

      //Check if the player has won, after revealing this cell - COMPLETED
      int completeCount=0,flagCount=0;
      for (int row = 0; row < ROWS; ++row) {
          for (int col = 0; col < COLS; ++col) {
              if(!mines[row][col] && btnCells[row][col].getBackground()==FGCOLOR_REVEALED){
                  completeCount++;
                  if((ROWS*COLS-numMines) == completeCount){
                      JOptionPane.showMessageDialog(null, "CONGRATULATIONS!");
                  }
              }
          }
      }
   }
}

A: It appears you are calling addMouseListener each time the game is initialized.  This does not replace the existing MouseListener from previous games, so you now have an additional listener on buttons where you did not call removeMouseListener.  I would investigate this first, if certain buttons are not firing the event.
It would be better to only add the listeners once, when the Frame is first created.  Then add logic to the mouseClicked event method to ignore clicks on buttons which are "deactivated", rather than removing and adding the listener over and over again.
If you must take this approach, I recommend removing all MouseListeners from any buttons which have them (they can be found using the method getMouseListeners), before adding the listener inside the initGame method.
As stated by ArielB, it is best practice to separate your model (the position of the mines and states of the tiles, etc) into another class away from your UI code.


text:
Q: Could not find com.google.ads.AdActivity
^ there is the image so you know I'm using sdk 3.2. There is more to this code, but basically this is everything for my java code inside my main one, and it doesn't load my ads when I go to load them.  There are no errors and nothing in my Main.XML for the ad  Basically the ad is not showing at all
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class LearningLettersActivity extends Activity

    private AdView adView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create the adView
        adView = new AdView(this, AdSize.BANNER, "aXXXXXXXXXXXXXXXX); //<---My   Publisher Id there"
        // Lookup your LinearLayout assuming it's been given
        // the attribute android:id="@+id/mainLayout"    \
        LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
        // Add the adView to it
        layout.addView(adView);
        // Initiate a generic request to load it with an ad
        adView.loadAd(new AdRequest());

Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.better.work.learning.letters.and.more"
          android:versionCode="3"
          android:versionName="1.00">
    <application
            android:icon="@drawable/icon"
            android:label="@string/app_name">
        <activity
                android:name=".LearningLettersActivity"
                android:label="@string/app_name"
                android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
    </application>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-sdk android:minSdkVersion="4"/>
</manifest>

Basically nothing is pooping up for my ads at all when I go to test it on my phone, I tried using the code below and still nothing.
AdRequest adrequest = new AdRequest();
adrequest.setTesting (true);
adView.loadAd(adrequest);

I've also tried:
AdRequest adrequest = new AdRequest();
adrequest.setTesting (true);
adrequest.setTestingDevices("HT0CWHL11423") //<--- the name of my phone that appears when I go to load the emulator tab
adView.loadAd(adrequest);

Result:
01-18 03:50:19.874: E/Ads(16938): Could not find com.google.ads.AdActivity, please make sure it is registered in AndroidManifest.xml.
01-18 03:50:19.874: E/Ads(16938): You must have AdActivity declared in AndroidManifest.xml with configChanges.

A: The Google AdMob Ads SDK for Android requires Android 1.5 or later. Make sure you have the latest copy of the Android SDK and that you're compiling against at least Android v3.2 (set target in default.properties to android-13).
So take android v3.2 as your target version for the latest copy (as your manifest file suggest that you have taken the latest one).
For more details please have a look on this
Hope this will help you.

A: Look in the logcat for anything with the Tag Ads.  Specifically, look for something like:

Ad Request successful, but no ad returned due to lack of inventory.

It is possible that you are not getting ads back because AdMob cannot fill an ad.
There are a couple of things to note here. AdRequest.setTesting(true), which only used to set test mode for emulators, is deprecated in favor of AdRequest.addTestDevice(AdRequest.TEST_EMULATOR) for setting test mode on an emulator.  For setting a test device, the device id you are supposed to enter is a hashed device id, which you can find in the logcat as well if you are debugging on your device.
Finally, the picture that you're using shows you have the SDK included for a ButtonMasher app, but the code you provided looks like it's for a Letter Learning app.  Make sure you are indeed using 4.3.1 in this app.


text:
Q: fminsearch in R is worse than in Matlab There is my data (x and y columns are relevant):
https://www.dropbox.com/s/b61a7enhoa0p57p/Simple1.csv
What I need is to fit the data with the polyline. Matlab code that does this is:
spline_fit.m:
function [score, params] = spline_fit (points, x, y)

min_f = min(x)-1;
max_f = max(x);

points = [min_f points max_f];
params = zeros(length(points)-1, 2);

score = 0;
for i = 1:length(points)-1
    in = (x > points(i)) & (x <= points(i+1));
    if sum(in) > 2
        p = polyfit(x(in), y(in), 1);
        pred = p(1)*x(in) + p(2);
        score = score + norm(pred - y(in));
        params(i, :) = p;
    else
       params(i, :) = nan;
    end
end

test.m:
%Find the parameters
r = [100,250,400];
p = fminsearch('spline_fit', r, [], x, y)
[score, param] = spline_fit(p, x, y)

%Plot the result
y1 = zeros(size(x));
p1 = [-inf, p, inf];
for i = 1:size(param, 1)
    in = (x > p1(i)) & (x <= p1(i+1));
    y1(in) = x(in)*param(i,1) + param(i,2);
end

[x1, I] = sort(x);
y1 = y1(I);

plot(x,y,'x',x1,y1,'k','LineWidth', 2)

And this does work fine, producing following optimization: [102.9842, 191.0006, 421.9912]
I've implemented the same idea in R:
library(pracma);
spline_fit <- function(x, xx, yy) {

  min_f = min(xx)-1;
  max_f = max(xx);

  points = c(min_f, x, max_f)
  params = array(0, c(length(points)-1, 2));

  score = 0;
  for( i in 1:length(points)-1)
  {
    inn <- (xx > points[i]) & (xx <= points[i+1]);
    if (sum(inn) > 2)
    {
      p <- polyfit(xx[inn], yy[inn], 1);
      pred <- p[1]*xx[inn] + p[2];
      score <- score + norm(as.matrix(pred - yy[inn]),"F");
      params[i,] <- p;
    }
    else
      params[i,] <- NA;
  }
  score
}

But I get very bad results:
> fminsearch(spline_fit,c(100,250,400), xx = Simple1$x, yy = Simple1$y)
$xval
[1] 100.1667 250.0000 400.0000

$fval
[1] 4452.761

$niter
[1] 2

As you can see, it stops after 2 iterations and doesn't produce good points.
I'll be very glad for any help in resolving this issue.
Also, if anyone knows how to implement this in C# using any free library, it will be even better. I know whereto get polyfit, but not fminsearch.

A: The problem here is that the likelihood surface is very badly behaved -- there are both multiple minima and discontinuous jumps -- which will make the results you get with different optimizers almost arbitrary.  I will admit that MATLAB's optimizers are remarkably robust, but I would say that it's pretty much a matter of chance (and where you start) whether an optimizer will get to the global minimum for this case, unless you use some form of stochastic global optimization such as simulated annealing.
I chose to use R's built-in optimizer (which uses Nelder-Mead by default) rather than fminsearch from the pracma package.
spline_fit <- function(x, xx = Simple1$x, yy=Simple1$y) {

    min_f = min(xx)-1
    max_f = max(xx)

    points = c(min_f, x, max_f)
    params = array(0, c(length(points)-1, 2))

    score = 0
    for( i in 1:(length(points)-1))
    {
        inn <- (xx > points[i]) & (xx <= points[i+1]);
        if (sum(inn) > 2)
        {
            p <- polyfit(xx[inn], yy[inn], 1);
            pred <- p[1]*xx[inn] + p[2];
            score <- score + norm(as.matrix(pred - yy[inn]),"F");
            params[i,] <- p;
        }
        else
            params[i,] <- NA;
    }
    score
}

library(pracma) ## for polyfit
Simple1 <- read.csv("Simple1.csv")
opt1 <- optim(fn=spline_fit,c(100,250,400), xx = Simple1$x, yy = Simple1$y)
## [1] 102.4365 201.5835 422.2503

This is better than the fminsearch results, but still different from the MATLAB results, and worse than them:
## Matlab results:
matlab_fit <- c(102.9842, 191.0006, 421.9912)
spline_fit(matlab_fit, xx = Simple1$x, yy = Simple1$y)
## 3724.3
opt1$val
## 3755.5  (worse)

The bbmle package offers an experimental/not very well documented set of tools for exploring optimization surfaces:
library(bbmle)
ss <- slice2D(fun=spline_fit,opt1$par,nt=51)
library(lattice)

A 2D "slice" around the optim-estimated parameters.  The circles show the optim fit (solid) and the minimum value within each slice (open).
png("splom1.png")
print(splom(ss))
dev.off()

A 'slice' between the matlab and optim fits shows that the surface is quite rugged:
ss2 <- bbmle:::slicetrans(matlab_fit,opt1$par,spline_fit)
png("slice1.png")
print(plot(ss2))
dev.off()


text:
Q: Protection against electrostatic paint by draining the charge I have a circuit for an automotive sensor aimed for 24V supply. The circuit itself is well tested for EMC requirements including power line transients and EMC immunity. Usually the requirement is for all the terminal pins to be galvanically isolated from the metal housing. We have but a strange requirement from one of our customers that demands the opposite. They subject our sensors to electrostatic painting and it may be - just may be- that some charge gets induced on one of the terminal pins. They want some high resistance conduction path from the pins to the case-housing to provide as a relief valve for the charge to be grounded in such situation. I already have the Y-caps from case-housing to all the lines. I was thinking of some high resistors in parallel to each of these caps as a charge draining path. but then what effect would it have on the galvanic insulation requirement (>10Meg @ 500V)?

A: So it seems like placing a TVS in series with a suiatble high value resistor  across the CASE (Y) capacitor helps to leak this current out of the system. It also seems that I did not need to place this series combi across each Y Cap but only across the GND to CASE Y cap because all other terminals have some path to the GND (VCC and CAN lines via TVSs for example.)


text:
Q: App crashing when trying to setValue in NSMuableDictionary My app is crashing when I try to set value in NSMutableDictionary.
Here is the code below which demostrate the crash, I am not able to find out any crash log also in the console.
NSArray *b =[[a objectAtIndex:1] valueForKey:@"value"];
NSMutableDictionary *b1 =[b objectAtIndex:0];
NSString *str = self.tes;
[b1 setValue:str forKey:@"value"];

Please help me regarding this.
b1 Dictionary log
{
    question = "vale";
    type = a;
}

A: setValue:forKey: is part of the NSKeyValueCoding protocol, which among other things, lets you access object properties from the likes of Interface Builder. setValue:forKey: is implemented in classes other than NSDictionary.
setObject:forKey: is NSMutableDictionary's reason to exist. Its signature happens to be quite similar to setValue:forKey:, but is more generic (e.g. any key type).
So in your case just replace all setValue:forKey with setObject:forKey and valueForKey: with objectForKey:
--
Difference between objectForKey and valueForKey?

A: So you said you are getting EXC_BAD_ACCESS crash. Try turning on Zombies in Xcode's Scheme editor. See Enable and Debug Zombie objects in iOS using Xcode 5.1.1. That question explains how to use it, but you don't need to run Instruments as mentioned there.
Then just run the app and Xcode will show you the reason of EXC_BAD_ACCESS. Don't forget to turn Zombies off after you don't need it.
The name Zombie comes from the fact that under this mode all deallocated objects will be marked and will be kept as special regions of memory (not live, not dead, zombies). Once your code attempts to use such deallocated object, Xcode will notice and print helpful message.


text:
Q: How to add HashMap values into an ArrayList I have a HashMap and I am iterating like this:
for(HashMap<String, Integer> aString : value){
                System.out.println("key : " + key + " value : " + aString);

            }

I get the result as:
key : My Name value : {SKI=7, COR=13, IN=30}

Now I need to separate the `SKI , COR and IN into 3 different ArrayLists with their corresponding values? How to do that?

A: If your data is always JSON, you can simply decode it as you normally would using JSON:
ArrayList<Integer> array = new ArrayList<Integer>();
JSONArray json = new JSONArray(aString);
for (int i =0; i< json.length(); i++) {
    array.add(json.getInt(i));
}

A: I'm not super sure what your hashmap contains because your code is so brief, but it almost looks like it is giving you the toString() of the hashmap. The best way to iterate through a hashmap would be:
    Map mp;
    .....
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        String key = pairs.getKey();
        String value = pairs.getValue();
        //Do something with the key/value pair
    }

But if you are iterating through your hashmap correctly then below is the solution to manually parse that string into three different arraylists, this is probably the safest way to do it.
ArrayList < String > ski = new ArrayList < String > ();
ArrayList < String > cor = new ArrayList < String > ();
ArrayList < String > in = new ArrayList < String > ();

for (HashMap < String, Integer > aString: value) {
    System.out.println("key : " + key + " value : " + aString);
    aString.replace("{", "");
    aString.replace("}", "");
    String[] items = aString.split(", ");
    for (String str: items) {
        if (str.contains("SKI")) {
            String skiPart = str.split("=");
            if (skiPart.length == 2) ski.add(skiPart[1]);
        }
        elseif(str.contains("COR")) {
            String corPart = str.split("=");
            if (corPart.length == 2) cor.add(corPart[1]);
        }
        elseif(str.contains("IN")) {
            String inPart = str.split("=");
            if (inPart.length == 2) in.add(inPart[1]);
        }
    }

}

A: Here is an ArrayList (or List) full of HashMaps:
ArrayList<HashMap<String, Object>> userNotifications = new ArrayList<HashMap<String, Object>>();
int count = 0;

HashMap<String, Object> notificationItem = new HashMap<String, Object>();
notificationItem.put("key1", "value1");
notificationItem.put("key2", "value2");
userNotifications.add(count, notificationItem);
count++;

Then to retrieve the values:
ArrayList<HashMap<String, Object>> resultGetLast5PushNotificationsByUser = new ArrayList<HashMap<String, Object>>();

resultGetLast5PushNotificationsByUser = methodThatReturnsAnArrayList();
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(0);
String value1= item1.get("key1");
String value2= item1.get("key2");
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(1);
String value1= item1.get("key1");
String value2= item1.get("key2");

A: It is not clear what is the shape of your expected output.
Three lists like this:
[7]
[13]
[30]

or a mapping from keys to three lists like this:
{ "SKI" -> [7]  }
{ "COR" -> [13] }
{ "IN"  -> [7]  }

?
Nevertheless, here are some options:
Option 1
// HashMap does not preserve order of entries
HashMap<String, Integer> map = new HashMap<>();
map.put("SKI", 7);
map.put("COR", 13);
map.put("IN", 30);

List<List<Integer>> listOfLists = map.values()
                                     .stream()
                                     .map(Collections::singletonList)
                                     .collect(Collectors.toList());

listOfLists.forEach(System.out::println);

Output:
[7]
[30]
[13]

Option 2
// LinkedHashMap preserves order of entries
LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
map2.put("SKI", 7);
map2.put("COR", 13);
map2.put("IN", 30);

List<List<Integer>> listOfLists2 = map2.values()
                                       .stream()
                                       .map(Collections::singletonList)
                                       .collect(Collectors.toList());

listOfLists2.forEach(System.out::println);

Output:
[7]
[13]
[30]

Option 3
HashMap<String, Integer> map3 = new HashMap<>();
map3.put("SKI", 7);
map3.put("COR", 13);
map3.put("IN", 30);

HashMap<String, List<Integer>> result = new HashMap<>();
map3.forEach((key, value) -> result.put(key, Collections.singletonList(value)));

result.entrySet().forEach(System.out::println);

Output:
SKI=[7]
IN=[30]
COR=[13]

Option 4
Map<String, List<Integer>> result =
        map4.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    // key mapping
                    entry -> entry.getKey(),
                    // value mapping
                    entry -> Collections.singletonList(entry.getValue())
                    )
            );

result.forEach((key, val) -> System.out.println(key + " " + val));

Output:
SKI [7]
IN [30]
COR [13]


text:
Q: echo directories whose name doesn't start with 1 and has an odd number as second char Do you know how to write a command in bash which using "echo" will write all the directories in the current directory, which name does not start with a number one (1) and in the second position in the name has an odd number?

A: Using a simple glob:
echo [!1][13579]*/

$ ls
1567  1678  1789  1900  2011  2122  2233  2344
$ echo [!1][13579]*/
2122/ 2344/


text:
Q: How to add an object created from a class to an array using a method created on its class I created a Book class which includes a method to add a single object to an array when a button is clicked. But when I click it, what gets added is the button itself from the DOM.
Here is the code:
class Book {
    constructor(title, author, year, poster){
        this.title = title;
        this.author = author;
        this.year = year
        this.poster = poster
    }
    addToFavourite(){
        favouriteBooks.push(this)
    }

}
const favouriteBooks = []
const booksList = [ new Book('you don\'t know js', ' Kyle Simpson', 2014, 'https://images-na.ssl-images-amazon.com/images/I/41T5H8u7fUL._SX331_BO1,204,203,200_.jpg'),
                    new Book('javascript the definitive guide', 'David Flanagan', 1996, 'https://images-na.ssl-images-amazon.com/images/I/51wijnc-Y8L._SX379_BO1,204,203,200_.jpg'),
                    new Book('Eloquent JavaScript', 'Marijn Haverbeke', 2011, 'https://eloquentjavascript.net/img/cover.jpg')
                ]

const renderBooks = (booksToRender)=>{
    booksToRender.forEach(book =>{
        //elements to be created
        const bookContainer = document.createElement('article')
        const posterContainer = document.createElement('div')
        const poster = document.createElement('img')
        const bookTitle = document.createElement('h2')
        const bookYear = document.createElement('p')
        const bookAuthor = document.createElement('h3')
        const addToFavouriteBtn = document.createElement('button')

        //elements setup
        addToFavouriteBtn.addEventListener('click', book.addToFavourite)
        poster.src = book.poster
        bookTitle.textContent = book.title
        bookYear.textContent = book.year
        bookAuthor.textContent = book.author
        addToFavouriteBtn.textContent = 'Add to favourite'

        //elements render
        posterContainer.append(poster)
        bookContainer.append(posterContainer, bookTitle, bookYear, bookAuthor, addToFavouriteBtn)
        document.querySelector('main').append(bookContainer)

    })
}

renderBooks(booksList)

A: That's because the this refers to the button when the click event triggers and not to the book, You need to bind the book to the method so addToFavouriteBtn.addEventListener('click', book.addToFavourite) should be addToFavouriteBtn.addEventListener('click', book.addToFavourite.bind(book)) in order to make it work as expected

class Book {
    constructor(title, author, year, poster){
        this.title = title;
        this.author = author;
        this.year = year
        this.poster = poster
    }
    addToFavourite(){
        favouriteBooks.push(this)
        // just demonstration
        console.clear();
        console.log("---Favourite Books:---\n", favouriteBooks);
    }

}
const favouriteBooks = []
const booksList = [ new Book('you don\'t know js', ' Kyle Simpson', 2014, 'https://images-na.ssl-images-amazon.com/images/I/41T5H8u7fUL._SX331_BO1,204,203,200_.jpg'),
                    new Book('javascript the definitive guide', 'David Flanagan', 1996, 'https://images-na.ssl-images-amazon.com/images/I/51wijnc-Y8L._SX379_BO1,204,203,200_.jpg'),
                    new Book('Eloquent JavaScript', 'Marijn Haverbeke', 2011, 'https://eloquentjavascript.net/img/cover.jpg')
                ]

const renderBooks = (booksToRender)=>{
    booksToRender.forEach(book =>{
        //elements to be created
        const bookContainer = document.createElement('article')
        const posterContainer = document.createElement('div')
        const poster = document.createElement('img')
        const bookTitle = document.createElement('h2')
        const bookYear = document.createElement('p')
        const bookAuthor = document.createElement('h3')
        const addToFavouriteBtn = document.createElement('button')

        //elements setup
        addToFavouriteBtn.addEventListener('click', book.addToFavourite.bind(book))
        poster.src = book.poster
        bookTitle.textContent = book.title
        bookYear.textContent = book.year
        bookAuthor.textContent = book.author
        addToFavouriteBtn.textContent = 'Add to favourite'

        //elements render
        posterContainer.append(poster)
        bookContainer.append(posterContainer, bookTitle, bookYear, bookAuthor, addToFavouriteBtn)
        document.querySelector('main').append(bookContainer)

    })
}

renderBooks(booksList)
<main></main>


text:
Q: How to fix the "Illegal reference to memory A" error I created an 8-bit comparator, and I want to put it in testbench for simulation, but I have compile errors for testbench.
It is my module:
`include "BCS_RTL_VERILOG.v"
`timescale 1ns/1ns
module eight_bit_comparator(input [0:7] A, [0:7] B, E0, G0, output E8, G8);
wire [0:8] W1;
wire [0:8] W2;
assign W1[0] = E0;
assign W2[0] = G0;
genvar k;
generate
    for(k=0; k<8; k=k+1) begin: BCSgates
    RTL_BCS rtl_bcs(A[k], B[k], W1[k], W2[k], W1[k+1], W2[k+1]);
end
endgenerate
endmodule

and it is my testbench for my module with 6 error:
`timescale 1ns/1ns
module comp_eight_tb();
wire E_out, G_out;
reg A[0:7], B[0:7], E_in, G_in;
eight_bit_comparator(A, B, E_in, G_in, E_out, G_out);
initial begin
#25 A[0]=1;
#25 A[1]=1;
#25 A[2]=1;
#25 A[3]=1;
#25 A[4]=1;
#25 A[5]=1;
#25 A[6]=1;
#25 A[7]=1;
#0 B[0]=1;
#0 B[1]=1;
#0 B[2]=1;
#0 B[3]=1;
#0 B[4]=1;
#0 B[5]=1;
#0 B[6]=1;
#0 B[7]=1;
#5 E_in=1;
#0 G_in=1;
#20 $stop;
end
endmodule

errors:
comp_eight_tb.v(5): (vlog-2110) Illegal reference to memory "B".
comp_eight_tb.v(5): (vlog-2110) Illegal reference to net array "#implicit-wire#1".
comp_eight_tb.v(5): (vlog-2110) Illegal reference to memory "B".
comp_eight_tb.v(5): (vlog-2110) Illegal reference to memory "A".
comp_eight_tb.v(5): (vlog-2110) Illegal reference to net array "#implicit-wire#0".
comp_eight_tb.v(5): (vlog-2110) Illegal reference to memory "A".

These errors are for line 5 in testbench, but I couldn't recognize the problem. Can anyone solve this and explain why?

A: In the testbench, you should declare the bit range to the left of A and B.  Also, it is more conventional to specify the MSB to the left of the LSB.  Since you didn't post the code for the RTL_BCS module, I commented the instances of it out.  This code compiles for me without errors:
module eight_bit_comparator (
    input [7:0] A,
    input [7:0] B,
    input E0,
    input G0,
    output E8,
    output G8
);
wire [0:8] W1;
wire [0:8] W2;
assign W1[0] = E0;
assign W2[0] = G0;
/*
genvar k;
generate
    for(k=0; k<8; k=k+1) begin: BCSgates
    RTL_BCS rtl_bcs(A[k], B[k], W1[k], W2[k], W1[k+1], W2[k+1]);
    end
endgenerate
*/
endmodule

`timescale 1ns/1ns
module comp_eight_tb();
wire E_out, G_out;
reg [7:0] A, B;
reg E_in, G_in;

eight_bit_comparator dut (A, B, E_in, G_in, E_out, G_out);

initial begin
    #25 A[0]=1;
    #25 A[1]=1;
    #25 A[2]=1;
    #25 A[3]=1;
    #25 A[4]=1;
    #25 A[5]=1;
    #25 A[6]=1;
    #25 A[7]=1;
    #0 B[0]=1;
    #0 B[1]=1;
    #0 B[2]=1;
    #0 B[3]=1;
    #0 B[4]=1;
    #0 B[5]=1;
    #0 B[6]=1;
    #0 B[7]=1;
    #5 E_in=1;
    #0 G_in=1;
    #20 $stop;
end
endmodule

I fixed another compile error by adding the dut instance name in the testbench.


text:
Q: Run linq-to-XML operations without namespace I have a lot of code like this in one of my projects (from before I knew how to use yield return):
    public EditorialReviewDTO[] GetEditorialReviews(string URL) {
        XDocument xml = XDocument.Load(URL);
        XNamespace ns = xml.Root.Name.NamespaceName;
        List<EditorialReviewDTO> result = new List<EditorialReviewDTO>();

        List<XElement> EdRevs = xml.Descendants(ns + "EditorialReview").ToList();
        for (int i = 0; i < EdRevs.Count; i++) {
            XElement el = EdRevs[i];
            result.Add(new EditorialReviewDTO() { Source = XMLHelper.getValue(el, ns, "Source"), Content = Clean(XMLHelper.getValue(el, ns, "Content")) });
        }

        return result.ToArray();
    }

    public static string getValue(XElement el, XNamespace ns, string name) {
        if (el == null) return String.Empty;

        el = el.Descendants(ns + name).FirstOrDefault();
        return (el == null) ? String.Empty : el.Value;
    }

My question is: is there a way to run these queries without having to pass around the namespace?  Is there a way to say xml.Descendants("EditorialReview") and have it work even if that element has a namespace attached?
Needless to say, I have no control over the XML format returned.

A: No, Descendants("EditorialReview") selects elements with local name EditorialReview in no namespace so that call does not select any elements which are in a namespace. However for your method getValue you could eliminate the XNamespace argument ns and instead use public static string getValue(XElement el, XName name) and then simply call it as e.g. getValue(el, ns + "Source").


text:
Q: In Linux how do you set it that Google Chrome runs in debugging mode by default I specifically need this for puppeteer to open a window in my current browser so that my user data can be accessed and I can login to places automatically
In Windows, you enable the setting by adding this to the shortcut icon's 'target' field, '–remote-debugging-port=9222'
This will automatically run Chrome with that setting so you have all your login sessions available
How can I have the same effect in Linux where I enable the setting permanently?
There is a way to run Chrome in this way by running  /usr/bin/google-chrome-stable --remote-debugging-port=9220 in your terminal, but where can I edit a file to have this permanently enabled?
I've also run into a small error right now trying to start my puppeteer script.
FetchError: Failed to fetch browser webSocket URL from http://localhost:9222/json/version: request to http://localhost:9222/json/version failed, reason: connect ECONNREFUSED 127.0.0.1:9222
    at ClientRequest.<anonymous> (/home/me/Coding/whatsapp-bot-puppeteer/node_modules/node-fetch/lib/index.js:1461:11)
    at ClientRequest.emit (node:events:526:28)
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED'
}

I'm Linux noob, so I need some help please ^-^

A: I have found a slight workaround, but it does require you to create a chrome instance through the terminal and then use a websocket connection string
You will also have to log into your new chrome window and sign in wherever
/usr/bin/google-chrome-stable --remote-debugging-port=9222 --no-first-run --no-default-browser-check --user-data-dir=remote-profile

Running this in a Linux terminal will provide you with a ws connection you copy and then paste into your puppeteer script
Please look here for an example:
https://blog.nutjane.me/how-to-run-puppeteer-with-existing-chrome-profile-f42954bfc70c
You just have to make sure not to close this browser instance if you're planning on having a puppeteer script run the whole time. Otherwise you'll have to restart the chrome browser from the terminal and update the ws connection string in your puppeteer file :)
I've tested a quick script with puppeteer now, and I am having success with it :D


text:
Q: NSPopUpButton in a TrackingArea -> mouse exited when selecting an item from the menu I have an NSPopUpButton inside a trackingArea. Now when I open the PopUp and select an item, the mouseExited: method gets called. Even if my mouse is still inside the trackingArea. I assume that that is because the NSMenu is a view itself and when I click the mouse it is not in the view with the tracking rect anymore.
How can i workaround this problem? Is there a way to set a tracking area on top of all views?
The tracking area I use:
NSUInteger options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
NSTrackingArea* trackingArea = [[NSTrackingArea alloc] initWithRect:rect options:options owner:self userInfo:nil];

A: Try NSTrackingActiveInActiveApp instead of NSTrackingActiveInKeyWindow. I'm not sure about this offhand, but it's possible that the window resigns key status (but not main, which would be why its appearance doesn't change) when the menu begins tracking, so that the user can navigate the menu with the keyboard. (You could check this by being the window's delegate and responding to a couple of delegate messages.)
Of course, this does mean you'll have to check whether the window is main before handling the user's mouse movements.


text:
Q: Azure DevOps Deployment shows InvalidRequestContent: Request content contains one or more instances of unsupported reference property names We get an error on deploying our Logic-App with Azure DevOps.
I can't explain why this error occurs all at once.
Has anyone seen this error message before?
InvalidRequestContent:
Request content contains one or more instances of unsupported reference property names ($id, $ref, $values) creating ambiguity in paths 'properties.definition.actions.Parse_JSON.inputs.schema.properties.caseId.$ref,properties.definition.actions.Parse_JSON.inputs.schema.properties.integrationId.$ref'.
Please remove the use of reference property names and try again.

Our logic-app contains following JSON-Parse code. Apparently the variable "#/definitions/nonEmptyString" is defined twice.
"caseId": {
    "$ref": "#/definitions/nonEmptyString",
    "type": "string"
},

A: Issue reproduced from my end and got expected results.

*

*The issue is with $ref which is not supported by Azure logicapps as mentioned in error got.

*Created logic app as shown below and the sample JSON-Parse code is taken as per your requirement

{
"caseId": {
"$ref": "#/definitions/nonEmptyString",
"type": "string"
  }
     }

*

*By taking $ref got the same error as shown below

Failed to save logic app parselp. Request content contains one or more instances of unsupported reference property names ($id, $ref, $values) creating ambiguity in paths 'properties.definition.actions.Parse_JSON.inputs.schema.caseId.$ref'. Please remove the use of reference property names and try again.

*

*Then removed $ and taken ref in Parse Json as shown and logic App saved successfully without that error and workflow ran successfully.

A: I have fixed the problem by changing the following code
"definitions":{
   "nonEmptyString":{
      "minLength":1,
      "type":"string"
   }
},
"properties":{
   "caseId":{
      "$ref":"#/definitions/nonEmptyString",
      "type":"string"
}

to this code
"properties":{
   "caseId":{
      "minLength":1,
      "type":"string"
}

Maybe the problem was simply that my old solution defined "type": "string" twice. But I have not tested that yet.


text:
Q: VM Cloning Transfers cause Blade outage I used to be able to do this sort of thing without any problems, though the speed was still not all that great.
Hardware:
HP Proliant C3000 enclosure
BL460c G7 blades
BLc SB40c Storage blade
Enclosure is connected to Netgear Gigabit switch
Nowadays, whenever I try to do a Clone in Vcenter from one blade to another, one of the blades loses connectivity to Vcenter and the network - usually not the one involved in the transfer.  It appears to me that the blade loses network connectivity altogether, but the VMs conitnue to run.  I can't confirm this because I can't ping any of them during this time.  But the blade power remains constant and when the transfer finishes, the blade reconnects and all services are restored.
Knowing this problem was occurring and that I had to a massive VM transfer that could take overnight, I powered down all VMs with the hopes that the transfer speed would improve.  This, sadly, was not the case. The transfer took longer than expected and I had to cancel it altogether just to get services back up for business.
So my two concerns are
1. Why such slow transfer speeds when all blades are communicating via the interconnects or, at worst, a Gigabit switch?
2. Does anyone know the cause of the blade losing connectivity during transfer processes of any kind?
These are intolerant symptoms when one has VM's that require more space than what is simply required for an OS.
I realize this may not be due to VM configuration, but it quite possibly could be...


text:
Q: CKEditor - getting the default toolbar array BACK prior to instantiation I have not found this on the CKEditor documentation and am reasonably sure it can be accomplished.  I know that if you explicitly pass toolbar: to CKEditor when instantiating an editor, you can control the toolbar config.
What I would like to do is first GET the default toolbar and remove buttons based on some user requirements.  How would I fetch the CKEDITOR toolbar array first?  Thanks!
(NOTE: I thought it might be found in CKEDITOR.config.toolbar_Full like in this link here but that shows as undefined; I'm using CKE 4.7.1.)
(NOTE 2: Turns out you can construct a menu negatively using the removeButtons attribute, but I'll leave the question up as getting the entire menu as an array might still be useful.  Example:
CKEDITOR.replace('my-region', { removeButtons: 'Save,Copy,About,Source' });

)

A: I am also using version 4.7.1. I also have customized toolbars related to user requirements. Here is the snippet
In the config definition:
initToolbarSets(config);
config.toolbar = 'Default';

The function for building the different toolbar sets(including custom plugins):
function initToolbarSets(config) {
    config.toolbar_Empty = [];
    config.toolbar_Default = [
        { name: '1', items: ['Cut','Copy','Paste','PasteText','PasteFromWord'] },
        { name: '2', items: ['Undo','Redo','-','Find','Replace'] },
        { name: '3', items: ['DataTF', 'DataCB', 'Select', 'Table', 'Image','HorizontalRule'] },
        '/',
        { name: '4', items: ['Bold','Italic','Underline','Strike'] },
        { name: '5', items: ['NumberedList','BulletedList','-','Outdent','Indent'] },
        { name: '6', items: ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'] },
        { name: '7', items: ['SpecialChar','PageBreak'] },
        { name: '8', items: ['Font','FontSize'] },
        { name: '9', items: ['TextColor','BGColor'] },
        { name: '10', items: ['Maximize'] }
    ];

    config.toolbar_Mail= [
        { name: '1', items: ['Cut','Copy','Paste','PasteText','Preview'] },
        { name: '2', items: ['Undo','Redo','-','Find','Replace'] },
        { name: '3', items: ['TextField', 'Checkbox', 'Select', 'Table','Image', 'HorizontalRule', 'Link'] },
        '/',
        { name: '4', items: ['Bold', 'Italic', 'MyPlugin', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat'] },
        { name: '5', items: ['NumberedList','BulletedList','-','Outdent','Indent'] },
        { name: '6', items: ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'] },
        { name: '7', items: ['SpecialChar', 'PageBreak'] },
        { name: '8', items: ['Font', 'FontSize', 'Styles'] },
        { name: '9', items: ['TextColor','BGColor'] },
        { name: '10', items: ['Maximize'] }
    ];
    config.toolbar_Helpdoc= [
        { name: '1', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'Preview'] },
        { name: '2', items: ['Undo', 'Redo', '-', 'Find', 'Replace'] },
        { name: '3', items: ['Table', 'HorizontalRule', 'Link'] },
        '/',
        { name: '4', items: ['Bold', 'Underline', 'Strike', 'MyPlugin', 'Superscript', 'RemoveFormat'] },
        { name: '5', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'] },
        { name: '6', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
        { name: '7', items: ['SpecialChar', 'PageBreak'] },
        { name: '8', items: ['Styles']},
        { name: '9', items: ['Maximize'] }
    ];

    //...some other toolbar profiles
};

Now it depends on you how to continue. Either you develope a logic (probably within the config) to decide which toolbar profile has to be shwon to the current user. Another approach could be a control that encapsulates the whole CKEditor. In my case (ASP.NET) the editor is embedded like this:
<mynamespace:MyHTMLTextEditor ID="ckE" runat="server" Toolbar="Helpdoc" StylesSet="helpdoc" ForcePasteAsPlainText="true"/>


text:
Q: Integrating Google or Bing map with Dynamics 365 for finance and operations App: Microsoft Dynamics 365 for Finance and Operations
Product version: 10.0.18
Platform version: Update42
Requirement to update address of the record as per pointer in Google or Bing maps.
The MAP button in Addresses grid of "All customers" reads the address and open corresponding Bing map in new tab.
Q1: is there a way to show map in the form itself, maybe using X++ code?
Q2: The pointer or address in not movable, so how to do that and read and update the existing address?
Kindly help with understanding the same.

A: A1:
Below is the post in Microsoft Forum that answers first question with the usage of HTML and JS resources in X++ form with observe method usage in order to get dynamics values
https://community.dynamics.com/365/financeandoperations/f/dynamics-365-for-finance-and-operations-forum/437773/google-maps-in-microsoft-dynamics-365-finance-and-operation-s-form/1203259


text:
Q: i have written a list with four arguments.i get a user input for two of the arguments.dont know how to search in the list which have these arguments public List<train> ViewTrains()
{
    object source1;
    object destination1;

    Console.WriteLine("enter the source of the train");
    source1= Console.ReadLine();

    Console.WriteLine("enter the destination of the train");
    destination1 = Console.ReadLine();
}

these are the input.
and my list is like this.
public void TrainDetails()
{
    ListOfTrainDetails.Add(new train(001, "vivek express", "mangalore", "bhubhaneshwar"));
    ListOfTrainDetails.Add(new train(002, "ganhidham express", "mangalore", "surat"));
    ListOfTrainDetails.Add(new train(003, "mangalore express", "mangalore", "chennai"));
}

A: Assuming "TrainDetails" is a List
Foreach(var train in TrainDetails)
{
     if(string.Compare(source1,train.Source)==0)
         if(string.Compare(destination1,train.Destination)==0)
         {
            //Source and destination matches, do stuff
         }
}


text:
Q: From subquery giving error in oracle I am having this query :
SELECT T.custno,T.custlastname,AVG(T.OrderAmount) , T.OrderCount
FROM(
      SELECT  A.custno,A.custlastname,count(b.ordno) as OrderCount,    sum(c.qty*d.prodprice) AS  OrderAmount
  FROM customer A
      JOIN ordertbl B ON A.custno=b.custno
      JOIN ordline C ON b.ordno=c.ordno
      JOIN  product D ON c.prodno=d.prodno
  WHERE A.custstate='CO'
  GROUP BY A.custno,A.custlastname, b.ordno) AS T
GROUP BY T.custno,T.custlastname;

I get this error :
ORA-00933: SQL command not properly ended

When i execute inner subquery explicitly, it runs fine. Please let me know the reason.
One can try at http://sqlfiddle.com/#!4/6b48d/12

A: I guess You are missing one column in group by clause in outer query. Try the below query
SELECT T.custno,T.custlastname,AVG(T.OrderAmount) , T.OrderCount
       FROM (SELECT  A.custno,
                    A.custlastname,
                    count(b.ordno) as OrderCount,
                    sum(c.qty*d.prodprice) AS  OrderAmount
             FROM customer A
             JOIN ordertbl B ON A.custno=b.custno
             JOIN ordline C ON b.ordno=c.ordno
             JOIN  product D ON c.prodno=d.prodno
             WHERE A.custstate='CO'
             GROUP BY A.custno,A.custlastname, b.ordno) T
       GROUP BY T.custno,T.custlastname,T.OrderCount;

A: Try this :
SELECT T.custno,T.custlastname,avg(T.OrderAmount) , T.OrderCount
       FROM (SELECT  A.custno,
                    A.custlastname,
                    count(b.ordno) as OrderCount,
                    sum(c.qty*d.prodprice) AS OrderAmount
             FROM customer A
             JOIN ordertbl b ON A.custno=b.custno
             JOIN ordline c ON b.ordno=c.ordno
             JOIN  product d ON c.prodno=d.prodno
             WHERE A.custstate='CO'
             GROUP BY A.custno,A.custlastname,b.ordno,OrderAmount,
             OrderCount) AS T)
       GROUP BY T.custno,T.custlastname,T.OrderAmount,T.OrderCount;


text:
Q: Solved: Applying: [2021/05/01] Usage of raw option list on input line 252 All of a sudden running PdfLaTeX I get this error:
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (TeX Live 2021) (preloaded format=pdflatex 2021.6.13)  15 JUN 2021 23:48
entering extended mode
 \write18 enabled.
 %&-line parsing enabled.
**\makeatletter\def\cathedral@pagesize{a5}\makeatother\makeatletter \newcommand
{\select@version}{\version@final} \makeatother\newif\ifStatisticSelected\Statis
ticSelectedfalse\newif\ifFinalSelected\FinalSelectedtrue\newif\ifDraftSelected\
DraftSelectedfalse\newif\ifKindleSelected\KindleSelectedfalse\AtBeginDocument{\
SetWatermarkText{}}\input Een-halve-Surinamer-D.tex
 (./Een-halve-Surinamer-D.tex
(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrbook.cls
Document Class: scrbook 2021/03/17 v3.33 KOMA-Script document class (book)
(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrkbase.sty
Package: scrkbase 2021/03/17 v3.33 KOMA-Script package (KOMA-Script-dependent b
asics and keyval usage)

(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrbase.sty
Package: scrbase 2021/03/17 v3.33 KOMA-Script package (KOMA-Script-independent
basics and keyval usage)

(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrlfile.sty
Package: scrlfile 2021/03/17 v3.33 KOMA-Script package (file load hooks)

(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrlfile-hook.sty
Package: scrlfile-hook 2021/03/17 v3.33 KOMA-Script package (using LaTeX hooks)

(/zfs/texlive/2021/texmf-dist/tex/latex/koma-script/scrlogo.sty
Package: scrlogo 2021/03/17 v3.33 KOMA-Script package (logo)
)))
(/zfs/texlive/2021/texmf-dist/tex/latex/graphics/keyval.sty
Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
\KV@toks@=\toks16
)
Applying: [2021/05/01] Usage of raw option list on input line 252.
Already applied: [0000/00/00] compatibility for LaTeX before 2021/05/01 on inpu
t line 337.

! Missing \endcsname inserted.
<to be read again>
                   \relax
l.580 \FamilyProcessOptions{KOMA}
                                 \relax

This is with TL2021. Wenn using TL2020 it compiles smoothly. Both TL updated.
Can somebody give me a hint in what direction to go to solve this (apart from just using TL2020)?
Here is the minimal example Ulrike asked for:
\documentclass[%
\iffalse%
parskip=half,%
\fi%
]{scrbook}
%
\begin{document}
%
\end{document}

This compiles on TL2020. and also on TL2021 when \iffalse and \fi are removed. As the example also compiles for class book, I think it is a bug in the KOMA class scrbook.


text:
Q: Conformal maps from hyperbolas and parabolas to upper half-plane I've studied basic conformal mappings in a complex analysis class I took (mostly with discs and rectangular regions), but I've recently been faced with finding other conformal mappings that I've found my knowledge has left me....unfit.... to solve.
Finding bijective conformal mappings from
a) between the branches of the hyperbola $xy=1$ to the upper half plane
b) under the parabola $y=x^2$ to upper half plane
I've been trying to construct maps to discs (something I'm more familiar with) and then take it to the upper half plane (which is easy), but I am not really making any progress.
Thoughts or Hints?
Much appreciated!


text:
Q: Tkinter | How to ignore all queued events? I'm currently trying to build a small app using Tkinter for Python 3.X (I'm working with Python 3.8.10 on Ubuntu 20.04.4 LTS).
I use a tk.Canvas to simulate pseudo-3D and ZQSD to simulate displacement.
I was hoping that when I hold down a movement button (e.g. 'Z') the movement would be in sync with the Canvas.
So I realized that a time lapse is created and seems proportional to the time the key is pressed, which creates a rather unpleasant visual effect.
I think the events are put in a queue and the event handler only handles one event at a time, which would create this delay effect (proportional to the pressure time).
I already tried something like this, but there is no difference. I couldn't find a case closer to mine.
Here is my (simplified) code :
import tkinter as tk
# local modules
import camera, carte, image, joueur

class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        # initialization

        def event_handler(event=None):
            # checking and redirecting controls here

            self.camera.update() # redraw Canvas

        self.bind_all('<Key>', event_handler)
        tk.mainloop()

if __name__ == "__main__":
    app = Application()
    exit(0) # release resources

In other words, I would like to ignore events that have not yet gone through the callback and are therefore present in the queue of events to process. Is it possible ?
Someone told me about threading, but i don't know much about it...


text:
Q: Matplotlib ConnectionPatch line is blocked by other axes When I tried to draw an arrow, the pointing end got blocked by other axes, do you know how to make that part visible?
It'll be great if you could edit on top of the sample code I have here.
from matplotlib.patches import ConnectionPatch
import matplotlib.pyplot as plt
import numpy as np

grid_data = np.array([[[-0.1779874 , -0.90335705, -0.31157705,  0.77770067],
        [ 0.93698288,  0.79215241,  0.10155888,  0.96101718],
        [ 0.72994894, -0.83939131,  0.24713443,  0.74839211],
        [ 0.10039462, -0.95778299,  0.43554077,  0.61927077]],

       [[ 0.52294259, -0.0247383 ,  0.23717517, -0.0857769 ],
        [-0.43539246,  0.28503173, -0.39443502, -0.1478289 ],
        [-0.2327904 , -0.08339054,  0.33072907,  0.74634504],
        [-0.524284  , -0.72919194, -0.61543159,  0.17086563]]])
fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (2.6, 2.8))
for i in range(2):
    c = axes[0,i].pcolormesh(grid_data[i], cmap = 'RdBu_r', vmin = -1., vmax = 1.)
xyA = (0.5,0)
xyB = (0.5,.5)
coordsA = "axes fraction"
coordsB = "axes fraction"
con = ConnectionPatch(xyA = xyA, xyB = xyB, coordsA=coordsA, coordsB=coordsB,
                      axesA=axes[0,0], axesB=axes[0,1],
                      arrowstyle="->", shrinkB=5, linewidth = 5, edgecolor='b', clip_on=False)
axes[0,0].add_artist(con)
cb_ax = fig.add_axes([0.91, 0.13, 0.01, 0.75])
fig.colorbar(c, cax = cb_ax)
plt.draw()
plt.show()

A: Thanks to @Sam Mason for the pointer. One simple change to fix this would be to set the zorder to the reverse drawing order
for i in range(2):
    c = axes[0,i].pcolormesh(grid_data[i], cmap = 'RdBu_r', vmin = -1., vmax = 1.)
    axes[0,i].set_zorder(2-i)


text:
Q: Why is my app crashing during testing when I use if else statements instead of using tables? Since I am new to Android Development, I tried making a simple project similar to a calculator. I tried to input an age from user but the app keeps crashing when I use if else statements for setting the multiplier value. How can I fix this issue ?
The following is the code I have written.
package com.naveenscreations.thirdpartycompensationcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

import static java.lang.Integer.valueOf;

public class Main2Activity extends AppCompatActivity {
private EditText multiplier;
private EditText age;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    age=(EditText)findViewById(R.id.Age);
    multiplier=(EditText)findViewById(R.id.Multiplier);

    Integer year=Integer.valueOf(age.getText().toString());
    Integer mul =Integer.valueOf((multiplier.getText().toString()));
    if(year<=15)
    {
        mul=0;
        multiplier.setText(String.valueOf(mul));
    }
    else if (year>15 && year<=25)
    {
        mul=18;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>25 && year<=30)
    {
        mul=17;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>30 && year<=35)
    {
        mul=16;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>35 && year<=40)
    {
        mul=15;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>40 && year<=45)
    {
        mul=14;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>45 && year<=50)
    {
        mul=13;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>50 && year<=55)
    {
        mul=11;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>55 && year<=60)
    {
        mul=9;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>60 && year<=65)
    {
        mul=7;
        multiplier.setText(String.valueOf(mul));
    }
    else if(year>65 && year<=70)
    {
        mul=5;
        multiplier.setText(String.valueOf(mul));
    }
 }
}

Is there any other way I can optimize the code in a better way ?

A: This is crashing because your texts (age.getText() and multiplier.getText()) are empty. Try something like this :
private Integer getIntegerFromString(String value){
        if(value == null || value.isEmpty()){
            return 0;
        }

        return Integer.valueOf(value);
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    age=(EditText)findViewById(R.id.Age);
    multiplier=(EditText)findViewById(R.id.Multiplier);

    Integer year=getIntegerFromString(age.getText().toString());
    Integer mul =getIntegerFromString(multiplier.getText().toString());

    // The rest of your code
}


text:
Q: Consuming stream multiple times with Stream.sum()
A stream should be operated on (invoking an intermediate or terminal stream operation) only once.

I get the idea, but how come finding the sum of a stream does not consume it? I can run the code below, without any exceptions.
double totalPrice = stream.mapToDouble(product -> product.price).sum();
List<Product> products = stream.map(this::convert).collect(Collectors.toList());

Why sum is not a terminal operator? How is it different from collecting stream elements into a list?

A: Documentation
Whether a stream can be consumed once or multiple times is not specified. The documentation says "should be operated ... only once", not "must" or "can".
It depends on the underlying implementation and source of the stream. As such, the capability to execute it multiple times is undefined for streams in general.

Implementations
You might be able to find a stream that can be consumed twice or multiple times, especially for custom implementations or implementations where a prevention detection would maybe be too expensive to implement.
But again, it is not supported by the documentation. It may be by a current implementation, but this can change at any time, in any Java release. It may throw exceptions, it may result in buggy behavior, it is not specified.
Here is a small example which uses sum() that throws an exception because it has such a detection (JDK 11):
Stream<Integer> stream = List.of(1, 2, 3, 4).stream();

int first = stream
    .mapToInt(i -> i)
    .sum();

int second = stream
    .mapToInt(i -> i)
    .sum();

// throws IllegalStateException: stream has already been operated upon or closed

Conclusion
The intention is definitely to not use a stream multiple times, as hinted by the documentation. So even if it is maybe possible for a certain implementation, avoid it.

Why?
You may ask yourself why Stream does not support multiple iteration. After all, collections like ArrayList have no issue with that and it seems to be a common use case.
Streams have a much bigger scope than collections. A stream created on a typical collection could likely easily support multiple iterations. But a stream tied to a resource like a file or web-connection, for example the stream returned by Files.lines(...) could not. Such a feature would be extremely resource heavy and expensive for files and maybe not even supported for others, like a web-connection which may be closed afterwards.
It goes even further, you can easily create an infinite stream that generates random numbers:
Stream<Double> stream = Stream.generate(Math::random);

While it could easily support multiple usages, it would be impossible to generate the same sequence again when iterated again.
Another example, a stream that consumes resources without restoring them:
Queue<Integer> queue = ...
Stream<Integer> stream = Stream.generate(queue::poll);

This stream will remove elements from the queue. They are gone after stream usage. Another iteration of the stream wont be able to get hands on the dead objects anymore.


text:
Q: Options of symbols without evaluating them Try the following on a fresh kernel in 11.3
Options[Unevaluated[Plot]]
(* {} *)

The problem is that Plot -besides many other functions- is now auto-loaded when you need it. When you call
Options[Plot]

it shows all options, because in the evaluation chain, the symbol Plot is evaluated and therefore loaded for you.
There is a major problem though. What if you want to extract the options for many symbols? Wolfram took care that now some symbols will connect to servers, download the whole internet or have other side-effects merely by touching them.
Let's try to invoke Options for all System` symbols
Do[
  ToExpression[s, InputForm, Options],
  {s, Names["System`*"]}
];

After some seconds, I'm left with this

and after a while, my screen is full of error messages.
Therefore, on the one hand, I have to evaluate many functions before I can get their options and on the other hand, hell breaks loose when I do it.
Would someone know if there is a way to auto-load all symbols without explicitly evaluating them?

A: If you just need to look at the symbol options you don't need to load it any more, you can use WolframLanguageData to get all sort of information about symbols:
WolframLanguageData["Plot", "Options"] // Short

(* {"AlignmentPoint" -> "Center", <<58>>,
 "WorkingPrecision" -> "MachinePrecision"} *)

I assume it is contained in some downloadable paclet as it has no influence on the autoloads
Options[Unevaluated[Plot]]

(* {} *)

OwnValues[Plot]

(* {HoldPattern[Plot] :>
  System`Dump`AutoLoad[Hold[Plot],
    Hold[Plot, RegionPlot, DensityPlot, ContourPlot, ParametricPlot,
     Plot3D, ContourPlot3D, ParametricPlot3D, RegionPlot3D],
    "Visualization`SampledPlots`"] /; System`Dump`TestLoad} *)

If you plan to do that for multiple symbols, I suggest to use the listability in the first and second arguments to minimize the server calls
names = Names["System`*"];
options =
  AssociationThread[names, WolframLanguageData[names, "Options"]];


text:
Q: How to configure Spring Ws with keystore and trustore? Where do I place these commands in Spring Ws
-Djavax.net.ssl.keyStore=tomcat.keystore
-Djavax.net.ssl.keyStorePassword=tomcat
-Djavax.net.ssl.trustStore=tomcat.keystore
-Djavax.net.ssl.trustStorePassword=tomcat
-Djavax.net.debug=SSL

Do i have to place it as arguments or specify the properties in some class.I have Spring WS annotation based configuration can I configure the properties in the application itself.

A: I got the solution I can either set the properties using
System.setproperty("-Djavax.net.debug","SSL");

Or I can specify these arguments with tomcat7 when the server starts running.
Go to eclipse->right click on project->click run configuration->select tomcat ->select arguments->paste the property->click apply
And then restart tomcat


text:
Q: Should we install the OS on an SSD or not when running virtual machines? I have a new Dell Mobile Precision M6500 laptop with 8 GB RAM. It has two hard drives - 500 GB @7200 RPM and a 128 GB SSD. The main purpose of these laptop is software development in virtual machines.
The plan is to install the base OS (Windows 7) and all the programs in the 500 GB drive, and let the SSD only contain the virtual machine images. It is my understanding that the we get most performance from the virtual machines if the images are on a separate hard drive than the base OS. Is this the way to go, or should I install the OS on the SSD as well? What are the pros and cons?
The virtual machine images would be between 20 - 30 GB, and I might run 1 or 2 at a time.

A: One caveat to note: you won't get TRIM support from the virtualized instances, which means you'll lose performance over time on the SSD.
As to your original question, I see no reason to use the 500 GB for anything other than bulk storage (backups and the like); running the OS off of the SSD makes the most sense.  The reasoning behind separating the disks hosting a virtual OS and the host OS only really makes sense in a world of non-zero seek times, so since SSDs have no penalty for non-linear access, I'd say combining the two is the way to go.  That'd also let you remove the spinning disk entirely, which would save you quite a bit of battery discharge when you're on the road.

A: @BMDan
Trim should be conducted by windows trim service either way on windows because of wear leveling in the service... as the virtualization software attempts to rewrite a page that has been written, windows will change the lba of the page to a different address that has been written less times. Where you will see loss in performance is if the drive remains full for a long period of time while writing small intersections into the remaining free space repeatedly.  This is where the wear leveling fails as it will usually not move already written blocks, that don't get rewritten often, to worn down blocks, so that the fresher blocks can be used more aggressively.
With that said there is a disadvantage to having your os on the HDD's because the page file is usually on the disk you installed on.  In the case that your machine begins to thrash, you will see a massive degradation in performance. A likely scenario with 8 GB of ram running VM's. I would suggest that, if you decide to install on the hdd's, you at least move the page file to the ssd and increase it's size.  That way the spinning media will cache items to the ssd as they are unloaded from ram and be more accessible when needed later.
BMDan is correct in his suggestion though, having the os on the ssd and then only using the ssd will considerably reduce power consumption. Depends on how much space you need.

A: Certainly it'll be about as fast I can imagine it being (bar the use of FusionIO drives) - what I would say it that the VM's OSs will write as much they would on a regular disk in a non-virtualised environment, meaning write-wear. If that doesn't bother you then off you go.


text:
Q: converting ID to column name and also replacing NULL with last known value TABLE_A
Rev     ChangedBy
-----------------------------
1       A
2       B
3       C

TABLE_B
Rev Words      ID
----------------------------
1 description_1   52
1 history_1         54
2 description_2   52
3 history_2         54

Words column datatype is ntext.
TABLE_C
ID Name
-----------------------------
52 Description
54 History

OUTPUT
Rev ChangedBy Description        History
------------------------------------------------
1     A   description_1      history_1
2     B   description_2      history_1
3     C   description_2      history_2

Description and History column will have the previous known values if they dont have value for that Rev no. i.e. Since for Rev no. 3 Description does not have an entry in TABLE_B hence the last known value description_2 appears in that column for Rev no. 3 in the output.

A: With help from following posts
PIVOT on Common Table Expression
SQL QUERY replace NULL value in a row with a value from the previous known value
I was able to come up with following query to get the desired output.
    ;WITH CTE_A AS
    (
        SELECT a.Rev, a.ChangedBy, CAST(b.Words as nvarchar(max)) as [Words],c.Name FROM Table_A AS a
        INNER JOIN Table_B AS b ON a.Rev = b.Rev
        INNER JOIN Table_C AS c ON b.FId = c.Id
    ),
    CTE_B AS
    (

    select Rev, ChangedBy, [Description], [History] from
    CTE_A
    PIVOT
    (
        MAX([Words])
        FOR [Name] in ([Description],[History])
    ) as p
    )

select Rev,ChangedBy,
ISNULL([Description],(select top 1 [Description] from CTE_B where Rev < t.Rev and [Description] is not null order by Rev desc)),
ISNULL([History],(select top 1 [History] from CTE_B where Rev < t.Rev and [History] is not null order by Rev desc))
from CTE_B t


text:
Q: Joomla com_users component unable to load some templates I have modified the users component of Joomla, specifically the file components/com_users/controllers/profile.php and included some custom templates in components/com_users/views/profile/tmpl
It is mostly some forms which I am submitting and then redirecting to specific pages for further actions.
Example scenario :

Above option is accessible to user right after login. I have put it on the profile page by modifying default profile template.
So when someone enters a name, and presses search, then this form is submitted through form
action="<?php echo JRoute::_('index.php?option=com_users&task=profile.selectSendMessage'); ?>"

This in turn calls the function named selectSendMessage which is placed in profile.php file. The function looks like :

As you can see the function redirects to
index.php?option=com_users&view=profile&layout=sendMessage

I have placed sendMessage.php template in com_users/views/profile/tmpl
Everything works fine on localhost which I have set up on MAMP in MacOS
I moved the website to a live server a few days ago. I have followed all proper steps to migrate website and database from localhost to live server. Still any of the custom templates I have put in are never reached.
The strange thin is that Edit User Profile which is redirected to from the same profile.php file from a function edit(), with template in the same location as I have put in edit.php in views/profile/tmpl works as expected.
I am using 1and1 shared hosting plan 1&1 Unlimited for hosting the website.
I have been trying to fix this for quite some time now, but cannot understand the problem. I have tried reinstalling the website several times, tried installing from web apps from 1&1 control panel and modifying it, but no success.
Any tips and insights are welcome. Thank you.

A: It turns out that 1and1.com hosting somehow doesn't support layout names with a capital letter in it. I changed all layout names to lower case alphabets and everything worked fine like it should.
If someone faces the same issue, this is worth a try. It was particularly hard to debug since you will never suspect that could be a problem. I accidentally stumbled on the solution while playing around.
Thanks.


text:
Q: How can I add a row manually to a dataframe? This is probably a very simple answer, but I am not able to find a solution.
I have a dataframe:
 structure(list(year = structure(1:23, .Label = c("1990", "1991",
"1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
"2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
"2008", "2010", "2011", "2012", "2013"), class = "factor"), val = c(8,
3, 1, 17, 5, 9, 6, 7, 3, 15, 11, 6, 2, 11, 15, 11, 15, 1, 14,
2, 15, 4, 6)), .Names = c("year", "val"), row.names = c(NA, -23L
), class = "data.frame")

I want to add a row manually (year=2009, val=20) right between 2008 and 2010 year.
I am doing this using Add new row to dataframe, at specific row-index, not appended?:
#1
r<-seq(4)
newrow<-c(2009,5)
insertRow <- function(df, newrow, r) {
  df[seq(r+1,nrow(df)+1),] <- df[seq(r,nrow(df)),]
  df[r,] <- newrow
  df
}

insertRow(df, newrow, r)

But I am getting this:
Error in seq.default(r, nrow(df)) :
  'from' must be of length 1

#2
newrow<-c(2009,20)
rbind(df,newrow)

Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(1L, 2L, 3L, 4L, 5L, 6L, 7L,  :
  invalid factor level, NA generated


text:
Q: How to type exponential notation and multiply sign in R I want R to write the following:

My requirements are:

*

*The multiplication sign should not be "*", but the real multiplication sign as above;

*Scientific notation should not be expressed in 5e6, but rather 6 raised to the power of 10.

What is the R code? I feel the expression function or formatC or format should be used, but I am not sure how to do it. Thank you.

A: x <- c(5*(10^(1:5)))
plot(x, x, xaxt="n", log="x", las = 2)
labels <- parse(text = gsub("e\\+", " %*% 10^", sprintf("%.0e", x)))
axis(1, at = x, labels = labels)

Thanks to @VincentGuillemot for a simplification.


text:
Q: Timer on iOS doesn't work I'm trying to make a timer by myself but it doesn't work. It seems like it goes nil every time it repeats, anyone?  It works on OS X but not on iOS.
I just need a working loop method - any suggestions?
Header:
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *timerOutlet;
- (void)timer:(id)sender;
@end

Implementation:
@synthesize timerOutlet;

- (void)viewDidLoad
{
    [super viewDidLoad];
    started = TRUE;
    [self timer:nil];
}

- (void)timer:(id)sender {
    int test = 1;
    NSString *number = [NSString stringWithFormat:@"%i",test];
    timerOutlet.text = number;
    [self performSelector:@selector(timer:) withObject:Nil afterDelay:1.0];
    test ++;
}

A: The problem is that you re-declare test and assign 1 to it every time the timer method executes. So if you either omit the declaration and make test an instance variable, or make it static, that should help. Apart from that, however, you should really use an NSTimer object instead of raping the framework.
- (void)viewDidLoad
{
    [super viewDidLoad];
    started = TRUE;
    test = 1;
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timer:) userInfo:nil repeats:YES];
}

- (void)timer:(id)sender {
    NSLog(@"%i",test);
    test++;
}

A: You forgot "static" in int test = 1;
static int test = 1;

and you should be happy.


text:
Q: Is there a better way to store data about 2 table relationship? Currently, I have one SQL Database with a tables.
I'll call them table A, and table B.
Each table A item is associated with anywhere from 0 to all existing table B columns (I use a sort of 'tags' system, which are stored in that B table)
Right now my solution to this was to create a third table, call it C, which simply has three columns -
Id(key)
AId
BId
Count

example
So if I have A item with ID 1
Id| Name
1 | ColumnOne

Which is associated with 3 other items from table B - e.g, Id: 1, 2, 3
Id| Name
1 | TagOne
2 | TagTwo
3 | TagThree

Then C is going to look something like
Id|AId|BId
1 | 1 | 1
2 | 1 | 2
2 | 1 | 3

I just feel it's pretty redundant to have multiple entries for the same A table. Is there some better way to do this?

A: First of all, you have to determine the type of relationship between these 2 tables. If each record of table A is associated with multiple elements (0 or more) of table B, and each record of table B is also associated multiple elements of table A, then you have a many-to-many relationship. In this case, you have to create a third table (table C) with a composite primary key consisting of the primary keys of tables A and B. This means that you can drop the Id column:
Table C:
AId|BId
1 | 1
1 | 2
1 | 3