text:
Q: react-native build failing with error code 65 and ___darwin_check_fd_set_overflow I am trying to build a React Native app. I have already worked with other react native projects previously and haven't faced any issues. This time, I am not able to run the app.
I created a new react-native project with:
npx react-native init demoproject

and ran it with:
cd demoproject
npx react-native start
npx react-native run-ios

In the terminal, I got this error:

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening demoproject.xcworkspace. Run CLI with --verbose flag for more details.

When I tried running it with Xcode, I got this error:
Undefined symbols for architecture x86_64:
  "___darwin_check_fd_set_overflow", referenced from:
  _RAND_poll in libcrypto.a(rand_unix.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried these steps without any success.
react-native start --reset-cache
rm -rf node_modules/
rm -rf package-lock.json
cd ios
pod deintegrate
cd ..
rm -rf ios/Podfile.lock
npm install
npm audit fix
react-native link
cd ios
pod install
cd ..
react-native run-ios

Environments:
Xcode: 11.2 (11B52)
OS: mac OS Catalina 10.15.1
react-native-cli: 2.0.1
react-native: 0.62.2

I have a few other react-native projects that I tried and they run successfully. They also run on the same react-native version(0.62.2)
Is there anyway to solve the issue? Will updating Xcode to another version like 11.4 or 11.6 solve the problem?

A: You have to remove Flipper Pod from file goto
Your Project Folder->ios->Podfile and comment Flipper from that file as below
 #use_flipper!
 #post_install do |installer|
   #flipper_post_install(installer)
 #end

Now from ios folder enter below command in terminal
 pod install

It will fix this issue.

A: A temporarily workaround:

*

*Comment all flipper functions in podfile;

*Remove flipperInit in appDelegate.m;

*Run pod install inside ios folder;

*Clean project;

*Run project again.

A: I solved this issue with
1.Comment all the below mentioned 4 flipper function lines in Podfile
use_flipper!
post_install do |installer|
flipper_post_install(installer)
end
2.run pod install
3.run the project.
This resolved my issue.


text:
Q: maxima returns wrong result when using subscripts I am using WxMaxima for some calculations so I can export the results directly into my LaTeX file. I have some Greek variables with Greek subscripts which are giving me a headache. In the past in Maxima I used to put the subscripts in the bracket []. But I have noticed that the conventional LaTeX syntax of _ also works. Except it doesn't work for greek letters:

So I have to use the brackets one [] when I want to subscript the Greek letters with Greek letters. But it is causing some calculation errors.
For example consider two simple functions:
%epsilon[r](r):=c[1]-c[2]/r^2;
%epsilon[%theta](r):=c[1]+c[2]/r^2;

now if I run:
fullratsimp(%epsilon[r](r)+%nu*%epsilon[%theta](r));

it gives me:
((c[1]*%nu+c[1])*r^2+c[2]*%nu+c[2])/r^2

Which is obviously wrong because the correct result can be calculated by:
fullratsimp((c[1]-c[2]/r^2)+%nu*(c[1]+c[2]/r^2));

I would appreciate if you could help me know what is the problem and how I can solve it.

A: The problem is that foo[x1](y) := ... and foo[x2](y) := ... defines just one function foo, and the second definition clobbers the first one, so that only foo[x2](y) := ... is defined.
You can get the effect you want by creating lambda expressions (unnamed functions) and assigning them to subscripted variables.
(%i1) %epsilon[r](r):=c[1]-c[2]/r^2 $
(%i2) %epsilon[%theta](r):=c[1]+c[2]/r^2 $
(%i3) %epsilon[r];
                                  c
                                   2
(%o3)                 lambda([r], -- + c )
                                   2    1
                                  r
(%i4) %epsilon[%theta];
                                  c
                                   2
(%o4)                 lambda([r], -- + c )
                                   2    1
                                  r
(%i5) kill(%epsilon) $
(%i6) %epsilon[r] : lambda([r], c[1]-c[2]/r^2) $
(%i7) %epsilon[%theta] : lambda([r], c[1]+c[2]/r^2) $
(%i8) %epsilon[r];
                                       c
                                        2
(%o8)                 lambda([r], c  - --)
                                   1    2
                                       r
(%i9) %epsilon[%theta];
                                       c
                                        2
(%o9)                 lambda([r], c  + --)
                                   1    2
                                       r
(%i10) fullratsimp(%epsilon[r](r)+%nu*%epsilon[%theta](r));
                                2
                 (c  %nu + c ) r  + c  %nu - c
                   1        1        2        2
(%o10)           ------------------------------
                                2
                               r

Note that foo[x](y) := ... also creates lambda expressions, but you need to ensure your own definition here, not the definition which is created automatically by Maxima.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lagrange multipliers for discrete random variables. In "Elements of Information Theory" (author Thomas Cover) problem 2.30 reads:
Find the probability mass function $p(x)$ which maximizes the entropy $H(X)$ of a non-negative integer valued random variable $X$ subject to the constraint $$F(p)=E[X]=\sum_{n=0}^\infty np(n) = A$$
My approach (confirmed after some internet sleuthing for written solutions online) involves applying Lagrange multipliers to the function $$H(p)=-\sum_{n=0}^\infty p(n)\log p(n)$$ subject to the constraint above as well as $$G(p)=\sum_{n=0}^\infty p(n)=1.$$
That is, assuming there exist scalars $\lambda_1,\lambda_2$ such that $\nabla F(p)=\lambda_1\nabla H(p)+\lambda_2\nabla G(p)$, and using that (with the constraints) to solve for $p$.
I'm worried about the formal validity of applying Lagrange multipliers in this case, since these functions actually live on the infinite-dimensional space $\mathbb{R}^{\mathbb{N}}$ and I don't think the usual arguments justifying the method applies there. I'm also confused as to why the solutions I've seen think it's sufficient to appeal to the concavity of $H(p)$ to argue that a single critical point must yield a global maximimum. There are choices of $p$ for which $H(p)$ is infinite, so surely it isn't clear a priori that these constraints imply a single critical point is a global max.
My question is: is there a formally valid way to use Lagrange multipliers to solve this problem? In what generality can we apply such techniques on real-valued functions with domain $\mathbb{R}^{\mathbb{N}}$?

A: I was thinking about the same problem this week, and I think I found a way to justify the use of Lagrange multipliers, although there are steps I couldn't formally justify (and I hope someone can complete my answer).
Let $S$ be a Hilbert space over $\mathbb{R}$ and $J: S \to \mathbb{R}$ a functional to be maximized. Let $y \in S$ be a local maximum of $J$ and $\eta \in S$, $\epsilon \in \mathbb{R}$. We have:
\begin{equation}
 \label{eq:eq1}
    \tag{1}
    J(y + \epsilon\eta)  = g(\epsilon) = g(0) + g'(0)\epsilon + o(\epsilon)
\end{equation}
For $y$ to be a local maximum, we must have:
\begin{equation}
    \label{eq:eq2}
    \tag{2}
    g'(0) = 0 \implies \frac{\mathrm{d}}{\mathrm{d}\epsilon}J(y + \epsilon\eta) \bigg\rvert_{\epsilon=0} = \delta J_y(\eta) = 0
\end{equation}
Suppose we include a constraint $F: S \to \mathbb{R}$:
\begin{equation}
 \label{eq:eq3}
    \tag{3}
    F(y) = C
\end{equation}
Equation \ref{eq:eq2} must be satisfied for every $\eta$ such that $F(y + \epsilon\eta) = C$. We have:
\begin{equation}
 \label{eq:eq4}
    \tag{4}
    \frac{\mathrm{d}}{\mathrm{d}\epsilon}F(y + \epsilon\eta) = \frac{\mathrm{d}}{\mathrm{d}\epsilon}F(y + \epsilon\eta) \bigg\rvert_{\epsilon=0} = \delta F_y(\eta) = 0
\end{equation}
Then, to find local maximum candidates we have to find values of $y$ such that:
\begin{equation}
 \label{eq:eq5}
    \tag{5}
 \delta J_y(\eta) = 0 \quad \forall \eta \mbox{ such that } \delta F_y(\eta) = 0
\end{equation}
Returning to the entropy problem, let's consider that the probability mass function $p = (p_0, p_1, ...)$ belongs to the Hilbert space of non-negative square summable sequences $\ell^2$ with the inner product $\langle x,y\rangle= \sum_{i=0}^\infty x_i y_i$.
We wish to maximize the entropy $H: \ell^2 \to \mathbb{R}_+$ (where I take the absolute value of $p_i$ because $\ell^2$ may contain sequences with negative elements):
\begin{equation}
 \label{eq:entropy}
    H(p) = -\sum_{i=0}^\infty |p_i| \log |p_i|
\end{equation}
subject to the constraints
\begin{equation}
 \label{eq:constraints}
    \begin{split}
     & F(p) = \sum_{i=0}^\infty p_i = 1 \\
        & G(p) = \sum_{i=0}^\infty ip_i = A
    \end{split}
\end{equation}
We take $q \in \ell^2$ and $\epsilon \in \mathbb{R}$ and we suppose that the optimum $p$ is such that $p_i > 0$ for all $i$ (and that $\epsilon$ is small enough to ensure that $p_i + \epsilon q_i \geq 0$ for all $i$). According to \eqref{eq:eq5}, we have:
\begin{equation}
 \begin{split}
  \delta H_p(q) &= \frac{\mathrm{d}}{\mathrm{d}\epsilon}H(p + \epsilon q) \bigg\rvert_{\epsilon=0} \\ &= - \frac{\mathrm{d}}{\mathrm{d}\epsilon} \left( \sum_{i=0}^\infty (p_i+\epsilon q_i) \log (p_i+\epsilon q_i) \right)\bigg\rvert_{\epsilon=0} \\
        & = -\sum_{i=0}^\infty (1 + \log p_i)q_i = 0
 \end{split}
\end{equation}
for every $q$ such that
\begin{equation}
 \begin{split}
  &\delta F_p(q) = \sum_{i=0}^\infty q_i = 0 \\
        &\delta G_p(q) = \sum_{i=0}^\infty iq_i = 0
 \end{split}
\end{equation}
We conclude that $1 + \log p_i$ must be equal to $\lambda_1 + i\lambda_2$, where $\lambda_1$ and $\lambda_2$ are real constants (the Lagrange multipliers), otherwise we cannot ensure that $\delta H_p(q)$ will be zero. This way, we have:
\begin{equation}
 \delta H_p(q) =  -\sum_{i=0}^\infty (1 + \log p_i)q_i = -\sum_{i=0}^\infty (\lambda_1 + i\lambda_2)q_i = -\lambda_1\sum_{i=0}^\infty q_i - \lambda_2\sum_{i=0}^\infty iq_i = 0
\end{equation}
Summing it up, if the probability mass function $p$ is a local maximum of $H(p)$, it must satisfy:
\begin{equation}
 \label{eq:conclusion}
    \begin{cases}
        &1 + \log p_i = \lambda_1 + i\lambda_2, \quad \forall i \in \mathbb{N} \\
        &\sum_{i=0}^\infty p_i = 1\\
        &\sum_{i=0}^\infty ip_i = A
    \end{cases}
\end{equation}
Which is the same as setting to zero the "gradient" of :
\begin{equation}
 \label{eq:lagrange}
    L(p, \lambda_1, \lambda_2) = -\sum_{i=0}^\infty p_i \log p_i + \lambda_1\left( \sum_{i=0}^\infty p_i - 1\right) + \lambda_2\left( \sum_{i=0}^\infty ip_i - A\right)
\end{equation}
As I said before, there are steps that need to be justified more rigorously and, also, I am not sure about how to use the concavity of $H(p)$ to prove that the probability function that is found using this method is indeed the global optimum, and I hope someone will be able to help me with that!
A few useful references:

*

*Calculus of Variations and Optimal Control Theory (sections 1.2, 1.3, 2.3 and 2.5) http://liberzon.csl.illinois.edu/teaching/cvoc/node1.html

*Functional derivative https://en.wikipedia.org/wiki/Functional_derivative#Entropy


text:
Q: What is the difference between sequence diagram and communication diagram? Could anyone explain me what is the difference between sequence diagram and communication diagram?

A: emphasizing the time ordering of messages (using sequence diagrams)
emphasizing the structural relationships among the objects that interact (using communication diagrams).
reference :UML user manual

A: Sequence diagrams illustrate interactions in a kind of fence format, in which each new object is added to the right.
What might this represent in code? Probably, that class A has a method named doOne and an attribute of type B. Also, that class B has methods named doTwo and doThree. Perhaps the partial definition of class A is:
public class A
   {
   private B myB = new B();

   public void doOne()
   {
   myB.doTwo();
   myB.doThree();
   }
   // . .
   }

Communication diagrams illustrate object interactions in a graph or network format, in which objects can be placed anywhere on the diagram (the essence of their wall sketching advantage).
What are the Strengths and Weaknesses of Sequence vs. Communication Diagrams?
Each diagram type has advantages, and modelers have idiosyncratic preference—there isn't an absolutely "correct" choice. However, UML tools usually emphasize sequence diagrams, because of their greater notational power.
Sequence diagrams have some advantages over communication diagrams. Perhaps first and foremost, the UML specification is more sequence diagram centric—more thought and effort has been put into the notation and semantics. Thus, tool support is better and more notation options are available. Also, it is easier to see the call-flow sequence with sequence diagrams—simply read top to bottom. With communication diagrams we must read the sequence numbers, such as "1:" and "2:". Hence, sequence diagrams are excellent for documentation or to easily read a reverse-engineered call-flow sequence, generated from source code with a UML tool.
But on the other hand, communication diagrams have advantages when applying "UML as sketch" to draw on walls (an Agile Modeling practice) because they are much more space-efficient. This is because the boxes can be easily placed or erased anywhere—horizontal or vertical. Consequently as well, modifying wall sketches is easier with communication diagrams—it is simple (during creative high-change OO design work) to erase a box at one location, draw a new one elsewhere, and sketch a line to it. In contrast, new objects in a sequence diagrams must always be added to the right edge, which is limiting as it quickly consumes and exhausts right-edge space on a page (or wall); free space in the vertical dimension is not efficiently used. Developers doing sequence diagrams on walls rapidly feel the drawing pain when contrasted with communication diagrams.

A: Both diagrams give the same information, but the sequence diagram emphasizes time in its layout and the communication diagram emphasizes the objects that are communicating in its layout.
Time is implicit in sequence diagrams (it is inferred by vertical position), while it is given explicitly in communication diagrams (via numbers).
To quote Scott Ambler

The main difference between communication diagrams and sequence diagrams is that sequence diagrams are good at showing sequential logic but not that good at giving you a "big picture view" whereas communication diagrams are the exact opposite.

A: The below link is the short answer for difference between sequence diagram and communication.
Please refer it.
difference between sequence diagram and communication

A: A fundamental rule in Object Oriented Design is to use different diagrams based on diverse purposes. In this regard, sequence diagrams are used to model sequential logic while to show the behavior of several objects collaborating together to fulfill a common purpose the communication diagrams, formerly known as collaboration diagrams in UML 1.x, can be used. - Read more >> here << and >> here <<


text:
Q: Problema al actualizar datos de objetos usando EditText en un RecyclerView Espero que me entiendan.
Tengo una activity que contiene un RecyclerView. En este llamo datos de una API de algunos productos el cual son listados y el stock de cada artículos queda en un EditText. Necesito verificar si uno o todos los datos son modificados y rescatar en un ArrayList (tal vez) de los objetos ya actualizados al presionar un botón para efectuar la modificación en mi base de datos. Dejo el código a continuación.
activity_minuta_entrega2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.ActivityMinutaEntrega">

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

        <include
            android:id="@+id/news_title"
            layout="@layout/custom_action_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/btn_confirmar_entrega"
            android:layout_below="@+id/news_title"
            android:layout_marginBottom="30dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Datos de entrega"
                android:textSize="20sp"
                android:textStyle="bold" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerView_minuta"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="30dp"
                android:layout_marginRight="10dp" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_confirmar_entrega"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="30dp"
            android:text="Confirmar Edición" />
    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

item_minuta_entrega.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cvItemListRuta"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        app:cardBackgroundColor="@color/light_pitch"
        app:cardCornerRadius="15dp"
        card_view:cardElevation="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="12">

            <LinearLayout
                android:id="@+id/status_bar_ruta"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal">

                <CheckBox
                    android:id="@+id/checkbox_total"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_gravity="center" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/layout_textos"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="6"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/txt_name_article"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center_vertical"
                        android:text="Articulo" />

                    <TextView
                        android:id="@+id/txt_description_article"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center_vertical"
                        android:text="descripcion " />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="5"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/btn_sustrac"
                    android:layout_width="45dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center_vertical"
                    android:text="-"
                    android:textSize="18sp" />

                <EditText
                    android:id="@+id/edt_cantidad"
                    android:layout_width="60dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:gravity="center"
                    android:inputType="number"
                    android:textSize="18sp" />

                <Button
                    android:id="@+id/btn_add"
                    android:layout_width="45dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center_vertical"
                    android:text="+"
                    android:textSize="18sp" />

            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

ActivityMinutaEntrega.java
public class ActivityMinutaEntrega extends AppCompatActivity {
    @BindView(R.id.txt_nombre_ruta)
    TextView txt_ruta;
    private RutasSingleton rutasSingleton;
    RecyclerView recycle_lista_minuta_entrega;
    private MinutaEntregaAdapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;
    private RutaDetalleSingleton rutaDetalleSingleton;
    private Button btn_confirmar_entrega;

    private ArrayList<BultosDetalle> bultosDetalleArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        layoutManager = new LinearLayoutManager(this);
        rutasSingleton = RutasSingleton.getInstance();
        rutaDetalleSingleton = RutaDetalleSingleton.getInstance();
        setContentView(R.layout.activity_minuta_entrega2);
        ButterKnife.bind(this);

        txt_ruta.setText("Ruta:" + rutasSingleton.getRutaId());

        btn_confirmar_entrega = findViewById(R.id.btn_confirmar_entrega);

        recycle_lista_minuta_entrega = findViewById(R.id.recyclerView_minuta);
        traerDetalleBultos(String.valueOf(rutaDetalleSingleton.getRutaDetId()));

        btn_confirmar_entrega.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    public void traerDetalleBultos(String rutasdetid) {

        DetalleBultoServiceApi detalleBultoServiceApi = new DetalleBultoServiceApi();
        final ProgressDialog progressDialog = new ProgressDialog(ActivityMinutaEntrega.this);
        progressDialog.setCancelable(false); // set cancelable to false
        progressDialog.setMessage("Please Wait"); // set message
        progressDialog.show();

        mAdapter = new MinutaEntregaAdapter(detalleBultoServiceApi.traerBultosDetalle(ActivityMinutaEntrega.this, rutasdetid, new DetalleBultoResponseListener() {
            @Override
            public void requestStarted() {

            }

            @Override
            public void requestCompleted() {
                progressDialog.dismiss();

                recycle_lista_minuta_entrega.setHasFixedSize(true);
                recycle_lista_minuta_entrega.setLayoutManager(layoutManager);
                recycle_lista_minuta_entrega.setAdapter(mAdapter);
            }

            @Override
            public void requestEndedWithError(VolleyError error) {
                progressDialog.dismiss();
                Log.d("error", "" + error);
            }
        }));
    }
}

DetalleBultoServiceApi.java
public class DetalleBultoServiceApi {

    DetalleBultoResponseListener mListener;
    ArrayList<BultosDetalle> bultos;
    BultosDetalle bulto;

    public ArrayList<BultosDetalle> traerBultosDetalle(Context context, String rutasDetId, DetalleBultoResponseListener mlistener) {
        this.mListener = mlistener;
        bultos = new ArrayList<>();
        mListener.requestStarted();
        DatosUsuario datosUsuario = DatosUsuario.getInstance();

        try {
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            JSONObject jsonBody = new JSONObject();
            jsonBody.put(TAG_USUARIO,datosUsuario.getUsername());
            jsonBody.put(TAG_CLAVE, datosUsuario.getPass());
            jsonBody.put(TAG_SIM,datosUsuario.getSim());
            jsonBody.put(TAG_RUTAS_DETALLE_ID, rutasDetId);

                MyJsonArrayRequest stringRequest = new MyJsonArrayRequest(Request.Method.POST, Config.BASE_URL + Config.API_DETALLE_BULTO, jsonBody, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.i("LOG_RESPONSE", response.toString());

                    JSONObject jsbulto = null;
                    try {

                        if (response != null) {
                            BultoSingleton bultoSingleton = BultoSingleton.getInstance();
                            for (int i = 0; i < response.length(); i++) {
                                jsbulto = response.getJSONObject(i);
                                bulto = new BultosDetalle();

                                bulto.setRutasDetId(jsbulto.getInt(TAG_RUTAS_DETALLE_ID));
                                bulto.setBultos(jsbulto.getInt(TAG_BULTO));
                                bulto.setCodigoArticulo(jsbulto.getString(TAG_CODIGO_ARTICULO));
                                bulto.setDescripcion(jsbulto.getString(TAG_DESCRIPCION));
                                bulto.setUnidadMedida(jsbulto.getString(TAG_UNIDAD_MEDIDA));
                                bulto.setNumeroSerie(jsbulto.getString(TAG_NUMERO_SERIE));
                                bulto.setFechaVecto(jsbulto.getString(TAG_FECHA_VENCICMIENTO));
                                bulto.setArmado(jsbulto.getInt(TAG_ARMADO));
                                bulto.setRevisionDetId(jsbulto.getInt(TAG_REVISION_DET_ID));
                                bulto.setEanTrece(jsbulto.getString(TAG_EAN_TRECE));

                                if (bultoSingleton.getNroBulto() == bulto.getBultos()){
                                    bultos.add(bulto);

                                }
                            }
                        }
                        mListener.requestCompleted();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("LOG_RESPONSE", error.toString());
                    mListener.requestEndedWithError(error);
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    return params;
                }

            };

            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();

        }
        return bultos;
    }
}

MinutaEntregaAdapter.java
public class MinutaEntregaAdapter extends RecyclerView.Adapter<MinutaEntregaAdapter.MinutaEntregaViewHolder>{

    private List<BultosDetalle> mDataset;
    private static ClickListener clickListener;
    private BultoSingleton bultoSingleton;
    private int cant;
    private String[] array;

    public List<BultosDetalle> getmDataset() {
        return mDataset;

    }

    public static class MinutaEntregaViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        public TextView txt_articulo, txt_descripcion;
        public EditText cantidad;
        public Button btn_add, btn_disc;
        public CheckBox status;

        public MinutaEntregaViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_articulo = itemView.findViewById(R.id.txt_name_article);
            txt_descripcion = itemView.findViewById(R.id.txt_description_article);
            cantidad = itemView.findViewById(R.id.edt_cantidad);
            btn_add = itemView.findViewById(R.id.btn_add);
            btn_disc = itemView.findViewById(R.id.btn_sustrac);
            status = itemView.findViewById(R.id.checkbox_total);
        }

        @Override
        public void onClick(View view) {
            clickListener.onItemClick(getAdapterPosition(), view);
        }

        @Override
        public boolean onLongClick(View view) {
            clickListener.onItemLongClick(getAdapterPosition(), view);
            return false;
        }
    }

    public void setOnItemClickListener(ClickListener clickListener) {
        MinutaEntregaAdapter.clickListener = clickListener;
    }

    public interface ClickListener {
        void onItemClick(int position, View v);

        void onItemLongClick(int position, View v);
    }

    public MinutaEntregaAdapter(List<BultosDetalle> mDataset) {
        this.mDataset = mDataset;
    }

    @NonNull
    @Override
    public MinutaEntregaAdapter.MinutaEntregaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View listItem = layoutInflater.inflate(R.layout.item_minuta_entrega, parent, false);
        MinutaEntregaAdapter.MinutaEntregaViewHolder viewHolder = new MinutaEntregaAdapter.MinutaEntregaViewHolder(listItem);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MinutaEntregaViewHolder holder, int position) {

        bultoSingleton = BultoSingleton.getInstance();

        holder.txt_articulo.setText(mDataset.get(position).getCodigoArticulo());
        holder.txt_descripcion.setText(mDataset.get(position).getDescripcion());

        holder.cantidad.setText(String.valueOf(mDataset.get(position).getArmado()));

        holder.status.setOnCheckedChangeListener(null);
        holder.status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.status.isChecked()) {
                    holder.cantidad.setText("0");
                    cant = 0;
                } else {
                    holder.cantidad.setText(String.valueOf(mDataset.get(position).getArmado()));
                    cant = mDataset.get(position).getArmado();
                }
            }
        });

        holder.btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.cantidad.getText().toString().trim().equals("")){
                    cant = 0;
                } else {
                    cant = Integer.parseInt(holder.cantidad.getText().toString());
                }
                cant++;
                holder.cantidad.setText(String.valueOf(cant));
            }
        });

        holder.btn_disc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.cantidad.getText().toString().trim().equals("")){
                    cant = 0;
                } else {
                    cant = Integer.parseInt(holder.cantidad.getText().toString());
                }

                if (cant == 0){
                    Toast.makeText(view.getContext(), "La cantidad de arículos no puede ser menor a 0", Toast.LENGTH_SHORT).show();
                } else {
                    cant--;
                }
                holder.cantidad.setText(String.valueOf(cant));
            }
        });

        holder.cantidad.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (holder.cantidad.getText().toString().trim().equals("")) {
                    holder.cantidad.setText("0");
                    cant = 0;
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }
}

El valor que aparece en los EditText son los que rescato de la BD.
Cualquier información extra intentaré responder a la brevedad.

A: Si actualizas los datos que obtienes al consultar una API y quieres que estos cambios se reflejen en tu RecyclerView, simplemente debes notificar este cambio al Adapter mediante el método notifyDataSetChanged():
mAdapter.notifyDataSetChanged();

notifyDataSetChanged() Notifica a los observadores adjuntos que
  los datos subyacentes han cambiado y que cualquier Vista que refleje
  el conjunto de datos debería actualizarse.


text:
Q: Check and extract composition args in sympy python i want to check if an expression is a composition of two functions and extract the args for example
Log(x-1) :

i want get :
[log(x),x-1]

and
sin(x)/(1-sin(x))

i want get :
[x/(1-x),sin(x)]

are there any sympy function or should i do it by myself

A: There isn't a simple function that does it. You could use cse to pull out common subexpressions and expr.args to pull out non-common subexpressions from those.


text:
Q: Run Time Error 1004 - Reference isn't valid I am getting the highlighted error shown in the photo on this piece of coding. It worked absolutely fine last month and the error has appeared when i've rolled the file over for a new month.
Any idea how I can get around this?
Many thanks!


text:
Q: Inseting table inside table in angularjs With reference to this code,if I am having three columcolumns (eg: including mrks after sub and the mrkd also have different number of rows like subjects.What change should I do now?
add multiple rows in one column using angular ng-repeat

A: I have updated the fiddle mentioned in the answer of mentioned question.
I have just added below code in html :
<td>{{subject.mark}}</td>
And added the mark in users object.
Please refer UpdatedFiddle


text:
Q: Where is the latest revision of subsonic 3? When I click the big download button at
http://github.com/subsonic/SubSonic-3.0
I don't know what version I'm getting. On the download panel there are 3 additional versions listed for download. Which is the most recent, the default or 3.0.0.3?
And does the big download button get me everything for that version?

A: On GitHub, when you click the "Download" button (not the tab), you will download the latest revision (known as the master branch in Git) in the repository. This is potentially untested code and should be avoided in production environments.
To answer your question specifically, you should download 3.0.0.3 unless you want potentially untested, beta-quality code.
For more reliable information, check the SubSonic Download page.


text:
Q: Fixed subfield of the field of rational functions
Let $K(X)$ be the field of rational functions of $X$ over some field $K$. Let $\phi: K(X) \rightarrow K(X)$ be the $K$-morphism such that $\phi (X)=1-X$. We have $L:=\{ f\in K(X) : \phi (f)=f\}$. Find some element $Y \in K(X)$ such that $K(Y)=L$.

I am fairly certain that $Y=(2X-1)^{2}$ and can easily show that $K(Y) \subset L$. I am having some trouble with showing that $L \subset K(Y)$.

A: Here's another method. You know that your transformation $\phi$ is of order two, and that the "conjugate" of $X$ is $1-X$. The minimal polynomial for $X$ over the fixed field is accordingly $f(T)=T^2-T+(X(1-X))$. Here I've used the sum of the conjugates for the linear coefficient (with the necessary change of sign) and the product of the conjugates for the constant term. So it would seem that the fixed field is $K(X(1-X))$. Indeed, if we call $X(1-X)=\xi$ temporarily, we certainly know that $K(\xi)$ is a good field, and that $X$ is a root of $T^2-T+\xi$, with the property that it generates $K(X)$. Notice that this proof works just as well in characteristic two.

A: If $\operatorname{char}(K)\neq 2$, then $X$ satisfies a polynomial of degree $2$ over $K(Y)$ (namely, $p(t)=(2t-1)^2-Y$), so $[K(X):K(Y)]\leq 2$.  Since $K(Y)\subseteq L\subset K(X)$, it follows that $K(Y)=L$.
If $\operatorname{char}(K)=2$, on the other hand, this doesn't work (the polynomial $p(t)$ used above is identically $0$).  And in fact it is clear that $K(Y)\neq L$, since $Y=1$ so $K(Y)$ is just $K$ in this case.  So you need to find a different $Y$.  As a hint, you can notice that since $\phi\circ\phi$ is the identity, $f\phi(f)\in L$ for any $f\in K(X)$.


text:
Q: How can I use Javascript to loop through HTML elements and remove inline attributes? I was working with an online store platform that doesn't provide full editing access to the HTML on page and was looking for a vanilla JS solution to remove various inline styling which I can't remove directly.
I was interested in a reusable function for such a purpose, so that I could use this type of capability on another project later.

A: My solution involved the creation of a two dimensional array and two helper functions. I hope someone else finds this useful on one of their projects:
Step 1 - Setup element/node list
The first part of this is to fill your application what elements you want to work with. This nested arrays have two values: the CSS selector for the element in question, and a boolean (true/false) flag to indicate if that element's children should also have their attributes removed.
var element_array = [
    ['.selector', true],
    ['.other-selector', false]
];

Step 2: Setup inline attribute array
The next step is to indicate which HTML attributes you want to remove from each element. Each is simply entered into an array:
var remove_attributes_array = [
    'style',
    'align',
    'border',
    'cellpadding',
    'cellspacing',
    'width',
    'height'
];

Step 3: Setup helper functions
The helper functions perform the logic of searching through the elements and removing their inline styles.
Function 1: agnostize_element_styles(array);
This function loops through the element_array variable (array literal from step 1) and executes the second function (which actually removes the attributes). If the 2nd array value is true, then that element's children are iterated over and their inline attributes are also removed.
Function source
function agnostize_element_styles(array) {
    for(var i = 0; i < array.length; i++)
    {
        var element_list = document.querySelectorAll(array[i][0]);

        for(var i = 0; i < element_list.length; i++)
        {
            inline_html_attributes( element_list[i], remove_attributes_array );

            if( array[i][1] === true && element_list[i].hasChildNodes() )
            {
                var child_nodes = element_list[i].querySelectorAll('*');

                for(var i = 0; i < child_nodes.length; i++)
                {
                    inline_html_attributes( child_nodes[i], remove_attributes_array );
                }
            }
        }
    }
}

Function 2: inline_html_attributes(element);
This function accepts an element as an argument, then removes all inline attributes which were specified in step 2's array variable.
Function source:
function inline_html_attributes(element, attribute_array) {

    for(var i = 0; i < attribute_array.length; i++)
    {
        element.removeAttribute(attribute_array[i]);
    }
}

Step 5: Call Function 1 using the Step 1 array
To make all of this work, simply run the first function (agnostize_element_styles) passing in the two dimensional array from Step 1 as an argument:
agnostize_element_styles(element_array);
View Full Code
var element_array = [
    ['.selector', true],
    ['.other-selector', false]
];

var remove_attributes_array = [
    'style',
    'align',
    'border',
    'cellpadding',
    'cellspacing',
    'width',
    'height'
];

function agnostize_element_styles(array) {
    for(var i = 0; i < array.length; i++)
    {
        var element_list = document.querySelectorAll(array[i][0]);

        for(var i = 0; i < element_list.length; i++)
        {
            inline_html_attributes( element_list[i], remove_attributes_array );

            if( array[i][1] === true && element_list[i].hasChildNodes() )
            {
                var child_nodes = element_list[i].querySelectorAll('*');

                for(var i = 0; i < child_nodes.length; i++)
                {
                    inline_html_attributes( child_nodes[i], remove_attributes_array );
                }
            }
        }
    }
}

function inline_html_attributes(element, attribute_array) {

    for(var i = 0; i < attribute_array.length; i++)
    {
        element.removeAttribute(attribute_array[i]);
    }
}

agnostize_element_styles(element_array);


text:
Q: Qt hide column in QTableView I want to hide the ID column in the QtableView and i can't do that on my implementation. Can anyone help me?
void MainWindow::on_actionClear_Search_triggered()
{
model = new QStandardItemModel(cars.size(),6,this);
//create header
createHeader(model);
//set data to the table view
populate(cars);

ui->tableView->setColumnHidden(6,true);
ui->tableView->setModel(model);

}

void MainWindow::createHeader(QStandardItemModel *model){

model->setHorizontalHeaderItem(0,new QStandardItem("Car"));
model->setHorizontalHeaderItem(1, new QStandardItem("Type"));
model->setHorizontalHeaderItem(2, new QStandardItem("Mileage"));
model->setHorizontalHeaderItem(3, new QStandardItem("Year"));
model->setHorizontalHeaderItem(4, new QStandardItem("Is registered"));
model->setHorizontalHeaderItem(5, new QStandardItem("ID"));
}

void MainWindow::populate(const QList<Vehicle> &vehicles)
{
int j = 0;
QList<Vehicle>::ConstIterator iter;
for( iter= vehicles.begin(); iter != vehicles.end(); iter++){
    const Vehicle& car = *iter;
    //set car
    QString makeAndModel = car.getGeneralData().getMake() + car.getGeneralData().getModel();
    QStandardItem *mAndM = new QStandardItem(QString(makeAndModel));
    mAndM->setEditable(false);
    model->setItem(j,0,mAndM);

    //set type
    QStandardItem *type = new QStandardItem(QString(car.getGeneralData().getType()));
    type->setEditable(false);
    model->setItem(j,1,type);

    //set mileage
    QString mileageString = QString::number(car.getGeneralData().getMileage());
    QStandardItem *mileage = new QStandardItem(QString(mileageString));
    mileage->setEditable(false);
    model->setItem(j,2,mileage);

    //set year
    QString yearString = QString::number(car.getGeneralData().getYear());
    QStandardItem *year = new QStandardItem(QString(yearString));
    year->setEditable(false);
    model->setItem(j,3,year);

    //set registration
    QString regString = VehicleHelper::convertBoolToString(car.getRegistration().isRegistered());
    QStandardItem *regDate = new QStandardItem(QString(regString));
    regDate->setEditable(false);
    model->setItem(j,4,regDate);

    //set ID column
    QStandardItem *idNumber = new QStandardItem(QString(car.getVehicleID().getID()));
    idNumber->setEditable(false);
    model->setItem(j,5,idNumber);
    j++;
}

}

A: You use ui->tableView->setColumnHidden(6, true);, but there is no column with index 6. You should write ui->tableView->setColumnHidden(5, true); instead, because ID column number is rather 5 than 6.
UPDATE:
You also need to hide column(s) after you set the model to the view, i.e:
ui->tableView->setModel(model);
ui->tableView->setColumnHidden(5, true);

A: Another approach is set specified column's width to zero : ui->tableView->setColumnWidth(col,0); ui->tableWidget->setColumnWidth(col,0);.

A: Ui->tableView->horizontalHeader()->hideSection(col);
where col - number of table column


text:
Q: Error: The Bumblebee daemon has not been started I saw that there are some posts about that, but any of them I can find the solution to fix mine. I have a Sony Vaio vpcz11c5e with Ubuntu 11.10.
Graphics:

*

*Nvidia GeForce GT 330M

*Intel graphics

I followed BumbleBee on wiki.ubuntu.com but when I run: sudo optirun glxspheres I get:
[ 3399.786675] [ERROR]The Bumblebee daemon has not been started yet or the socket path /var/run/bumblebee.socket was incorrect.
[ 3399.786711] [ERROR]Could not connect to bumblebee daemon - is it running?

I tried to follow all the other posts but I could not get with the error.
I am kind of Ubuntu new player, so if you need to know the kernel version or something like this, specify the command so we could go faster please.
Error message on
more  /var/log/syslog | grep bumblebeed

Mar  4 20:50:39 xinxi-VPCZ11C5E bumblebeed[4187]: Module bbswitch could not be loaded (timeout?)
Mar  4 20:50:39 xinxi-VPCZ11C5E bumblebeed[4187]: No switching method available. The dedicated card will always be on.
Mar  4 20:50:39 xinxi-VPCZ11C5E bumblebeed[4187]: Invalid configuration: no driver configured.


text:
Q: Node gets wrong HTML from package.json when executing npm start I have a package.json file that looks like:
{
  "name": "assignment-1",
  "version": "1.0.0",
  "description": "This is the Git and Node basic learning project",
  "main": "aboutus.html",
  "scripts": {
    "start": "npm run lite",
    "test": "echo \"Error: no test specified\" && exit 1",
    "lite": "lite-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://path_to_git/first-assignment.git"
  },
  "author": "",
  "license": "ISC",
  "homepage": "https://path_to_git/first-assignment#readme",
  "devDependencies": {
    "lite-server": "^2.2.2"
  },
  "bugs": {
    "url": "https://path_to_git/first-assignment/issues"
  },

but when I execute npm start, instead of aboutus.html, the index.html webpage opens.
Any idea what I am doing wrong and I don't get the aboutus.html loading as I want it to?

A: I think I've found the solution:
The index.html appears as the default page, in localhost:3000. Then I simply need to write localhost:3000/aboutus.html to get to the page I wanted to go... Seems like it was pretty simple after all!


text:
Q: Trying to change my image - ADD to ADDED when onclick on the img, no idea how to go about it. I am new to React import React, { useState } from 'react';
import NavBar from "../../components/navBar/navbar";
import "./profile.scss"
import add from './Images/add.png'
import added from './Images/added.png'

const Profile = () => {

    return (

        <NavBar/>

    )
}

export default Profile;

This is the section im having troubles with. Ive tried lots of online methods but constantly ran into errors and cant seem to find a definitive way to onclick change image with ReactJS

A: just simply use the useState to keep track of your image, something like this:
import React, { useState } from "react";
import NavBar from "../../components/navBar/navbar";
import "./profile.scss";
import add from "./Images/add.png";
import added from "./Images/added.png";

const Profile = () => {
  const [image, setImage] = useState("left");

  const handleClick = () => {
    if (image === "left") {
      setImage("right");
    } else {
      setImage("left");
    }
  };

  return (

      <NavBar />

         handleClick()}
        />

  );
};

A: I ended up fixing this issue by using state as above mentioned like this. Thank you for the reply <3
const [isFollowed, setIsFollowed] = useState(false);
const [isFollowedtext, setIsFollowedtext] = useState(false);

const followHandler = () => {
        setIsFollowed(!isFollowed);
        setIsFollowedtext(!isFollowedtext);
      };

{isFollowed ?

Connected with user!
 :
Connect with user!
}

{isFollowedtext ?
 : }


text:
Q: custom sound not working in unnotificationrequest ios 10 objC custom sound not working in unnotificationrequest - iOS 10
I tried :
[UNNotificationSound soundNamed:@"Alarm.mp3"]
or
[UNNotificationSound soundNamed:@"Alarm"]
and the file is exist in bundle or Library/Sounds
but always played default sound when app is in background.
is anybody know why?

A: It appears there's a bug in iOS 10. If you delete your app from the iPhone or Simulator and install fresh, your custom sounds should work fine. It's only when you re-run the app from Xcode do the custom sounds stop working.
It also appears that updates to an app through TestFlight/HockeyApp and presumably from the App Store itself will break the custom sounds. I'd count on Apple fixing this in future releases.
There's a conversation about this bug on the Apple Developer Forums, and multiple radars have been filed.


text:
Q: PHP force download of a .app file? I am trying to force the download of a .app file..
Tried the following but its just giving me a empty .app file:
<?php
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=Application.app");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

?>

A: Replace
header("Content-Type: application/zip");

with
header("Content-Type: application/octet-stream");

and then output your file with i.e. readfile(). And I'd also suggest to get rid of ?> tag. So it should be:
<?php
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=Application.app");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");

readfile('Application.app');     // replace Application.app with right filename or full path to subject file

A: Add this line at the end:
readfile('Application.app');

Because you are not outputting the file content.

A: <?php
$file = "http://example.com/application.app";

header("Content-Description: File Transfer");
header("Content-Type: application/zip");  // proper octet-stream
header("Content-Disposition: attachment; filename=\"$file\"");

readfile ($file);
?>

If the file is not opening with the browser..
<?php header("Location: http://example.com/application.app"); ?>


text:
Q: How to fill the html form in jsp with the dispatched data from servlet? I am new to JSP and Servlet. I need your suggestion in following task.
I have a jsp page which hava a html form which accepts some information from user.
JSP page
info.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<%
    if(request.getAttribute("reply")!=null){
        out.println(request.getAttribute("reply"));
    }
%>

<form action="actionservlet" method="post" name="myform">
user Name:<input name="username" type="text" size="10" />

First Name:<input name="username" type="text" size="10" />

Last Name:<input name="username" type="text" size="10" />

Email id:<input name="username" type="text" size="10" />

<input name="submit" type="submit" value="Submit" />
<input name="Reset" type="reset" value="Reset" />

</form>

As this client enters information and submits the form the data in the form is set to actionservlet which check whether the username entered by user
is already exists in database. If username already exists then it sends the data back to the calling jsp and with an extra attribute that is "reply" and value as
appropriate message. i.e. "user already exists " if entered user name is already exists in database or "user information saved successfully!" if data saved successfully.
I want to do something like that Whenever the username which is already exists is entered by user and form submitted then in this case the all data send back to the jsp
should be get fill to their respective textbox. So that user can only enter the other username and submit this form again.
How to achieve the above task.
I am thinking of adding jsp scriplet to value property of each textbox and check that whether this replay message. if the reply message is regarding
duplicate username then it should assign the value to value property else the value property will remain empty. But I think that this solution is not optimum
because as the number of fields will increases in the form this solution will get little bit tedious. And also I think due to this the it give rise to some
sort of redundant code.
    So I want to ask experts that is there any other way to do the same. I want to fill the form only when the error or duplicate message comes and not
when success message comes.
Thank You!

A: Using Java code in JSP is a bad practice and Scriptlets are outdated, you should avoid using it.
JSP 2.0 Expression Language is the solution. Download jstl.jar and add it to your classpath.
JSP
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

${reply}

<form action="actionservlet" method="post" name="myform">
user Name:<input name="username" type="text" size="10" />

First Name:<input name="firstName" type="text" size="10" value=${firstName}/>

Last Name:<input name="lastName" type="text" size="10" value=${lastName}/>

Email id:<input name="email" type="text" size="10" value=${email}/>

<input name="submit" type="submit" value="Submit" />
<input name="Reset" type="reset" value="Reset" />
</form>

Get parameters in the Servlet. Perform operation/task you want to do.
Set request attributes in your Servlet. Forward page to JSP.
Servlet:
String firstName = request.getParameter("firstName");
// and so on get other form parameters..
// perform your opeations

request.setAttribute("reply", "User Already Exists"); // Just an example
request.setAttribute("firstName", firstName);
// set other form parameters..

RequestDispatcher dispatcher =
request.getRequestDispatcher("/el/scoped-vars.jsp");
dispatcher.forward(request, response);

Check more on this link if Expression Language does not work.
Read basic Expression Language : http://pdf.coreservlets.com/JSP-EL.pdf


text:
Q: Pandas UDF Function Takes Unusually Long to Complete on Big Data I'm new to PySpark and Pandas UDFs, I'm running the following Pandas UDF Function to jumble a column containing strings (For Example: an input 'Luke' will result in 'ulek')
pandas_udf("string")
def jumble_string(column: pd.Series)-> pd.Series:
  return column.apply(lambda x: None if x==None else ''.join(random.sample(x, len(x))).lower())

spark_df = spark_df.withColumn("names", jumble_string("names"))

On running the above function on a large dataset I've noticed that the execution takes unusually long.
I'm guessing the .apply function has something to do with this issue.
Is there anyway I can rewrite this function so it can effectively execute on a Big Dataset?
Please Advise

A: As the .apply method is not vectorized, the given operation is done by looping through the elements which slows down the execution as the data size becomes large.
For small sized data, the time difference is usually negligible. However, as the size increases, the difference starts to become noticeable. We are likely to deal with vast amount of data so time should always be taken into consideration.
You can read more about Apply vs Vectorized Operations here.
Therefore I decided to use a list comprehension which did increase my performance marginally.
@pandas_udf("string")
def jumble_string(column: pd.Series)-> pd.Series:
  return pd.Series([None if x==None else ''.join(random.sample(x, len(x))).lower() for x in column])

A: There is no implemented function in Spark that jumbles the strings in a column, so we are forced to resort to UDFs or Pandas UDFs.
Your solution is actually quite nice; perhaps we can improve it by removing the .apply method from the series and using only base Python on a string for each row.
@pandas_udf("string")
def jumble_string_new(column: pd.Series)-> pd.Series:
  x = column.iloc[0]   # each pd.Series is made only of one element
  if x is None:
    return pd.Series([None])
  else:
    return pd.Series([''.join(random.sample(x, len(x))).lower()])

The results are the same to your function; however, I've not been able to test it on a very large dataframe. Try it yourself and see whether it's computationally more efficient.


text:
Q: Connect localhost database to web application? I'm very new to web development in general. I have a database on localhost that will receive requests from my Heroku web app. Can I use SimpleHTTPServer for the case? or it has to be other modules like ngrok which I don't want to use because it renames its HTTP every time it restarts or is there some way to navigate the problem?

A: In order for your local database to receive requests from the internet, it will need to be reachable by a public address.
One way to have a stable public address is to use a paid ngrok plan which will allow you to reserve a TCP address.
With a reserved TCP address, you can start a ngrok tunnel that will forward traffic to your local database with something like ngrok tcp --remote-addr=<your reserved TCP address> <database port>.


text:
Q: How to fetch categories of an article in joomla? I have a joomla theme and bringing latest recent 6 articles, now i want to print categories of those articles as well on my theme. I'm new in joomla any help please

A: You should check out any Joomla Module which displays latest articles. There you can see how they access category names. Maybe you can use the module directly.
Checkout the helper.php from \modules\mod_articles_latest.

A: You don't say what version you are using but it's a standard parameter option to display an article's category. Look in the long list of options for show/hide category and set it to show.


text:
Q: DirectX - BackBuffer concept I am new to DirectX, and after spending some time in reading the documentation I came to know that there are two video buffers, the FrontBuffer and the BackBuffer. I am performing a POC to verify the fastest method of screen capture, and the BackBuffer, according to some sources might do this trick. (FrontBuffer access is too slow for me)
But unfortunately there aren't so many good articles on the internet that explains the theory in detail. I have some questions that also might help others, if answered.

*

*Is the back buffer simply a surface where an application can write into?

*Is the back buffer application specific? i.e. separate back buffer for each DX app?

*If I am running some app which shows some data on screen using DirectX, can I capture its back buffer? (According to FRAPS analysis a DLL can be hooked to the app to do this. But any guidelines?)

A: *

*Yes. Depending on which version of DirectX you use, the back buffer is a surface or texture created as a render target.

*Yes. Every application has its own back and front buffer. An application is not even limited to using one back buffer. Instead it could use three or more buffers or no back buffer at all.

*Well, I am not an expert at hooking DirectX applications, but this should be possible. Basically, you would replace the Present method with a method that captures the buffer before presenting it. See here for some additional Information.


text:
Q: how to intercept innerHTML changes in javascript? I need to intercept any changes in the content of a cell inside my webpage.
The following code shows me that addEventListener does not work.
function modifyText() {
alert("!");
}

var el=document.getElementById("mycell");
el.innerHTML="a"
el.addEventListener("change", modifyText, false);
// After next instruction I expect an alert message but it does not appear...
el.innerHTML="Z";

The code is just a toy example. In my real case the changes in the page (and therefore in the cell, too) are made by a webapp that I have NO control over.

A: There is a modern way to catch innerhtml changes:
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
Example:
// identify an element to observe
elementToObserve = window.document.getElementById('y-range').children[0];

// create a new instance of 'MutationObserver' named 'observer',
// passing it a callback function
observer = new MutationObserver(function(mutationsList, observer) {
    console.log(mutationsList);
});

// call 'observe' on that MutationObserver instance,
// passing it the element to observe, and the options object
observer.observe(elementToObserve, {characterData: false, childList: true, attributes: false});

childList mutation fires on innerHTML change.

A: You can't listen to a DOM element change that way. change event is mostly for inputs
There is some other new DOM 3 events that would help you on this.
Here is some:
DOMCharacterDataModified  //Draft
DOMSubtreeModified

A: Does this Most efficient method of detecting/monitoring DOM changes? help?
It seems like there aren't any 100% cross browser solutions, and one of the workarounds is to poll the elements of interest to see if their innerHTML.length changes!


text:
Q: Page Transition in JSF I am working on a web application using JSF and Hibernate framework. I created the following sub folders views, products and users under the WEB-INF for my xhtml views as shown below
WEB-INF
--views
-----products
---------createProduct.xhtml
-----users
---------createUser.xhtml
Using  tag, I specify "/WEB-INF/views/products/createProduct.xhtml" as the outcome attribute which the navigation case is matched. The problem is when I run the project and click on the link, it is not rendered or parsed appropriately, rather it appears as localhost:8080/appname/WEB-INF/views/products/createProduct.xhtml thereby returning Http 404 error.
Also, I have two template clients jsf created from a single template called "mainTemplate". The mainTemplate contains some  with an action attribute bound to a bean method. However, I noticed that when I run the project and open two different pages, the commandButton mentioned earlier has two different action attribute which shows the viewID rather than the bean method it is bound to.
Any suggestion to get me moving pass this stage will be appreciated.
Thanks
kalis

A: You cannot access files directly inside Web-Inf folder.  So place your files outside WEB-INF folder.
Still if your problem is not solved, update the question with the code you have used.
Read this
What is WEB-INF used for in a Java EE web application?
for more details.


text:
Q: Selected value from dropdown into PHP variable I know many people have been asking the same thing, but I don't seem to get anywhere with this. How do I extract the value from my select drop down and put it into a Php variable. I need variable for calling the database later.
This is my select list in html:
<form action="" method="post">

STREAM

    <select name="selectStream">
    <?php foreach($array as $option) : ?>
        <option value="<?php echo $option->ID; ?>"><?php echo   $option->stream_name; ?></option>
    <?php endforeach?>
    </select>
    <input type="submit" name="formStream" value="Select">
</form>

My result from a mysqli call is already in the $array. I would then like to use the selected value from this form and simply even just echo it. I can get the information from MySQL into the drop down, but getting the selected variable out is a nightmare. I've been trying to capture this with:
if(isset($_POST['formStream']))
{
  $selected = $_POST['selectedStream'];
  echo "This is what I get: ".$selected;
}

I know I can do this by sending the value to an external php, but I would need to have the variable here. Could someone please assist?

A: Name of your dropdown is selectStream not selectedStream
This is wrong
$selected = $_POST['selectedStream'];

it should be
$selected = $_POST['selectStream'];

Here is the working code
<form action="" method="post">

STREAM

    <select name="selectStream">

        <option value="1"><1</option>

    </select>
    <input type="submit" name="formStream" value="Select">
</form>
<?php
if(isset($_POST['formStream']))
{
  $selected = $_POST['selectStream'];
  echo "This is what I get: ".$selected;// will echo This is what I get: 1
}

?>


text:
Q: Why do I get incorrect characters when decoding a Base64 string to NVARCHAR in SQL Server? I've been looking at how to decode Base64 with SQL Server and after searching around many solutions online (some from here) seem to be based upon this sort of method.
SELECT CAST(CAST('Base64StringHere' as XML ).value('.','varbinary(max)') AS VARCHAR(250))

When I have ASCII text this works perfectly. However when I have the following French text it gets corrupted (presumably due to the restrictions of VARCHAR).
Où est le café le plus proche?
T8O5IGVzdCBsZSBjYWbDqSBsZSBwbHVzIHByb2NoZT8=

And provides the following output.
Où est le café le plus proche?

I thought the relatively simple fix would be to change the CAST to NVARCHAR but this results in corruption again.
SELECT CAST(CAST('T8O5IGVzdCBsZSBjYWbDqSBsZSBwbHVzIHByb2NoZT8=' as XML ).value('.','varbinary(max)') AS NVARCHAR(250) )

썏₹獥⁴敬挠晡꧃氠汰獵瀠潲档㽥

My search engine skills may be failing me, but I cannot seem to find someone else who has my problem.
Any thoughts?

A: The problem is that you encoded a UTF-8 encoded string into Base64. So, decoding the Base64 gives you back the original UTF-8 sequence of bytes. SQL Server uses UTF-16 Little Endian only for NVARCHAR data, and even for XML. Hence, ù is the 8-bit version of the two-byte UTF-8 sequence for ù (0xC3 and  0xB9).
Fortunately, it is possible to convert a UTF-8 encoded string into UTF-16, or even into a non-Unicode Code Page (IF the Code Page supports all characters being converted). The trick is to convert the Base64 decoded bytes, in their text representation (even with incorrectly converted characters) into XML. The trick to this trick is that you need to add the <?xml ...> declaration (typically omitted) and specify the source encoding:
DECLARE @Base64Value NVARCHAR(500) = N'T8O5IGVzdCBsZSBjYWbDqSBsZSBwbHVzIHByb2NoZT8=';

DECLARE @BinaryValue VARBINARY(500) =
    CONVERT(XML, @Base64Value).value('.','varbinary(max)');

DECLARE @IntermediaryValue VARCHAR(500) = CONVERT(VARCHAR(500), @BinaryValue);

SELECT @BinaryValue, @IntermediaryValue;
-- 0x4FC3B920657374206C6520636166C3A9206C6520706C75732070726F6368653F
-- Oֳ¹ est le cafֳ© le plus proche?

-- This is to NVARCHAR, which will always work:
SELECT CONVERT(NVARCHAR(500),
    CONVERT(XML, '<?xml version="1.0" encoding="UTF-8"?>' +  @IntermediaryValue)
              );
-- Où est le café le plus proche?

-- This is to VARCHAR, but "success" will depend on the Code Page
-- specified by the default Collation of the current Database:
SELECT CONVERT(VARCHAR(500),
    CONVERT(XML, '<?xml version="1.0" encoding="UTF-8"?>' +  @IntermediaryValue)
              );

 -- In a DB with a Latin1_General Collation it works:
 -- Où est le café le plus proche?

 -- In a DB with a Hebrew Collation, it gets the following error:
 /*
   Msg 6355, Level 16, State 1, Line XXXXX
   Conversion of one or more characters from XML to target collation impossible
 */

Please note that this trick only works for converting from various source encodings into UTF-16 Little Endian (as that is how the XML datatype in SQL Server stores strings internally). This method cannot be used to convert UTF-16 into UTF-8 or some other non-SQL Server-supported encoding.

Below is an Inline-TVF encapsulating the steps shown above:
GO
CREATE FUNCTION dbo.ConvertBase64EncodedUTF8ToUTF16LE
(
  @Base64EncodedUTF8String VARCHAR(8000)
)
RETURNS TABLE
AS RETURN

    SELECT
        CONVERT(NVARCHAR(500),
                CONVERT(XML,
                        '<?xml version="1.0" encoding="UTF-8"?>' +
                        CONVERT(VARCHAR(500),
                                CONVERT(XML, @Base64EncodedUTF8String)
                                  .value('.','varbinary(max)')
                               )
                       )
               ) AS [DecodedValue];

GO

And then test:
SELECT *
FROM   dbo.ConvertBase64EncodedUTF8ToUTF16LE(
          'T8O5IGVzdCBsZSBjYWbDqSBsZSBwbHVzIHByb2NoZT8=');
-- Où est le café le plus proche?

Just use with CROSS APPLY if doing a set-based operation.


text:
Q: Does g(n) ∈ O(f(n)) imply f(n) ∈ Ω(g(n))? I am just trying to understand how Big O and Big Omega work. I know that Big O means no better than, and Big Omega means no worse than running times. So if I have a function g(n) such that g(n) = O(f(n)) then can I say that f(n) = Ω(g(n))?

A: Notation-wise, it is better to write g(n) ∈ O(f(n)), because "O(f(n))" can be seen as the set of all functions that grow no faster than a multiple of f(n).
Let us restate the two relevant formal definitions used in complexity theory:

*

*g(n) ∈ O(f(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [|g(n)| ≤ k·|f(n)|]

*f(n) ∈ Ω(g(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [f(n) ≥ k·g(n)]

If we can assume that f and g are non-negative functions (which is almost always the case for functions used in computer science), then we can drop the absolute value signs. Thus:

*

*g(n) ∈ O(f(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [g(n) ≤ k·f(n)]

*f(n) ∈ Ω(g(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [f(n) ≥ k·g(n)]

Next, flip the inequality on the second logical statement:

*

*g(n) ∈ O(f(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [g(n) ≤ k·f(n)]

*f(n) ∈ Ω(g(n)) ⇔ ∃k>0 ∃N≥0 ∀n≥N [k·g(n) ≤ f(n)]

Now let's prove that the right-hand side of the first statement implies the right-hand side of the second statement:

*

*Assume that ∃k>0 ∃N≥0 ∀n≥N [g(n) ≤ k·f(n)] is true.

*Instantiate the k>0 that satisfies ∃N≥0 ∀n≥N [g(n) ≤ k·f(n)].

*Let kʹ = 1/k, which is legal because k ≠ 0.

*Instantiate the N≥0 that satisfies ∀n≥N [g(n) ≤ k·f(n)].

*Let n be an arbitrary number such that n≥N.

*Then we have g(n) ≤ k·f(n).

*Next we have g(n)/k ≤ f(n).

*By substitution, we have kʹ·g(n) ≤ f(n).

*Because n is arbitrary, we derive that ∀n≥N [kʹ·g(n) ≤ f(n)].

*We derive that ∃N≥0 that satisfies ∀n≥N [kʹ·g(n) ≤ f(n)].

*We derive that ∃kʹ>0 ∃N≥0 ∀n≥N [kʹ·g(n) ≤ f(n)].

*We rename kʹ to k, so that ∃k>0 ∃N≥0 ∀n≥N [k·g(n) ≤ f(n)].

*Thus [∃k>0 ∃N≥0 ∀n≥N [g(n) ≤ k·f(n)]] implies [∃k>0 ∃N≥0 ∀n≥N [k·g(n) ≤ f(n)]].

*Therefore g(n) ∈ O(f(n)) implies f(n) ∈ Ω(g(n)), as wanted.


text:
Q: Error while importing JQuery library net::ERR_Aborted 404 Working on a Java project in eclipse ide. I downloaded and added jQuery library in my Web/module_name/WebContent/js folder. In my code I have imported the file as:

<script src="/module_name/js/jquery-1.12.4.js"></script>

When I run the server, I am getting error as net::ERR_Aborted 404 and the address in the error line is showing as:
GET http://localhost:8080/module_name/js/jquery-1.12.4.js net::ERR_ABORTED 404


text:
Q: Compile sass and export to css using webpack 2 I've just started a react project with webpack and I'm trying to compile my sass files and export to css using webpack but nothing seems to happen. I'm not getting any errors but i don't see any .css files the project. Any advice would be great.
My webpack config is as follows:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: './src/app.js',
    output: { path: __dirname, filename:'./dist/bundle.js' },

    module: {
        loaders: [{
            test: /.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query: { presets: ['es2015', 'react'] }
        },{
            rules: [{
                test: /\.scss$/,
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"},
                    {loader: "sass-loader"}
                ]
            }]
        }]
     },
     plugins: [new ExtractTextPlugin('../src/css/main.css')]
};

Here is the versions / dev dependencies i'm using:
"devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "css-loader": "^0.26.1",
    "extract-text-webpack-plugin": "^2.0.0-rc.3",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.1",
    "style-loader": "^0.13.1",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
}

Thanks in advance! :)

A: From the plugin documentation (https://github.com/webpack-contrib/extract-text-webpack-plugin):
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

So two things seem to be missing. First is that you didn't add the plugin in the rules, and second is that you haven't mentioned if you're importing any .scss files in your entry file or any of its imports.
Once you do those two things, you should be on track.

A: Try this in your Webpack config file:
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "app.css"
});

module.exports = {
    entry: [
        './src.app.js'
    ],
    output: { path: __dirname, filename:'./dist/bundle.js' },
    plugins: [
        extractSass
    ],
    module: {
      loaders: [{
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: { presets: ['es2015', 'react'] }
      },{
        rules: [{
            test: /\.scss$/,
            loader: extractSass.extract({
                loader: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }]
            })
        }]
    }
}

The css file would be named app.css - feel free to use any other name.
And then in your src/app.js file you need to import the scss file. Without this part Webpack won't include it.
import React from 'react';
import {render} from 'react-dom';

import 'app.scss'; // or other file which is your main scss file

render(<MyComponent />, document.getElementById('appContainer'));


text:
Q: I can't get the marquee effect in Android even after trying all things public class Crunk extends Activity {
    TextView textView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crunk);
        Button button = null;

        button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Log.e("It's Clicked", "Don't Worry");
                textView.setText("SeeMe");
                textView.setEllipsize(TruncateAt.MARQUEE);

            }
        });
        textView = (TextView)this.findViewById(R.id.textView1);
        textView.setSelected(true);
        textView.setText("Waitin'....");
    }

This code just shows the text not the marquee effect.
Help me out getting the effect.
I want the text to show the effect when the button is tapped.
Still can't get the desired effect even though tried most of the things....
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="180dp"
    android:text="@string/TapMe" />

<TextView
    android:text="@string/SeeMe"
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="51dp"

    android:textAppearance="?android:attr/textAppearanceLarge" />

A: You can set these properties in your layout.xml
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"

A: Set all the require three things (ellipsize, selected, and singleLine):
TextView tv = (TextView)findViewById(R.id.someTextView);
tv.setSelected(true);
tv.setText("Simple application that shows how to use marquee, with a long ");
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setSingleLine(true):

A: Does your TextView R.id.textView1 has this property ?

android:singleLine="true"

A: Add to textview xml property......
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:singleLine="true"

A: Try following code in your onClick() of Button:
    button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Log.e("It's Clicked", "Don't Worry");

            textView.setText("Simple application that shows how to use marquee, with a long ");
            textView.setEllipsize(TruncateAt.MARQUEE);
            textView.setSelected(true);
            textView.setSingleLine(true);
        }
    });

as you have set in textView.setText("SeeMe"); is small text then textView's width.


text:
Q: Learning to write unit tests I am trying to learn how to write tests for my code in order to write better code, but I just seem to have the hardest time figuring out how to actually test some code I have written. I have read so many tutorials, most of which seem to only cover functions that add two numbers or mock some database or server.
I have a simple function I wrote below that takes a text template and a CSV file as input and executes the template using the values of the CSV. I have "tested" the code by trial and error, passing files, and printing values, but I would like to learn how to write proper tests for it. I feel that learning to test my own code will help me understand and learn faster and better. Any help is appreciated.
// generateCmds generates configuration commands from a text template using
// the values from a CSV file. Multiple commands in the text template must
// be delimited by a semicolon. The first row of the CSV file is assumed to
// be the header row and the header values are used for key access in the
// text template.
func generateCmds(cmdTmpl string, filename string) ([]string, error) {
    t, err := template.New("cmds").Parse(cmdTmpl)
    if err != nil {
        return nil, fmt.Errorf("parsing template: %v", err)
    }

    f, err := os.Open(filename)
    if err != nil {
        return nil, fmt.Errorf("reading file: %v", err)
    }
    defer f.Close()

    records, err := csv.NewReader(f).ReadAll()
    if err != nil {
        return nil, fmt.Errorf("reading records: %v", err)
    }
    if len(records) == 0 {
        return nil, errors.New("no records to process")
    }

    var (
        b    bytes.Buffer
        cmds []string
        keys = records[0]
        vals = make(map[string]string, len(keys))
    )

    for _, rec := range records[1:] {
        for k, v := range rec {
            vals[keys[k]] = v
        }
        if err := t.Execute(&b, vals); err != nil {
            return nil, fmt.Errorf("executing template: %v", err)
        }
        for _, s := range strings.Split(b.String(), ";") {
            if cmd := strings.TrimSpace(s); cmd != "" {
                cmds = append(cmds, cmd)
            }
        }
        b.Reset()
    }
    return cmds, nil
}

Edit: Thanks for all the suggestions so far! My question was flagged as being too broad, so I have some specific questions regarding my example.

*

*Would a test table be useful in a function like this? And, if so, would the test struct need to include the returned cmds string slice and the value of err? For example:

type tmplTest struct {
    name     string   // test name
    tmpl     string   // the text template
    filename string   // CSV file with template values
    expected []string // expected configuration commands
    err      error    // expected error
}

*How do you handle errors that are supposed to be returned for specific test cases? For example, os.Open() returns an error of type *PathError if an error is encountered. How do I initialize a *PathError that is equivalent to the one returned by os.Open()? Same idea for template.Parse(), template.Execute(), etc.

Edit 2: Below is a test function I came up with. My two question from the first edit still stand.
package cmd

import (
    "testing"
    "strings"
    "path/filepath"
)

type tmplTest struct {
    name     string   // test name
    tmpl     string   // text template to execute
    filename string   // CSV containing template text values
    cmds     []string // expected configuration commands
}

var tests = []tmplTest{
    {"empty_error", ``, "", nil},
    {"file_error", ``, "fake_file.csv", nil},
    {"file_empty_error", ``, "empty.csv", nil},
    {"file_fmt_error", ``, "fmt_err.csv", nil},
    {"template_fmt_error", `{{ }{{`, "test_values.csv", nil},
    {"template_key_error", `{{.InvalidKey}}`, "test_values.csv", nil},
}

func TestGenerateCmds(t *testing.T) {
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            cmds, err := generateCmds(tc.tmpl, filepath.Join("testdata", tc.filename))
            if err != nil {
                // Unexpected error. Fail the test.
                if !strings.Contains(tc.name, "error") {
                    t.Fatal(err)
                }
                // TODO: Otherwise, check that the function failed at the expected point.
            }
            if tc.cmds == nil && cmds != nil {
                t.Errorf("expected no commands; got %d", len(cmds))
            }
            if len(cmds) != len(tc.cmds) {
                t.Errorf("expected %d commands; got %d", len(tc.cmds), len(cmds))
            }
            for i := range cmds {
                if cmds[i] != tc.cmds[i] {
                    t.Errorf("expected %q; got %q", tc.cmds[i], cmds[i])
                }
            }
        })
    }
}

A: You basically need to have some sample files with the contents you want to test, then in your test code you can call the generateCmds function passing in the template string and the files to then verify that the results are what you expect.
It is not so much different as the examples you probably saw for simpler cases.
You can place the files under a testdata folder inside the same package (testdata is a special name that the Go tools will ignore during build).
Then you can do something like:
func TestCSVProcessing(t *testing.T) {
    templateStr := `<your template here>`
    testFile := "testdata/yourtestfile.csv"
    result, err := generateCmds(templateStr, testFile)
    if err != nil {
        // fail the test here, unless you expected an error with this file
    }
    // compare the "result" contents with what you expected
    // failing the test if it does not match
}

EDIT
About the specific questions you added later:

Would a test table be useful in a function like this? And, if so, would the test struct need to include the returned cmds string slice and the value of err?

Yes, it'd make sense to include both the expected strings to be returned as well as the expected error (if any).

How do you handle errors that are supposed to be returned for specific test cases? For example, os.Open() returns an error of type *PathError if an error is encountered. How do I initialize a *PathError that is equivalent to the one returned by os.Open()?

I don't think you'll be able to "initialize" an equivalent error for each case. Sometimes the libraries might use internal types for their errors making this impossible. Easiest would be to "initialize" a regular error with the same value returned in its Error() method, then just compare the returned error's Error() value with the expected one.


text:
Q: jQuery: How to fire event when an element is empty or when element has children How can I write a jQuery script that will keep an eye on an element's children.
If the element has no children => scrolling for the whole page is enabled (as default)
If the element has children => scrolling for the whole page is disabled
Scrolling actions are:
Deactivate scrolling: jQuery("body").mousewheel(function(event,data){event.preventDefault();return false;});
Activate scrolling:   jQuery("body").unbind("mousewheel");

Thank you for your help.

A: You can use window.setInterval("javascript function", milliseconds) function. Have in mind that the second parameter is the interval in miliseconds. In the example the interval is 1000 miliseconds = 1 second
var interval = window.setInterval(function(){
   //check for children here
}, 1000)

You can get more information about the timing events in java script here:
http://www.w3schools.com/js/js_timing.asp


text:
Q: forecasting decimal points using ARIMA I am trying to forecast below data which is a ratio of a population. When I run the arima forecast I dont get the results in ratio format (see results below). I don't understand why.
Data:
  Date                ratio
   <dttm>              <dbl>
 1 2018-02-01 00:00:00  1.61
 2 2018-03-01 00:00:00  0.75
 3 2018-04-01 00:00:00  0.64
 4 2018-05-01 00:00:00  0.9
 5 2018-06-01 00:00:00  1.46
 6 2018-07-01 00:00:00  1.49
 7 2018-08-01 00:00:00  2.17
 8 2018-09-01 00:00:00  3.01
 9 2018-10-01 00:00:00  2.38
10 2018-11-01 00:00:00  2.45
11 2018-12-01 00:00:00  3.02
12 2019-01-01 00:00:00  1.2
13 2019-02-01 00:00:00  0.61
14 2019-03-01 00:00:00  0.84
15 2019-04-01 00:00:00  0.78
16 2019-05-01 00:00:00  0.88
17 2019-06-01 00:00:00  1.09
18 2019-07-01 00:00:00  1.45
19 2019-08-01 00:00:00  0.81
20 2019-09-01 00:00:00  1.88
21 2019-10-01 00:00:00  0.88
22 2019-11-01 00:00:00  1.17
23 2019-12-01 00:00:00  1.76

Results:
forecast1
   Point Forecast      Lo 80      Hi 80      Lo 95      Hi 95
24     1577806184 1577363075 1578249293 1577128507 1578483861
25     1580422018 1579940160 1580903876 1579685080 1581158956
26     1583056151 1582469469 1583642833 1582158898 1583953404
27     1585679803 1585041517 1586318090 1584703629 1586655978
28     1588309459 1587604566 1589014352 1587231418 1589387499
29     1590935676 1590180198 1591691154 1589780272 1592091080
30     1593563862 1592755550 1594372174 1592327656 1594800068
31     1596190920 1595335983 1597045858 1594883406 1597498435
32     1598818625 1597917873 1599719376 1597441044 1600196205
33     1601445959 1600502492 1602389426 1600003051 1602888867
34     1604073505 1603088694 1605058317 1602567366 1605579645
35     1606700930 1605676707 1607725154 1605134515 1608267345

code below
autoarima <- auto.arima(mymodel[,1])

autoarima

forecast1 <- forecast(autoarima, h = 12)
plot(forecast1)
forecast1


text:
Q: what is the probability that the rows of a matrix sum to a given vector? Given a random matrix of 1s and 0s with the upper half set to zeros, as shown:
$$
\left(
\begin{eqnarray}
0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0\\
0 & 0 & 1 & 0\\
1 & 1 & 0 & 1
\end{eqnarray}
\right)$$
Furthermore, assume the sums of each column are given  In the above case, that would be:
$$
\left(
\begin{eqnarray}
1 & 1 & 1 & 2
\end{eqnarray}
\right)$$
Is there a efficient algorithm for computing the probability that the rowwise sums will be a given value?  So, If I pass the algorithm a guess at the sum (eg.
$$
\left(
\begin{eqnarray}
1\\
0\\
1\\
3
\end{eqnarray}
\right)$$
the algorithm will return with a probability of 0 to 1.0?


text:
Q: Pular uma linha no textView Como pular uma linha em uma textView no Android Studio? Ou mesmo no que se refere a propria formatação do texto, deixar alguma parte em negrito por exemplo? existe algo integrado automático ou eu teria que mexe no .xml?

A: Descobri como pular a linha. basta usar o "\n\n"

A: Você usa \n para a quantidade de linhas que deseja pular, tipo, se quiser pular uma linha: \n, duas linhas: \n\n, três linhas: \n\n\n  e assim sucessivamente !
quanto ao Negrito: eu uso no textstyle: bold
EX.:
<TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:text="Teste"/>


text:
Q: Display transfer speed when performing "cp" from the command line? Is this possible?

A: The standard coreutils cp command doesn't support this. There's a Gentoo patch floating around that adds it for different versions, although it's not included in Gentoo anymore for some reason; the version for coreutils 6.10 is in their bugzilla, and I'm sure there are lots of others around.
If you don't want to patch cp, you need to use some other command. For example, rsync has a --progress flag, so you can do:
rsync --progress source destination

If instead of copying you cat the data and then redirect stdout to the destination (i.e. cat source > destination), then you can use a program that measures pipe throughput and insert it in the middle (cat source | SOME-PROGRAM > destination); there are a couple mentioned in this related question. The one I recommended there was pv (Pipe Viewer):

If you give it the --rate flag it will show the transfer rate

A: Hi Another way to show the transfer speed is to use scp on localhost like this:
scp -rv src_folder user@localhost:/dest_folder

A: I find that using pv in this manner works well for that purpose
pv -p file1 > file2

The -p switch shows the file transfer progress. To see the transfer speed, add the -r switch. If you want to see the average transfer rate over time, you can use the -a switch.
pv -pra file1 > file2

A: I know this is rather old, but...
If you do not actually want to display the rate, but only want to watch if something is happening on copying of a large file, you can also just use the watch command (also works with mv):
cp /path/to/myfile /path/to/target/myfile

Then, in another shell, or pushing the copy-command to the background (e.g. with Ctrl + Z followed by bg), you can check the result with:
watch "ls -sh1 /path/to/target"

This will continuously update the output of the ls command update (by default every 2.0s), displaying something like:
Every 2.0s: ls -sh1 /path/to/target
Tue Jan 12 15:02:45 2016

total 1.1G
4.0K data
130M tmp1.txt
137M tmp2.txt
151M tmp3.txt
168M tmp4.txt
162M myFile

A: Here is a script that uses du to monitor throughput. This is more application agnostic and is also referenced in https://unix.stackexchange.com/a/301490/183269. Execute the script on the destination host.
monitorio () {
# show write speed for file or directory
    interval="10"
    target="$1"
    size=$(du -ks "$target" | awk '{print $1}')
    firstrun="1"
    echo ""
    while [ 1 ]; do
        prevsize=$size
        size=$(du -ks "$target" | awk '{print $1}')
        #size=$(ls -l "$1"  | awk '{print $5/1024}')
        kb=$((${size} - ${prevsize}))
        kbmin=$((${kb}* (60/${interval}) ))
        kbhour=$((${kbmin}*60))
        # exit if this is not first loop & file size has not changed
        if [ $firstrun -ne 1 ] && [ $kb -eq 0 ]; then break; fi
        echo -e "\e[1A $target changed ${kb}KB ${kbmin}KB/min ${kbhour}KB/hour size: ${size}KB"
        firstrun=0
        sleep $interval
    done
}

example use:
user@host:~$ dd if=/dev/zero of=/tmp/zero bs=1 count=50000000 &
user@host:~$ monitorio /tmp/zero
/tmp/zero changed 4KB 24KB/min 1440KB/hour size: 4164KB
/tmp/zero changed 9168KB 55008KB/min 3300480KB/hour size: 13332KB
/tmp/zero changed 9276KB 55656KB/min 3339360KB/hour size: 22608KB
/tmp/zero changed 8856KB 53136KB/min 3188160KB/hour size: 31464KB
^C
user@host:~$ killall dd; rm /tmp/zero


text:
Q: Data Binding to TextBlock this.PieSeries = new ObservableCollection<RevenueProperties>()
            {
                new RevenueProperties() { Items = "iTunes", Revenue = 6},
                new RevenueProperties() { Items = "Others", Revenue = 4},
                new RevenueProperties() { Items = "iPhone", Revenue = 48},
                new RevenueProperties() { Items = "iPad", Revenue = 21},
                new RevenueProperties() { Items = "Mac", Revenue = 18},
                new RevenueProperties() { Items = "iPod", Revenue = 2},
            };
        this.DataContext = this;

<Window.Resources>
        <DataTemplate x:Key="labelTemplate">
            <Grid>
                <TextBlock Text="{Binding Items}"/>
                <TextBlock Text="{Binding Revenue}"/>
            </Grid>
        </DataTemplate>
    </Window.Resources>

<Grid>
<Chart:PieSeries ExplodeIndex="0" ExplodeRadius="15" ExplodeAll="False" Palette="Custom" LabelPosition="Inside"
                                      ItemsSource="{Binding PieSeries}" XBindingPath="Items" YBindingPath="Revenue">

                    <Chart:PieSeries.AdornmentsInfo>
                        <Chart:ChartAdornmentInfo FontSize="9" ShowLabel="True" SegmentLabelContent="Percentage"
                                                       ShowConnectorLine="True" LabelTemplate="{StaticResource labelTemplate}"/>
                    </Syncfusion:PieSeries.AdornmentsInfo>
</Chart:PieSeries>

I try the above program textblock values doesn't bind anything, when i run this program get empty pie chart. Please help to resolve this binding problem

A: Have you implemented INotiFyProperty interface on your window code behind class?
if not, implement Inotify... on your window and call the OnPropertyChanged method from the setter of PieSeries, Items  and Revenue fields.
Check below link on detailed explanation of INotify... interface:
http://www.codeproject.com/Articles/41817/Implementing-INotifyPropertyChanged


text:
Q: TortoiseSVN vs Command Prompt svn switch error I'm trying to switch my WC between releases (and/or trunk), and can easily do it if I
Right-click > TortoiseSVN > "Switch..."

inside the WC directory, but if I try to run svn switch from cmd, I get an error that I'm trying to switch into a different repository:
C:\svn\EGS>svn switch file:///c:/repositories/repo2/releases/r2019
svn: E155025: 'svn switch' does not support switching a working copy to a different repository
svn: E155025: 'file:///C:/Repositories/repo2/trunk'
is not the same repository as
'file:///C:/repositories/repo2'

where C:\svn\EGS> is currently a WC for file:///c:/repositories/repo2/trunk.

A: Your problem is that subversion repositories are case-sensitive, particularly when you're using URLs. While yes, when you're navigating through Windows Explorer or the cmd line, Windows can handle it, but svn needs to be compatible with case-sensitive file systems such as Linux/Unix and MacOS for example  as compared to Windows's case-insensitive file system. Therefore, it's better to get into the habit of keeping your naming conventions in your repository consistent for both your directory structure and your svn commands/scripts.
To resolve your issue, you just need to update your command to:
svn switch file:///C:/Repositories/repo2/releases/r2019


text:
Q: Inputting a multiple tuples in list in Python language I created a program that will input an element to tuple then append it into list.
Here is my code:
def tuple_and_list():
    my_list = []
    my_tuple = ()
    n_list = int(input("Enter how many element you want in list: "))
    for i in range(4):
        n_tuple = int(input("Enter how many element you want in tuple: "))
        for j in range(n_tuple):
            e_tuple = int(input("Enter a number: "))
            my_tuple = my_tuple + (e_tuple,)
        my_list.append(my_tuple)
    print(my_list)

tuple_and_list()

This is the output of my program: [(1, 2), (1, 2, 1, 2), (1, 2, 1, 2, 1, 2), (1, 2, 1, 2, 1, 2, 1, 2)]
It keeps appending the element of the 2nd-4th loop to the 1st loo
How I can my output like this?
[(1, 2), (1, 2), (1, 2), (1, 2)]

A: Tuples are not mutable; maybe you want to append to a list, and cast to tuple upon storing into my_list?
I added better input prompts that let the user clearly see what data is requested, and tabs to further clarify.
def tuple_and_list():

    my_list = []
    n_list = int(input("Enter how many tuples you want in my_list: "))
    for idx in range(n_list):

        n_tuple = int(input("Enter how many element you want in tuple: "))
        my_input = []
        for jdx in range(n_tuple):
            my_input.append(int(input(f"\ttuple {idx+1}: Enter {jdx+1}th. element: ")))

        my_list.append(tuple(my_input))   # cast the accumulator list to tuple, then append it

    print(my_list)

tuple_and_list()

example run:
Enter how many tuples you want in my_list: 3
Enter how many element you want in tuple: 2
    tuple 1: Enter 1th. element: 1
    tuple 1: Enter 2th. element: 2
Enter how many element you want in tuple: 3
    tuple 2: Enter 1th. element: 3
    tuple 2: Enter 2th. element: 4
    tuple 2: Enter 3th. element: 5
Enter how many element you want in tuple: 2
    tuple 3: Enter 1th. element: 6
    tuple 3: Enter 2th. element: 7
[(1, 2), (3, 4, 5), (6, 7)]

A: Simple fix is writing my_tuple = () inside 1st for loop.
See below Code
def tuple_and_list():
    my_list = []
    n_list = int(input("Enter how many element you want in list: "))
    for i in range(n_list):
        n_tuple = int(input("Enter how many element you want in tuple: "))
        my_tuple = ()
        for j in range(n_tuple):
            e_tuple = int(input("Enter a number: "))
            my_tuple = my_tuple + (e_tuple,)
        my_list.append(my_tuple)
    print(my_list)

print(tuple_and_list())