text:
Q: MySQL outputting multiple rows if QTY > 1 Is there any way to output multiple table rows if a certain field in the table is greater than 1.
Here's my example:
I'm building an auction website, where we sell tickets for a raffle.
The tickets are stored in a table like so:
id, order_id, product_id, qty, price
When the time comes to print the tickets, I want to dump all of it into a CSV.
So far, I'm doing this query (simplifying, omitting INNER JOIN):
SELECT id, order_id, product_id, qty, price FROM order_details

And then running something like the following loop on it:
foreach($rows as $row) {
   for($i = 0; $i < $row['qty']; $i++) {
      $tickets[] = $row;
   }
}

so that I get a separate entry for each qty (so that people get the correct amount of entries...).
Is there any way to accomplish this in SQL itself, so that each row is multiplied x times, where x is a certain field in the table (qty in this example)?

A: You can accomplish this purely in MySQL using a blackhole table and a trigger
Set up tables
First create the blackhole table you're going to insert to and the memory (or temporary table) the blackhole will reroute to.
CREATE TABLE Blackhole1 LIKE order_details ENGINE = BLACKHOLE;

CREATE TABLE temp_order_results LIKE order_details ENGINE = MEMORY;

Set up trigger
Now create a trigger on the blackhole table that will reroute the insert to the memory table, duplicating the rows with qty > 1.
DELIMITER $$

CREATE TRIGGER ai_Blackhole1_each AFTER INSERT ON blackhole1 FOR EACH ROW
BEGIN
  DECLARE ACount INTEGER;
  SET ACount = new.qty;
  WHILE ACount > 1 DO BEGIN
    INSERT INTO temp_order_results
    VALUES (new.id, new.order_id, new.product_id, 1, new.price)
    SET ACount = ACount - 1;
  END; END WHILE;
END $$

DELIMITER ;

Statements to do the query
Now do a insert .. select into the blackhole
INSERT INTO blackhole1
  SELECT id, order_id, product_id, qty, price FROM order_details;

And a select on temp_order_results.
SELECT id, order_id, product_id, qty, price FROM order_details;

A: To expand on @zdennis' answer, you could do this in MySQL:
    SELECT order_details.*
      FROM order_details
INNER JOIN kilo
           ON kilo.i < order_details.qty;

where the "kilo" relation has the integers 0 - 999, a contrivance adapted from a post by xaprb:
CREATE TABLE deca (i integer not null);
INSERT INTO deca (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
CREATE VIEW kilo (i) AS
      SELECT iii.i * 100 + ii.i * 10 + i.i
        FROM deca iii
  CROSS JOIN deca ii
  CROSS JOIN deca i;

A: There's not really a performance reason to. MySQL has a couple of strong suits: sorting, indexing, searching, storing, etc. You might as well do this in PHP.

A: I think this might be possible in Sql Server or Oracle by using a recursive common table expression (CTE) that joins the original table to itself and includes Qty-1 as an expression in place of Qty in the select list of the CTE.  Sadly, last I heard MySql doesn't support CTEs yet.
Another option is to build a simple sequence table that just includes a numeric column and rows that start with 1 and end with the largest number you'll realistically have in the Qty column of your original table.  You can join this to your orders table with a WHERE clause limiting the digits results to less than the Qty field and duplicate the rows this way.  To quickly build the sequence table, create a digits table with records for 0 through 9 and cross join it to itself once for each power of 10.

A: The appropriate response is likely to use dual connect by level. See this question for related information: How can I return multiple identical rows based on a quantity field in the row itself?
Although this doesn't work in MySQL, see: How do I make a row generator in MySQL?
If you're using MySQL you'll need to be content with doing it in PHP or doing something gross (like the trigger that Johan posted). I'd vote to simply do it in PHP if that was the case.

A: I was required to do the same thing in order to avoid a cursor. My solution is for SQL Server and is really simple because for my case, qty is never greater than 99, so here is a sample using temporary tables:
create table #t (
     id int
    ,qty int
)

insert into #t values (1,2)
insert into #t values (2,3)

create table #n (
     id int
)

insert into #n values (1)
insert into #n values (2)
insert into #n values (3)
insert into #n values (4)
insert into #n values (5)

select t.*
from #t t
inner join #n n on
    n.id <= t.qty

You just need to insert into #n the max qty you expect (in my case 99).


text:
Q: Create centered table that dynamically spreads over required space I want to put an itemization inside a table's cell and came across the tabu/longtabu package. Like tabularx it provides a X column that allows for including an itemization, i.e. something that spreads over multiple lines.
My goal is to create a table with two columns that is centered and is only as width as its content requires it to be (no spanning, spreading, ...!). However, it seems like I always have to specify a width:
\begin{longtabu} to \linewidth [c]{|r|X[-l]|} % \linewidth is not what I want
    some text  & \begin{itemize}[label={},leftmargin=*]
                     \item 11
                     \item 22
                 \end{itemize}
\end{longtabu}

I could replace \linewidth with something like 10cm but that's a static and stupid solution. I basically don't know the required width because I fill the itemization inside the table dynamically during runtime.
Unlike to tabular which only spreads over the actually required width but doens't allow line breaks:
\begin{tabular}{rl} % works like I want it to work
    some text  & \begin{itemize}[label={},leftmargin=*] % fails
                     \item 11
                     \item 22
                 \end{itemize}
\end{tabular}

I'm looking for an easy solution (no hacky solutions with command redefinitions, ...) for an easy problem like itemizations inside tables.

A: Simple solution by using varwidth package:
\begin{table}
    \centering
    \setlength{\tabcolsep}{3pt} % add some value otherwise LaTeX puts no space at all between the columns
    \begin{tabular}{rl}
        \LaTeX~is:  & \begin{varwidth}[t]{\linewidth}\begin{itemize}[nosep,after=\strut,label={},leftmargin=0pt]
                \item Nice and powerful,
                \item but sometimes off target.
        \end{itemize}\end{varwidth}
    \end{tabular}
\end{table}

will result in

Note 1: Replace t with c if you want the left colum's content to be vertically centered.
Note 2: Specifying \linewidth for varwidth is only a workaround since I don't know the actual maximum column width. Make sure your itemization isn't to wide and doesn't consume more space that the column can provide.

A: TikZ workaround:
\documentclass{article}

\usepackage{enumitem}
\usepackage{tikz}

\begin{document}
\noindent
\begin{tabular}{|r|l|} % works like I want it to work
    \hline
    some text  &
    \begin{tikzpicture}[anchor=west, y=.5cm]
        \node[anchor=west] at (0, 0)  {looooooooooooong item};
        \node[anchor=west] at (0,-1)  {short item};
        \node[anchor=west] at (0,-2)  {tiny};
    \end{tikzpicture}
    \\
    \hline
\end{tabular}
\end{document}

Result:

Don't use vertical lines, nor \hline; I used them in order to highlight this 1 by 2 table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to automatically execute deployed war file in Jboss? I am running jsf application on Jboss. Every time I start JBoss, the war file is successfully deployed, but I have to manually open the browser and enter the URL to start the application. The problem is that this app should start automatically when the server is restarted. I have a shell script that starts JBoss, but the app is started only when I open the browser and enter the url.
How can I achieve this?

A: If you have any servlet in your war file then load that servlet on application startup. And start the execution in init method of that servlet.

A: I solved the problem with adding @Singleton and @Startup annotations to my starting managed bean class.


text:
Q: Can a topological space satisfying the first axiom of countability, which is not Hausdorff but every sequence has a unique limit, exist? My textbook (Principles of General Topology, by Pervin) says "A topological space $X$ satisfying the first axiom of countability is a Hausdorff space iff every convergent sequence has a unique limit."
Let $<x_{n}>$ be a sequence converging to $x\in X$. Let there be another point $y\in X$. By the first axiom of countability, for every open set $G$ containing $x$, there is a  $B_{n}(x)\subseteq G$, and for every open set $H$ containing $y$, there is a $B_{n}(y)\subseteq H$. Also, for every open set containing $x$, for a certain N, all $x_{j}$, $j\geq N$ lie in that open set.
Let every open set containing $y$ intersect every open set containing $x$, and let the intersection consist of points other than points of the sequence $<x_{n}>$. Then, this is not a Hausdorff space, but the sequence $<x_{n}>$ still tends to the unique limit $x$ (provided, for every other point in $X$ apart from $y$, we assume there is at least one open set containing that point which does not intersect with an open set containing $x$. Hence the sequence can't have any of those points as its limit)!
Is this not a contradiction then? We have created a space satisfying the first axiom of countability, in which every sequence tends to a unique limit, but the space is not Hausdorff?
One possible contradiction I see is if we can define a sequence in the intersections between the open sets containing $x$ and $y$. All these intersections will intersect amongst themselves if ANY two open sets containing $x$ and $y$ intersect, and hence such a sequence may be possible. It would be great if someone could tell me whether this is the reason why the theorem stands true.
Thanks a lot!

A: It's not true that every sequence in $X$ tends to a unique limit. Suppose that every open nbhd of $x$ intersects every open nbhd of $y$, let $\{B_n(x):n\in\Bbb N\}$ be a countable local base at $x$, and let $\{B_n(y):n\in\Bbb N\}$ be a countable local base at $y$. We may assume that these bases are nested, i.e., that $B_{n+1}(x)\subseteq B_n(x)$ and $B_{n+1}(y)\subseteq B_n(y)$ for each $n\in\Bbb N$.
For each $n\in\Bbb N$ we know that $B_n(x)\cap B_n(y)\ne\varnothing$, so there is a point $z_n\in B_n(x)\cap B_n(y)$; I claim that the sequence $\langle z_n:n\in\Bbb N\rangle$ converges to both $x$ and $y$. Let $U$ be any open nbhd of $x$; then there is an $m\in\Bbb N$ such that $B_m(x)\subseteq U$, and for each $n\ge m$ we then have
$$z_n\in B_n(x)\subseteq B_m(x)\subseteq U\;.$$
This shows that $\langle z_n:n\in\Bbb N\rangle$ converges to $x$. An exactly similar argument shows that it also converges to $y$. Thus, there is at least this one sequence in $X$ that converges to two different limits, and that's all that we had to show.


text:
Q: 'No module' error for my own function despite having same directory I am writing a script file in the Jupyter notebook & I need to call a function. I created another file called myfunctions.py and defined my function called give_ans() there. I will have many more functions here later. But I get an error in the main script file when I use the following command
from myfunctions import give_ans

The error is No module named 'myfunctions'. I use pwd to see their path and it is exactly the same which is 'C:\Users\my name\OneDrive\my_code'. So I don't know what is the cause of this error. Please advise. I have always been a Matlab coder and this is my first attempt here.
Update: I found the problem & fixed it. I gave the solution in my answer below.

A: I found out what was going wrong. Both of my Jupyter files are of the .ipynb extension whereas the myfunctions.ipynb script that I intend to import should be in .py form. To do so, I went to the command window (Anaconda one in my case), went to the same directory as mentioned in the question, and did the following.
pip install ipynb-py-convert
jupyter nbconvert --to python myfunctions.ipynb

This produced a .py file and then there was no error upon using the import statements as I wrote in the question.
Edit: Anyone reading this answer please also make sure to read the comments below.


text:
Q: We define a function $f : \mathbb Z/n\mathbb Z \to\mathbb Z/n\mathbb Z$ by$ f([l])=[7l^2]$. Let $n$ be a natural number and let $k$ be an integer number. Let $[x]$ be the relation class of $x$  (integer number) modulo $n$.
How now to prove this is a function?

A: $\textbf{Hint:}$ You have to prove that the map given by $[l] \mapsto [7l^2]$ is well defined, i.e. that it does not depend on the choice of a representative for $[l]$.

A: To prove this is a function you need it to be well-defined.  That is, there are multiple choices of $l$ for $[l]$; you need to prove that regardless of this choice, the function $f$ will have the same result.  That is, you need to prove that if $[l_1]=[l_2]$, then $[7l_1^2]=[7l_2^2]$.


text:
Q: How to read after a space until the next space in Python I have this program:
import sys
import itertools
from itertools import islice

fileLocation = input("Input the file location of ScoreBoard: ")

input1 = open(fileLocation, "rt")

amountOfLines = 0
for line in open('input1.txt').readlines(  ):
    amountOfLines += 1

timestamps = [line.split(' ', 1)[0][0:] for line in islice(input1, 2, amountOfLines)]
teamids = [line.split(' ', 1)[0][0:] for line in islice(input1, 2, amountOfLines)]

print(teamids)

and this text file:
1
5 6
1 5 1 5 0
1 4 1 4 1
2 1 2 1 1
2 2 3 1 1
3 5 2 1 1
4 4 5 4 1

For teamids, I want it to start reading after the first space and to the next space, starting from the second line which, I have already achieved but don't get how to start reading after the first space to the next. For timestamps i have managed this but only starting from the first character to the first space and don't know how to do this for teamids. Much help would be appreciated

A: Here's one suggestion showcasing a nice use case of zip to transpose your array:
lines = open(fileLocation, 'r').readlines()[2:]
array = [[int(x) for x in line.split()] for line in lines]
transpose = list(zip(*filter(None, array)))

# now we can do this:
timestamps = transpose[0]  # (1, 1, 2, 2, 3, 4)
teamids = transpose[1]     # (5, 4, 1, 2, 5, 4)

This exploits the fact that zip(*some_list) returns the transpose of some_list.
Beware of the fact that the number of columns you get will be equal to the length of the shortest row. Which is one reason why I included the call to filter to remove empty rows caused by empty lines.


text:
Q: React-modal not working properly with bootstrap im trying to use the react-model component but bootstrap is messing it. When i put it outside the div with col class it works fine but separaiting it messes up the layout. Here the component in which i use the modal.
class BeerItem extends Component {
constructor(props){
  super(props);
  this.state = {
    showModal: false,
  };
}

handleOpenModal = () => {
  this.setState({ showModal: true });
}

render(){
  Modal.setAppElement('#root');
  return (

{this.props.beer.name}

{this.props.beer.tagline}

      <Modal
        className="modal"
        isOpen={this.state.showModal}
        onRequestClose={ () => this.setState({ showModal: false }) }
        shouldCloseOnOverlayClick={true}
        ariaHideApp={false}
      >
        {this.props.beer.name}
    </Modal>

  )
}
}

This is an item component which is rendered in a list component. I tried to put the modal in the list component but then i cant figure how to pass the beer id into it. The list is in a infinity scroll component and when i want to update the state in the list by passing a function to item component which takes the id of clicked beer i get an error with maximum depth exceed...

A: *

*You can use <React.Fragment>, so the you doesn't wrap the components with an extra
.

*Many modal render outside the view window when it's closed (For animation purpose). However, you might want to completely remove it from the DOM after close event.

The tested code. Notice, the Modal is rendered conditionally based on this.state.showModal:
const MyModal = props => (
  <Modal
    className="modal"
    isOpen
    onRequestClose={props.onClose}
    shouldCloseOnOverlayClick
    ariaHideApp={false}
  >
    {props.beer.name}
  </Modal>
);

class BeerItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false,
    };
  }

  handleOpenModal = () => {
    this.setState({ showModal: true });
  };

  onModalClose = () => {
    this.setState({ showModal: false });
  };

  render() {
    return (
      <React.Fragment>

Click me

        {this.state.showModal && <MyModal onClose={this.onModalClose} beer={{name: "Beer"}} />}
      </React.Fragment>
    );
  }
}


text:
Q: Desarrollo en .net Compact (Smart Device) Estoy desarrollando una aplicación en .NET Compact para Windows Embedded con lenguaje C# y base de datos SQL Compact 3.5.
La aplicacion tiene 3 columnas con varias filas, tengo 2 columnas que muestran en sus filas una información ya establecida en la base de datos y en la tercera columna iría lo que el usuario digita, esto va montado en un DataGrid en donde se llama la información de la base de datos, tengo un Textbox en donde se coloca la información que va en la tercera columna y dos botones uno para editar y otro para guardar.
Se presenta el siguiente problema:
Cuando yo quiero ejecutar desde el equipo donde estoy desarrollando, me sale un error nativo 25009 que no me deja de pasar de la línea de abrir la base de datos, por otra parte cuando yo lo ejecuto en el dispositivo, éste me arroja un error de mapeo. Ya compruebo la ruta y la ruta de la base de datos es la correcta disco C/Carpeta Base de datos y dentro de ahí esta mi base de datos .sdf,

Adjunto el código fuente:
    private void btnEditar_Click(object sender, EventArgs e)
    {
        DataGridCell currentCell;
        string currentCellData;
        //  Se obtiene el texto a poner en la celda actual.
        currentCellData = txtCantidad.Text;
        //  Se obtiene la celda actual.
        currentCell = dtFrutas.CurrentCell;
        //  Se asigna la data a la celda actual.
        dtFrutas[currentCell.RowNumber, currentCell.ColumnNumber] = currentCellData;
        txtCantidad.Text = "";
    }

    private void btnGuardar_Click(object sender, EventArgs e)
    {
        SqlCeConnection conn = null;
        //SqlCeConnection con = new SqlCeConnection("Data Source =\"\\Program Files\\FrutayPastelino\\MisPedidos.sdf\";");
        SqlCeConnection con = new SqlCeConnection("Data Source = C:\\Base de datos\\MisPedidos.sdf");
        //con.Open();
        SqlCeCommand ad = new SqlCeCommand("UPDATE Fruta SET Cantidad = @cantidad WHERE Codigo_Integra = @codigo_integra", con);
        con.Open(); // Error nativo 25009 en el ordenador.

        try
        {
           ad.Parameters.AddWithValue("@cantidad",txtCantidad.Text);
           ad.Parameters.AddWithValue("@codigo_integra", " ");   //ERROR DE MAPEO EN EL DISPOSITIVO
           //ad.ExecuteNonQuery();
            MessageBox.Show("Pedido bien");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
            ad.Dispose();
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: esta línea de código carga datos en la tabla 'misPedidosDataSet.Fruta' Puede moverla o quitarla según sea necesario.
        this.frutaTableAdapter.Fill(this.misPedidosDataSet.Fruta);
    }

A: Coloca el siguiente código en el btnGuardar y actualiza tu cadena de conexión.
string ruta;
ruta = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
MessageBox.Show(ruta);

Por otro lado, cuando hagas debugging de tu aplicación en tu dispositivo/emulador, revisa y verifica que la propiedad Copy to Output Directory of your .sdf file tenga el valor adecuado, así no se sobreescribirá la siguiente vez.
En ese MessageBox se encuentra el lugar donde se ejecuta tu programa, lo que nos da la ruta adecuada. Hasta donde estuve investigando en los PocketPC las rutas no tienen letras y toda ruta inicia con doble backslash \ por lo que mencionas del error nuevo, parece que la base de datos está en el lugar adecuado, sin embargo, por lo visto, el "código integra" debe ser numérico y como le estás asignando un campo vacío, lanza el error.
Lo que debe ir en el "código integra" es el ID de la fruta que vas a actualizar.
 UPDATE Fruta SET Cantidad = @cantidad WHERE Codigo_Integra = @codigo_integra

Esto quiere decir: actualizamos la tabla Fruta, el nuevo valor del campo @Cantidad será lo que hay en la variable cantidad, esto se aplica para todos los elementos que cumplen la condición: Codigo_Integra (campo de la tabla Frutas) es igual a @codigo_integra (el valor que le asignas).
Revisa la información de la grilla, te aseguro que ahí se encuentra el ID único (código_integra) que necesitas para actualizar la cantidad de la fruta :D y en caso exista, guárdala temporalmente en un textbox oculto y en cada actualización limpias ese textbox para evitar que se mezclen las cantidades con otros productos.
En caso que falte el ID de la grilla, revisa la consulta SQL y agrega ese ID faltante (codigo_integra), luego la puedes ocultar a la vista, pero el dato ya estará presente

A: Intenta cambiar esta linea
SqlCeConnection con = new SqlCeConnection("Data Source = C:\\Base de datos\\MisPedidos.sdf");
                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Por
SqlCeConnection con = new SqlCeConnection(@"Data Source = C:\Base de datos\MisPedidos.sdf");
                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Otro tip, es que no dejes espacios en blanco en el path, por ejemplo "Base de datos", yo recomendaría usar algo mas compacto como: C:\bd\pedidos.sdf
Editado
Presiamente me ocurrió lo mismo y me dí cuenta que todo el tiempo estuve poniendo mal direccionado el archivo .sdf
            using (var cnn = new SqlCeConnection("Data Source=MyData.sdf;Persist Security Info=False;"))
        {
            var command = new SqlCeCommand("update...", cnn);
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.AddWithValue("@p1", "valor3");
            command.Parameters.AddWithValue("@p2", "valor2");

            try
            {
                cnn.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }


text:
Q: Error en metodos onClick Tengo un error al cual no consigo respuesta ya que, desde mi punto de vista, este código esta bien.
Codigo XML
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="¿Cuantos panes desea comprar?"
        android:textSize="15sp"
        android:textColor="#000"
        android:layout_marginBottom="16dp"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:text="+"
            android:onClick="incrementar"
            />

        <TextView
            android:id="@+id/quantity_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textSize="30sp"
            android:textColor="#000"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="5dp"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:text="-"
            android:onClick="disminuir"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/name"
            android:layout_marginTop="20dp"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:hint="Nombre"/>

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Orden Completa"
        android:textSize="15sp"
        android:textColor="#000"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp" />

    <TextView
        android:id="@+id/ordenS_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="30sp"
        android:textColor="#000" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="Ordenar"
        android:onClick="enviarOrden"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/ordenarCafe"
            android:layout_alignParentBottom="true"
            android:layout_width="wrap_content"
            android:layout_height="50dp"

            android:text="Pedir Cafe" />

    </RelativeLayout>

</LinearLayout>

Codigo JAVA
  package android.curso.coffeshop;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Declaramos la variable donde guardaremos la cantidad de panes ordenados

    int cantidad = 0;

    // Creamos un EditText para guardar nuestro nombre

    EditText editName;

    // Creamos un Button para que mantegan el ID del boton

Button ordenarCafe;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Intent i = new Intent (this, NewActivity.class);

    ordenarCafe = (Button) findViewById(R.id.ordenarCafe);

    ordenarCafe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(i);
        }
    });

    // Le decimos a la app que este EditText se encuentra en el activity_main y tiene esta ID

    editName = (EditText)findViewById(R.id.name);
}

    // En esta funcion, primero recibimos los parametros de cantidad y le decimos donde queremos mostrar la cantidad, a continuacion pondremos alli esa cantidad con un setText

    private void mostrarCantidad(int numeroDePanes){
        TextView cantidadTextView = (TextView) findViewById(R.id.quantity_text_view);
        cantidadTextView.setText(numeroDePanes);
    }

    // Le restamos y sumamos 1 a la cantidad de panes segun desees

    public void incrementar(View v){
        cantidad = cantidad + 1;

        // Llamamos a la funcion y le pasamos los parametros

        mostrarCantidad(cantidad);
    }

    public void disminuir(View v){
        cantidad = cantidad - 1;
        mostrarCantidad(cantidad);
    }

    // Primero, debemos decir donde se va a mostrar nuestra orden final.
    // Luego recibiremos toda la informacion en un string y lo mostraremos

    private void mostrarPrecio(String mensajePrecio) {
        TextView precioTextView = (TextView) findViewById(R.id.ordenS_text_view);
        precioTextView.setText(mensajePrecio);
    }

    // Calculamos el precio, en los parametros recibimos la variable cantidad y el precio lo colocaremos como parametro en la funcion "enviarOrden"

    private int calcularPrecio(int cantidad, int precio) {
        return cantidad * precio;
    }

    // Buscamos el mensaje que va a recibir mostrarPrecio

    public void enviarOrden (View v) {
        mostrarPrecio(crearOrden());
    }

    // Enviamos los parametros de cantidad y su precio
    // Retornamos un mensaje que envie el nombre que coloquemos en el editText, obteniendo su texto y transformandolo en string, la cantidad a traves de la variable
    // El total esta calculado un linea antes y una linea de agradecimiento

    private String crearOrden(){
        int total = calcularPrecio(cantidad, 2);
        return "Nombre: " + editName.getText().toString() + "\nCantidad: " + cantidad + "\nTotal: $" + total + "\nGracias!";
    }

}

El problema es que cuando doy Click en incrementar o disminuir (+ o -) la APP se cierra y me da este Error
Error

E/AndroidRuntime: FATAL EXCEPTION: main
      Process: android.curso.coffeshop, PID: 30444
      java.lang.IllegalStateException: Could not execute method for android:onClick
          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
          at android.view.View.performClick(View.java:5647)
          at android.view.View$PerformClick.run(View.java:22479)
          at android.os.Handler.handleCallback(Handler.java:761)
          at android.os.Handler.dispatchMessage(Handler.java:98)
          at android.os.Looper.loop(Looper.java:156)
          at android.app.ActivityThread.main(ActivityThread.java:6595)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
       Caused by: java.lang.reflect.InvocationTargetException
          at java.lang.reflect.Method.invoke(Native Method)
          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
          at android.view.View.performClick(View.java:5647)
          at android.view.View$PerformClick.run(View.java:22479)
          at android.os.Handler.handleCallback(Handler.java:761)
          at android.os.Handler.dispatchMessage(Handler.java:98)
          at android.os.Looper.loop(Looper.java:156)  Application terminated.

A: El problema surge al llamar los métodos desde el layout mediante la propiedad android:onClick, el llamado es correcto pero lo que realizan dentro estos métodos tiene un error.
 public void incrementar(View v){
        cantidad = cantidad + 1;

        // Llamamos a la funcion y le pasamos los parametros

        mostrarCantidad(cantidad);
    }

    public void disminuir(View v){
        cantidad = cantidad - 1;
        mostrarCantidad(cantidad);
    }

Este error se encuentra en el método mostrarCantidad(), el error se debe a que no debes usar el método setText() para asignar un valor entero, convierte el valor numeroDePanes a String,
   private void mostrarCantidad(int numeroDePanes){
        TextView cantidadTextView = (TextView) findViewById(R.id.quantity_text_view);
        cantidadTextView.setText(String.valueOf(numeroDePanes)); //* Cambio
    }

de otra forma el método setText() tratará de buscar el id de un recurso que en realidad no existe en el proyecto.

setText(int resId)  Establece el texto que se mostrará utilizando
  un identificador de recurso de cadena.

Con respecto a abrir la Activity usando un Intent, esta es la forma correcta de realizarlo:
//Intent i = new Intent (this, NewActivity.class);

private Intent i;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ordenarCafe = (Button) findViewById(R.id.ordenarCafe);

    ordenarCafe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            i = new Intent (MainActivity.this, NewActivity.class);
            startActivity(i);
        }
    });

A: No se ve bien tu código, espero te ayude esto.
Para que puedas darle click a un botón y te muestre una acción(o quieres que haga algo) debes de realizarlo de esta forma:

1.- Tiene que instanciar tu boton para que pueda hacer alguna acción:
TU_BOTON=(Button)findViewById ( R.id.btn_TU_BOTON );

2.- Y después, recien hacer el OnClickListener
 TU_BOTON.setOnClickListener ( new View.OnClickListener () {
        @Override
        public void onClick(View view) {
                //(y acá adentro colocas todo lo que tu botón va a hacer)

        }
    } );

espero te ayude en algo, seria bueno que describas bien tu problema y pongas más información.


text:
Q: Providing a One-way Heat Sink How would one design a component that allows heat to flow freely in one direction only, while preventing heat conductivity in the reverse direction?
I imagine such device might be thought of as a "Heat-flow Diode" or "Thermal Gate", that would, eg, allow neighboring appliances with vastly different heat dissipation requirements and tolerances to share a common heat sink, preventing heat from entering any appliance via heat sink backflow.

A: *

*Active devices would include mechanical refrigeration systems and peltier devices - the latter probably being more practical.

*Passive devices would be some sort of liquid convection cooling with the heat source at the bottom and heat sink at the top. The lower density hot fluid would rise to the top.

A quick web search for one-way heat conductor showed up:
... and a thermal rectifier!

Figure 1. Japanese researchers have developed a new diode that only transmits heat currents in one direction, and they think it could represent a new future for thermal computing. Source: PopSci.
The article goes on to say:

Similar work has succeeded with individual electrons in superconductors and in lone nanotubes, according to Technology Review. But this represents the first time anyone has managed the trick in a bulk solid, which in this case consists of two types of perovskite cobalt oxides.
Researchers have long theorized that such diodes, or thermal rectifiers, could become possible with the right material. Such a material would have to have high thermal conductivity at low temperatures and vice versa, so that that heat would flow continuously in one direction -- and then researchers could combine the material with another having the opposite characteristic.
Such a device has clear use in creating heat sinks that keep microchips running cool. Yet Wataru Kobayashi at Waseda University and his colleagues have put forth a more ambitious goal: controlling heat currents to create a new type of information processing with thermal transistors, thermal logic gates, and thermal memory. [Italics mine.]

I originally thought this development was the same thing but @DaveTweed points out -

I think you misunderstood the first [now second] reference about polyethylene molecules -- this creates an anisotropic material (heat flows along one axis, but not along the other two), but cannot produce a "diode" effect.

I'll leave it in out of general interest.

Figure 2. Chains of polyethylene molecules like the one above tend to arrange themselves chaotically, but by figuring out how to make the molecules line up straight, MIT researchers have created a highly conductive new polymer that conducts heat in only one direction. Source: PopSci.

A: A tubular thermosiphon (aka heat pipe) can be arranged to work in a manner such as described. Indeed, much development work on them was concerned with making them work against their natural directional inclination.


text:
Q: Is there anyway to have Notepad++ highlight both PHP and HTML at the same time? I've used Notepad++ for PHP editing with HTML tags echoed out.  Notepad++ had always highlighted, and interacted with the HTML, CSS, Javascript, and PHP code all in the same document.
The latest versions seem to only highlight PHP code only, and all the rest of the code be it HTML, CSS, Javscript just gets greyed out, and bunched together.
Here's the screenshot of how the html and javascript look. Switching the language from the menu bar to PHP, HTML, or Javascript doesn't change anything though.

Is there any way to enable this feature again?

A: Looking at the screenshot, it seems your markup is all in a string that's being echoed out. In that case, Notepad++ is acting normally, highlighting the entire string as a PHP string.
Remember that you don't need to use echo to print HTML. You can embed PHP in HTML (or HTML in PHP) by using PHP's opening and closing delimiters to break out and back in to PHP code anywhere in your files (see the manual). If you close your PHP code with ?> rather than use echo ", and open it back up at the end of the string with <?php instead of ";, your HTML should highlight as HTML again.

A: Thankfully, no.
I ran into this 'problem' too. Then after an hour of trying to enable this 'feature' I realized: hey, at this point, I should be using templates anyway.
After some consideration I've come to the conclusion that Notepad++ shouldn't do this, to encourage good coding practices.
I'm only embarrassed that it took me so long to realize that it was no longer my editor's job to make my code readable, but mine.
GLHF


text:
Q: Angular route guard not calling return I have an auth class set up like this:
export class AuthService {
  user = new Subject<string>();

  login(name: string) {
    this.user.next(name);
  }

}

I have an auth guard set up to check to see if my user subject has a value like this:
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.authService.user
      .pipe(
        map(user => {
          const isAuth = !!user;
          if (isAuth) {
            return true;
          }
          return this.router.createUrlTree(['/login']);
        })
      );
  }
}

I put print statements in the return and they never get called. The page never loads and it never re-directs either. If I just return true or false it works but by returning my authService.user nothing seems to happen.

A: The apparently issue with your currently code is that no part of your app is pushing any data into user subject when subscribing to it in your guard.
How about using BehaviorSubect so that when ever you subscribe to it you'll accept a value? using BehaviorSubect unless you push into it a new value you'll accept the initial value right away when subscribing to it.
export class AuthService {
   user = new BehaviorSubject<string>(null);

   login(name: string) {
     this.user.next(name);
   }
}


text:
Q: Creating draft email from gmail addon that extends compose UI I'm running my gmail add-on with the following scopes:
https://mail.google.com/
https://www.googleapis.com/auth/gmail.addons.execute
https://www.googleapis.com/auth/gmail.addons.current.action.compose
https://www.googleapis.com/auth/gmail.addons.current.message.metadata
https://www.googleapis.com/auth/script.external_request

I have a button, and corresponding compose action event, that is supposed to read recipient, subject, and body information from some input fields and insert this info into the compose UI.
The compose action callback looks like this:
function autofillEmailDraft(e) {
  var recipient = e.formInput.recipient;
  var subject = e.formInput.subject;
  var body = e.formInput.body;

  GmailApp.setCurrentMessageAccessToken(e.messageMetadata.accessToken);
  var draft = GmailApp.createDraft(recipient, subject, body);

  // Return a built draft response. This causes Gmail to present a
  // compose window to the user, pre-filled with the content specified
  // above.
  return CardService.newComposeActionResponseBuilder()
    .setGmailDraft(draft).build();
}

On clicking the button, the addon crashes with the following error message: TypeError: Cannot read property "accessToken" from undefined.
e.messageMetadata seems to be undefined. Should I be looking for the access token somewhere else?
Simply removing the offending line
GmailApp.setCurrentMessageAccessToken(e.messageMetadata.accessToken);

doesn't work. The add-on crashes with a different error
Access denied: : Missing access token for authorization. Request: MailboxService.CreateDraft.

Update after comments:
This is the code for the button widget that triggers the compose action:
var submitButton = CardService.newTextButton()
      .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
      .setText('Yes')
      .setComposeAction(
        CardService.newAction().setFunctionName('autofillEmailDraft'),
        CardService.ComposedEmailType.STANDALONE_DRAFT
      );

This is the logged 'e' object:
{
    formInput={body=Hello},
    parameters={},
    draftMetadata={
        toRecipients=[abcd@example.com],
        bccRecipients=[],
        ccRecipients=[]
    }
}

A: As this open issue indicates, filling the recipient and subject fields of an email draft from an addon that extends the compose UI is not currently supported.


text:
Q: Angular POST gets net::ERR_EMPTY_RESPONSE when server takes 3 mins to finish Hi i run into this problem, did search online but cannot find exact answer yet.
Basically i'm doing a POST from web client, node.js server will pick it up and starts to execute the command.
If it works, this command (say my_cmd 1234) finishes within 30 seconds, and angular gets the response and updates the status in the webpage.
Now if i pass in an different for this command (my_cmd 2345), it takes 3 minutes to finish, i did run this by hand in the linux console. After 3 minutes it does finish and prints out status message. But Angular POST returns net::ERR_EMPTY_RESPONSE.
So is there a default timeout value i should set ? Thanks !

A: Ok, actually i changed the timeout value in the server side and it worked.
I followed this.
How to modify the nodejs request default timeout time?


text:
Q: simplify functions in Quickgraph and good documentation? I'm figuring out whether Quickgraph is beneficial for my problems (F# project). Does it have graph reduction functions/algorithms? Similar to Matlab's simplify functions.
Furthermore, I'm having troubles with finding architectural documentation (principals and data structure) of Quickgraph and tutorials for a flying start. The same goes for the BoostGraph where it seems to be ported from. Any suggestions?
Regards, WP

A: Old question, but thought I'd share this for future readers since the QuickGraph page on CodePlex now only has broken links.
Documentation from Dec 2017 can be found here (web archive for QuickGraph).
It might not be completely up-to-date with the latest source code, but it can contains a nice overview of graph types and algorithms.


text:
Q: SQLite - Reference to another database table I have two databases (so also two files) db1 and db2. In db1 I have a table foo and and a column c1. In db2 there is a table bar with the primary key p. I want to reference c1 to p, so referencing a value between various databases. So I thought it could be possible to do something like
create table foo(
    c1 references db2.bar (p)
);

But this not work. Is there any way to do this in sqlite?


text:
Q: Colour of photos in different browsers? I've just put some photos up online and I noticed that they photos appear to be a different colour in Firefox and Safari to IE and Chrome... Any ideas on what the issue could be? Due the browsers interpreter colours spaces differently or something?
Cheers
Anthony

A: They interpret color spaces differently because some browsers ignore ICC color profiles that are part of the images themselves.  Safari and Firefox 3+ don't however, though Firefox needs to be configured to enable it.
Here's a related link: http://www.gballard.net/psd/go_live_page_profile/embeddedJPEGprofiles.html

A: I've noticed that png format especially differs cross browser wise. When I noticed this, I converted to jpg and it resolved it.


text:
Q: Is it always possible to construct this integer sequence? Let $A_n$ be a sequence of monotonically increasing, positive integers. How can one construct another sequence $a_n$, again positive integers, such that $$\lim_{n \to \infty} \frac{A_n}{\displaystyle \prod_{k=1}^n a_k} = 1$$
Is it even always possible to construct such a sequence?
The obvious thing is to choose $a_{n+1}$ to be $\frac{A_{n+1}}{A_n}$, but its not always guaranteed that this will be an integer. I tried to use $a_{n+1} = \lfloor \frac{A_{n+1}}{A_n} \rfloor$, but I cant seem to work it out. For sequences like $A_n = k^n$ it is very easy to construct $a_n$ if $k$ is an integer itself. What about $A_n =\lfloor \alpha^n \rfloor $ if $\alpha$ is any number greater than 1?

A: It is not always possible.
Let $A_n=n$ and $p(n)=a_1.a_2....a_n$. Then suppose that, for $n\ge N$, $$0.9<\frac{n}{p(n)}< 1.1$$
Then $\frac{2n}{p(2n)}= \frac{2}{A}\frac{n}{p(n)}$ for some integer $A$. For this to be in the assumed range we require $A=2$ but then $$\frac{n}{p(n)},\frac{2n}{p(2n)},\frac{4n}{p(4n)},...$$  are all constant and so do not tend to $1$.
The only remaining possibility is that, for all sufficiently large $n$, $\frac{n}{p(n)}=1$. But then $p(n)$ does not divide $p(n+1)$.


text:
Q: Dropdown's SelectedIndexChanged event is not fired when its populated from client side I have a dropdown on my page which I am populating from client side javascript code. The SelectedIndexChanged does not fire. But when I populate my dropdown from code behide (.cs file) the even is fired.
Any idea how to handle SelectedIndexChanged when dropdown is being populated from code behind. I could see that dropdown is getting populated as per my needs. Only SelectedIndexChanged even is not getting fired. Also note that the drop down is inside UpdatePanel. Will that be a reason?
Here is my html, javascript and code behind event:
<asp:DropDownList ID="ddS" runat="server" OnSelectedIndexChanged="ddS_SelectedIndexChanged"
                AutoPostBack="True" Style="position: absolute; width: 50%;">

Javascript:
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');

CS
protected void ddS_SelectedIndexChanged(object sender, EventArgs e)
{
}

Any help would be appreciated. Thanks in advance.
Edit
My main reason behind doing this is:
I have used jquery ui js for a popup, it has a multi-select drop down list. Since the button in a popup cannot have a server side event I have used ajax call to a web-method in .cs file. This method will update my tables from the database with the options selected in the multi-select drop down. Once it is done I want to close the popup and populate a drop down based on the options selected in multi-select.
I cannot populate my dropdown from code behind because the web-method is a static method and hence any method called from that method has to be a static method. If I write a static method then I cannot access UI controls(my drop down) from a static method. So I was hoping I can populate it from JS and then trigger my indexchange event for further computation.

A: The short answer is don't do this.  This is not how ASP.NET Server Controls were designed to work and you will end up creating a Rube Goldburg making it work.  Details below:
ASP.NET has a security feature (Event Validation) built in to prevent data being posted that was not present in the control after the Render stage of the page life-cycle.  If this occurs an ArgumentException will be thrown.  You can disable event validation or override Render and stick lots of code in your Page_Load function, but I wouldn't recommend it.
So why does all of this happen?  ASP.NET Server controls use ViewState in an attempt to create state like the state in a desktop application (Windows Forms => Web Forms see what they did there).  ViewState gets upset if it doesn't know about the <options> you added to the <select>.  A few solutions are:
1) Populate the DropDownList on the Server-Side (unless you have a very good reason not to) and let the ASP.NET Framework do what it was intended to do (you may also have to add the EnableViewState=true attribute to the DropDownList control although I believe it is the default).  If the DropDownList is in an update panel ViewState is updated form the PartialPostBack triggered by the panel so the ViewState stays happy while you get flicker-free updates.
2) Forget the Server-side code and create and populate the <select> control using JavaScript.
a) You can bind a JavaScript event listener to update a hidden field when the selected item is changed.  Then on PostBack you can read the value of the hidden field to get the value of the last selected item.
b) You can bind a JavaScript event listener to run a POST or GET (AJAX Request) when the selection changes if you need to communicate those changes with the server-side code.  You never really said what your objective is...
EDIT AFTER QUESTION UPDATE:
There are three ways I can think of:
1)  Remove the ASP DropDownList control and make it a regular HTML select control.  Give the control a name (use the name attribute not just the id attribute). ex:
<select name='options'></select>

On POST, HttpContext.Current.Request.Form is a NameValueCollection that will contain Key-Value pairs of the POSTed data.  you should be able to get the selected items from your select control by using the name you gave the select control:
var options = HttpContent.Current.Request.Form["options"].Split(',');

options will now be a list of the selected values.  If you need this to be AJAX enabled (no page refresh) wrap it in an UpdatePanel.
2) Write the selected items to a hidden field and collect the values from the hidden field on POST.
3) Trigger a POST to a Web Method that updates a session object which can then be read from inside your non-static code behind class members/methods.  There is an optional attribute for the Web Method decoration that enables session:
[WebMethod(EnableSession = true)]

A: Generally, you need to make sure that your event handlers (your SelectedIndexChanged) are set after all DOM operations. In your case you append your html element by jQuery's append method. Unfortunately, adding callbacks to that method is not possible.
A settimeout with the timer "1ms" however always puts the function in the settimeout on the bottom of the call stack.
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
setTimeout(function() {
  // set listener here
  // e.g. $("#ddS option").change(function(){
  //   ddS_SelectedIndexChanged()
  // });
}, 1);


text:
Q: Class Not Found Exception in Spring MVC I am getting this exception but when I look into my MAVEN DEPENDENCIES folder I could see all the classes being downloaded properly by the pom.xml.
            Jun 10, 2014 9:43:49 AM org.apache.catalina.core.AprLifecycleListener init
            INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_05\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.8.0_05/bin/../jre/bin/server;C:/Program Files/Java/jdk1.8.0_05/bin/../jre/bin;C:/Program Files/Java/jdk1.8.0_05/bin/../jre/lib/amd64;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Program Files\Java\jdk1.8.0_05\bin;C:\Program Files\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\Common Files\Microsoft Shared\Microsoft Online

Services;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;d:\Program Files (x86)\ZipGenius 6\;.;D:\Program Files\TortoiseSVN\bin;.;C:\ANT;.;E:\Software\BB 10 IDE\bbndk\sdkinstall.bat;.;E:\ADT_BUNDLE_SETUP\adt-bundle-windows-x86-20130729\sdk\platform-tools\;.;D:\BB7InstallationFolder\webworks;.;E:\ADT_BUNDLE_SETUP\adt-bundle-windows-x86-20130729\sdk\tools;.;D:\Tomcat 7.0\bin;.;C:\Users\sandhiya.sankara\AppData\Roaming\npm;;D:\eclipse;;.
            Jun 10, 2014 9:43:49 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
            WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld' did not find a matching property.
            Jun 10, 2014 9:43:49 AM org.apache.coyote.AbstractProtocol init
            INFO: Initializing ProtocolHandler ["http-bio-8080"]
            Jun 10, 2014 9:43:49 AM org.apache.coyote.AbstractProtocol init
            INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
            Jun 10, 2014 9:43:49 AM org.apache.catalina.startup.Catalina load
            INFO: Initialization processed in 628 ms
            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardService startInternal
            INFO: Starting service Catalina
            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardEngine startInternal
            INFO: Starting Servlet Engine: Apache Tomcat/7.0.54
            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardContext listenerStart
            SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
            java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
                at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
                at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
                at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:529)
                at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
                at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:139)
                at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4888)
                at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
                at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
                at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
                at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
                at java.util.concurrent.FutureTask.run(FutureTask.java:266)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
                at java.lang.Thread.run(Thread.java:745)

            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardContext listenerStart
            SEVERE: Skipped installing application listeners due to previous error(s)
            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardContext startInternal
            SEVERE: Error listenerStart
            Jun 10, 2014 9:43:50 AM org.apache.catalina.core.StandardContext startInternal
            SEVERE: Context [/mvc] startup failed due to previous errors
            Jun 10, 2014 9:43:50 AM org.apache.coyote.AbstractProtocol start
            INFO: Starting ProtocolHandler ["http-bio-8080"]
            Jun 10, 2014 9:43:50 AM org.apache.coyote.AbstractProtocol start
            INFO: Starting ProtocolHandler ["ajp-bio-8009"]
            Jun 10, 2014 9:43:50 AM org.apache.catalina.startup.Catalina start
            INFO: Server startup in 575 ms

Here is my pom.xml:
 <project xmlns="http://maven.apache.org/POM/4.0.0"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>

      <groupId>HelloWorld</groupId>
      <artifactId>HelloWorld</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>

      <name>HelloWorld</name>
      <url>http://maven.apache.org</url>

      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.0.5.RELEASE</spring.version>
      </properties>

      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>

        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
      </dependencies>
    </project>

I have referred all other answers provided by stack overflow for similar problems.Nothing helped me. Also my project is successfully built.

A: I deleted the maven repository folder .repository
And updated all dependencies from eclipse, then this issue was solved

A: Use following in your web.xml :
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/context.xml</param-value>
    </context-param>

    <!-- Spring Context Listener -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

A: I deleted the war files in my "target" directory, restarted eclipse and then made a  clean install in maven. This resolved my issue.


text:
Q: Get every first element of two dimensional list Is there any way how I can get every first/second/third/... Element of a two dimensional list, e.g. from the list
list = [[1,2], [3,4], [5, 6]]

Get the values 1,3,5 or is it only possible with a loop? Because a loop wouldn't be very practical if I want to do
If 2 in list:
...

A: A list comprehension will work just fine. You index each element separately:
firsts = [x[0] for x in lst]  # [1,3,5]
seconds = [x[1] for x in lst]  # [2,4,6]
# etc

You can use the list comprehension in-line if desired:
if 2 in [x[1] for x in lst]:
    print("Found 2 in a sublist")

A: You could use zip to transpose the list:
lst = [[1,2], [3,4], [5, 6]]
lst_transp = list(zip(*lst))

print(lst_transp)
# output: [(1, 3, 5), (2, 4, 6)]

A: You could use map
l = [[1,2], [3,4], [5, 6]]
result = map(lambda x: x[0], l)
print(list(result))


text:
Q: where to put the properties file in an eclipse project Please tell me where exactly do i put my .properties file in my eclipse project. Do I make a separate folder for it ?
I want to put it in such a way that I will be able to distribute my project easily in JAR form.
Thanks.
EDIT:
I want to put the properties file in such a way that it can be easily edited later, on any OS.

A: The approach I use in order to be able to easily change configuration without redeployment.
One version of the property file (with the defaults) in the root of your project, I always let it in the application package (foo.bar.myapp). I load the default one with getResourceAsStream("/foo/bar/myapp/config.properties") or like in the sample relative to the class package.
And additionally I ready a system property:
String configFileLocation = System.getProperty("config");

And just override the default with the properties read from the config file passed as property.
For instance:
Properties props = new Properties();
props.load(Main.class.getResourceAsStream("mydefault.properties"));

System.out.println("default loaded: " + props);

String configFile = System.getProperty("config");
if (configFile != null) {
    props.load(new FileInputStream(configFile));
    System.out.println("custom config loaded from " + configFile);
}

System.out.println("custom override: " + props);

This would load first your resource stored under your project in foo.bar package named mydefault.properties, and after it if system property config is configured it will load override the loaded properties with the one the the referred path.
The system property can be set using -D parameter, in this case would be something like: java -Dconfig=/home/user/custom.properties foo.bar.Main. Or if you are in a web application (Tomcat for instance) you can set this property using CATALINA_OPTS.

A: src/main/resource would be an ideal choice.


text:
Q: LUKS encryption, header on a dongle USBdrive? I am going to install Linux the LUKS/LVM way, in order to have an encrypted disk.
In addition, I would like to put the header and passphrase in a USB Key.
Thus, instead of entering the passphrase, I only plug the USB drive dongle.
Is it possible and how?

A: I am writing now from the machine that works exactly that way.

*

*First, you will need to put whole /boot folder on the dongle.

*Encrypt the disk with key file and put the keyfile into the boot dongle too.

*Edit /etc/crypttab, add this line
sda2_crypt UUID=14-88 /dev/disk/by-uuid/88-14:/rootfs.key     luks,keyscript=/lib/cryptsetup/scripts/passdev

where sda2_crypt is arbitrary name, first UUID is of encrypted root partition, second - of dongle partition and rootfs.key is the keyfile name.

*Then Update your /etc/fstab accordingly.

*Mount dongle as /boot and do update-initramfs
This should be enough. Different instructions suggest you to add kernel boot arguments, but in my case it worked without.If you ever want to use password instead of keyfile, just edit /etc/crypttab and do update-initramfs.


text:
Q: Specifying URL address. Apache Tomcat I have Web app, which is deployed by instructions: open localhost:port/manager open .war file and click deploy. That's ok. Site is working through localhost:port/appname. So I want this address to connect from outside not only local PC. I need to specify URL for my site. How?

A: If you are trying to use it within local network then you can use your local IP address instead of localhost.
localip:port/appname

You can find the IP of your machine running ipconfig/ifconfig command on the command prompt.
If you want to open it over the internet then you need a public IP for this and associated configurations.This will be quite some task.


text:
Q: Store ESX5 images on a NAS? I have a basic NAS device (Buffallo LinkStation Duo) that can only present SMB fileshares to the network. For testing annd for getting a dying physical machine working I would like to store my VMDK on here. Is that possible, or will I have to find some way of presenting this as an iSCSI target of some sort?
I've only used iSCSI or local storage in the past, but this isn't possible at the moment.
Thanks.

A: I dont even think it is possible to mount a SMB share as storage en ESX..
And the performance would be terrible.
You should either go for some NFS storage, or iSCSI/local storage.

A: Ack, many NAS systems do NFS, and that works OK for ESXi. I would strongly recommend you set up dedicated NICs and a dedicated switch for NFS... it might also help to get a NAS and switch that can deal with jumbo frames.


text:
Q: Sending email via SES in localstack, with an event destination with a sns topic, not working I am trying to receive a message in a queue when triggering an email with SES in localstack. The SES service is using an event destination that connects to a SNS topic. The SNS topic is connected to a queue, where I want to receive the bounce, click information.
Here are the steps:
// 1 whitelist email sender
aws --endpoint-url=http://localhost:4566 ses verify-email-identity --email-address sender@test.com --profile test-profile --region eu-central-1 --output table | cat

// 2 create sqs queue
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name ses_events_queue --profile test-profile --region eu-central-1 --output table | cat

// 3 create sns topic
aws --endpoint-url=http://localhost:4566 sns create-topic --name ses_events_topic --region eu-central-1 --profile test-profile --output table

// 4 subscribe sqs queue to sns topic
aws --endpoint-url=http://localhost:4566 sns subscribe --topic-arn arn:aws:sns:eu-central-1:000000000000:ses_events_topic --protocol sqs --notification-endpoint arn:aws:sqs:eu-central-1:000000000000:ses_events_queue --profile test-profile --region eu-central-1 --output table | cat

up until here, if I publish a message with:
aws --endpoint-url=http://localhost:4566 sns publish --topic-arn arn:aws:sns:eu-central-1:000000000000:ses_events_topic --message "{\"subject\":\"Subject\",\"body8\":\"Body 8\",\"from\":\"test@test.com\",\"to\":\"to@ta.com\"}" --profile test-profile --region eu-central-1 --output table | cat

it works, I can see message in queue.
Now the SES setup:
// 5 create config set
aws --endpoint-url=http://localhost:4566 ses create-configuration-set --configuration-set "{\"Name\":\"ses_config_set\"}" --profile test-profile --region eu-central-1 --output table | cat

// 6 create event destination
aws --endpoint-url=http://localhost:4566 ses create-configuration-set-event-destination --configuration-set-name ses_config_set --event-destination '{"Name":"some_name2","Enabled":true,"MatchingEventTypes":["send","bounce","delivery","open"],"SNSDestination":{"TopicARN":"arn:aws:sns:eu-central-1:000000000000:ses_events_topic"}}' --profile test-profile --region eu-central-1 --output table | cat

And now the actual sending of the email:
// 7 send email via ses using config set
aws --endpoint-url=http://localhost:4566 ses send-email --destination '{"ToAddresses":["receiver@mail.com"]}' --message '{"Subject":{"Data":"some sub","Charset":"string"},"Body":{"Text":{"Data":"some tesxt body","Charset":"string"}}}' --configuration-set-name ses_config_set --from 'sender@test.com' --profile test-profile --region eu-central-1 --output table | cat

Email is sent, but if I check messages in queue, there's none:
aws --endpoint-url=http://localhost:4566 sqs receive-message --queue-url http://localhost:4566/000000000000/ses_events_queue --profile test-profile --region eu-central-1  --output table | cat

Not sure where the error is. I'm also not sure what is the best way to debug. I tried to use --debug in the email sending, but I can't find anything useful.
My suspicion is that the create event destination step can be wrong, since there are may options inside, but not sure.
I've also tried to add permissions to the queue:
aws --endpoint-url=http://localhost:4566 sqs set-queue-attributes --queue-url http://localhost:4566/000000000000/ses_events_queue --attributes file://set_queue_attributes.json --profile test-profile --region eu-central-1 --output table | cat

in set_queue_attributes.json:
{"Policy" : "{\"Id\": \"Policy1564523767951\",\"Version\": \"2012-10-17\",\"Statement\": [{\"Sid\": \"Stmt1564523766749\",\"Action\": \"sqs:*\",\"Effect\": \"Allow\",\"Resource\": \"arn:aws:sqs:us-east-1:12345678:example-queue\",\"Condition\": {\"ArnEquals\": {\"aws:SourceArn\": \"arn:aws:sns:us-east-1:73628827939:MySNS\"}},\"Principal\": \"*\"}]}"}

But it does not work either. Not sure if this might be the issue, because publishing directly to sns, I can see the queue receiving the message. I don't know how to debug, that ses sends the message, and that ses publishes a message in the sns topic

A: In the doc, they state

Whether you create a new SNS topic or select an existing one, you need to give access to SES to publish notifications to the topic.

In your case, try to add this permission, after step 3 //create sns topic
awslocal sns add-permission \
--topic-arn arn:aws:sns:eu-central-1:000000000000:ses_events_topic \
--label Publish-Permission \
--aws-account-id 000000000000 \
--action-name Publish

I use the thin wrapper awslocal
Also, use option "--max-number-of-messages 10" in "sqs receive-message".
Default is "1"

A: the reason it was not working was because the feature was not implemented. I opened an issue and they worked fast on it:
https://github.com/localstack/localstack/issues/7184
I post this answer in case anyone finds something similar


text:
Q: ADCS - How can I diagnose the exact reason a certificate request was denied by a policy module? I need to develop operational procedures to audit and understand why a specific request was rejected by an Active Directory Certificate Services (ADCS) Policy Module.
I've attempted turning on all logging (checkboxes) in the GUI, and checked the Eventlog.  I only see one event log entry per failed request, however I don't have a clear way of determining what caused it to fail.  An example of a failure is below:

Active Directory Certificate Services denied request 4 because The
  certification authority's certificate contains invalid data.
  0x80094005 (-2146877435 CERTSRV_E_INVALID_CA_CERTIFICATE).  The
  request was for CN=Issue01a, CN=Bits.com, OU=For email security,
  O=Bits LLC, C=US.  Additional information: Denied by Policy Module

The above example is a sub-ca that intentionally had a validity period that would extend beyond the validity of the parent CA.
I'm hoping to derive that reason from the error code above, or some other location.
What I've done:
Searching for the error "2146877435" in google, results in this very post being pulled up.  None of the results on the first few pages are a list of error codes and reasons.

A: This link describes how to extract more logging from the certificate service.  A restart may be required.
To enable debug logging for the native Windows CertEnroll client, execute the following command:

Certutil –setreg enroll\debug 0xffffffe3 The log file is in the
  following location: %windir%\CertEnroll.log
certutil –setreg ca\debug 0xffffffe3 The log file is in the following
  location: %windir%\certsrv.log

A: mr.spuratic commented:

FWIW, another possible cause of that error code is the policy being incompatible with the attempted action: specifically trying to sign a new CA with a CA whose pathlen is 0 (so there's nothing "invalid" about the CA data, it's merely an inappropriate action).

As this was exactly my problem, I want to preserve this comment in an answer and elaborate it a little more:
Before setting up the root CA, you have to allow sub CAs in the file C:\Windows\CAPolicy.inf in the following section:
[BasicConstraintsExtension]
PathLength=0

If PathLength is set to 0, no sub CAs are allowed. If set to 1, you can have sub CAs. If set to 2, you can have sub CAs that can have sub CAs and so on. If it is not defined or set to none, you can have infinite levels of sub CAs. You cannot alter this value after you already installed your root CA.


text:
Q: How to handle update_all when empty data returned I am updating some of my database details using update all. When the returned data is empty update all fails ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column
I know this can be fixed for example, but this looks like a redundant use, because in my code base I am doing many changes as follows
Product.where(local_product: true).update_all(tax: 0) if Product.where(local_product: true).present?

I wish if update_all had handled this by itself, or is there any other way?

A: Just do it in one line you dont need to check if there are any records.
Product.where(local_product: true).update_all(tax: 0) will generates next sql query:
UPDATE "products" SET "tax" = true WHERE "products"."local_product" = true

Database filters records for you, you dont need to check it twice, if there are no data for update it will do nothing.

A: Try this to avoid redundant
@products = Product.where(local_product: true)
@products.update_all(tax: 0) if @products.present?


text:
Q: applying a (row) function to a DataFrame changes column types Having an issue with unintended changes to column types, distilled as shown below.  Column x is floats, column icol is ints.  when the testfunction (which does nothing) is applied, column icol is changed to type float64, as demonstrated by this code:
df = pd.DataFrame({'x':[1000, -1000, 1.0]})
df['icol'] = 1
print(df.dtypes)

def testfunction(r):
    pass
    return(r)
df = df.apply(testfunction, axis='columns')
print(df.dtypes)

However, if I make both the x and icol columns ints, then the types do not get changed.
df = pd.DataFrame({'x':[1000, -1000]})
df['icol'] = 1
print(df.dtypes)

def testfunction(r):
    pass
    return(r)
df = df.apply(testfunction, axis='columns')
print(df.dtypes)

This is a potential hazard, for example if one may use an int column as a key later, etc.
Is this a feature, or am I doing something wrong here ?  running python 3.7.3 on ubuntu
Thanks

A: All Pandas operations try to be as numerically efficient as possible.  When applying an operation to a row, Pandas tries to construct a Series from the row first.  If the row is a mix of ints and floats, these will be converted to floats, just like when you pass a mixed list to the Series constructor: Series([1000.0, 1]) is converted to all floats: i.e. Series([1000.0, 1.0])
Consequentially, if your row contains a string, the object dtype is used and all of the types are preserved at the cost of performance.  In general, you should avoid apply if at all possible and use other Pandas methods to get the results.
df = pd.DataFrame({'x':[1000, -1000, 1.0]})
df['y'] = 1
df['z'] = 'hello'

print(df.apply(testfunction, axis='columns').dtypes)
# prints:
x    float64
y      int64
z     object
dtype: object

A: Thanks for the informative answer and comments.  Here is another simple work-around, for anyone else who doesn't want to repent from using the row function pattern:
df = pd.DataFrame({'x':[1000, -1000.1]})
df['icol'] = 1
print(df.dtypes)

def testfunction(r):
    pass
    return(r)

# save the types
types = df.dtypes

df = df.apply(testfunction, axis='columns')
print(df.dtypes)

# put 'em back
df = df.astype(types.to_dict(), copy=False)

print(df.dtypes)


text:
Q: Ввод текста в canvas Без градиента текст выводится, но с градиентом его нет, не могу понять почему. И ещё, как можно сделать так, чтобы пользователь сам выбирал цвет текста?

<canvas id="canvas" width='600px'></canvas>
<input type="text" id="text"></input>
<button onclick="func();"> Ввод</button>
<input type="color" id="color">
<script>
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d");
  var grd = ctx.createLinearGradient(0, 5, 150, 220);
  grd.addColorStop(0, "red");
  grd.addColorStop(1, "purple");
  ctx.fillStyle = grd;
  ctx.fillRect(0, 0, 300, 200);

  function func() {
    var e = document.getElementById("text"),
      t = document.getElementById("canvas"),
      n = t.getContext("2d");
    n.textBaseline = "top";
    n.fillText(e.value, 150, 0);
  }
</script>

A: Вы забыли указать цвет для текста.
Берем цвет из вашего поля ввода цвета, как:
  colorText = document.getElementById("color"),

и перед "отрисовкой" текста указываем:
n.fillStyle = colorText.value;

Более подробно об fillStyle
Ваш пример:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 5, 150, 220);
grd.addColorStop(0, "red");
grd.addColorStop(1, "purple");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 300, 200);

function func() {
  var e = document.getElementById("text"),
    t = document.getElementById("canvas"),
    colorText = document.getElementById("color"),
    n = t.getContext("2d");
  n.textBaseline = "top";
  n.font = "30px serif";
  n.fillStyle = colorText.value;
  n.fillText(e.value, 50, 0);
}

func();
<canvas id="canvas" width='600px'></canvas>
<hr>
<input type="text" id="text" value="TestText"></input>
<button onclick="func();"> Ввод</button>
<input type="color" id="color">


text:
Q: Custom Visualforce Component Help i want to build a custom visualforce component as shown in following image. I am currently thinking of a custom MultiPickList using div and ul. But i will have to write a lot of javascript for it.
So, I want to ask for some tips as to how can i build it efficiently. Also i am open to other ideas if i can achieve similar functionality by changing GUI.

A: Here's a Salesforce JavaScript Remoting integration for Sencha Ext JS. The sample code demonstrates how to read hierarchical data.

Then you could add drag+drop between a TreePanel and a GridPanel.

A: Seems like this project might help you out.
http://wwwendt.de/tech/dynatree/doc/sample-dnd3.html
http://wwwendt.de/tech/dynatree/


text:
Q: Wordpress $args select query from multiple custom post with custom category check Hi to all I want to create $args query to check that if custom post has category then check if category value is none or not if not then check if custom field value is true or false. and for other post type that category is not available.
here is my code
$args = array(
    'posts_per_page' => 10,
    'paged' => $page_no,
    'post_type' => array('ct_photo', 'ct_event', 'ct_video', 'ct_thought'),
    //'post_type' => 'ct_video',
    'orderby' => 'post_date',
    'order' => 'DESC',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'vid_category',
            'compare' => 'IN',
            'value' => array(10, 11, 12),
        ),
        array(
            'relation' => 'AND',
            array(
                'key' => 'vid_category',
                'compare' => 'IN',
                'value' => array(10, 11),
            ),
            array(
                'key' => 'display_home',
                'compare' => '=',
                'value' => 'true',
            )
        ),
    )
);

Now what i Want
I want that this query will return result which check that if post type is video then it check that if category value is available then check custom field "display_home" is true or not and if category is not selected then it must be show in query.
and for other post type it will not check category.
i tried to use case & if but that is not working.
Kindly help me.

A: Ohkay I found my answer
SELECT wp.id, wp.post_type, wpm.meta_key, wpm.meta_value FROM `wp_posts` as wp Inner Join wp_postmeta as wpm ON wp.id = wpm.post_id where (wpm.meta_key = 'vid_category' AND wpm.meta_value ="true") OR (wpm.meta_key = 'display_home' and wpm.meta_value ="true") OR(wp.post_type IN ('ct_photo', 'ct_event', 'ct_thought')) and wp.post_status = 'publish' GROUP BY wp.id ORDER BY `id` ASC


text:
Q: What is a good definition of 'time'? I know this is a silly question, but I'm only asking this because I honestly can't seem to find a good definition of time that doesn't include another word that relies on the definition (or logical understanding rather) of time.
For example, in many dictionaries the definition of time is as follows:

Time is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.

But the concept of 'past', 'present', and 'future' (mostly the first and last) rely heavily on time.
My best shot at a definition of time is this:

Time is the dimension on which the evolution of state of a system is allowed to occur.

Is this question senseless? Is the notion of time best left axiomatic? Do you know of a good/better definition of time? (The more concise the better)

A: Well , here is my experimentalist answer:
Time is a necessary parameter in order to describe observed  changes in three dimensional space, dx/dt, dy/dt, dz/dt.  If there were no observable changes in the (x,y,z) contour map of the world (including us as contours also) there would be no time parametrization needed.
These changes are an experimental fact and to start with the day and night clock was used to define the parameter. Clocks can be anything that consistently reproduces periodically the same (x,y,z) for a specific location/point.
This is classical time. Special relativity and even more General Relativity are a different story with much more sophisticated mathematical modeling.

A: Physics uses a system of units, of which duration, length, and mass are examples.
The goal of a physical prediction is to use these units and a fundamental concept of "betweenness".  And the predictions go something like, if you measure this length then the measurement would be between the 2.14 meter marking and the 2.16 meter marking.  Another prediction might be the flash occurs between the 3:14:56 reading of the clock and the 3:14:58 reading of the clock.  It is the exact same concept of betweenness in the two cases.  And since the modern definition of the meter is actually based on clocks, they truly are the same thing now.
Every measurement is predicted as being between one fiduciary marking/reading and another. So clocks and their reading are how we measure units of time, and always as a prediction as being between two markings or readings. Distances are measured by rulers.  When you have a theory, you have to ultimately figure out a way to get a prediction about something we can measure.

A: There are two kinds of time not to be confounded one with each other:

*

*Time is proper time. Mass is transporting energy through time, we may call it "persistence" or "aging" of an object, as synonyms of time. Time is measured by any clock. A clock becomes "suitable" if we can make some synchronization with our own clock, but any clock is measuring time. A clock cannot measure consecutively in two time directions, it would be no clock.

*We can use our own clock or any other clock to evaluate simultaneity of events, that means we are comparing the moment of an event with our clock of reference by categories such as "before", "after" or "simultaneous". Simultaneity is relative and is proper to each clock.
In summary we have to distinguish between proper times of objects which cannot be part of the same coordinate system and coordinate time of one clock of reference which puts all events in one coordinate system.
Time is linked to space by the spacetime mechanism wherein it is considered as a kind of fourth dimension. But apart from this mechanism there is no similitude between space and time.


text:
Q: how u maintain a static menu bar in gwt using mvp framework I would love to know from anyone who knows how we can keep the a widget in mvp static by putting it in the entry point class.Or is it recommended to include the widget in appcontroller.
I have an issue like I want to make my menu bar static throughout my page. For this I follow

*

*I will create a RootPanel

*I divide the page into two by adding two panels.I would like to send the mainpanel to the Appcontroller by goTo and change the main panel with respect to the click in the menu bar.

*Here i am confused like where should I add my menu bar to handle its events.
Can anyone help me out with this


text:
Q: How to update this classic Swift line to a more recent Swift (compatible with Xcode 12 and iOS 14) properly? How to update this classic Swift line to a more recent Swift (compatible with Xcode 12 and iOS 14) properly?:
var sceneData = NSData(bytesNoCopy: path, length: .DataReadingMappedIfSafe, freeWhenDone: true)
Thanks in advance!

A: I trudged through and found a way, so answering the question:
extension SKNode {
            class func unarchiveFromFile(_ file : String) -> SKNode? {
                if let url = Bundle.main.url(forResource: file, withExtension: "sks") {
                    do {
                        var sceneData = try NSData(contentsOfFile: url.absoluteString, options: NSData.ReadingOptions.mappedIfSafe)
                        var archiver = NSKeyedUnarchiver(forReadingWith: sceneData as Data)

                        archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
                        let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! GameScene
                        archiver.finishDecoding()
                        return scene
                    } catch {
                        return nil
                    }
                } else {
                    return nil
                }
            }
}


text:
Q: Help with Jquery autocomplete - nearly finished I've been customizing the Jquery UI auto-complete to ensure that users submit only data from the geonames datasource.
DEMO
Upon selecting a city name I also retrieve the country, latitude, and longitude from the geonames webservice and add them to hidden inputs.
To ensure that people actually select a city from the suggestion list, I clear the input if  you click away from the suggestion list.
(I'm also doing some validation in php)
The issue: after clicking out of the suggestion list, it does not reappear when you type a city name unless you press the spacebar. I'm not sure what is causing this.. Also when you type a city with spaces, sometimes the suggestion list disappears.
Could someone please share some guidance? I also welcome any other suggestions!

A: The autocomplete plugin used to have an option called "mustMatch" - It did what you wanted but has since been removed.
I believe you can re-implement it by following these instructions:
How to implement "mustMatch" and "selectFirst" in jQuery UI Autocomplete?
ANOTHER OPTION:
replace your change (in your revised fiddle) or close (in original fiddle) with the following ugly workaround:
        change: function (event, ui) {
            //if the value of the textbox does not match a suggestion, clear its value
            if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                $(this).val('####');
                $(this).autocomplete("search");
                $(this).val('');
                $(this).autocomplete("close");
            }
        }


text:
Q: how to manage .htaccess in hostinger? I'm trying to upload large video in my web app and send it to vimeo api server-side and my web hosting provider is hostinger, i follow the instructions on their page (this is the link: https://www.hostinger.ph/tutorials/php-maximum-upload-size) on how to maximize the file size so that i can upload large files, I set the values  into this
php_value upload_max_filesize -1
php_value post_max_size -1
php_value max_input_time 0
php_value max_execution_time -1

but still I'm getting error of this. enter image description here(the website has cloudflare security) after two minutes , the video is about 1.2gb, The minimum to upload is 1gb what will be other solution to this? ,,

A: It looks like you want max_input_time = -1 and max_execution_time = 0.
These values seem to be reversed.
Other questions:

*

*Are the PHP values recognised when viewing the configuration in phpinfo()?

*Does the error occur for small uploads? I.e. are any uploads successful with the current configuration?

*How long does it take for the page to time out? I.e. is it consistent for uploads of different sizes?

The documentation advises that "the post_max_size should always be larger than upload_max_filesize to avoid an error when uploading". You may want to set explicit values for testing. E.g. 1500M
Finally, there may be other values (possibly outside of your control) affecting the upload. E.g. memory_limit should be larger than post_max_size.


text:
Q: How to sort an array in-place given an array of target indices? How would you sort a given array arr in-place given an array of target indices ind?
For example:
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [ 4,   0,   5,   2,   1,   3 ];

rearrange(arr, ind);

console.log(arr); // => ["B", "E", "D", "F", "A", "C"]

arr = ["A", "B", "C", "D"];
ind = [ 2,   3,   1,   0 ];

rearrange(arr, ind);

console.log(arr); // => ["D", "C", "A", "B"]

I tried the following algorithm, but it fails on the second example above.
function swap(arr, i, k) {
  var temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
}

function rearrange(arr, ind) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (ind[i] !== i) {
      swap(arr, i, ind[i]);
      swap(ind, i, ind[i]);
    }
  }
}

How would you solve this in O(n) time and O(1) extra space?
Could you provide a proof that your algorithm works?

Note: This question looks similar to this one, but here mutating ind is allowed.

A: The algorithm fails because it has only one loop over the indices of your list.
What happens in your algorithm is this :
i=0 -> ["A", "B", "C", "D"] , [ 2,   3,   1,   0 ]
i=1 -> ["C", "B", "A", "D"] , [ 1,   3,   2,   0 ]
i=2 -> ["C", "D", "A", "B"] , [ 1,   0,   2,   3 ]
i=3 -> ["C", "D", "A", "B"] , [ 1,   0,   2,   3 ]

Note how by the first swap, 1 is in position 0 and you will not visit it again unless you swap it with 0, which does not happen in this example.
What your algorithm misses is an internal loop that runs through sub-cycles of indexes. Try replacing the if by while in rearrange:
function rearrange(arr, ind) {
   for (var i = 0, len = arr.length; i < len; i++) {
      while (ind[i] !== i) {
         swap(arr, i, ind[i]);
         swap(ind, i, ind[i]);
      }
   }
}

Note on complexity: although this is a double loop, complexity does not change because at each swap, one element is correctly placed, and each element is read at most twice (once through the cycling, once though the for loop).
Note on proof: I will not do a complete proof of this algorithm here, but I can give leads. If ind is a permutation, then all elements belong to closed permutative sub-cycles. The while loop ensures that you're iterating entire cycles, the for loop ensures that you're checking for every possible cycle.

A: I suggest to swap until the same index is reached and then take the next outer index.

function swap(arr, i, k) {
    var temp = arr[i];
    arr[i] = arr[k];
    arr[k] = temp;
}

function rearrange(arr, ind) {
    var i = arr.length;
    while (i--) {
        while (ind[i] !== i) {
            swap(arr, i, ind[i]);
            swap(ind, i, ind[i]);
        }
    }
}

var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [ 4,   0,   5,   2,   1,   3 ];

rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]

arr = ["A", "B", "C", "D"];
ind = [ 2,   3,   1,   0 ];

rearrange(arr, ind);
console.log(arr); // => ["D", "C", "A", "B"];

A:
How would you solve this in O(n) time?

By simply using a temporary array and iterating the arrays twice, you can reduce it to O(n)
function rearrange(arr, ind)
{
  var temp = [], len = arr.length;
  //first re-arrange in a new array
  for(var counter = 0; counter < len; counter++)
  {
     temp[ind[counter]] = arr[counter];
  }
  //copy the values as per new indices from temp
  for(var counter = 0; counter < len; counter++)
  {
     arr[counter] = temp[counter];
  }
}

A: If you satisfied with doing that with less complexity method, then there is a one:

*

*Make a new array with length equal to arr length and with empty objects

*splice the new array by the index of ind[i], remove 1 object , and replace it with arr[i]

*Equalize the old array(arr) with the new one

window.onload = function () {

    'use strict';

 var arr = ["A", "B", "C", "D", "E", "F"];
 var ind = [ 4,   0,   3,   2,   1,   5 ];
 var temp = [];

 for (var i = 0; i < arr.length; i++) {
     temp[i] = '';
 }

 for (var v = 0; v < arr.length; v++) {
     temp.splice(ind[v], 1, arr[v]);
 }

 arr = temp;
 console.log(arr);
};

A: I suggest that you return your result in a new array
   function createArray(arr, ind) {
        var result = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            result.push(arr[ind[i]]);
        }
        return result;
    }

This is in O(n) time
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
console.log(createArray(arr,ind))

A: There is a lot of discussion on a similar problem In-place array reordering?
The difference is that in original problem ind[i] is a required index for element arr[i], while in the similar problem i is a required index for element arr[ind[i]]
Going back to the original algorithm, a working alternative may be
function swap(arr, i, k) {
  var temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
}

function rearrange(arr, ind) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (ind[i] !== i) {
      swap(arr, i, ind[i]);
      swap(ind, i, ind[i]);
      if (ind[i] < i) {
        i = ind[i]-1;
      }
    }
  }
}

It's still O(1) space, but it makes redundant checks and may be more complex than O(n)

A: It's a bit faster to "rotate" the cycles rather than use swaps. C example:
    // reorder A in place according to sorted indices in I
    // tA is temp value for A
    for(i = 0; i < n; i++){
        if(i != I[i]){
            tA = A[i];
            k = i;
            while(i != (j = I[k])){
                A[k] = A[j];
                I[k] = k;
                k = j;
            }
            A[k] = tA;
            I[k] = k;
        }
    }


text:
Q: Weird text/characters in input boxes--Help! I just re-opened a website I'm developing, and my submit buttons are freaking out!
I really don't have any idea what happened, and rather than root around the 20+ components I've been working on, I thought I'd ask the experts first.
What can cause this?  Any ideas?
What's going on!? http://img30.imageshack.us/img30/7616/screenshot20100119at221.png

A: Are you using Firefox? Does that button call for Helvetica in its CSS? Do you have Helvetica installed on your system? If the answers to those questions are "yes," then I know your problem. Try reinstalling Helvetica and rebooting.
EDIT: Try looking at the headlines on Smashing Magazine. They use Helvetica. I had this problem before, and it looked like this:


text:
Q: More efficient way to create a list in Ruby Just working with the 2-9 in a deck of cards.
What is the preferred and/or most efficient way to get the deck created in Ruby?
Is it what I have below, or how else can/should I do it?
deck = []
suits = ["spades", "diamonds", "clubs", "hearts"]

for x in suits
  for y in 2..9
    w = y.to_s
    deck.push(w+" of "+x)
  end
end

A: I like product w/ a block
a, suits = [], ["spades", "diamonds", "clubs", "hearts"]
suits.product((2..9).to_a) {|t,n| a << "#{n} of #{t}"}

A: Well, you could just use maps:
suits = ["spades", "diamonds", "clubs", "hearts"]
deck = suits.map { |d| (2..9).map { |x| "#{x} of #{d}" } }.flatten

But the efficiency is mostly the same.

A: suits = ["spades", "diamonds", "clubs", "hearts"]
deck = suits.product((2..9).to_a).map { |x,y| "#{y} of #{x}" }

If you want all 52 cards:
suits = ["spades", "diamonds", "clubs", "hearts"]
faces = { 1 => 'Ace', 11 => 'Jack', 12 => 'Queen', 13 => 'King' }
deck = suits.product((1..13).to_a).map { |x,y| "#{faces[y]||y} of #{x}" }
# => Ace of spades, 2 of spades, ..., King of spades, Ace of diamonds, etc.

A: How about:
suits.flat_map {|s| (2..9).map{|r| "#{r} of #{s}"}}

A: suits, values, deck = %w(spades hearts diamonds clubs), [*2..9], values.product(suits).map { |card| card * ' of ' }