text:
Q: Get the no of columns in excel In my java application I am trying to convert excel to pdf using apache-poi.In my excel file,the number of columns are different in some rows.First and second rows contain one column,remaining rows contains 8 columns.Here is my code
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
int cellNumber = 0;
if (flag) {
            table = new PdfPTable(row.getLastCellNum());
            flag = false;
}

// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                        if (temp == 0) {
                                    numberOfColumns = row.getLastCellNum();
                                    PdfPCell c1 = new PdfPCell(new Phrase(
                                                            cell.getStringCellValue()));
                                    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    table.addCell(c1);
                                    table.setHeaderRows(1);

                        }else{
                                    cellNumber =checkEmptyCellAndAddCellContentToPDFTable(cellNumber,cell,table);
                        }
                        cellNumber++;
                        break;

            case Cell.CELL_TYPE_NUMERIC:
                        cellNumber =checkEmptyCellAndAddCellContentToPDFTable(cellNumber,cell,table);
                        cellNumber++;
                        break;
            }
}
temp = 1;
if(numberOfColumns != cellNumber){
            for(int i=0;i<(numberOfColumns-cellNumber);i++){
                        table.addCell(" ");
            }
}

}
So when I execute this,I will get the pdf file with only one column.But I want same as my excel format.How can I achieve this in my code dynamically(I have to apply this logic for other excel files also)?

A: You can use this approach to iterate each cell of every row .
     Sheet sheet = workbook.getSheetAt(0);
            //Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if(isRowEmpty(row)){
                    System.out.println("Row "+row.getRowNum()+"is a empty row");
                    continue;
                }
    Iterator<Cell> cellIterator = row.cellIterator();
                    Cell cell =null;
                    while (cellIterator.hasNext()) {
                         cell = cellIterator.next();

                            switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_BOOLEAN:
                                    String value = String.valueOf(cell.getBooleanCellValue());
                                    break;
                                case Cell.CELL_TYPE_NUMERIC:
                                    Double d = cell.getNumericCellValue();
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    String value = cell.getStringCellValue().trim();
                                    break;
                                case Cell.CELL_TYPE_BLANK:
                                    break;
                            }

                    }
}


text: Q: create a cricket score card with two pages one to display and one to update score using html I want to make a score card overlay for OBS stream using html and CSS and JS. I want to make two web pages, one to update the score and one to display the score card as an overlay for OBS. I need help pls

redpajama_set_name: RedPajamaStackExchange


text:
Q: join() JS for HTML tables I need to use join() as JS own method to add a table format to the values in those arrays.
This is an example of my two arrays to diplay, and the table layout should look like this.
This is the part of my code; ovbiously is not working ok, because Im getting a wrong "L" table style format when it runs.

I know its look terrible to parse HTML like that, but this code is in
  Google Apps Scripts, so this table is gonna be send it by email.

Any idea how to get the proper format?
Thanks.
|-------|-------|
| user  | skill |
|-------|-------|
| user  | skill |
|-------|-------|

   body +=
      "
" +

         outUsers.join("
") + "
" +

         outSkills.join("
") + "
" +

      "
";

A: In this case Array.prototype.join() doesn't do the job I'd use Array.prototype.reduce() instead
Here is an example of what it could look like:
EDIT according to PHPglue comment to have both users and skills on the same row:
var body ='';
var outUsers = ['me', 'you', 'her'],
    outSkills = ['eating', 'sleeping', 'working hard'],
    STYLE = {
        TABLE: "border: red;",
        TD: "border: blue;"
    },
    getTR = function (prev, curr, index) {
        return prev + '
' + openingTD + curr + '	' + openingTD + outSkills[index] + '
';
    };

var openingTD = '';

body += '
' +

         outUsers.reduce(getTR, '') +

        "
";

A: I think this is what you need to see:
var table = '

';
for(var i=0,l=outUsers.length; i<l; i++){
  table += '
'+outUsers[i]+'	'+outSkills[i]+'
';
}
table += '

';

You should style with CSS. You should read my comments above, as well.


text:
Q: Implode with array with keys in PHP I need to write an array to a .csv file in PHP.
Example array:
$array = array(
    "name" => "John",
    "surname" => "Doe",
    "email" => "nowhere@nowhere.com"
);

By using implode(",", $array), I get a result like this:
John,Doe,nowhere@nowhere.com
However, I need to also write the key of each element to the file.
The desired output is this:
name:John,surname:Doe,email:nowhere@nowhere.com
How would I achieve this?

A: Try this code:
$out = $sep = '';
foreach( $array as $key => $value ) {
    $out .= $sep . $key . ':' . $value;
    $sep = ',';
}

A: $csv = "";

foreach($array as $key => $data)
{
    // be sure to add " in your csv
    $csv .= '"'.$key.':'.$data.'",';
}

// and add a new line at the end
$csv .= "\n";

echo $csv;

A: The answers above outputs a trailing comma at the end. To correct this, I use the following function:
$array = array(
    "name" => "John",
    "surname" => "Doe",
    "email" => "nowhere@nowhere.com"
);
function implodeKV($glueKV, $gluePair, $KVarray){
    $t = array();
    foreach($KVarray as $key=>$val) {
        $t[] = $key . $glueKV . $val;
    }
    return implode($gluePair, $t);
}

echo implodeKV( ':' , ',' , $array);
// outputs  name:John,surname:Doe,email:nowhere@nowhere.com

http://phpassist.com/2dde2#2

A: If you're using PHP 5.3+, then an anonymous function can make your code a lot cleaner, though a simple for loop has the best performance. (Using array_walk comes close though!)
I ran some tests with a few different approaches (using PHP 5.4.33):
function makeArray(&$a) {
    $a = array();
    for($i = 0; $i < 100000; $i++) {
        $a[rand()] = rand();
    }
    return $a;
}

makeArray($array);
$before = microtime(true);
$result = implode(
    ",",
    array_map(
        function($k, $v) {
            return "$k:$v";
        },
        array_keys($array),
        $array
    )
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ anonymous function: {$dur}s
";

makeArray($array);
$before = microtime(true);
function kv_func($k, $v) {
    return "$k:$v";
}
$result = implode(
    ",",
    array_map(
        "kv_func",
        array_keys($array),
        $array
    )
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ function: {$dur}s
";

makeArray($array);
$before = microtime(true);
array_walk(
    $array,
    function(&$v, $k) {
        $v = "$k:$v";
    }
);
$result = implode(
    ",",
    $array
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Walk w/ anonymous function: {$dur}s
";

makeArray($array);
$before = microtime(true);
$ff = true;
$sep = ",";
$out = "";
foreach($array as $key => $val) {
    if($ff) $ff = false;
    else $out .= $sep;
    $out .= "$key:$val";
}
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop w/ loop flag: {$dur}s
";

makeArray($array);
$before = microtime(true);
$out = "";
foreach($array as $key => $val) {
    $out .= "$key:$val,";
}
$out = substr($out, 0, -1);
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop + substr: {$dur}s
";

Results:
Array Map w/ anonymous function: 0.13117909431458s
Array Map w/ function: 0.13743591308594s // slower than anonymous
Array Walk w/ anonymous function: 0.065797805786133s // close second
Foreach loop w/ loop flag: 0.042901992797852s // fastest
Foreach loop + substr: 0.043946027755737s // comparable to the above

And just for kicks, I tried the for loop without correcting for the trailing comma. It didn't really have any impact:
Foreach loop w/ trailing comma: 0.044748067855835s

A: <?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere@nowhere.com"
);
foreach( $array as $key=>$data ) {
$output .= $comma . $key . ':' . $data;
$comma = ',';
}

echo $output;

?>


text:
Q: Can't Run bash file inside ZSH I've placed a bash file inside .zshrc and tried all different ways to run it every time I open a new terminal window or source .zshrc but no luck.
FYI: it was working fine on .bashrc
here is .zshrc script:
#Check if ampps is running
bash ~/ampps_runner.sh & disown

Different approach:
#Check if ampps is running
sh ~/ampps_runner.sh & disown

Another approach:
#Check if ampps is running
% ~/ampps_runner.sh & disown

All the above approaches didn't work (meaning it supposes to run an app named ampps but it doesn't in zsh.
Note: It was working fine before switching to zsh from bash. so it does not have permission or syntax problems.
Update: content of ampps_runner.sh:
#! /usr/bin/env

echo "########################"
echo "Checking for ampps server to be running:"

check=$(pgrep -f "/usr/local/ampps" )

#[  -z "$check" ] && echo "Empty: Yes" || echo "Empty: No"

if [ -z "$check" ]; then
    echo "It's not running!"
    cd /usr/local/ampps
    echo password | sudo -S ./Ampps
else
    echo "It's running ..."
fi


text:
Q: Skip a line using BufferedReader (skip, but not read it) Hi guys I am currently using BufferedReader to read files. I have something like:
br.readLine() != null

for each call loop.
And now what should I do if I want to skip a line. Here, I've read several similar questions other people posted, most of them suggested using readLine().
I know calling readLine() once will cause the pointer to the next line. But this is not preferred as I am considering the reading performance here. Although you seem to skip a line, the system actually read it already, so it is not time-efficiency. What I want is to move the pointer to the next line, without reading it.
Any good idea?

A: It's not possible to skip the line without reading it.
In order to know where to skip to, you have to know where the next new line character is, so you have to read it.
P.S. Unless you have a good reason not to, BufferedReader should be fine for you - it's quite efficient

A: You'll sometimes have a problem skipping the first line with code analysis tools (sonar etc), complaining that you didn't use the value.  In the case of CSV, you may want to skip (i.e. not use) the first row if its headers.  In which case, you could stream the lines and skip perhaps?
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
  Stream<String> lines = reader.lines().skip(1);

  lines.forEachOrdered(line -> {

  ...
  });
}

A: In general, it's not possible in any language and with any API.
To skip a line you need to know the next line's offset. Either you have a file format that provides you that information, you are given line offsets as input, or you need to read every single byte just to know when a line ends and the next begins.

A: Have you read the code of readLine()? It reads chars one by one until it finds an \r or a \n and appends them to a StringBuffer. What you want is this behaviour without the burden of creating a StringBuffer. Just override the class BufferedReader and provide your own implementation which juste reads chars until /r or /n without building the useless String.
The only problem I see is that many fields are private...

A: If you care about the memory wasted in the intermediate StringBuffer, you can try the following implementation:
public static void skipLine(BufferedReader br) throws IOException {
    while(true) {
        int c = br.read();
        if(c == -1 || c == '\n')
            return;
        if(c == '\r') {
            br.mark(1);
            c = br.read();
            if(c != '\n')
                br.reset();
            return;
        }
    }
}

Seems that it works nicely for all the EOLs supported by readLine ('\n', '\r', '\r\n').
As an alternative you may extend the BufferedReader class adding this method as instance method inside it.


text:
Q: Memory allocated by an IO function is not getting freed even after the value has been computed Suppose we have to execute a number of complicated IO actions that each occupy a lot of space but return a rather simple value, such as Int or String. In real world that may be, for example, https get requests. I will refer to an action of such kind as hardIO here.
page <- hardIO

Naturally, as the program has progressed past this line, we would like to have all the memory hardIO had allocated freed, except for the small bit we keep the actual value in. There is no reason to keep large amounts of data that was only required to execute the action and compute the result.
I noticed that it's not in fact the case. Actually, page keeps occupying a lot of space until after the last reference to it. For example, if I want to print the result of execution of hardIO in the end of the program, no memory will be freed until then. No memory freed at all! In fact, it may even occupy twice as much memory after it was executed than the maximum of what it was occupying in the process of execution.
page <- hardIO
-- A lot of memory not getting freed!
print page

As we start to fetch linearly many pages, the space will get wasted linearly excessively. I believe the algorithm should run in constant time, except the linearly growing, but still relatively small list of results.

I'm trying to write a program that repeatedly gets certain https API endpoints and around about the hundredth request it finishes eating the RAM, starts swapping and I have to kill the process. (Aside: I guess the copying garbage collector doesn't go well with swapping.) This is very frustrating. You may review the actual code here (the commit fe0ebcb should more or less work).
In attempts to solve the issue I have put together a simplistic program that showcases the essence of the problem. If we find a solution for the simplistic case, the general solution will surely follow at once. You may review the simplistic program here. (I included the script that I use to build it and obtain the profiling results.) The memory profiling graph for hardIO cost centre shows us that at the time between the of binding and the release of its return value, a lot of space is being occupied by unlabeled gray stuff. I guess that's what we need to get rid of.


text:
Q: You do not have the permissionss necessary to view the contentss of "eclipse" I accidently entered below commands:
sudo chown -R root:root /home/shuvro/android-sdk-linux
sudo chmod -R +r /home/shuvro/android-sdk-linux

Arter running the commands, now I am unable to open eclipse.  Now what can I do?
Here android-sdk-linux is the folder where I put eclipse adt.

A: You changed the ownership of the folder. Now it can be opened only by root, i.e. using sudo command. You need to change the permission to the user again. Just type:
chown -R <your user name> <path to the folder>

Also read some guides how to use chown and chmod commands. Here are two examples: chown chmod
If you are a begginer in android programming, I'd recommend to start with Android Studio instead of Eclipse ADT, as Eclipse is out of further development.


text:
Q: Easy export and table formatting of R dataframe to Word? Is there an easy way to automatize the conversion of a R dataframe to a pretty Word table in APA format for publishing manuscripts? I'm currently doing this by saving the table in a csv, opening that in excel, copying the excel table to Word, and formatting it there, but I'm hoping there would be a way to automatize the formatting in R, so that when I convert it to Word, it would already be in APA format, because Word sucks in automatization.
Basically, I want to continue writing the manuscript itself in Word, while doing my analyses in R. Then gather all the results in R to a table (with manually modifiable formatting) by a script and convert it to whatever format I could then simply copy-paste to Word (so that the formatting actually holds). When I need to modify the table, I would make the changes in R and then just run the script again without the need to do any changes in Word.
I don't want to learn LaTeX, because everyone in my field uses Word with features like track changes, and I use Zotero add-in for citations, so it's simpler to just keep the writing separate from the analyses. Also, I am a psychologist, not a coder, so learning a lot of new technologies just for this is probably not worth the effort for me. Typically with new technologies come new technical problems, and I am aiming to make my workflow quicker, but not at the cost of unpredictability (which may make it slower exactly at the moment when I cannot afford it).
I found a R+knitr+rmarkdown+pander+pandoc solution "with as little overhead as possible", but it seems to be quite heavy still because I don't know any of those technologies apart from R. And I'm not eager to start learning all that, as it seems to be aimed for doing the writing and all in R to the very end, while I want to separate my writing and my code - I never need code in my writing, only the result tables. In addition, based on the examples, it seems to fetch the values directly from R code (e.g., from summary() to create a descriptive table), while I need to be able to tinker with my table manually before converting it, for instance, writing the title and notes (like a specific note to one cell and explaining it in the bottom). I also found R2wd, but it seems to be an older attempt for the same "whole workflow in R" problem as the solution above. SWord does not seem to be working anymore.
Any suggestions?

A: (Just to let you know, I am the author of the packages I recommend you...)
You can use package ReporteRs to output your table to Word. See here a tutorial (not mine):
http://www.sthda.com/english/wiki/create-and-format-word-documents-using-r-software-and-reporters-package
Objects FlexTable let you format and arrange tables easily with some standard R code. For example, to set the 2nd column in bold, the code looks like:
myFlexTable[, 2] = textBold()

There are (old) examples here:
http://davidgohel.github.io/ReporteRs/flextable_examples.html
These objects can be added to a Word report using the function addFlexTable. The word report can be generated with function writeDoc.
If you are working in RStudio, you can print the object and it will be rendered in the html viewer so you can export it in Word when you are satisfied with its content.
You can even add real Word footnotes (see the link below)
http://davidgohel.github.io/ReporteRs/pot_objects.html#pot_footnotes
If you need more tabular output, I recommend you also the rtable package that handles xtable objects (and other things I have to develop to satisfy my colleagues or customers) - a quick demo can be seen here:
http://davidgohel.github.io/tabular/
Hope it helps...

A: I have had the same need, and I have ended up using the package htmlTable, which is quite 'cost-efficient'. This creates a HTML table (in RStudio it is created in the "Viewer" windows in the bottom right which I just mark using the mouse copy-paste to Word. (Start marking form the bottom of the table and drag the mouse upwards, that way you are sure to include the start of the HTML code.) Word handles these tables quite nicely. The syntax of is quite simple involving just the function htmlTable(), but is still able to make somewhat more complex tables, such as grouped rows and primary and secondary column headers (i.e. column headers spanning more than one column). Check out the examples in the vignette.
One note of caution: htmlTable will not work will factor variables, i.e., they will come out as integer numbers (according to factor levels). So read the data using stringsAsFactors = FALSE or convert them using as.character().
Including trailing zeroes can be done using the txtRound function. Example:
mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)

It is not completely straightforward to assign formatting soch as bold or italics, but it can be done by wrapping the table contents in HTML code. If you for instance want to make an entire column bold, it can be done like this (please note the use of single and double quotation marks inside paste0):
library(plyr)
mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)
txt$x <- aaply(txt$x, 1, function(x)
               paste0("", x, "</span")
              )
htmlTable(txt)

Of course, that would be easier to to in Word. However, it is more interesting to add formatting to numbers according to some criteria. For instance, if we want to emphasize all values of x that are less than 0.2 by applying bold font, we can modify the code above as follows:
library(plyr)
mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)
txt$x <- aaply(txt$x, 1, function(x)
               if (as.numeric(x)<0.2) {
                  paste0("", x, "")
               } else {
                  paste0("", x, "")
               })
htmlTable(txt)

If you want even fancier emphasis, you can for instance replace the bold font by red background color by using span style='background-color: red' in the code above. All these changes carry over to Word, at least on my computer (Windows 7).

A: The short answer is "not really."  I've never had much luck getting well formatted tables into MS Word.  The best approach I can offer you requires using Rmarkdown to render your tables into an HTML file.  You can copy and paste you results from the HTML file to MS Word, but I make no guarantees about how well the formatting will follow.
To format your tables, you can try something like the xtable package, or the pixiedust package.  But again, no guarantees that the formatting will transfer.


text:
Q: Get TextView line count in RecyclerView adapter? I'm trying to count the number of lines of a TextView in a RecyclerView adapter.
Following answers from other questions (although not related to RecyclerViews), I tried adding this to my onBindViewHolder method:
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    Message message = messages.get(position);

    holder.textView.setText(message.getMessage());

    holder.textView.setVisibility(View.VISIBLE);

    // Get the number of lines
    holder.textView.post(new Runnable() {
        @Override
        public void run() {
            int lineCount = holder.textView.getLineCount();

            Log.d("COUNT", String.valueOf(lineCount));
        }
    });
}

But when I open my app, the first RecyclerView item will initially show COUNT 0 (even though it has 5 lines). But when I scroll down a few items and then scroll back up to the first item, it will show the correct number of lines (COUNT 5).
So what am I doing wrong?

A: textView is reference to converted view in layout manager. When run() is executed, holder.textView maybe used in another item.
UPDATED
If you fast scroll, some views maybe won't be prepared. You can check that text in current view equals message.
Message message = messages.get(position);

holder.textView.setText(message.getMessage());

holder.textView.setVisibility(View.VISIBLE);

// Get the number of lines
holder.textView.post(new Runnable() {
    @Override
    public void run() {
        if (holder.textView.getText().toString().equals(message.getMessage()) {
            int lineCount = holder.textView.getLineCount();
            Log.d("COUNT", String.valueOf(lineCount));
        }
    }
});


text:
Q: Why can't the flux be an integral for electric field passing over an area? I need to know why we can't use the $ \int\vec{E}.d\vec{S}$ as the electrical flux. But we try to define electrical flux density vector $ \vec{D}=\epsilon_{0}\vec{E}$ and then try to use $ \int\vec{D}.d\vec{S}$.
In Sadiku  Elements of electromagnetic he has just mentioned

The flux due to the electric field E can be calculated by using the general definition of flux
in $ \int\vec{E}.d\vec{S}$. For practical reasons, however, this quantity is not usually considered to be the most useful flux in electrostatics.

A: There is nothing wrong with defining the flux of the field with $\int \mathbf{E}\cdot d\mathbf{S}$. For any general field $\mathbf{F}$, flux $\Phi$ is defined as :
$$\Phi=\int\mathbf{F}\cdot d\mathbf{S}$$
Now if we replace $\mathbf{E}$ to $\mathbf{D}$, it will become flux for a different field.
The $\mathbf{D}$ is what is known as the electric displacement. Defined as
$$\mathbf{D}\equiv \epsilon_0 \mathbf{E}+\mathbf{P}$$
Gauss's law reads
$$\nabla\cdot \mathbf{D}=\rho_f$$
This is a particularly
a useful way to express Gauss's law, in the context of dielectrics, because
it makes reference only to free charges, and the free charge is the stuff we control.
The bound charge comes along for the ride. when we put the free charge in place,
a certain polarization automatically ensues and
this polarization produces the bound charge. In a typical problem, therefore, we
know $ρ_f$ , but we do not (initially) know $ρ_b$; Eq. lets us go right to work with
the information at hand. In particular, whenever the requisite symmetry is present,
we can immediately calculate $\mathbf{D}$ by the standard Gauss's law methods.


text:
Q: Button in Cell of JTable: Keep Caption constant while storing data in the cell I am working on a JTable that has one column that contains a List<List<String>>. This column should show a button to the user. When he clicks on the Button, something is to be done with the data of the cell.
All that works really fine with the following code:
    JFrame testFrame = new JFrame("TEST");
    testFrame.setLayout(new BorderLayout() );
    testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    List<List<String>> list = new ArrayList<List<String>>();
    list.add(new ArrayList<String>());
    list.get(0).add("Hello World");

    OptConstraintTableModel dm = new OptConstraintTableModel(
        new String[] {"Data with a button"}, new Class<?>[] {List.class}, new Object[][] { {list} }
            );
    JTable table = new JTable(dm);
    Action action_show = new AbstractAction()
    {
        private static final long serialVersionUID = 1L;
        public void actionPerformed(ActionEvent e)
        {
            JTable table = (JTable)e.getSource();
            int modelRow = Integer.valueOf( e.getActionCommand() );
            System.out.println(((List<List<String>>) table.getValueAt(modelRow,0)).get(0).get(0));
        }
    };
    ButtonColumn button_show = new ButtonColumn(table, action_show, 0);
    testFrame.add(table);

    testFrame.pack();
    testFrame.setVisible(true);

Where ButtonColumn is taken from here and where the TableModel is implemented as follows:
public class OptConstraintTableModel extends AbstractTableModel {

/**
 * Default Serial Version UID
 */
private static final long serialVersionUID = 1L;

private String[] columnNames;
private List<Object[]> data;
private Class<?>[] values;

/**
 * @param objects2
 * @param objects
 *
 */
public OptConstraintTableModel(String[] columnNames, Class<?>[] values, Object[][] data) {
    this.columnNames = columnNames;
    this.values = values;
    this.data = new ArrayList<Object[]>();
    for(Object[] row : data) {
        this.data.add(row);
    }
}

/**
 * Adds the given Object array as last row into the TableModel
 * @param objects   the row to be added
 */
public void addRow(Object[] objects) {
    this.data.add(objects);
    this.fireTableRowsInserted(data.size()-1, data.size()-1);
}

/* (non-Javadoc)
 * @see javax.swing.table.TableModel#getColumnCount()
 */
@Override
public int getColumnCount() {
    return columnNames.length;
}

/* (non-Javadoc)
 * @see javax.swing.table.TableModel#getRowCount()
 */
@Override
public int getRowCount() {
    return data.size();
}

/* (non-Javadoc)
 * @see javax.swing.table.TableModel#getValueAt(int, int)
 */
@Override
public Object getValueAt(int row, int col) {
    return data.get(row)[col];
}

/*
 * (non-Javadoc)
 * @see javax.swing.table.AbstractTableModel#setValueAt(java.lang.Object, int, int)
 */
public void setValueAt(Object aValue, int row, int column) {
    data.get(row)[column] = aValue;
}

/*
 * (non-Javadoc)
 * @see javax.swing.table.AbstractTableModel#getColumnClass(int)
 */
public Class<? extends Object> getColumnClass(int c) {
    return values[c];
}

/*
 * (non-Javadoc)
 * @see javax.swing.table.AbstractTableModel#getColumnName(int)
 */
public String getColumnName(int col) {
    return columnNames[col];
}

/*
 * (non-Javadoc)
 * @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
 */
public boolean isCellEditable(int row, int col) {
    if (col == 1) return (Boolean) this.getValueAt(row, 0);
    if (col == 3) return (Boolean) this.getValueAt(row, 2);
    return true;
}

/**
 * Removes the indicated row from the table model
 * @param i     the index of the row to be delete
 */
public void removeRow(int i) {
    this.data.remove(i);
    this.fireTableRowsDeleted(i, i);
}
}

Question is: How to I change the Caption of the Button? Right now, the current data of the cell is also displayed as caption of the Button, which is not very user-friendly. I would like all buttons to bear the caption "Edit", how can I realize this?

A: In ButtonColumn class rewrite method getTableCellRendererComponent() and set what you want to button caption.
Instead of
renderButton.setText( value.toString() )

write
renderButton.setText("Edit");

A: That is done in the ButtonColumn class
renderButton.setText( value.toString() );
renderButton.setIcon( null );

If you just set "Edit" as text instead of value.toString() all buttons will show 'Edit'
This has to be done in the method getTableCellRendererComponent. The same has to be done for the editButton in the method getTableCellEditorComponent, otherwise the value is still shown on the button, while the user performs a click on it.


text:
Q: Reason for subjunctive in "If God be for us, who can be against us?" Romans 8:31 (KJV): "If God be for us, who can be against us?"
This sounds natural but old-fashioned to my ear as an English speaker, but I can't explain intellectually the reason for the subjunctive mood. If you asked me to articulate a list of common reasons for the use of the subjunctive, then the only things I could come up with would be: (1) commands and (2) counterfactuals. This isn't either of those.
So why is the subjunctive used here?

A: This attempt at a self-answer may be completely wrong. I originally wrote it as an edit to the question, but it seems more sensible to post it as a self-answer and see what people think.
Stuart F suggests in comments that the subjunctive may be used here to describe a condition that is "probable." If that applies here, then I feel that a satisfying answer should explain when we would not use the subjunctive for a condition. Actually the quote from Romans doesn't suggest to me at all that the hypothesis is only probable -- the speaker is certain of the hypothesis. I don't know, maybe it suggests hypothetical uncertainty on an impersonal basis, or implicitly attributes that uncertainty to someone else.
For example, I could write this: "Given President Smith's conduct, impeachment follows as the night follows the day. If two plus two be four, then she deserves impeachment." This seems correct to my ear, and yet there is no uncertainty about whether 2+2=4, only a rhetorical strategy of supposing that some unnamed person might have all sorts of absurd doubts.
How about this? "My dog barks at the mailman. If she bark at him today, I will give her a time-out in the laundry room." This sounds off to me. I'm not sure if it's because the apodosis is personal rather than impersonal. Maybe the subjunctive sounds wrong here because doubt about the condition isn't necessary to the sense of the sentence -- there is no hypothetical person saying, "Aw, maybe she won't bark."
This sounds much more natural to me: "My dog barks at the mailman. If she bark at him today, then may she suffer a time-out in the laundry room." I'm not sure if it sounds right because the archaic tone is more uniform. I think the reason it sounds right may rather be that the apodosis is impersonal.
Maybe the formula here is that (1) the subjunctive introduces hypothetical doubt about the condition (but not necessarily doubt by the speaker); (2) the doubt is necessary to the sense; but (3) such a construction simultaneously requires the depersonalization the apodosis.


text:
Q: Regex to find comments starting with either ; or # characters I have ini files that have comments in the  but in one ini file the comments start with
; Enable the PHP scripting language engine under Apache.
engine = On
; Enable compatibility mode with Zend Engine 1 (PHP 4.x)
zend.ze1_compatibility_mode = Off
; Allow the <? tag.  Otherwise, only <?php and <script> tags are recognized.

and the other with
# The default storage engine that will be used when create new tables when
default-storage-engine=INNODB

# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
max_connections=255

currently find the beginning of the first using regex involves using
^(;).*$\n

I tried to modify this using
^[;#].*$\n

to find either of the two comments but it did not work what would be the correct regex to find comments of either type?
All of your suggestion where very helpful. The additional thing that I need to do was close the application and then reopen it to see the change take effect.

A: ^(;|#).*$\n

Seems to work fine here

A: That should work, however you can try the alteration syntax:
^(;|#).*$

A: In some regex flavors, # denotes an inline comment (meaning that it comments out part of the regex). If ^(;).*$\n works but ^[;#].*$\n doesn't, I would try escaping the # with a backslash.
I'd consider ignoring leading whitespace as well:
/^\s*[;\#].*?$/m

Note the /m to activate multiline mode. This (combined with the lazy .*?) is what you want to use in order to apply the pattern to each line. I also don't think you want \n at the end, as in your pattern; putting \n after $ makes no sense except in multiline mode, where it will essentially do nothing except prevent a match on the final line.
It might help to let us know which regex flavor you're using, and what exactly happened when you tried your version.


text:
Q: jquery.load function can not load csrf token fron django template, csrf token is missing index.html template from where i am loading a form from forms.html template:
{% extends 'base.html' %}

{% load static %}

{% block title %} jQuery Load Function {% endblock %}

{% block extrahead %}

{% endblock %}

{% block content%}

Register

Sign In

{% endblock %}

forms.html from where form is loading which contains csrf token:
{% extends 'base.html' %}
{% block content %}

<form action="/learn/register/" method="post">
    {% csrf_token %}

        name
        <input type="text" placeholder="name" name="name">

        Username
        <input type="text" placeholder="username" name="username">

        Password
        <input type="password" name="password">

        Varify Password
        <input type="password" name="varify_password">

        <input type="submit" name="register" value="register">

</form>

<form action="/learn/sign_in/" method="post">
    {% csrf_token %}

        Username
        <input type="text" placeholder="username" name="username">

        Password
        <input type="password" name="password">

        <input type="submit" name="signin" value="sign in">

</form>

{% endblock %}

views.py:
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.template import RequestContext

from learn.models import Registration
from learn.forms import RegistrationForm
from django.contrib.auth.models import User

def index(request):
   return render_to_response('index.html')

def get_latest_news(request):
    return render_to_response('forms.html')

def register(request):
    if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        user = User(username=form.cleaned_data['username'],password=form.cleaned_data['password'])
        user.save()
        registered_user = Registration(user=user, name=form.cleaned_data['name'])
        registered_user.save()
        return HttpResonse('form is successfully submitted')
    else:
        return render_to_response('forms.html',{'form':form},context_instance=RequestContext(request))
else:
    form = RegistrationForm()
    return render_to_response('forms.html',{'form':form},context_instance=RequestContext(request))

I am calling jquery.load function on index page's div#register_signup on click event.
    If register form is called directly from url using register view then it shows with no problem and csrf_token is also available there, but when loading this form via jquery load function csrf token is missing.
Please suggest me where i am doing wrong. I want to load registration and signin form inside index.html.

A: read ajax section in django docs


text:
Q: how to add total sum for the row in sharepoint I see option to calculate total of the columns but not row.. I don't have access to sharepoint designer well.. is there anyway to do it through front-end..
Ex:
50 50 = 100 (I know this is possible)
50
34
34
------
168 (not able to do this)

A: Assuming you have Field1, Field2, Field3 - all numeric.
To have a Field4 that sums a row, use calculated column with =SUM(...) function.
To have a pseudo-row that sums a column, modify the view to enable totals.
This will not work with calculated columns.

A: Update view and use the total option to sum the values in a column.

A: In order to make a workflow I would recommend downloading sharepoint designer. Then load up the site you are trying to change and create a list workflow for the list you are trying to manipulate. Use workflow variables in a looping structure to loop through the columns in the row and sum the totals.


text:
Q: What really is codomain? Pretty simple:
Is the codomain of a matrix simply the number of rows, or is it the rank? (The linearly independent rows?)
Maybe I can ask about some examples. Here are the questions and my answers.

A: I'm assuming you are referring to the codomain when we interpret the matrix as a function, as I am not aware of any other connection between codomains and matrices.
If so, then the dimension of the codomain is given by the rank of the matrix, and the codomain itself is the span of the linearly independent rows or columns.
Remember that a matrix is just a representation. In this case we use a matrix $M$ to represent a linear function:
$$ M:\mathbb R^n\rightarrow \mathbb R^m.$$
So $M$ sends $a\in \mathbb R^n$ to $M(a)=b\in
\mathbb R^m$. Practically (and with finite dimensions), this comes down to matrix multiplication: $Ma=b$ or $a^TM=b^T$, depending on whether you represent $\mathbb R^n$ and $\mathbb R^m$ with rows or columns.
Now, the codomain is the collection of vectors that are the image under $M$ of some $a\in \mathbb R^n$, that is, it is the collection
$$\{b\in\mathbb R^m\mid b=M(a) \text{ for some }a\in\mathbb R^n\}.$$
It can be shown that this collection in fact is a subspace of $\mathbb R^m$, and that it is spanned by the column- or rowvectors, depending on your choice of representation.


text:
Q: Change the default behavior of my own classes to output value I am creating a mini class in Java:
public class ObjectInfo {
    public Object value = null;
    public Boolean isMax = null;
}

I want to make it so this class will output value whenever I call an instance.
Example:
public final void testSomething() {
    ObjectInfo actual = new OjbectInfo(11f, true);
    assertEquals(11f, (Float) actual);
}

I would like to make the class such that when I call actual like above, it knows to extract out the value parameter.
Is there any way to do this?
What I'd also like to do is say
actual = 1234f
I would like Java to know to shove that value into value and
actual = false
Put that into isMax
I know this can be done in C++ with operator overloading, but I can't seem to find anything on it for Java, at least on Google...

A: No, Java doesn't have user-definable operator overloading.
The best you could do is add an asFloat() method.

A: You cannot do this in Java. Instead you should add setter and getter methods or the properties you want to access. For example #setFloat( float value ) and #getFloat(). Then write test something like this:
assertEquals( 11f, actual.getFloat() );


text:
Q: Cannot Resolve ContextCompat in Android I have an AlertDialogue object called dialog. I am attempting to add an icon to it. I see that this syntax is now deprecated:
dialog.setIcon(getResources().getDrawable(R.drawable.myImage);

I'm reading everywhere that this should work:
dialog.setIcon(ContextCompat.getDrawable(context, R.drawable.myImage));

However, the ContextCompat syntax is not being recognized by Android Studio. Is there something that I should be importing? Thank you.
***Update: Thank's to @Sharj for the correct answer below. I made a quick video too if you guys need a visual: https://www.youtube.com/watch?v=eFiaO0srQro&feature=youtu.be

A: ContextCompat is part of support library v4. Have you added support library 4 to your project?
android.support.v4.content.ContextCompat

You can include support library to your build.gradle file under app folder if you haven't already
dependencies {
// other stuff here
    compile 'com.android.support:support-v4:23.0.0'
// update the 23.0.0 to latest version available

}

A: androidx.core.content.ContextCompat

from AndroidX dependency
implementation 'androidx.appcompat:appcompat:1.1.0'

A: I had the same issue and this and a few more posts helped me.
With Android studio you have multiple Gradle files.
I got my code to work by adding the dependencies section into Gradle (Module : Library) or the file that has "android {" ...
dependencies {
        // other stuff here
        compile 'com.android.support:support-v4:23.+'
        // update the 23.0.0 to latest version available
    }

A: If you are using Android gradle plugin 3.0.1, add google() to your allProjects repositories in the build.gradle file (project level) then sync
like this:
allprojects {
    repositories {
        google()
        ....
        //other repos
    }
}

A: Adding this to build.gradle(Module:App) under dependencies resolved the problem
compile 'com.android.support:support-v4:23.0.0'


text:
Q: Why does multi-columns indexing in SQLite slow down the query's performance, unless indexing all columns? I am trying to optimize the performance of a simple query to a SQLite database by using indexing. As an example, the table has 5M rows, 5 columns; the SELECT statement is to pick up all columns and the WHERE statement checks for only 2 columns. However, unless I have all columns in the multi-column index, the performance of the query is worse than without any index.
Did I index the column incorrectly, or when selecting all columns, am I supposed to include all of them in the index in order to improve performance?
Below each case # is the result I got when creating the SQLite database in hard-disk. However, for some reason using the ':memory:' mode made all the indexing cases faster than without index.
import sqlite3
import datetime
import pandas as pd
import numpy as np
import os
import time

# Simulate the data
size = 5000000
apps = [f'{i:010}' for i in range(size)]
dates = np.random.choice(pd.date_range('2016-01-01', '2019-01-01').to_pydatetime().tolist(), size)
prod_cd = np.random.choice([f'PROD_{i}' for i in range(30)], size)
models = np.random.choice([f'MODEL{i}' for i in range(15)], size)
categories = np.random.choice([f'GROUP{i}' for i in range(10)], size)

# create a db in memory
conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
c = conn.cursor()
# Create table and insert data
c.execute("DROP TABLE IF EXISTS experiment")
c.execute("CREATE TABLE experiment (appId TEXT, dtenter TIMESTAMP, prod_cd TEXT, model TEXT, category TEXT)")
c.executemany("INSERT INTO experiment VALUES (?, ?, ?, ?, ?)", zip(apps, dates, prod_cd, models, categories))

# helper functions
def time_it(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print("time for {} function is {}".format(func.__name__, time.time() - start))
        return result
    return wrapper

@time_it
def read_db(query):
    df = pd.read_sql_query(query, conn)
    return df

@time_it
def run_query(query):
    output = c.execute(query).fetchall()
    print(output)

# The main query
query = "SELECT * FROM experiment WHERE prod_cd IN ('PROD_1', 'PROD_5', 'PROD_10') AND dtenter >= '2018-01-01'"

# CASE #1: WITHOUT ANY INDEX
run_query("EXPLAIN QUERY PLAN " + query)
df = read_db(query)
>>> time for read_db function is 2.4783718585968018

# CASE #2: WITH INDEX FOR COLUMNS IN WHERE STATEMENT
run_query("DROP INDEX IF EXISTs idx")
run_query("CREATE INDEX idx ON experiment(prod_cd, dtenter)")
run_query("EXPLAIN QUERY PLAN " + query)
df = read_db(query)
>>> time for read_db function is 3.221407890319824
# CASE #3: WITH INDEX FOR MORE THEN WHAT IN WHERE STATEMENT, BUT NOT ALL COLUMNS
run_query("DROP INDEX IF EXISTs idx")
run_query("CREATE INDEX idx ON experiment(prod_cd, dtenter, appId, category)")
run_query("EXPLAIN QUERY PLAN " + query)
df = read_db(query)
>>>time for read_db function is 3.176532745361328

# CASE #4: WITH INDEX FOR ALL COLUMNS
run_query("DROP INDEX IF EXISTs idx")
run_query("CREATE INDEX idx ON experiment(prod_cd, dtenter, appId, category, model)")
run_query("EXPLAIN QUERY PLAN " + query)
df = read_db(query)
>>> time for read_db function is 0.8257918357849121

A: The SQLite Query Optimizer Overview says:

When doing an indexed lookup of a row, the usual procedure is to do a binary search on the index to find the index entry, then extract the rowid from the index and use that rowid to do a binary search on the original table. Thus a typical indexed lookup involves two binary searches.

Index entries are not in the same order as the table entries, so if a query returns data from most of the table's pages, all those random-access lookups are slower than just scanning all table rows.
Index lookups are more efficient than a table scan only if your WHERE condition filters out much more rows than are returned.
SQLite assumes that lookups on indexed columns have a high selectivity. You can get better estimates by running ANALYZE after filling the table.
But if all your queries are in a form where an index does not help, it wold be a better idea to not use an index at all.

When you create an index over all columns used in the query, the additional table accesses are no longer necessary:

If, however, all columns that were to be fetched from the table are already available in the index itself, SQLite will use the values contained in the index and will never look up the original table row. This saves one binary search for each row and can make many queries run twice as fast.
When an index contains all of the data needed for a query and when the original table never needs to be consulted, we call that index a "covering index".


text:
Q: EditText error is not getting down when keyboard is disable In my layout I have 3 EditText with validation condition. When soft keyboard is open error message will display below of EditText. When it goes hide EditText will move down error message still placed top of the layout.
I used custom edittext and my layout is in scroll view still error message is not get down with edit text.
I have 3 edit text and on button if we click on button it will validate and if everything is correct it will open new activity.
else if in edit text data is not entered error message display.It is process.
When keyboard is show error message display.Keyboard get hide edittext will back to it place but error message still top of layout.

A: Try giving this in your scroll view in xml file
app:layout_behavior="@string/appbar_scrolling_view_behavior"

A: It seems to be a bug which hasn't been fixed yet. However you can work around this problem by subclassing EditText class (i.e. custom class) and implementing its onKeyPreIme call back method.
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
        // User dismissed the keyboard, so hide and re-show the error message
        revalidateEditText();
        return false;
    }

    return super.dispatchKeyEvent(event);
}

public void revalidateEditText(){
       // Dismiss your original error dialog
       setError(null);

       // Validate the content and re-show the error message if needed
       validate();
}

Derived from: Android: Error popup on EditText doesn't move down when keyboard goes away
Note that by implementing onKeyPreIme, you can be notified whenever user dismisses the soft keyboard.


text:
Q: XSLT Advance a node without using for-each Pretty green on XSLT and one of the systems I'm working on is using it to generate some tables on the front end.  Basically performing a query against a db2 instance the result set is being parsed into xml and the output is similar to...
<ResultSet>
    <Row>
        <node1></node1>
        <node2></node2>
        <etc>
    </Row>
    <Row>
    </Row>
</ResultSet>

I'm wondering how to advance a node without being required to use a for-each loop.  This is from my understanding of variables inside of XSLT (which is limited).
At the end of the page I have to create a table using the variables that I create above.  What is assumed of the result set is that it will return three rows and no more/less. Some of the code from my xslt is as follows...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    <xsl:template match="/">
    ....after some html population...

            Column

                    <xsl:call-template name="formatAsCurrencyNoDecimals">
                        <xsl:with-param name="numberToFormat"
                            select="summarizedLoads/summary/total" />
                    </xsl:call-template>

                .....xsl continues for this row....

Once this is done what needs to be done to advance to the next row?  My though was that I would have to modify the root template match to <xsl:template match="/summarizedLoads/"> and then call that after each row.
Inside of each row I'll need to be creating several variables for use at the end.
Also all rows contain the same amounts of data.  Hopefully this is clear as to what I'm trying to do and if anything else is needed from me please let me know.

A: Suppose you have following XML:
<root>
  <row>1</row>
  <row>2</row>
  <row>3</row>
  <row>4</row>
  <row>5</row>
</root>

To select only 3 rows you can use XPath: //row[position() < 4], e.g. XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates select="//row[position() < 4]"/>
  </xsl:template>

  <xsl:template match="row">
    <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

Output should be:
<row>1</row>
<row>2</row>
<row>3</row>

A: The sweet spot in XSLT is when you use nested templates.  You've got one template already; let's make another one below the one you currently have where match = "Row".  In that template, do all your row-specific stuff.  Then call it from within your main template (match = "/") where you want your final rows to be like so:
<xsl:apply-templates select = "./Row[0]"/>
<xsl:apply-templates select = "./Row[1]"/>
<xsl:apply-templates select = "./Row[2]"/>

If you wanted all the rows instead of just the first 3, you would do this instead:
<xsl:apply-templates select = "./Row"/>

The dot stands for the current element.  Since we're in the main template, that's the root element ResultSet.  /Row means we're applying the first template that matches Row to all the descendant Row elements.


text:
Q: Error when adding project library in eclipse when adding google-play-services_lib in eclipse they fail and show the message: select
at least one project, this is the message:

whats the problem ?
thanx

A: You would need to use the same copy of android-support-v4.jar on the main and library project.
You can find a detailed explanation here as well


text:
Q: Implode an array range in PHP Is there an easy way, preferably a one-liner, to implode an array range.
Example:
array(1,4,6,88,51,3,5,48,59,4);

In addition, how would I be able to implode between the first and the third value only?

A: implode(',', $range);
implode(',', array_slice($range, 0, 3));


text:
Q: Sub Menu is not showing up. I am trying to add the sub menu in my theme. But it's now showing up. I am using WordPress on my website.
I don't know why the CSS is not working.
Please see the code below for details.
Thanks for the help.

header nav {

  position: absolute;
  top: 92px;
  right: 20px;
}

header nav ul {

  margin: 0;
  padding: 0;

}

header nav ul li {

  margin: 0;
  padding: 0;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  list-style: none;
  position: relative;
  float: left;
}

header nav ul li a {

  padding: 2px 12px 5px 12px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  text-decoration: none;
}

header nav ul li a:hover, header nav ul li.current-menu-item a, header nav li.current-page-ancestor a {

  background: #202020;
  color: #ffffff;
}

header ul.sub-menu {

  height: auto;
  width: 210px;
  text-align: left;
  position: absolute;
  left: 0;z-index: 9999;
  display: none;

}

header ul.sub-menu li {

  height: auto;
  width: 210px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  float: none !important;
  position: relative !important;

}

header ul.sub-menu a {

  padding: 2px 12px 5px 12px;
  background: #202020;
  color: #ffffff;
  display: block;
  text-decoration: none;
  position: relative !important;

}

Home

About Us

Asbestos Testing

Asbestos Roofing

Testimonials

Contact

Blog

A: HI now used to this
header nav ul > li:hover ul{display:block;}

--- Demo here

header nav {

  position: absolute;
  top: 92px;
  right: 20px;
}
header nav ul > li:hover ul{display:block;}
header nav ul {

  margin: 0;
  padding: 0;

}

header nav ul li {

  margin: 0;
  padding: 0;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  list-style: none;
  position: relative;
  float: left;
}

header nav ul li a {

  padding: 2px 12px 5px 12px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  text-decoration: none;
}

header nav ul li a:hover, header nav ul li.current-menu-item a, header nav li.current-page-ancestor a {

  background: #202020;
  color: #ffffff;
}

header ul.sub-menu {

  height: auto;
  width: 210px;
  text-align: left;
  position: absolute;
  left: 0;z-index: 9999;
  display: none;

}

header ul.sub-menu li {

  height: auto;
  width: 210px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  float: none !important;
  position: relative !important;

}

header ul.sub-menu a {

  padding: 2px 12px 5px 12px;
  background: #202020;
  color: #ffffff;
  display: block;
  text-decoration: none;
  position: relative !important;

}

Home

About Us

Asbestos Testing

Asbestos Roofing

Testimonials

Contact

Blog

A: you can try this one:
header nav {

  position: absolute;
  top: 92px;
  right: 20px;
}

header nav ul li:hover ul{

  margin: 0;
  padding: 0;
    display:block;

}

header nav ul li {

  margin: 0;
  padding: 0;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  list-style: none;
  position: relative;
  float: left;
}

header nav ul li a {

  padding: 2px 12px 5px 12px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  text-decoration: none;

}

header nav ul li a:hover, header nav ul li.current-menu-item a, header nav li.current-page-ancestor a {

  background: #202020;
  color: #ffffff;

}

header ul.sub-menu {

  height: auto;
  width: 210px;
  text-align: left;
  position: absolute;
  left: 0;z-index: 9999;
  display: none;

}

header ul.sub-menu li {

  height: auto;
  width: 210px;
  font: 400 18px 'PT Sans Narrow';
  color: #6d6d6d;
  display: block;
  float: none !important;
  position: relative !important;

}

header ul.sub-menu a {

  padding: 2px 12px 5px 12px;
  background: #202020;
  color: #ffffff;
  display: block;
  text-decoration: none;
  position: relative !important;

}

DEMO HERE


text:
Q: Get the count of the first column in multiple sheets and display them in separate sheet I'm dealing with Excel VLOOKUP and COUNTIF that gets the count of number of entries in first column of every sheet and display the results in separate sheet accordingly with the product
Example:
I have 4 sheets in excel (4 sheet related to 4 products say oldnavy/purell/BB/Macys)
Each sheet has multiple columns.
Im looking to get just get the count of number of rows in first column for all 4 sheets and place in fift sheet with product name in each row and count of it
Tried using VLOOKUP and COUNTIF

Any help would be greatly appreciated

A: If you're trying to dynamically reference worksheets, you need to use INDIRECT().
If, in Sheet5 you have your worksheet names "oldnavy/purell/BB/Macys" in A1:A4 respectively, then in cell B1 you could put
=COUNTA(INDIRECT("'" & A1 & "'!A:A"))

And drag it down. COUNTA counts all non-blank cells in a range.

A: If I understand correctly, do this:
=COUNTIF(Sheet1!A:A,"<>")

I believe you understand COUNTIF()
Condition "<>" basically means 'not equal to empty/nothing', so 'count all that is not empty'
Hope that helps


text:
Q: jackson deserializer not getting invoked I am getting the following error on Date deserialization in Java:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "22-09-2020T05:08:05+0000": not a valid representation (error: Failed to parse Date value '22-09-2020T05:08:05+0000': Cannot parse date "22-09-2020T05:08:05+0000": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

My input date is in this format 22-09-2020T05:08:05+0000
I am using
 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'HH:mm:ssZ")
    OffsetDateTime lastAnalysisDate;

How to resolve this error ? Inspite of using custom JsonFormat, the error message says it is not of the standard data types.
I am using the date formatter validation tool online
https://javadevtools.com/simpledateformat
And the format I specified is valid as per this evaluation tool

A: The issue is very likely consisting not in the date format but in the configuration of the ObjectMapper where you have to register JavaTimeModule to process classes from java.time package:
Example:
public class TestOffsetDate {
    @Getter
    @Setter
    static class D {
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'HH:mm:ssZ")
        private OffsetDateTime lastAnalysisDate;
    }

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule()); // <--- this is required

        String json = "{\"lastAnalysisDate\":\"22-09-2020T05:08:05+0000\"}";
        D d = mapper.readValue(json, D.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(d));
    }
}

Parsing of the sample JSON succeeds, the following output is printed:
{
  "lastAnalysisDate" : "22-09-2020T05:08:05+0000"
}


text:
Q: Inner Join, only return 1 row for each product Hopefully this is something simple but what i am trying to do is only pull back 1 row for each product in the CartContents table. The problem i have is some products have multiple images so and these are being returned if there is more than 1 image linked to a product.
This is what i created however it still pulls back multiple rows for each product.
SELECT DISTINCT (pri.FileName), p.Title, tc.Quantity, tc.FK_ProductID
    FROM [Ordering].[CartContents] tc
    INNER JOIN [Ordering].[Products] p ON p.ProductID = tc.FK_ProductID
    INNER JOIN [Ordering].[ProductImages] pri on pri.FK_ProductID = p.ProductID
    WHERE FK_UserID = @FK_UserID

Thanks

A: "in" would get rid of the problem, assuming you didn't have the filename:
SELECT p.Title, tc.Quantity, tc.FK_ProductID
FROM [Ordering].[CartContents] tc  INNER JOIN
     [Ordering].[Products] p
     ON p.ProductID = tc.FK_ProductID
where p.ProductID in (select pri.FK_ProductID
                      from [Ordering].[ProductImages] pri
                     ) and
      FK_UserID = @FK_UserID

With the filename, you have to choose one arbitarily:
SELECT min(pri.FileName) as FileName, Title, tc.Quantity, tc.FK_ProductID
FROM [Ordering].[CartContents] tc  INNER JOIN
     [Ordering].[Products] p
     ON p.ProductID = tc.FK_ProductID INNER JOIN
     [Ordering].[ProductImages] pri on pri.FK_ProductID = p.ProductID
where FK_UserID = @FK_UserID
group by Title, tc.Quantity, tc.FK_ProductID


text:
Q: setting the values of AWS_ACCESS_KEY_ID and AWS_SECRET_KEY using SQSConnectionFactory I am using aws sqs in my current project. I need to know how to set access key and secret key (to be read from a properties file) using SQSConnectionFactory.
Please find my code below:
public void createConnectionFactory() throws JMSException{
    try {
        SQSConnectionFactory connectionFactory = SQSConnectionFactory.builder()
            .withRegion(Region.getRegion(Regions.US_EAST_1))
            .withAWSCredentialsProvider(new EnvironmentVariableCredentialsProvider())
            .build();

            // Create the connection.
            SQSConnection connection = connectionFactory.createConnection();
    }
    catch (JMSException ex)
    {
        throw ex;
    }
}

I tried searching methods through which I can set, but couldn't find any. How to proceed from here? Should I write another method for Basic Authentication and invoke it here or is there any better way to do this?

A: It's best to use the default credentials provider chain which allows to supply credentials in multiple ways
In summary it allows for a very flexible configuration for both your development teams and when deploy to the cloud with multiple environments and multi-region setup.
You can include the bean like this:
 <bean id="awsCredentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain">
 </bean>
 <bean id="awsConnectionFactoryBuilder" class="com.amazon.sqs.javamessaging.SQSConnectionFactory$Builder">
     <property name="regionName" value="${aws.region}"/>
     <property name="numberOfMessagesToPrefetch" value="5"/>
     <property name="awsCredentialsProvider" ref="awsCredentialsProviderBean"/>
 </bean>

or use java
@Bean
public AWSCredentialsProviderChain awsCredentials() {
    return new DefaultAWSCredentialsProviderChain();
}

A: Thanks , I found the mistake !
Here are the changes that I made and now its working fine
private BasicAWSCredentials credentials;

public void createConnectionFactory() throws JMSException,FileNotFoundException{
try {

        Properties properties = new Properties();
        properties.load(new FileInputStream("/src/main/resources/AwsCredentials.properties"));
        this.credentials = new   BasicAWSCredentials(properties.getProperty("accessKey"),
                properties.getProperty("secretKey"));

        SQSConnectionFactory connectionFactory =
                SQSConnectionFactory.builder()
                        .withRegion(Region.getRegion(Regions.US_EAST_1))
                        .withAWSCredentialsProvider(new EnvironmentVariableCredentialsProvider())
                        .build();

        // Create the connection.
        SQSConnection connection = connectionFactory.createConnection(credentials.getAWSAccessKeyId(),credentials.getAWSSecretKey());

    }
    catch (JMSException ex)
    {
        throw ex;
    }
    catch (FileNotFoundException ex)
    {
        throw ex;
    } catch (IOException e) {
        e.printStackTrace();
    }


text:
Q: x86_64 stack alignment - purpose of excessive bytes Recently I was learning about the topic of memory alignment and related issues and it led me to a following program:
#include <cstdio>
#include <cstdint>

struct XX
{
    uint8_t a;
    uint32_t b;
    uint16_t d;
    uint64_t c;
};

int main()
{
     printf("\n\ntype size: %zu\n", sizeof(XX));

     XX one;
     XX two;
     XX three;
     printf("addresses of one-three:\n\t%p\n\t%p\n\t%p\n", reinterpret_cast<void *>(&one), reinterpret_cast<void *>(&two), reinterpret_cast<void *>(&three));
     printf("\ndifference of addresses between one and two: %lu\n", reinterpret_cast<unsigned long>(&one) - reinterpret_cast<unsigned long>(&two));
     printf("difference of addresses between two and three: %lu\n", reinterpret_cast<unsigned long>(&two) - reinterpret_cast<unsigned long>(&three));
     printf("alignment of type alone: %zu\n", alignof(XX));

     XX arr[2];
     printf("\ndifference of addresses in array: %lu\n", reinterpret_cast<unsigned long>(&arr[1]) - reinterpret_cast<unsigned long>(&arr[0]));
     printf("alignment of array type: %zu\n", alignof(XX[]));
}

I compiled this with GCC 8.1.0 as:

g++ -std=c++17 -O0 main.cpp

The ouput says that:

*

*alignment is 8-byte,

*size is 24 bytes,

*XX instances differ by 24 bytes inside the array (contiguous memory - no surprise), but by 32 bytes as free-standing variables.

Why are there excessive 8 bytes between the free-standing variables?


text:
Q: WPF MVVM Data Binding - One Way? I am new to WPF but have an small understanding of MVVM, so far this is what I have implemented.
UpdateTableView - View (Short snippet of larger user control)
<UserContol.DataContext>
    <local:UpdateTableViewModel />
</UserContol.DataContext>

<StackPanel>
    <TextBox Text="{Binding InputPath}"/>
    <TextBlock Content="Placeholder" />
</StackPanel>

UpdateTableModel - Model
public class UpdateTableModel : ObservableObject
{
    private string _inputPath;

    public string InputPath
    {
        get
        {
            return _inputPath;
        }
        set
        {
            if (value != _inputPath)
            {
                _inputPath = value;
                OnPropertyChanged("InputPath");
            }
        }
    }
}

ObservableObject
public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanaged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanaged;
        if (handler != null)
        {
            PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }
}

And an empty UpdateTableViewModel
class UpdateTableViewModel : ObservableObject { }

My question is how would I use data binding so that as a user when I enter a inputPath in the text box, firstly whatever I type is store in the property _inputPath so I can use it in code behind and additionally be reflected in the text block.
I have done some research and found about one way and two way data binding and can't really work out what else I need to add for my desired functionality.
Thanks in advance.

A: Your view models must contain the properties you want to bind to.
Generally the TextBox.Text property automatically binds TwoWay. This is the default behavior. So, without specifying the Binding.Mode explicitly, the text entered into the TextBox will be automatically sent to the binding source. In your case the input would be automatically sent to the InputPath property.
UpdateTableModel.cs
public class UpdateTableModel
{
  public void SaveUserNameToFile(string filePath, string userName)
  {
    File.AppendAllText(filePath, userName, Encoding.UTF8);
  }
}

UpdateTableViewModel.cs
An implementation of RelayCommand can be found at
Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern - Relaying Command Logic
class UpdateTableViewModel : ObservableObject
{
  private UpdateTableModel UpdateTableModel { get; }

  public ICommand SaveUserCommand => new RelayCommand(SaveUserName);

  private string _userName;
  public string UserName
  {
    get => _userName;
    set
    {
      if (value != _userName)
      {
        _userName = value;
        OnPropertyChanged(nameof(UserName));
      }
    }
  }

  private string _inputPath;
  public string InputPath
  {
    get => _inputPath;
    set
    {
      if (value != _inputPath)
      {
        _inputPath = value;
        OnPropertyChanged(nameof(InputPath));
      }
    }
  }

  public UpdateTableViewModel()
  {
    this.UpdateTableModel = new UpdateTableModel();
  }

  // Alternative constructor
  public UpdateTableViewModel(UpdateTableModel updateTableModel)
  {
    this.UpdateTableModel = updateTableModel;
  }

  private void SaveUserName(object param)
  {
    // Pass the data to the model
    this.UpdateTableModel.SaveUserNameToFile(this.InputPath, this.UserName);
  }
}

UpdateTableView.xaml
<UserControl>
  <UserContol.DataContext>
    <local:UpdateTableViewModel />
  </UserContol.DataContext>

  <StackPanel>
    <TextBox Text="{Binding UserName}" />
    <TextBox Text="{Binding InputPath}" />
    <Button Command="{Binding SaveUserCommand}"
            Content="Save to File" />
  </StackPanel>
</UserControl>


text:
Q: AudioKit: AKNodeRecorder randomly stops microphone I've got a strange one - I'm using an AKRecorder to record short segments from the AKMicrophone. However randomly every now and again, the microphone goes silent. Sometimes it happens fairly quickly, sometimes it takes a few minutes.
I've stripped back the code to the minimum to replicate this problem. Basically, I'm doing the following:

*

*Passing an AKMicrophone instance into an AKBooster instance.

*Using the AKBooster instance to instantiate both an AKNodeRecorder and an AKMixer.

*Passing the AKMixer into AudioKit output.

*Starting the AKRecorder recording.

*Firing a timer every 2 seconds that resets the AKNodeRecorder and requesting it to start recording again.

Here is the code:
    import UIKit
    import AudioKit
    import AudioKitUI

    class TempViewController: UIViewController {
        var recorder: AKNodeRecorder!
        var micBooster: AKBooster!
        var mainMixer: AKMixer!
        var timer: Timer?

        let mic = AKMicrophone()

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)

            do {
                try AKSettings.setSession(category: .playAndRecord, with: .allowBluetoothA2DP)
            } catch {
                AKLog("Could not set session category.")
            }

            AKSettings.defaultToSpeaker = true
            micBooster = AKBooster(mic)

            do {
                recorder = try AKNodeRecorder(node: micBooster)
            } catch {
                AKLog("Couldn't create Recorder")
            }

            mainMixer = AKMixer(micBooster)

            AudioKit.output = mainMixer
            do {
                try AudioKit.start()
            } catch {
                AKLog("AudioKit did not start!")
            }
        }

        override func viewDidLoad() {
            super.viewDidLoad()
            self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(repeatRecorder), userInfo: nil, repeats: true)
            do {
                try recorder.record()
            } catch { AKLog("Error on first record")}
        }

        @objc func repeatRecorder() {
            do {
                try self.recorder.reset()
                try self.recorder.record()
            } catch { AKLog("Errored recording.") }
        }
    }

I would much appreciate the help if anyone has any idea either:

*

*how to prevent the microphone from going silent.

*how to detect when the mic has gone silent and wake it up again.

If you would like a github project that illustrates the problem, here it is: https://github.com/craiggrummitt/AudioKitBug
You will need to call 'pod update' to add AudioKit.


text:
Q: Override Angular providers provided in root I import a modal library of ng-bootstrap in a lazy module.
@NgModule({imports: [NgbModalModule]})

This library has a NgbModal service provided in root.
@Injectable({providedIn: 'root'})
class NgbModal {...}

I inject it into a component.
constructor(private modal: NgbModal) {}

I develop a class extension of that one.
export class CustomNgbModal extends NgbModal{...}

How can I override NgbModal type with CustomNgbModal?
Using modules will be
{provide: NgbModal, useClass: CustomNgbModal}

but using providedIn root metadata, no clue.
So, how can I override a module which is provided in root?

A: create some static function forFeature() (like "useCustom")
@NgModule({
  // the default provider
  providers: [NgbModal]
})
export class NgbModalModule {
  static useCustom(): ModuleWithProviders<NgbModalModule> {
    return {
      ngModule: NgbModalModule,
      providers: [
        {provide: NgbModal, useClass: CustomNgbModal}
      ]
    };
  }
}

then when importing this module to another do it this way:
@NgModule({
  // import it using the static function
  imports: [NgbModalModule.useCustom()]
})
export class AnotherModule { }

A: You can just specify provider on some level and it will be available to all components/modules down the hierarchy. root is NOT your main module but "above it" so you can override it as any other provider
Example stackblitz
@Injectable({providedIn:'root'})
export class BaseServiceService {
  constructor() { }
  sayHello(){
    console.log("Hello from the base!!!")
  }
}

@Injectable()
export class ExtendedServiceService extends BaseServiceService {
  constructor() {
    super();
   }
   sayHello(){
     console.log("Hello EXTENSION")
   }
}

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  providers:[
    {provide:BaseServiceService, useClass:ExtendedServiceService}
  ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

export class AppComponent  implements OnInit{
  constructor(private s:BaseServiceService){}
ngOnInit(): void {
  this.s.sayHello();
}
}

Which results in

Hello EXTENSION

which means that you have effectively overriden 3rd party service provided in 'root' for the whole application. The same applies to any of your modules (no matter lazy or not).

A: I beleieve what you are trying to achieve can be done with
//module
providers: [
  CustomNgbModal, // so you can inject your custom service
  {provide: NgbModal, useExisting: CustomNgbModal} // to the library would use this service instead of its own
]


text:
Q: Cant print my last node in linked list Im doing a project that creates a linked list to form two polynomials, then gives the user the option to do math operations with the lists. I've gotten to the point where i'm reading my list in, and using stack to order it properly. Then I wanted to make sure my list was being read in properly and so far so good, EXCEPT my tail end isn't being read in. Or maybe its my syntax on my while loop?
import java.util.*;

public class IntegerNode {

    private int coefficient;
    private int exponent;
    private IntegerNode next;

    public IntegerNode() {
        coefficient = 0;
        exponent = 1;
        next = null;
    }

    public IntegerNode(int c, int e) {
        coefficient = c;
        exponent = e;
        next = null;
    }

    public IntegerNode(int c, int e, IntegerNode n) {
        coefficient = c;
        exponent = e;
        next = n;
    }

    public void setCoefficient(int newCoefficient) {
        coefficient = newCoefficient;
    }

    public void setExponent (int newExponent) {
        exponent = newExponent;
    }

    public int getExponent() {
        return exponent;
    }//end getItem

    public int getCoefficient() {
        return coefficient;
    }//end getItem

    public void SetNext (IntegerNode nextNode) {
        next = nextNode;
    }//end setNext

    public IntegerNode getNext () {
        return next;
    }//end getNext

}//end class IntegerNode

class Driver {

public static void main(String[] args) {

    //First polynomial:
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter coefficient: ");
    int coeff = sc.nextInt();
    System.out.println("Enter exponent: ");
    int exp = sc.nextInt();
    Stack<IntegerNode> p1 = new Stack<IntegerNode>();
    IntegerNode n = new IntegerNode(coeff, exp);
    p1.push(n);
    while (exp != 0){
        System.out.println("Enter coefficient: ");
        coeff = sc.nextInt();
        System.out.println("Enter exponent: ");
        exp = sc.nextInt();
        IntegerNode m = new IntegerNode(coeff, exp);
        p1.push(m);
    }

    IntegerNode tail = p1.pop();
    IntegerNode head = null;
    while(!p1.empty()){
        head = p1.pop();
        head.SetNext(tail);
        System.out.println(head.getCoefficient() + " to " + tail.getCoefficient());
        tail = head;
    }

    IntegerNode cur = tail;
    while(!(cur.getNext()).equals(null)){
        System.out.println(cur.getCoefficient()+" "+cur.getExponent());
        System.out.println("NEXTNODE: " + cur.getNext().getCoefficient());
        cur = cur.getNext();
    }
    //Read in two integers, check each time if exponent is zero
    //create linked list in reverse order of input
    //Use stack to create LIFO list

    //Repeat above, but for second polynomial

    //Prompt user to choose which operation
    //Prompt user to specify what order if subtracted

    //iterate through p1
    //for every element in p1:
    //iterate through p2 and see if that element matches the current element
    //in p1. If so, then add their coefficients
    //Store results as you go
    //Output the results and indicate what operation was done

    // TODO Auto-generated method stub

}

Here is the error:
Exception in thread "main" java.lang.NullPointerException
    at Driver.main(IntegerNode.java:85)

That would be at my last while loop. Any ideas?

A: while(!(cur.getNext()).equals(null))

instead of above try this once:
while(!(cur.getNext())==null)

You can never call the .equals() method on an object reference that is null. It is a method, just like the rest, so if the object reference is truly null it will just throw a NullPointerException.
Try this :
do{

} while(((cur.getNext())!=null))

A: First of all, when you're doing this:
IntegerNode tail = p1.pop();

... you should make sure that there is something to pop.
Second, this:
while(!(cur.getNext()).equals(null))

...is what probably causing your problem.  You're doing a comparison with a null object.  Can't do that.  Use this:
while(cur.getNext() != null)

As far as printing your last value, well, you get your last node and then you're out of them, so you're never going to print what was on the last node.  I'd use do{}while().


text:
Q: How to route cutom URL with to custom controller in CodeIgniter? I have a PHP CodeIgniter Controller with name User and have a method that get details of user user_detail($username)
Now when i need to show user data for example for userName mike
I call this URL
http://www.example.com/user/user_detail/mike
My target
How to make user data accessible by next URLs
http://www.example.com/user/mike
or / and
http://www.example.com/mike

A: You have to read the this page from the official documentation of codeigniter. It covers all related things to Routing URLs easily. All routes must be configured via the file:
application/config/routes.php

It could be something like this :
$route['user/(:any)'] = "user/user_detail/$1";

A: This can be achieved by overriding CI_Controller class BUT dont change the original core files, like I said override the controller and put your logic in it.
Help: https://ellislab.com/codeigniter/user-guide/general/core_classes.html
how to create Codeigniter route that doesn't override the other controller routes?
Perhaps an easier solution would be to route it with the help of apache mod_rewrite in .htaccess
Here is an detailed explanation on how to achieve it: http://www.web-and-development.com/codeigniter-remove-index-php-minimize-url/

A: Hatem's answer (using the route config) is easier and cleaner, but pointing the usage of the _remap() function maybe helpful in some cases:
inside the CI_Controller, the _remap() function will be executed on each call to the controller to decide which method to use. and there you can check if the method exist, or use some defined method. in your case:
application/controllers/User.php
class User extends CI_Controller {
    public function _remap($method, $params = array())
    {
        if (method_exists(__CLASS__, $method)) {
            $this->$method($params);
        } else {
            array_unshift($params, $method);
            $this->user_detail($params);
        }
    }

    public function user_detail($params) {
        $username = $params[0];
        echo 'username: ' . $username;
    }

    public function another_func() {
        echo "another function body!";
    }
}

this will result:

http://www.example.com/user/user_detail/john => 'username: john'
  http://www.example.com/user/mike ........... => 'username: mike'
  http://www.example.com/user/another_func ... => 'another function body!'

but it's not going to work with: http://www.example.com/mike , since the controller -even if it's the default controller- is not called at all, in this case, CI default behaviour is to look for a controller called mike and if it's not found it will throws 404 error.
for more:
Codeigniter userguide 3: Controllers: Remapping Method Calls
Redirect to default method if CodeIgniter method doesn't exists.


text:
Q: Where to put dom manipulation of small scripts in angularJS I'm new to angular and i'm wondering where to put some code. I know that dom manipulation should not happen in a controller but in a directive.
Do i realy have to create a directive for this small bit of javascript code (a click on a button adds a class to the <body> tag?)

A: Yes, create a directive. Multiplying directives in your code base is not a bad thing at all. Look at the angular source code for directives like ngBind, and you'll realise that small doesn't matter at all, it is quite the opposite (directives are meant to be specialised).


text:
Q: Importing bootstrap js file I recently started using bootstrap installed from npm and i  have trouble importing the js file though
this is my main js file and  where i want to use all the tools
import * as bootstrap from '../node_modules/bootstrap/dist/js/bootstrap.min.js';

console.log(bootstrap);
my main .html file (where i put my js file)
<script src="Js/js_main.js" type="module"></script>

When i run my page the tools/plugins dosen't work so... Is there a way  to save this tools/plugins into your own js file like sass? or which is the best way to use them?

A: As I understood this, you are using bootstrap via npm to create html and js page. You are trying to get object of bootstrap js file but that is not the appropriate approach because it does not return anything.
You can use the absolute path of "../node_modules/bootstrap/dist/js/bootstrap.min.js" in your html page so that bootstrap will be available in your html page.
<!doctype html>
<html lang="en">
<head>
    <title>Starter Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
    <link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
    <script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
    <!-- Custom styles for this template -->
    <style>
        body {
            padding-top: 5rem;
        }
        .starter-template {
            padding: 3rem 1.5rem;
            text-align: center;
        }
    </style>
</head>
<body>
 <!--MAIN HTML LAYOUT-->
</body>
</html>

A: Actually now in Bootstrap 5 is possible import the esm version of Bootstrap like that for example (code in the src/index.js file and node_modules folder on the same level of the js folder):
import * as bootstrap from '../node_modules/bootstrap/dist/js/bootstrap.esm.min.js'

const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')

const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

In this way there is a problem with the path of Popper.js dependency.
You can open the bootstrap.esm.min.js and replace the import of Popper with:
import * as Popper from '../../../@popperjs/core/dist/esm/index.js'

The advantage in this way is that I can import only the component I want namely:
import {Popover} from '../node_modules/bootstrap/dist/js/bootstrap.esm.min.js'
but remember that each import is an http request thereby you have to use webpack for example and in that case becomes more simple handle the project (in a different slightly different way from here).


text:
Q: If classes hold an object reference as their value, why doesn't the "new" keyword overwrite them? I'm struggling to understand all of the implications of pass-by-reference vs pass=by=value.
I understand that in C#, unless explicitly stated, you always pass variables by value. However, since non-primitive types hold references as their values, you're technically passing those references around.
So, this is why if I had a class Book with a Name property. I could so something like
Book book1 = new Book("Fight club");
ChangeBookName(book1, "The Wolfman");

void ChangeBookName(Book book, string name){
    book.Name = name;
}

Then doing a Console.WriteLine(book1.name) would output "The Wolfman", because even though there was a pass by value, the value was a reference of the object's location in memory, so changing that also changed the original object.
However, if I do something like
Book book1 = new Book("Fight club");
    ChangeBookName(book1, "The Wolfman");

    void ChangeBookName(Book book, string name){
        book = new Book(name);
    }

Then book1.Name won't actually be "The Wolfman", it'll still be "Fight club".
What is happening here behind the scenes? Is the new keyword creating a new object reference? But then, what is happening to the original value that was passed? Why is the new instance of Book not overwriting the old one?

A: Book book1 = new Book("Fight club");          // <-- book1 holds a ref to 'Fight Club'
ChangeBookName(book1, "The Wolfman");         // <-- a copy of that ref is passed as an argument
// ...                                        // <-- book1 still holds the original ref to 'Fight Club'

void ChangeBookName(Book book, string name){  // <-- receives the copy of the ref to 'Fight Club'
    book = new Book(name);                    // <-- overwrites it with a ref to 'The Wolfman'
}                                             // <-- lifetime of the temp copy ends here
                                              // <-- 'The Wolfman` object becomes eligible for gc

A: It's probably easier to understand if you forget all that "pass by reference" vs "pass by value" - they're poor terms of phrase, as you're finding out because they tend to make you conceive that the Book memory data is either being copied when it is passed to the method, or the original is passed. "Pass by copy of reference" and "pass by original reference" might be better - class instances are always passed by reference
I find it more helpful to think of nearly every variable in a program as being a reference in its own right, and "pass by value/reference" refers to whether a new reference is created or not when calling a method.
So you have your line:
Book book1 = new Book("Fight club");

Immediately after we execute this line, there is one variable name in your program, book1, and it refers to some block of data at memory address 0x1234 that contains "Fight club"
ChangeBookName(book1, "The Wolfman");

We call the ChangeBookName method and c# establishes another reference, called book, because that is what it says in the method signature, also pointing to address 0x1234.
You have two references, one block of data. The book reference will be lost when the method ends- it's lifetime is only between the { } of the method
If you use this additional book reference to change something about the data:
book.Name = "The wolfman";

Then the first reference, book1 will see the change- it points to the same data, the data changes.
If you point this additional book reference to a whole new block of data elsewhere in memory:
 book = new Book("The wolfman");

You now have two references, two blocks of data - book1 points to "fight club" at 0x1234, and book points to "the wolfman" at 0x2345. The wolfman data and the book reference will be lost when the method ends
The crucial point here about having two references to one block of data is that you can change some property of the data and both references see it? But if you point one of the references to a new block of data the original reference remains pointing to the original data
If you want a method to be able to swap out the block of data for a whole new block of data and also have the original reference experience the change, you use the ref keyword. Conceptually this causes C# not to make a copy of the reference at all, but reuse the same reference (albeit with a different name)
void ChangeBookForANewOne(ref Book tochange){
  tochange = new Book("Needful things");
}

Book b = new Book("Fight club");
ChangeBookForANewOne(b);

All through this code there is only one reference to one block of data. Changing the block of data for a new one inside the method causes the change to be remembered when the method exits
We seldom do ref; if you want to change your book for a new one you should really return it from the method and change reference b to be the newly returned book. People use ref when they want to return more than one thing from a method but really that's an indicator that you should be using a different class as the return type

The same notions are true for value types (usually primitive things like int) but the slight difference is that if you pass an int to a method then you end up with two variable names but also two ints in memory; if you increment the int inside the method the original int doesn't change because the additional variable established for the lifetime of the method call is a different data in memory - the data really is copied and you have two variables and two numbers in memory. Ref style behaviour is more useful and more common for things like this, with things like int.TryParse - it returns a true or false indicating whether parsing succeeded but in order to return the parsed value to you it needs to use the original variable you passed in, not a copy of it.
To do this, TryParse uses a variation of ref called out - a marker on a method variable that indicates "this method will definitely assign a value to the variable you pass in; if you were to give it a variable already initialized to a value it would definitely be overwritten". In contrast, ref indicates "you can pass a variable in that is initialized to a value, I might use the value and I might overwrite it/point it to a new data in memory". If you have a method that doesn't need to take a value but definitely overwrites, like my ChangeForANewBook before, you should really use out - in 100% of cases ChnageForANewBook overwrites what was passed in, which could cause unintended data loss for a developer. Marking it as out would mean C# would make sure only blank references are used/passed in, helping prevent unintended data loss

A: So, as you said, reference will passed by value and "new" will return reference to new object, but it will overwrite a local copy of old reference. To avoid it you must pass book with keyword "ref" and then it be like "reference to reference of book".

A: If you want that the orginal book is replaced with a newly created you need the ref or out keyword:
void ChangeBookName(ref Book book, string name)
{
    book = new Book(name);
}

// ...
Book book1 = new Book("Fight club");
ChangeBookName(ref book1, "The Wolfman");

This means that the reference to original book is replaced by the newly created book and the orginal book is marked as obsolete.

Maybe this helps...


text:
Q: Calling on a class with an Ajax request Currently, I am using my own MVC framework. What I'm trying to do is make an Ajax call with jQuery(got that part down), and call on a method from the controller so that I can pass the get variables to it and get the output I want returned from the Ajax call.
I can't refresh the page because it is a page full of forms and I don't want each to be reset on a refresh. I also can't pass it to a "handle.php" where I could have the function I need, because what would be the point of the Model and Controller?
What can I do? Or rather, more importantly, what is the best way to approach such a thing? Can I load the classes I need again (would need about 6 because of the extends I use) and instantiate a new object which calls the appropriate method?
I guess it is my own fault for trying to build my own MVC framework instead of learning something like Zend, but whats done is done. Any help would be appreciated, just need to be pointed in the right direction.

A: From your question it's a bit difficult to find out what kind of data you're trying to get. Do you need to get data to fill the forms? Or do you need to pass data from the forms back to the database using your PHP script?
In both cases, i guess a 'handle.php' script would probably work fine. Just make some kind of bare-bones script that can handle your incoming data, validate it and load up the appropriate classes (maybe using __autoload) to save it in the database.

A: You would more than likely want to make a request to a page much the same way you would call any other controller/method combination.  For example, suppose you are trying to call controller Ajax and method Update... You would hopefully have URL routing so you would simply link to /ajax/update.  This is the ideal solution.
Within such a method you would want to echo your results as opposed to trying to display a template/layout/view combination.  This may mean you need to tweak your CMS to allow for such a thing but hopefully not.
Your method Update should more than likely have access to the globals $_POST and $_GET so that you may retrieve the data submitted from the AJAX request.

A: You should have some way to determine which command you are calling, so the controller can determine where you need to go.
For example, if you pass in a form # and command, your controller may pass this off to the controller for that specific form, who can then determine how to do the operation you need.
I think it is risky to have all this logic in one controller, as it will mean a very long switch statement, at some point.
You may want to explain more about how your controller handles input from the javascript (client), to determine routing, as, currently, it is just guesswork as to how to help you.

A: You're saying;

As of right now I don't have a
  controller handling javascript which
  is my problem

As I understand your controller doesn't need a controller handling an ajax request. You make the ajax request as you would a normal request. So if your controller knows what to do with a normal request its already handling javascript.
Again if I understand correctly for the books example you should do something like that;
$.get("/books/search/plato",  function(data){
    alert("Data Loaded: " + data);
});

And for the /playground and gradient thing this should work; You can invoke this from handle.php and it will request the playground controller and return the data;
$.get("/playground/gradient",  function(data){ //data is what is returned from playground file
    alert("Data Loaded: " + data);
});

Hope this helps


text:
Q: Are request and response part of two different TCP connections? I am very new to networking, so this might sound simple. Though I have tried to look here and here and here and have got few basics of TCP, there are few questions whose answers I am not certain about.

*

*Is a request and response part of 2 different TCP establishments. To explain that :

Is a connection established, kept alive until all packets are delivered, request sent and connection closed for each request and same happens for its response.
or
A connection is opened, request sent, connection kept alive, response arrives and connection closed.

*Is the ACK number always 1 + sequence number of sent segment.

A:

*

*Is a request and response part of 2 different TCP establishments

You need just 3 packets to handshake and establish a bidirectional TCP connection. So no, you do not establish TCP connection for receiving and sending parts.
On the other hand, there is a sutdown() system call which allows to shutdown a part of the bidirectional connection. See man shutdown(2). So there is a possibility to establish a unidirectional connection by opening a bidirectional and then shutdown one of the sides.

*Is the ACK number always 1 + sequence number of sent segment.

We usually do not send ACK for every received packet. There are also selective ACKs, retransmissions etc. So in general, the answer is no, the ACK number is not always seq + 1.
On the other hand, if you are sending a small amount of data and waiting for the confirmation, no errors or packet loss occurred, most probably there will be just one packet with that data and one ACK with seq + 1.
Hope that helps.