text:
Q: Supporting my_2D_Array[x][y] (double operator[]) on a const 2D array; Cannot get things working I am creating a 2D array class in C++. Everything works fine for a non-cost array.
I have yet to find a good explanation of const functions, and always seem to fumble around until it works. Now, however, I am at an impass.
Am I not understanding how to support const objects? Short of creating a second Row class, I can't think of a solution, and that solution seems unnecessary.
main.cpp
#include "Array2D.h"
int main()
{
    int const x(1), y(1);
    Array2D<int> arr(3, 3);

    int value(0);
    for (int row(0); row < 3; ++row)
        for (int column(0); column < 3; ++column)
            arr[row][column] = ++value;
    std::cout << arr[x][y];

    Array2D<int> const carr(arr);
    //Everything's fine up to here

    std::cout << carr[x][y]; //Error

    std::cout << "\n\n[ PAUSE: Press ENTER to exit the program. ]";
    std::cin.get();
    return 0;
}

When I try to access carr[x][y] it throws an error, which is to be expected. So I included a const and non-const overload of operator[] in Array2D
Array2D.h
    template <typename T>
    class Array2D
    {
    public:
       //===============
      //CONSTRUCTORS
     //
        inline Array2D();
        inline Array2D(int rows, int columns = 0);
        inline Array2D(Array2D const &array2D);

       //===============
      //OPERATORS
     //
        inline Array2D<T>& operator=(Array2D const &array2D);
        inline Row<T> operator[](int index);
        inline Row<T> const operator[](int index) const;

       //===============
      //GETTERS
     //
        inline int getRows() const { return _rows; }
        inline int getColumns() const { return _columns; }

       //===============
      //SETTERS
     //
        inline void setRows(int rows);      //May result in loss of data
        inline void setColumns(int columns); //May result in loss of data

    //OTHER

        inline T& select(int row, int column);
        inline T const & select(int row, int column) const;

       //===============
      //DESTRUCTOR
     //
        inline ~Array2D(){}

    private:
       //===============
      //DATA
     //

        Array<T>    _array;     //Two dimensional array in row-major order
        int         _rows;      //The number of rows in the array
        int         _columns;   //The number of data in each row

       //===============
      //PRIVATE FUNCTIONS
     //
        //Initializes the array with current data
        inline void initArray2D();
        //Throws exception if length is negative
        inline void checkLength(int length) const;
        //Throws exception if index is out of bounds
        inline void checkIndex(int rowIndex, int columnIndex) const;
    };
//CONSTRUCTORS

template <typename T>
Array2D<T>::Array2D() : _array(0), _rows(0), _columns(0)
{ initArray2D(); }

template <typename T>
Array2D<T>::Array2D(int rows, int columns) : _array(0), _rows(rows), _columns(columns)
{
    checkLength(rows);
    checkLength(columns);

    initArray2D();
}

template <typename T>
Array2D<T>::Array2D(Array2D const &array2D)
{ (*this) = array2D; }

//OPERATORS

template <typename T>
Array2D<T>& Array2D<T>::operator=(Array2D const &array2D)
{
    _rows = array2D._rows;
    _columns = array2D._columns;
    initArray2D();

    _array = array2D._array;
    return *this;
}

template <typename T>
Row<T> Array2D<T>::operator[](int index)
{
    return Row<T>(*this, index);
}
template <typename T>
Row<T> const Array2D<T>::operator[](int index) const
{
    Row<T> const toReturn(*this, index);;
    return toReturn;
}

//SETTERS

template <typename T>
void Array2D<T>::setRows(int rows)
{
    _array.setLength(rows * _columns);
}

template <typename T>
void Array2D<T>::setColumns(int columns)
{
    Array newArray(_rows * columns);

    //This will prevent truncated columns from being copied over
    int lesserColumn(columns > _columns ? _columns : columns);

    for (int row(0); row < _rows; ++row)
        for (int column(0); column < lesserColumn; ++column)
            newArray[row][column] = _array[row][column];
    _array = newArray;
}

//OTHER

template <typename T>
T& Array2D<T>::select(int row, int column)
{
    checkIndex(row, column);
    return _array[(row * column) + column];
}

template <typename T>
T const & Array2D<T>::select(int row, int column) const
{
    checkIndex(row, column);
    return _array[(row * column) + column];
}

// PRIVATE \\

template <typename T>
void Array2D<T>::initArray2D()
{
    _array = Array<T>(_rows * _columns);
}

template <typename T>
void Array2D<T>::checkLength(int length) const
{
    if (length < 0)
        throw Exception("LENGTH_LESS_THAN_ZERO");
}

template <typename T>
void Array2D<T>::checkIndex(int rowIndex, int columnIndex) const
{
    if (rowIndex >= _rows || columnIndex >= _columns)
        throw Exception("INDEX_LARGER_THAN_UPPER_BOUND");
    if (rowIndex < 0 || columnIndex < 0)
        throw Exception("INDEX_SMALLER_THAN_LOWER_BOUND");
}

The const functions seem to be in order, however an issue arises when it tries to create the Row object (explained in next paragraph) because it expects an Array2D&, but in the const function it passes a const Array2D&, which naturally does not work.
The idea of the Row object is to pass back something to handle the second [] operator without having to pass back array.
Row.h
template <typename T>
class Array2D;

template <typename T>
class Row
{
public:
   //==============
  //CONSTRUCTOR
 //
    inline Row(Array2D<T> &array2D, int row);

   //==============
  //OPERATORS
 //
    //The index will be validated by Array2D
    inline T& operator[](int column);
    inline T const & operator[](int column) const;

private:
   //==============
  //Data
 //
    Array2D<T>& _array2D;   //Source array
    int         _row;       //The row index
};

template <typename T>
Row<T>::Row(Array2D<T> &array2D, int row) : _array2D(array2D), _row(row)
{   }

template <typename T>
T& Row<T>::operator[](int column)
{
    return _array2D.select(_row, column);
}
template <typename T>
T const & Row<T>::operator[](int column) const
{
    return _array2D.select(_row, column);
}

Here is Array.h for reference
#pragma once

#include "Exception.h"

template <typename T>
class Array
{
public:
   //===============
  //CONSTRUCTORS
 //
    inline Array();
    inline Array(int length, int startIndex = 0);
    inline Array(Array const &copy);

   //===============
  //OPERATORS
 //
    inline Array& operator=(Array const &copy);
    inline T& operator[](int index);
    inline T const & operator[](int index) const;

   //===============
  //GETTERS
 //
    inline int getStartIndex() const { return _startIndex; }
    inline int getLength() const { return _length; }

   //===============
  //SETTERS
 //
    inline void setStartIndex(int index);
    inline void setLength(int length);

   //===============
  //DECONSTRUCTOR <coolface.jpg>
 //
    inline ~Array();

private:

   //===============
  //DATA
 //
    T*  _array;         //Pointer to array of type T
    int _length;        //Length of the array
    int _startIndex;

   //===============
  //PRIVATE FUNCTIONS
 //
    //Initializes the array with current LENGTH
    inline void init();

    //Throws exception if length is less than zero
    inline void checkLength(int length) const;

    //Throws exception if index is out of bounds
    inline void checkIndex(int index) const;

    //Copies contents of SOURCE to DESTINATION
    inline void copyArray(T * destination, T * source, int lastIndex);
};

//CONSTRUCTORS

template <typename T>
Array<T>::Array() : _array(0), _length(0), _startIndex(0)
{ init(); }

template <typename T>
Array<T>::Array(int length, int startIndex = 0) : _array(0), _length(length), _startIndex(startIndex)
{
    checkLength(length);
    init();
}

template <typename T>
Array<T>::Array(Array const &copy)
{ (*this) = copy; }

//OPERATORS

template <typename T>
Array<T>& Array<T>::operator=(Array const &copy)
{
    _length = copy._length;
    _startIndex = copy._startIndex;
    init();
    copyArray(_array, copy._array, _length);
    return *this;
}

template <typename T>
T& Array<T>::operator[](int index)
{
    checkIndex(index);
    return _array[index - _startIndex];
}
template <typename T>
T const & Array<T>::operator[](int index) const
{
    checkIndex(index);
    return _array[index - _startIndex];
}

//SETTERS
template <typename T>
void Array<T>::setStartIndex(int index)
{ _startIndex = index; }

    // ! WARNING: Setting length to a lower value than current will result in lost data
template <typename T>
void Array<T>::setLength(int length)
{
    checkLength(length);

    T* oldArray(_array);
    int oldLength(_length);

    _length = length;
    init();

    int lastIndex(oldLength < _length ? oldLength : _length);
    copyArray(_array, oldArray, lastIndex);

    delete [] oldArray;
}

//DECONSTRUCT <coolface.jpg>
template <typename T>
Array<T>::~Array()
{
    delete [] _array;
}

// PRIVATE \\

template <typename T>
void Array<T>::init()
{
    _array = new T[_length];
}

template <typename T>
void Array<T>::checkLength(int length) const
{
    if (length < 0)
        throw Exception("LENGTH_LESS_THAN_ZERO");
}

template <typename T>
void Array<T>::checkIndex(int index) const
{
    if (index - _startIndex >= _length)
        throw Exception("INDEX_LARGER_THAN_UPPER_BOUND");
    if (index - _startIndex < 0)
        throw Exception("INDEX_SMALLER_THAN_LOWER_BOUND");
}

template <typename T>
void Array<T>::copyArray(T * destination, T * source, int lastIndex)
{
    while (lastIndex--)
        destination[lastIndex] = source[lastIndex];
}

A: Sadly, I think you'll need two versions of Row: one for const Array and one for non-const. Just like the standard containers have iterators and const_iterators.


text:
Q: How to remove outline from Material UI button using by breakpoint I want to remove the outlined variant at the small medium and down breakpoint. To do this, I have tried to do the following:
const variantType = theme.breakpoints.down('md') ? '' : 'outlined';

<Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
  Buy
</Button>;

This does not do the job. I have tried researching and no one seemed to ask this question before. So here is the first of its kind. lol

A: You can do this by using the useTheme and the useMediaQuery hooks from Material UI.
import { Button, useTheme, useMediaQuery } from '@material-ui/core'

export default function App() {
  const theme = useTheme();
  const mediumDown = useMediaQuery(theme.breakpoints.down('md'));

  return (

      <Button name="buyFood" variant={mediumDown? 'text' : 'outlined' } onClick={this.openFoodModal}>
        Smart Suggest
      </Button>

  );
}

A: You can access your theme settings with the useTheme hook if you have custom theme.
After that you only have to compare the current window width with your breakpoint.
To do this you can simply write a hook that gives you the current window width.
Here is an elegant solution from @QoP
This could then look like this:
./App.js
import React from "react";
import { useTheme } from "@material-ui/core/styles";
import { Button } from "@material-ui/core";
import useWindowWidth from "./useWindowWidth";

export default function App() {
  const theme = useTheme();
  const width = useWindowWidth();

  const variantType = width < theme.breakpoints.values.md ? "text" : "outlined";

  return (

      <Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
        Smart Suggest
      </Button>

  );
}

./useWindowWidth.js
import { useState, useEffect } from "react";

const getWindowWidth = () => window.innerWidth;

export default function useWindowWidth() {
  const [windowWidth, setWindowWidth] = useState(getWindowWidth());

  useEffect(() => {
    function handleResize() {
      setWindowWidth(getWindowWidth());
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowWidth;
}

Live demo:

redpajama_set_name: RedPajamaStackExchange


text:
Q: A div inside an inline element: bad or not? I am creating a JavaScript tooltip program and wonder if it's alright to add the tooltip box (that is, a div node) as a child of the target that may be a span node or some other inline element, so the dom is as follows:
out of this:
Hello World!

turns into this when the tooltip has added the tip box:
Hello World!
A "Hello World" program is a computer program which prints out "Hello World" on a display device.

If the tip box is positioned relative to its parent it's easier to handle the mouseout event and others. So would it bad to insert a div inside an inline element in such case?

A: It does not conform to the standard, but this should be the easier way and it work cross browser.


text:
Q: Fetch all data from feathers-vuex I store a couple thousands google maps markers in an API done with feathersjs. I use feathers-vuex on the frontend and I need to fetch all this data on created(). This is what I have so far, but it only fetches 10 items.
<script>
    import { mapState, mapGetters, mapActions } from 'vuex'

    export default {
        name: 'a-map',
        computed: {
            ...mapGetters('plates', {
                plates: 'list'
            })
        },
        methods: {
            ...mapActions('plates', {
                findPlates: 'find'
            })
        },
        created() {
            // Query plates from Feathers
            this.findPlates();
        }
    }
</script>

A: There is a good explanation in the docs of feathers-Vuex. Look here:
hhttps://vuex.feathersjs.com/common-patterns.html#reactive-lists-with-live-queries
The issue is you have to read records from backend into Feather-vuex-store in created. With the getter in computed you get records from the feathers-Vuex store. The benefit of this is computed is synchronized with the backend, even if somebody add, mutate or delete records in the backend.

A: You have pagination on your service which  means (by default) only the first 10 items will show. You can either delete the pagination setting on your service, update it, or take advantage of the pagination by using $skip in subsequent requests.
Pagination documentation

A: WMDTech is right, this is because of pagination in your backend. A simple fix is to do the following, but be wary of large datasets
Give this a try:
    created() {
        // Query plates from Feathers
        this.findPlates( {
            paginate: false
        });
    }


text:
Q: If I wish to upsert data into Google BigQuery (and not in realtime) should this be done via Google Cloud Storage then to BQ? I'm researching how I can get data from some database over to Google BigQuery (aka. BQ). I'm expecting this to occur every 24 hours, or maybe 12 hours. But it needs to be UPSERTED.
Researching ways to do this, it feels like this should be done via exporting to data to Google Cloud Storage (aka. CS) first. Then exporting the data from there over to BQ. I know there's an API to BQ that allows me to stream in data on the fly, but I feel like this:

*

*is an over kill for not-real-time querying required

*there's quota's when trying to do this? (versus, no quota's when going though CS -> then -> BQ)

I know there's also 3rd party services bu I'm trying to determine how hard this is to do myself and if so, what are the common patterns of other people doing this, in their production scenario's.
Is this possible?


text:
Q: Comparación Strings ¿Por que no funciona en Android 7.0 y en otras versiones si? Este ejercicio sencillo no funciona en Android 7.0 y en versiones anteriores de Android si funciona, ¿por qué puede ser?`
    @Override
    protected String doInBackground(String... params) {
        String cadena = params[0];
        URL url = null;//
        String devuelve = "";
        try {
            url = new URL(cadena);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
                    "(Linux: Android 7.0; es-ES) Ejemplo HTTP");

            int respuesta = connection.getResponseCode();
            StringBuilder result = new StringBuilder();

            if (respuesta == HttpURLConnection.HTTP_OK) {

                InputStream in = new BufferedInputStream(connection.getInputStream());

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                JSONObject respuestaJSON = new JSONObject(result.toString());
                String resultJSON = respuestaJSON.getString("estado");

                if (resultJSON == "1") {
                    JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumnos");
                    for (int i = 0; i < alumnosJSON.length(); i++) {
                        devuelve = devuelve + alumnosJSON.getJSONObject(i).getString("id_alumno") + " " +
                                alumnosJSON.getJSONObject(i).getString("nombre") + " " +
                                alumnosJSON.getJSONObject(i).getString("direccion") + "\n";

                   }
                } else if (resultJSON == "2") {
                    devuelve = "No hay resultados";
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return devuelve;
    }`

En version 7.0, cuando compruebo que resultJSON == "1" me saca del if como si no fuera = 1 y sí lo es.
Cuando pruebo con otra version de Android o quito el if, funciona correctamente

A: Comparar un String como tu haces es poco mas que un suicidio. Para comparar String se hace asi:
if (resultJSON.equals("1"))

o asi
if (resultJSON.equalsIgnoreCase("1"))

la diferencia es que el segundo caso no tiene encuenta si la cadena a comparar tiene mayusculas o minisculas, es case insensitive.
Prueba y veras como seguro te funciona.
Saludos.

A:
¿Por que no funciona en Android 7.0 y en otras versiones si?

En realidad no funcionaría en ninguna versión de Android,
if (resultJSON == "1") {
...
...
 } else if (resultJSON == "2") {
      ...
}

la comparación de variables tipo String se realiza mediante el método **equals().**
if (resultJSON.equals("1")) {
...
...
 } else if (resultJSON.equals("2")) {
      ...
}

Usar equalsIgnoreCase(), no es necesario en este caso ya que aplica para caracteres alfabéticos.


text:
Q: Calling jQuery from a textbox event I'm trying to use an input mask in a smarty template.
This is the text box with an inline event handler:
<input type="text" name="{$fldname"} id ="{$fldname}" value="{$fldvalue}" onKeyUp="jQuery(function($){$("#phone").mask("999-999-9999",{placeholder:"_");});">

How do I make this work?

A: You should try something like this (Example)
HTML: (Assumed $fldname contains phone)
<input type="text" name="{$fldname}" id ="{$fldname}" value="{$fldvalue}" />

JS: (Put this between <head></head> tags)
<script type="text/javascript">
    jQuery(function($){
        $("#phone").mask( "999-999-9999", { placeholder : "_" } );
    });
</script>


text:
Q: ¿Cómo colocar en orden de fila, de la cantidad mas alta a la más baja en sql? ¿Cómo colocar en orden de fila, de la cantidad mas alta a la más baja en sql? Tengo lo siguiente:
 SELECT grupos, SUM(puntuaciones)
 FROM juego WHERE grupos IS NOT NULL
 AND puntuaciones != 0.00 AND grupos LIKE 'g%'
 GROUP BY grupos ORDER BY grupos;

Resultado:
 grupos  SUM(puntuaciones)
 grupo1  11
 grupo2  80
 grupo3  50
 grupo4  100

Me gustaría el resultado fuera:
 grupos  SUM(puntuaciones)
 grupo4  100
 grupo2  80
 grupo3  50
 grupo1  11

A: SELECT grupos, SUM(puntuaciones) AS total_puntuaciones
FROM juego
WHERE grupos IS NOT NULL
AND puntuaciones != 0.00
AND grupos LIKE 'g%'
GROUP BY grupos
ORDER BY total_puntuaciones DESC;

No lo probé, pero entiendo que debería andar. Le asignás un alias al SUM(...) para poder referenciarlo desde el ORDER. Como querés que ordene de mayor a menor, le indicás DESC.


text:
Q: Record count after clicking a hyperlink in Sharepoint List Is there any way to record click rate of the hyperlink in Sharepoint List item after clicked?
We have a column in a Sharepoint List storing a report hyperlink, we want to record how many click of the link by user. Is there any way to do without using Powerapps or flow? Thanks for any suggestion.
Joanne

A: To the best of my knowledge, there is no quick and easy solution for this. Personally, I would leverage SharePoint Framework (SPFx) to create an extension which would then allow you to run javascript on the site. From there you could then add events to links on the page for tracking purposes. For storing the click events you have several options such as writing to a SP List, back-end service, application insights, etc.
I don't think Power Automate (aka Flow) will help here as the events are tied to modifications (update/create/delete).
Note: Perhaps you could link to some sort of redirection service instead of the report directly, which would record the click, then forward to the report. This would avoid the need for SPFx.


text:
Q: Magento: where to find uploaded placeholder images uploaded from admin I uploaded three placeholder images from admin (System > Configuration > Catalog > Product Image Placeholders). I've confirmed in the DB (core_config_data table) that these settings have applied and I see the previews of these placeholder images in the admin as well.
However, when I navigate to /skin/frontend/.../images/catalog/product/placeholder, where ... is all of the themes there are (base, default, my_theme, etc.), the images are still the default Magento placeholders.
In what directory are the uploaded images stored on the server?

A: You can right-click on the little thumbnail image in the admin and click Properties or Inspect Element (depending on your browser).
On my base CE 1.7.0.2 install, the images are stored here: /media/catalog/product/placeholder/default/


text:
Q: How to execute DQL query in Symfony2? I am trying to get objects from DQL query.
Here is my code :
$em = $this->getDoctrine()->getRepository(Item::class);

$items = $em->createQuery($getQuery);
$items = $query->getResult();

$getQuery = DQL query string : SELECT from Entity WHERE ...

I am receiving error : Undefined method 'createQuery'. The method name must start with either findBy or findOneBy!
I don't understand it, bcz this example is copied from official documentation.
How I can execute DQL query in queryBuilder/createQuery?

A: Entity manager has a createQuery method.
$em = $this->getDoctrine()->getManager();

$query = $em->createQuery($getQuery);

$items = $query->getResult();

Repository has a createQueryBuilder method.
$em = $this->getDoctrine()->getManager();

$qb = $em->getRepository(Item::class)->createQueryBuilder();
$query = qb->select('[columns]')->from('Entity')->where('[condition]')->getQuery();
$items = $query->getResult();


text:
Q: PHP Creating an array inside a For Loop Looking for some help if possible.
$pilotsids is an array of ids.
merged is the table that holds the data.
For each pilotid, I'd like to create an array of newrat values, which I am going to use later to populate a chart. The index of the for loop must be added to the name of each array like this:
$data0[]
$data1[]
$data2[]...etc

It works when I do it separately:
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[0] order by mid asc");
    while($row = mysqli_fetch_assoc($result)) {
       $data0[] = $row['newrat'];
    }
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[1]' order by mid asc");
    while($row = mysqli_fetch_assoc($result)) {
       $data1[] = $row['newrat'];
    }
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[2]' order by mid asc");
    while($row = mysqli_fetch_assoc($result)) {
       $data2[] = $row['newrat'];
    }

It doesn't if I try to to iterate automatically for lets say 10 times:
for($i=0; $i < 10; $i++) {
        $result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
        while($row = mysqli_fetch_assoc($result)) {
            ${$data.$i}[] = $row['newrat'];

        }
   }

A: You can try this way:
$data = [];
for($i=0; $i < 10; $i++) {
    $result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
    while($row = mysqli_fetch_assoc($result)) {
        $data[$i][] = $row['newrat'];
    }
}

As you can see I'm using a two dimensional array which is defined outside of the loop.


text:
Q: Sending data from a child activity onActivityResult() to parent activity onActivityResult() I have an App with 2 Activities. Activity A (parent) starts Activity B (child) by calling:
startActivityForResult(intentB,B_Request);

Activity B is a barcode scanner. (I use this library: com.journeyapps:zxing-android-embedded:3.2.0@aar).
In this activity I have to override the onActivityResult() method in order to get the scanned code. After that I want to send the data stored in 'code' back to the parent (Activity A) onActivityResult(). I did this like this:
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        String code = null;

        if(result != null){
            if(result.getContents() == null){
                return;
            }
            else {
                code = result.getContents();
            }
        }
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }

        Intent intent = new Intent(getApplicationContext(),A.class);
        intent.putExtra("scannedCode", code);
        setResult(RESULT_OK, intent);
        finish();
}

The parent onActivityResult() looks like this:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CAMERA_REQUEST){
            if(resultCode == RESULT_OK){

                String scannedCode = data.getStringExtra("scannedCode");
                toastMessage("Scanned code: " + scannedCode);
            }
        }
    }

I get the following exception and instead of seeing Activity A, I'm redirected to the Activitie's A parent.
E/ActivityManager: Failed to schedule configuration change
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(Binder.java:1177)
        at android.app.IApplicationThread$Stub$Proxy.scheduleTransaction(IApplicationThread.java:1815)
        at android.app.servertransaction.ClientTransaction.schedule(ClientTransaction.java:129)
        at com.android.server.am.ClientLifecycleManager.scheduleTransaction(ClientLifecycleManager.java:47)
        at com.android.server.am.ClientLifecycleManager.scheduleTransaction(ClientLifecycleManager.java:100)
        at com.android.server.am.ActivityManagerService.updateGlobalConfigurationLocked(ActivityManagerService.java:24782)
        at com.android.server.am.ActivityManagerService.updateDisplayOverrideConfigurationLocked(ActivityManagerService.java:24902)
        at com.android.server.am.ActivityManagerService.updateDisplayOverrideConfigurationLocked(ActivityManagerService.java:24879)
        at com.android.server.am.ActivityStackSupervisor.ensureVisibilityAndConfig(ActivityStackSupervisor.java:1671)
        at com.android.server.am.ActivityStackSupervisor.realStartActivityLocked(ActivityStackSupervisor.java:1420)
        at com.android.server.am.ActivityStackSupervisor.startSpecificActivityLocked(ActivityStackSupervisor.java:1709)
        at com.android.server.am.ActivityStack.resumeTopActivityInnerLocked(ActivityStack.java:3043)
        at com.android.server.am.ActivityStack.resumeTopActivityUncheckedLocked(ActivityStack.java:2488)
        at com.android.server.am.ActivityStackSupervisor.resumeFocusedStackTopActivityLocked(ActivityStackSupervisor.java:2234)
        at com.android.server.am.ActivityStack.completePauseLocked(ActivityStack.java:1745)
        at com.android.server.am.ActivityStack.activityPausedLocked(ActivityStack.java:1669)
        at com.android.server.am.ActivityManagerService.activityPaused(ActivityManagerService.java:9657)
        at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:224)
        at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3820)
        at android.os.Binder.execTransact(Binder.java:752)

p.s. It's not enough for me to get the code in Activity B, I need the code back in Activity A.
Can you please tell me what am I doing wrong here?
Thank you!

A: just put new intent() instead of
new Intent(getApplicationContext(),A.class)
in your child activity


text:
Q: How to get the chosen source of a picture element before it is fully loaded? Assuming I have an image in my HTML code and I would like to show a spinner for as long as the image is loading. I could do so by loading the image in JavaScript and once loaded hide the spinner, for example:
async loadImage(src) {
  return new Promise((resolve, reject) => {
    let img = new Image()
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = src
  }).catch()
}

let image = document.getElementById('#image1')

loadImage(image.src).then(() => {
  // Image loaded, spinner can be hidden.
})

Now I am trying to do the same with the HTML picture element. Let's say I have the following HTML code:
<picture>
  <source srcset="image2.webp" type="image/webp" />
  <source srcset="image2.jpg" type="image/jpg" />
  <img src="image2.jpg" />
</picture>

Using above JavaScript code it would load the source of the img tag which is the JPG version. However the browser might not even choose to load the JPG version but the WebP version. I know of the currentSrc property of images but this property only gets applied to the image once the image is loaded.
Basically I need to know which image the browser is loading before it is completely loaded. Does anyone have an idea how this can be achieved?


text:
Q: How to use UITableView to change the content of UITextView i need your support to use Static UITable view with static with UITextView
Where i need to change the content of TextView when the table cell is pressed with different content??

A: Seems kind of broad, and unclear what you want to do, but if you have a cell (static), then place a textview in the cell, and then whenever that cell is tapped then update the textView


text:
Q: How to loop a function over columns in many dataframes in r I have a number of dataframes (96) that have columns of 0s and 1s. If there is more than one "1" in any one column of the dataframes, I want to replace the 1s with a equal fractions so that the sum of the values in the column is 1, as shown in the code below.
v1 <- c(0, 1, 0, 1, 1, 0)
v2 <- c(0, 0, 1, 0, 0, 0)
v3 <- c(0, 0, 1, 1, 0, 0)
df1 <- data.frame(v1, v2, v3)
df2 <-data.frame(v3, v3, v1)
df3 <- data.frame(v1, v3, v1)

new.df1 <- t(apply(df1, 2, FUN = function(x) {
  if(sum(x==1, na.rm=TRUE) ==2)  replace(x, x==1, 0.5)
  else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
  else x}))

new.df2 <- t(apply(df2, 2, FUN = function(x) {
  if(sum(x==1, na.rm=TRUE) ==2)  replace(x, x==1, 0.5)
  else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
  else x}))

new.df3 <- t(apply(df3, 2, FUN = function(x) {
  if(sum(x==1, na.rm=TRUE) ==2)  replace(x, x==1, 0.5)
  else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
  else x}))

I am able to create what I want with brute force as in the above example, but there must be a better (more concise) way. I'd greatly appreciate some help.

A: Store your code in a function, store your dataframes in a list and then use lapply to loop over each list element with your function.
 recalc <- function(df) {
        t(apply(df, 2, FUN = function(x) {
            if(sum(x==1, na.rm=TRUE) ==2)  replace(x, x==1, 0.5)
            else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
            else x}))
    }

lapply(dflist, function(df) recalc(df))

[[1]]
   [,1]      [,2] [,3]      [,4]      [,5] [,6]
v1    0 0.3333333  0.0 0.3333333 0.3333333    0
v2    0 0.0000000  1.0 0.0000000 0.0000000    0
v3    0 0.0000000  0.5 0.5000000 0.0000000    0

[[2]]
     [,1]      [,2] [,3]      [,4]      [,5] [,6]
v3      0 0.0000000  0.5 0.5000000 0.0000000    0
v3.1    0 0.0000000  0.5 0.5000000 0.0000000    0
v1      0 0.3333333  0.0 0.3333333 0.3333333    0

[[3]]
     [,1]      [,2] [,3]      [,4]      [,5] [,6]
v1      0 0.3333333  0.0 0.3333333 0.3333333    0
v3      0 0.0000000  0.5 0.5000000 0.0000000    0
v1.1    0 0.3333333  0.0 0.3333333 0.3333333    0

A: Similar to the other answer, but a little more modular and a improved version of your function:
## Put your data frames in a list
# df_list = list(df1, df2, df3)
df_list = mget(ls(pattern = "df[0-9]"))

## Write a function to modify one column
replace_ones = function(x) {
  sx = sum(x == 1, na.rm = TRUE)
  if(sx > 1) {
    x = replace(x, x == 1, 1 / sx)
  }
  return(x)
}

## Wrap it to modify a data frame:
replace_ones_df = function(df) {
  df[] = lapply(df, replace_ones)
  return(df)
}

## Apply the function to all columns of all data frames:
result_list = lapply(df_list, replace_ones_df)
# $df1
#          v1 v2  v3
# 1 0.0000000  0 0.0
# 2 0.3333333  0 0.0
# 3 0.0000000  1 0.5
# 4 0.3333333  0 0.5
# 5 0.3333333  0 0.0
# 6 0.0000000  0 0.0
#
# $df2
#    v3 v3.1        v1
# 1 0.0  0.0 0.0000000
# 2 0.0  0.0 0.3333333
# 3 0.5  0.5 0.0000000
# 4 0.5  0.5 0.3333333
# 5 0.0  0.0 0.3333333
# 6 0.0  0.0 0.0000000
#
# $df3
#          v1  v3      v1.1
# 1 0.0000000 0.0 0.0000000
# 2 0.3333333 0.0 0.3333333
# 3 0.0000000 0.5 0.0000000
# 4 0.3333333 0.5 0.3333333
# 5 0.3333333 0.0 0.3333333
# 6 0.0000000 0.0 0.0000000

A: Instead of manually counting the number of 1s in the binary column and using if/else, divide the datasets placed in a list with column sums (colSums)
lapply(mget(paste0("df", 1:3)), function(x) x/colSums(x)[col(x)])
#$df1
#         v1 v2  v3
#1 0.0000000  0 0.0
#2 0.3333333  0 0.0
#3 0.0000000  1 0.5
#4 0.3333333  0 0.5
#5 0.3333333  0 0.0
#6 0.0000000  0 0.0

#$df2
#   v3 v3.1        v1
#1 0.0  0.0 0.0000000
#2 0.0  0.0 0.3333333
#3 0.5  0.5 0.0000000
#4 0.5  0.5 0.3333333
#5 0.0  0.0 0.3333333
#6 0.0  0.0 0.0000000

#$df3
#         v1  v3      v1.1
#1 0.0000000 0.0 0.0000000
#2 0.3333333 0.0 0.3333333
#3 0.0000000 0.5 0.0000000
#4 0.3333333 0.5 0.3333333
#5 0.3333333 0.0 0.3333333
#6 0.0000000 0.0 0.0000000


text:
Q: Как в цикле выбрать все дочерние записи? Таблица

Как в цикле вытащить всю цепочку например за записью где id найден в parent_fid
Вот пример моего кода.
        $array_folderid = array();
        $startfor = 0;
        $folderdel_id = "155";
        for($i=0;$i<=$startfor;$i++) {

$sql_selectfolders = "SELECT * FROM user_folders WHERE parent_fid='$folderdel_id' ";
$query_selectfolders = mysqli_query($db,$sql_selectfolders) or die("Ошибка: " . mysqli_error($db));

            if (mysqli_num_rows($query_selectfolders) > 0) {
                while ($fid = mysqli_fetch_array($query_selectfolders)) {
                    array_push($array_folderid, $fid["id"]);
                }
            }

        }

В этоге я получаю вот такой массив.
Array
(
    [0] => 156
    [1] => 159
)

Но как теперь повторить цикл с этими данным, то есть теперь мне нужно вытащить все id по тем что в массиве.И глубина может бить не предсказуема.
Сам решить эту задачку не смог, помогите пожалуйста.


text:
Q: C# Generics and Constraints If I have a generic constraint where C must be a struct:
class MyNum<C> where C : struct
{
    C a;
    public MyNum(C a)
    {
        this.a = a;
    }
}

struct myStruct
{
    public int a;
}

I understand that this compiles:
    myStruct n = new myStruct();
    n.a = 5;
    MyNum<myStruct> str = new MyNum<myStruct>(n);

But why would this compile. ¿Is number 5 a structure?
I thought by doing this:
int b = 5;

b would be of type int, but not type struct.  I guess I´m missing something here.
Also just to use the correct terminology:
int b = 5;

Am I instantiating b? Creating an int instance? For some reason in my   mind when I think of "instances" I think of reference types.
Here:
Car c1 = new Car();

Here I understand that I´m creating a Car instance or instantiating c1.

A: According to MSDN  with a struct Type constraint, The type argument must be a value type. Any value type except Nullable can be specified.
And as diggEmAll mentioned already int is struct

A: Yes 5 is an int and int is a structure

A: int is a struct.
Look at Int32 definition on MSDN

EDIT:
Doing:
 int i = 5;

as well as:
MyStruct m = new MyStruct();

you're creating a memory location as big as the necessary space to contain the struct.
The difference with reference types, is that variables m and i aren't references to those memory locations storing values, but they're basically "the value itself".
Infact when you do:
MyStruct m1 = new MyStruct();
MyStruct m2 = m1;

m2 doesn't represent the same memory location of m1, but the content of m1 is copied in a new location of memory represented by the variable m2


text:
Q: How to visualize list of event parameters and their count in Google Data Studio I'm setting up a Dashboard in Google Data Studio where I would like to show the top event parameters in a table but I'm struggling to understand how to configure such a query.
Context
We are using Firebase Analytics in our app to post built in and some custom events about what the users are interacting with in the app. In this particular case, we are logging the built-in 'select_content' event (https://developers.google.com/analytics/devguides/collection/ga4/reference/events#select_content) where we pass in content_type and item_id of the type of content you clicked on, as well as a unique identifier of the item you clicked.
As an example, let's say we're logging different types of groceries and the grocery you selected (content_type: 'fruit', item_id: 'apples'). I would then like to create a table in Data Studio that lists let's say the top 50 groceries that have been interacted with and the number of times that those groceries have been clicked on.
I cannot for the life of me understand how I would set up such a table in Data Studio even though to me it sounds like one of the most basic things I would want to do. I've tried creating tables with different combinations of dimensions, metrics and sorting on the table but can never get anything but a counter that shows the aggregate of that event type is registered (which is not what I want). The exact table that I want is showing up perfectly fine if I go to Google Analytics -> Life Cycle -> Engagement -> Events -> and click on the 'select_content' event, see screenshot below.

Anyone got any idea or link that they can provide to shine some light onto this?

A: I ran into a similar issue trying to bring parameter data into Google Data Studio. Here's what worked for me:

*

*Create a custom dimension in GA4

Configure -> Custom Definitions -> Create custom dimensions
Name = Item ID
Scope = Event
Description = Optional text to identify your dimension
Event parameter = item_id

*Refresh Google Data Studio

Give it 24-48 hours. Then open your Data Studio report.
Resource menu -> Manage added data sources
Under the Actions header, click Edit next to your GA4 source.
At the bottom, click Refresh Fields.
You should see your Item ID custom dimension appear as a new field available in the report.


text:
Q: rails heroku asset precompile fail due to rake version When I tried to push to heroku I get this msg:
rake aborted!
       undefined method empty? for nil:NilClass
       (in /tmp/build_3d16ad44-0015-4ecb-a7cf-a41959f03f82/app/assets/stylesheets/application.css.scss)
Upon tracing it, I realized that it's because
rake aborted!
You have already activated rake 10.0.3, but your Gemfile requires rake 0.9.2.2. Using bundle exec may solve this.
This may be a really dumb question, but I am not sure how I am supposed to use bundle exec to do this for heroku?  Please help.  Thanks.

A: In case anyone else runs into a similar issue.  The problem was that heroku was using ruby 2.0 with all their new apps so in order to do that you have to put whatever ruby version you are using on the gemfile then reset git by typing git reset --soft HEAD~ and then git reset HEAD public/assets into your command line.  And rm -r public/assets if you have untracked files in public/assets.  Then save the changes and push up to your new site.
So if your app uses an older version of ruby than 2.0, you will have to make similar changes until the bug (sprocket?) is fixed.

A: Inside the project directory in terminal:
gem list rake

You will see more than one version. If so, then remove the version you don't need (i.e. 10.0.3 in your case) by command:
gem uninstall rake

It will ask you specific version to select from list, choose one and press enter.
Or, you can also update to specific rake version
bundle update rake -v '0.9.2.2'


text:
Q: Difference in initialization of two dates in Javascript Why do these two dates are differents :
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10); // month (from 0-11)
date1.setDate(1); // day of the month (from 1-31)

var date2 = new Date(2012, 10, 1, 0, 0, 0, 0);

Result :
Date 1 : Sat Dec 01 2012 14:56:16 GMT+0100
Date 2 : Thu Nov 01 2012 00:00:00 GMT+0100

whereas these two dates are equals :
var date3 = new Date();
date3.setFullYear(2012); // year (four digits)
date3.setMonth(9); // month (from 0-11)
date3.setDate(1); // day of the month (from 1-31)

var date4 = new Date(2012, 9, 1, 0, 0, 0, 0);

Result :
Date 3 : Mon Oct 01 2012 14:56:16 GMT+0200
Date 4 : Mon Oct 01 2012 00:00:00 GMT+0200

Another question is why do date1.setMonth(10) gives a date in December (should be November).

A: setMonth accepts a second parameter:

If you do not specify the dayValue parameter, the value returned from the getDate method is used.

When you set the month to 10 (November), it grabs the current day value (31) and sets that as the day. Since there are only 30 days in November, it rolls you over to December 1st.

A: Finally got it. new Date() sets the date to the current date and time. In other words, October 31st (at the time of this writing).
When you then try to set the month to November, what's it to do? November only has 30 days... so it wraps it round to December.
If you change the order so that you set the day-of-month before the month, it works:
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setDate(1); // day of the month (from 1-31)
date1.setMonth(10); // month (from 0-11)

Or as implied by jbabey's answer:
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10, 1); // month (from 0-11) and day (1-31)

The documentation isn't terribly clear, but it's at least suggestive:

If a parameter you specify is outside of the expected range, setMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for month.

("Accordingly" is far from precise, but it means the implementation is at least arguably correct...)

A: You're creating a var containing the current date (new Date()) and then you're changing some of it's keys (year, month and day).
On the other hand new Date(2012, 10, 1, 0, 0, 0, 0) means "create a date object with those exact values".
And that's why your date objects aren't equal.


text:
Q: Insert character in string conditional on number of characters from beginning and end I have a list of strings such as
myvar
[1] "VT" "AK" "AL2" "CA24" "NY12"
[6] "AZ6" "WY4"

I would like to insert the character "0" after the second character in all strings that have 3 characters, and "01" at the end of the string in all strings that have two characters, in order to obtain the output
myvar
[1] "VT01" "AK01" "AL02" "CA24" "NY12"
[6] "AZ06" "WY04"

I thought I could do this in one line using regex lookahead and lookbehind, but I can't get any further than this:
sub('(?<=.{2})(?=.{1})', '0', myvar, perl=T)

myvar
[1] "VT" "AK" "AL002" "CA024" "NY012"
[6] "AZ06" "WY04"

Any help would be much appreciated,
Simone

A: We can extract the numeric part using sub, convert the string to numeric class, change the NA values (from coercion) to 1, and use sprintf to paste the non-numeric (sub('\\d+', ...)) and the formatted numeric part.
 v1 <- as.numeric(sub('\\D+', '', myvar))
 v1[is.na(v1)] <- 1
 sprintf('%s%02d', sub('\\d+', '', myvar),v1)
 #[1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

Or use gsubfn.  We create an ifelse condition for those elements that don't have any numeric element and paste with 1. We match the numeric part in gsubfn (\\d+), replace it by formatting with sprintf.
 library(gsubfn)
 gsubfn('\\d+', ~sprintf('%02d', as.numeric(x)),
     ifelse(!grepl('\\d+', myvar), paste0(myvar, 1), myvar))
 #[1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

Or a slightly more compact version is using sub to append 1 to those elements that don't have numeric part
 gsubfn('\\d+', ~sprintf('%02d', as.numeric(x)) ,sub('(?<=[A-Z])$', '1', myvar, perl=TRUE))
 #[1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

Or to make it more compact without the lookarounds,
gsubfn('\\d+', ~sprintf('%02d', as.numeric(x)), sub('(\\D+)$', '\\11', myvar))
#[1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

A: On a static cut and paste idea:
paste0(substr(myvar, 0, 2), sub("00", "01", gsub(" ", "0", sprintf("% 2s", substr(myvar, 3, 4)))))

# [1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

Get the 2 last chars with substr, pad them to 2 char, replace the spaces by 0, and then 00 by 01, paste with the 2 first chars and you get the result.

A one liner (without regex as they're not needed and can't be really useful to determine the replacement size at all unless a using a complex choice after on which to replace with what):
myvar[nchar(myvar)<4] <- paste0(myvar[nchar(myvar)<4],sprintf(paste0("%0",4-nchar(myvar[nchar(myvar)<4]),"i"),1))

The goal is to get a vector of 4 chars entries, so for all entries under 4 chars (myvar[nchar(myvar)<4]) print them along the 0 left padded "1" of length 4 minus the actual entry length.
There's probably a way with with to avoid the redundant call to myvar[nchar(myvar)<4] but as I'm not used to it, I'm actually digging.

A: another option (could be a one-(long)liner...):
mapply(function(x, dc_x){
           if(nchar(x)<4) paste0(dc_x[1], "0", ifelse(length(dc_x)-1, dc_x[2], "1")) else x
        },
       x=myvar, dc_x=strsplit(myvar,  "(?<=^.{2})", perl=T))
#    VT     AK    AL2   CA24   NY12    AZ6    WY4
# "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"

explanation:
dc_x is a list of vectors, one for each element of myvar, with the 1st item being the 1st 2 characters of the corresponding item in myvar. So, for elements of less than 4 characters, you paste the 2 first characters with "01" if there are only 2 characters or with "0" and the rest of the string, if there are more than 2 characters.

A: You may put the output of sub or gsub command as input to another sub or gsub commands.
myvar <- c("VT", "AK", "AL2", "CA24", "NY12",
           "AZ6", "WY4")
sub("^(.{2})$", "\\101", sub("^(.{2})(.)$", "\\10\\2", myvar))
# [1] "VT01" "AK01" "AL02" "CA24" "NY12" "AZ06" "WY04"


text:
Q: How can I access various UIViews within a Nib, programmatically? First, I am super-new to Objective-C/iOS development and, in fact, this question is for my first, test project.  Also, I come from a C#/WinForms background so I'm coming into iOS development with certain pre-conceived notions of user interface design and application state.  Please bear with me and help clear up my confusion.
I just created my first iOS application project which, consists of a Single View.  I allowed Xcode to create all the files for me through the Single View project wizard.  When it was finished, I opened my new applications, single UIView Nib file in the designer and I dropped three sliders onto the view.
The desired purpose of this application is very simple-- each slider corresponds to either the R, G or B values associated with the background color of my view.
I have figured out how to set the background of my view but I can not figure out how to access the values of each slider objects.  Yes, I can hook-up and respond to an IBAction for each slider, but my plan is that each time a slider's value changes, I want the IBAction to call a refactored method that accesses the values of all three sliders and then set's the views Background Color based of the values associated with each one.
How can I access the values of my sliders?  Specifically, how can I access the value of the sliders that I created by dragging and dropping them into the Nib designer window?  I've seen code explaining how to programatically add a UISlider to your UIView and then access the value, but how do you access the value of a UISlider that's added to the Nib and, I assume, will be automatically "wired" in at compile time?
Hopefully this makes since?  If I'm missing an intermediate step or critical concept, please let me know.

A: You create UISlider ivars/properties and make them IBOutlets:
@property (nonatomic, retain) IBOutlet UISlider* yourSlider;

You synthesize it in your .m file and the connect the IBOutlet in interface builder. The yourSlider pointer is then a reference to the object you connected it to. Note that it will only be loaded with the view of the UIViewController and therefore will be nil until viewDidLoad is called. You also must set it back to nil
self.yourSlider = nil;

in your viewDidUnload method (so that it is released). In Xcode 4 you have a convenient way of doing all the above steps in one action (see the "Interface Builder is Built-in" of What's new in XCode 4)

A: Similar to CTRL+dragging from the UISlider to the .m file to create the IBAction, you can CTRL+drag the UISlider from your .nib designer to the associated .h file and have it create a property for you. Then, from your .m file, you can access self.mySlider (or whatever you name the property).
There's a video on this page that shows binding to a UISlider specifically.

A: Another approach is to use the tag property of a view.
@property(nonatomic) NSInteger tag

- (UIView *)viewWithTag:(NSInteger)tag

You can set the tag property of a view in the interface builder and later reference that view in your controller.
UIView *myViewFromTag = [self.view viewWithTag:theNumberYouSetInIB];

In general, it's better to stick with IBOutlets. However, there are certain situations where it makes more sense to use tags.
Good luck!


text:
Q: Restore deleted files after Windows HDD repair On an HDD Windows 10 wanted to check and repair the files. After the Check and Repair some files are gone. I do have Linux and I hoped Linux can just read them. I found the recycle bin on the HDD, however these missing files weren't in there.
Do you have any suggestion how to restore these files?
Kind regards

A: So: The solution for me was:
I found the LOST directory. There all my data were. However not in the correct file format. On Linux it was no problem to open these (as Linux doesn't care about the ending).
PDFs however aren't restored 100% correct. Just changing the ending to .pdf does the thing for Linux. However the friend of mine using Adobe Reader cannot open these (Opening the PDFs with a Browser like Edge seems to work).
So For PDFs I need to print them to pdf. This seems to work.


text:
Q: $ X_n = 2 Y_n + Y_{n+1} $ (non)Markov Chain
Let $Y_1,Y_2,\dots$ be iid random variables with $P(Y_n=0)=1-p,\; P(Y_n=1)=p$ where $p\in(0,1)$. Define
  $$ X_n = 2 Y_n + Y_{n+1} $$
  The question is, whether $\{X_n\}$ is a Markov chain or not.

This is a homework question. The implication is that it is not a Markov chain, since it was given as a counterexample against common intuition ("I see $n$ and $n+1$ in the definition, it's gotta be a Markov chain!")
My idea: It seems like the value of $X_n$ uniquely determines the values of $Y_n$ and $Y_{n+1}$, as each possible value ($0,1,2,$ or $3$) has a specific combination of $Y$'s that yield that combination. Thus it seems to me that the probability of different outcomes of $X_{n+1}$ is uniquely determined by $X_n$ regardless of the previous history, which points towards being a Markov chain.
Now I don't like spoiling the fun of finding the answer myself. But I've literally never encountered a problem that left me so clueless, usually I am at least aware of my lack of understanding.
So, please, I do not want a complete answer. I'd like to be reassured that I am indeed missing something elementary and perhaps just nudged in the right direction.
Thank you!


text:
Q: How get id from page with a controller to another page with different controller I have 3 tables: courriersEntrees, traitements, users
I have to create a traitement when the user clicks button 'affecter traitement' in index page that presents a list of courriers.
How can I get the id of the courrier clicked to the create function?
my index.blade.php of courriersEntreeController:

                emetteur
                sujet
                date recu
                type

            @foreach($courriers as $courrier)

                {{ $courrier->emetteur}}
                {{$courrier->sujet}}

                {{$courrier->date_recus}}
                {{$courrier->type}}

                    <form action="{{url('courriers/'.$courrier->id) }}" method="post">

                        {{csrf_field()}}
                        {{method_field('DELETE')}}

                          detail
                    id.'/edit')}}" class="btn btn-primary"> editer
                      Affecter Traitement
                    <button type="submit" class="btn btn-primary"> supprimer </button>
            </form>

            @endforeach

My traitementController
 public function create()
    {    $courrier= courriersEntree::find($id);
        return view('traitement.create');
    }

My traitement table:

A: you have to pass the id from your view to the controller :
id)}}" class="btn btn-primary"> Affecter Traitement

Or with url like :
id)}}" class="btn btn-primary"> Affecter Traitement

your controller seems to be :
public function create($courrier_id)
    {    $courrier= courriersEntree::find($courrier_id);
        return view('traitement.create');
    }

A: If you logged with any user, You can get logged user id using \Auth::user()->id . If you just want to forward object id you can sent it in route <a href="{{route('routename',['id'=$id])}}. May this will helpful for you.


text:
Q: MQ vs REST Performance in Multithreading Currently I have a messaging engine that processes thousands of requests per second, the performance is bad because the current implementation is consuming a REST service which is a blocking operation, so it ends up running out of threads from the thread pool, since consuming a REST service is running on top of HTTP what I understand is that there is no way for me to fire a "fire and forget" request, at least I need to wait for the HTTP Response, even if a Future is used this would be running in a different thread, so even if the main thread is not blocked it will end up starving the thread pool anyway, so my question is, if I have this high number of concurrency wouldn't it be better to send this to an MQ instead? this way this wouldn't be a blocking operation anymore, correct ? The app is currently running on Akka framework.

A: So the initial data are as follows:

*

*your program issues thousands of requests per second to a REST service,

*POST request is taking more than 1 sec,

*it ends up running out of threads from the thread pool.

First thing you should check: how many simultaneous requests the REST service is able to bear? Can it be so that it cannot handle thousands of requests per second, and the large timing of single request is a result of the service overloading? Then you have to set a mechanism to limit the rate of your requests. Actually, to set such a limit is a good idea under all circumstances.
Second, you should decide if such access rate can be achieved with synchronous or asynchronous I/O. Synchronous I/O is simpler and faster, but requires more memory consumption for threads. A rough estimate is as follows:

*

*less than 100 simultaneous requests: use sync

*more than 10000 simultaneous requests: use async

*in between: either way

If you decided to use synchronous I/O, then the most simple and natural way to set a request rate limit is using a Semaphore: a thread wanting to issue next requests acquires the semaphore object, and after recieving the reply releases it. Keep the number of threads in thread pool equal to the request limit.
If you decided to use asynchronous I/O, then there is no universal mechanism to set such a limit, because asynchronous semaphores usually are not available for developer. If your async I/O library has reactive interface, use it (async semaphores are part of backpressure mechanism). If not, you can create such a mechanism out of following components:

*

*a blocking queue for asynchronous requests

*a limiting Semaphore

*a thread, which in a loop does the following: acquires the semaphore, takes next request from the queue, and issues it. When the request is finished (no matter successfully or not), the semaphore is released by the request's callback.

This mechanism uses single thread for all the asynchronous requests, thus consuming not so much memory, and works fast enough. If, however, you need it to work faster, simply increase the number of threads.


text:
Q: hphpize not working when trying install hhvm mongo driver I was trying to install mongo driver for hhvm.
At some time, I have to install hhvm-dev so I can use hphpize later. This thing is that when I try to run hphpize, it returns "hphpize: command not found", even after install hhvm-dev.
Did anyone have the same problem?
Driver documentation here: https://github.com/mongodb/mongo-hhvm-driver
Thanks.

A: Use your package manager to determine the set of files that hhvm-dev installed. If hphpize is included, add the directory where it is located to PATH. If not included, you may need to install some other package.


text:
Q: I cloned the project with git. And now the error "Cannot find 'NewsTableViewController' in scope" appears I cloned the project with git.
And now the error "Cannot find 'NewsTableViewController' in scope" appears
I saw that there is no Target membership in the file attribute inspector with the error. So I don't understand how I can add it there - dragging and dropping didn't help.
Target membership

A: Sooo...I did it

*

*Add missing files (folders/folders with files) to the project by dragging and dropping

*In the window that appears, select the item with "groups", not "folders". Make sure that "Copy items if needed" is checked


text:
Q: Remove item column from Order PDF print I'd like to completely remove the Tax column from items list, in order pdf.
I've managed to remove the item tax value, but I can't find how to remove the "Tax" column header.
Any ideas?

A: Im showing the files where it is (you can override it )

vendor/magento/module-sales/Model/Order/Pdf/Items/Invoice/DefaultInvoice.php

Remove this on draw() function:
// draw Tax
        $lines[0][] = [
            'text' => $order->formatPriceTxt($item->getTaxAmount()),
            'feed' => 495,
            'font' => 'bold',
            'align' => 'right',
        ];

vendor/magento/module-sales/Model/Order/Pdf/Invoice.php

Remove this on _drawHeader function:

$lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' =>
  'right'];

A: Remove Tax from item row
Add below code in [Vendor]/[Module]/etc/di.xml file for ovrride file
<preference for="Magento\Sales\Model\Order\Pdf\Items\Invoice\DefaultInvoice" type="[Vendor]\[Module]\Model\Order\Pdf\Items\Invoice\DefaultInvoice" />

Create New file DefaultInvoice.php in [Vendor]\[Module]\Model\Order\Pdf\Items\Invoice\ directory and add below code in that file
namespace [Vendor]\[Module]\Model\Order\Pdf\Items\Invoice;

 class DefaultInvoice extends \Magento\Sales\Model\Order\Pdf\Items\Invoice\DefaultInvoice
{

public function draw()
{
    $order = $this->getOrder();
    $item = $this->getItem();
    $pdf = $this->getPdf();
    $page = $this->getPage();
    $lines = [];

    // draw Product name
    $lines[0] = [['text' => $this->string->split($item->getName(), 35, true, true), 'feed' => 35]];

    // draw SKU
    $lines[0][] = [
        'text' => $this->string->split($this->getSku($item), 17),
        'feed' => 290,
        'align' => 'right',
    ];

    // draw QTY
    $lines[0][] = ['text' => $item->getQty() * 1, 'feed' => 435, 'align' => 'right'];

    // draw item Prices
    $i = 0;
    $prices = $this->getItemPricesForDisplay();
    $feedPrice = 395;
    $feedSubtotal = $feedPrice + 170;
    foreach ($prices as $priceData) {
        if (isset($priceData['label'])) {
            // draw Price label
            $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedPrice, 'align' => 'right'];
            // draw Subtotal label
            $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedSubtotal, 'align' => 'right'];
            $i++;
        }
        // draw Price
        $lines[$i][] = [
            'text' => $priceData['price'],
            'feed' => $feedPrice,
            'font' => 'bold',
            'align' => 'right',
        ];
        // draw Subtotal
        $lines[$i][] = [
            'text' => $priceData['subtotal'],
            'feed' => $feedSubtotal,
            'font' => 'bold',
            'align' => 'right',
        ];
        $i++;
    }

    // draw Tax
    /*$lines[0][] = [
        'text' => $order->formatPriceTxt($item->getTaxAmount()),
        'feed' => 495,
        'font' => 'bold',
        'align' => 'right',
    ];*/

    // custom options
    $options = $this->getItemOptions();
    if ($options) {
        foreach ($options as $option) {
            // draw options label
            $lines[][] = [
                'text' => $this->string->split($this->filterManager->stripTags($option['label']), 40, true, true),
                'font' => 'italic',
                'feed' => 35,
            ];

            if ($option['value']) {
                if (isset($option['print_value'])) {
                    $printValue = $option['print_value'];
                } else {
                    $printValue = $this->filterManager->stripTags($option['value']);
                }
                $values = explode(', ', $printValue);
                foreach ($values as $value) {
                    $lines[][] = ['text' => $this->string->split($value, 30, true, true), 'feed' => 40];
                }
            }
        }
    }

    $lineBlock = ['lines' => $lines, 'height' => 20];

    $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
    $this->setPage($page);
 }
}

Remove Tax from item row header
Add below code in [Vendor]/[Module]/etc/di.xml file for ovrride file
<preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="[Vendor]\[Module]\Model\Order\Pdf\Invoice" />

Create New file Invoice.php in [Vendor]\[Module]\Model\Order\Pdf\ directory and add below code in that file
namespace [Vendor]\[Module]\Model\Order\Pdf;

 use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection;

 class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
protected function _drawHeader(\Zend_Pdf_Page $page)
{
    /* Add table head */
    $this->_setFontRegular($page, 10);
    $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
    $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
    $page->setLineWidth(0.5);
    $page->drawRectangle(25, $this->y, 570, $this->y - 15);
    $this->y -= 10;
    $page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));

    //columns headers
    $lines[0][] = ['text' => __('Products'), 'feed' => 35];

    $lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];

    $lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];

    $lines[0][] = ['text' => __('Price'), 'feed' => 360, 'align' => 'right'];

    /*$lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' => 'right'];*/

    $lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right'];

    $lineBlock = ['lines' => $lines, 'height' => 5];

    $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
    $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
    $this->y -= 20;
  }
}


text:
Q: Programming against a protocol in Objective-C I stumbled accross the SOLID principles. There is one burning question. Should I always use protocols? I never saw someone using them in the way that a Java developer would use them.
I tried it in a demo project and ended up with a .h file for the protocol, another .h for the header. A .m file for the implementation and sometimes a .xib for the UI.
Is there a reason why an ObjC developer would only use protocols for delegates? I never saw ObjC code with a test first approach. Does SOLID programming apply for ObjC?

A: TDD isn't hugely popular in the ObjC world.  Look at some of the official Apple SDK libraries and you'll find patterns that would make TDD advocates give up in disgust (there are a lot of singletons in the iOS SDK, and it's a pattern that works very well with ObjC).  Unit tests in general aren't that popular, either, which explains why the official unit test suite is a relatively recent edition to Xcode and why it's still third-rate.  The ObjC philosophy seems to be:

"Don't make your code more complicated in order to write tests: simple code is easier to debug."

That'll undoubtedly rattle the TDD guys, but it's the approach I've noted in ObjC developers.
ObjC takes a more pragmatic approach to protocols than Java devs do to interfaces ("every class must have an interface and an implementation, just in case!"):

*

*If you know that you'll need multiple classes with the same interface and want the compiler's help, you can create a protocol.

*If you know that you'll need multiple classes with the same interface but don't care about support from the compiler, you can use "informal protocols" (take a look at how to handle data from a GKSession object: you implement a method, not a protocol).

*If you're probably only going to use one class, just use the class and forget about protocols.

This is why you only tend to see protocols used in conjunction with delegates: they tend to be the only places that you'll create more than one class to implement the necessary functionality, especially as the delegate pattern is so pervasive.  Other languages tend to require you to either subclass and override or implement an interface to provide additional functionality; ObjC tends to use delegates instead.
The fact that ObjC is dynamic removes a lot of the need for protocols/interfaces.  Java, C++ and C# developers spend a lot of time trying to categorize and type everything as accurately as they can, resulting in multitudes of interfaces and classes.  That simply isn't necessary in a dynamic language (and it's one of the reasons I'm so happy to have switched from C# to ObjC: I can spend my time solving problems instead of describing type hierarchies).
ObjC is dynamic and supports duck typing, so if an object implements a method "quack" you can call that method without explicitly conforming to the "Duck" protocol; you can even identify if the object implements the method before calling it thanks to ObjC's excellent metaprogramming capabilities.

A: SOLID principles don't necessarily apply in any context, regardless of technology or programming language. Many developers choose to abide by them though, and it's certainly possible to do in Objective-C.
If you're interested in seeing test-first Objective-C, then take a look at BrowseOverflow: it's a completely test-driven app that makes use of UIKit and network services. I actually wrote it as the sample code for Test-Driven iOS Development, but if you're comfortable with the principles you can just look at the code. You can see there that even though the code was test-driven, it isn't brimming with protocols.
One reason for that is "duck typing". Objective-C, like Smalltalk before it and Ruby after it, doesn't actually care what type an object is, it just sends messages. The type safety system is entirely restricted to the compiler checking. You can therefore type a variable as specifically as you want and still (sometimes with some casting) supply a different type at runtime. As long as both types respond to the messages passed in your code, everything works. You can see that the tests in BrowseOverflow use this to pass in test fakes, even for variables that aren't typed using protocols.
In fact in historical Objective-C and Smalltalk (and in modern Ruby) many collaborating objects aren't typed at all: in Objective-C the id type means "any object". That's less common now in ObjC, but a lot of Apple's framework code is old enough to have been around when this was the norm. You'll notice that newer frameworks, and newer API on existing frameworks, uses stricter typing and protocol types for non-delegate collaborators.

Is there a reason why an ObjC developer would only use protocols for delegates?

Personal choice. There's no underlying technical reason to follow that approach.

Does SOLID programming apply for ObjC?

Yes. Or rather, it can do, and many developers choose to follow SOLID principles.


text:
Q: Multiple Attachment fields on an Infopath form I'm setting up a Infopath form which has a number of different views. On each view I need to ability to add a different attachment to each view, but every time I put the field in a view it duplicates the first Attachment Field. How do I make the Attachment Field unique to the view?

A: The attachments field in the underlying SharePoint list does not work like that. You would need metadata to go along with it, and the attachments field does not have that included.
You can probably achieve your goals if you create an associated document library. I would write the InfoPath form as a web-enabled form, and then add a web part for the doc library below the InfoPath form (not in it, because the tools from InfoPath are clumsy for this. Then you only need to manage the web filters passed to the web part, then make sure your document library requires the data you are filtering on.


text:
Q: What is the use of an empty abstract class? I want to know that is there any use of empty abstract class in Java? If so, what is it?

A: An empty abstract class is very much equivalent to an interface except that it can extend a class
abstract class myAbstractClass // extends anotherClass implements anInterface
{

}

interface myInterface // extends anotherInterface
{

}

This pattern is called Marker interface and SO has a lot of good data about it already: What is the purpose of a marker interface?

A: you can only inherit from one abstract class. Then this is useful to avoid inheritance.

A: Yes, sometimes you need a base class for implement polymorphism.


text:
Q: Stack Pointer reading incorrect value from register Why is Stack-pointer register not reading correct value from another register? When I move a value from register (r0) to stack pointer (r13), the SP reads incorrect value.
This is what is mean:
MOV R0, 10
MOV R13, R0

In this case, "A" should move to R13 but instead it gets 8.
Similarly,
MOV R0, 9
MOV R13, R0

In this case R13 stores 8 instead of 9.
Here's a simple program program that demonstrates the problem,
void Init()
{
    __asm(
        "LDR R0, =0x3FFFFDA7\n"
        "MOV R13, R0\n"
    );
}

int main(void)
{
    Init();
    return (1);
}

void SystemInit(void)
{
}

Nothing much is going on here. Just a simple function call. Inside the function I moved the address to r0. Then I moved the address to R13(SP), but instead of actual address i.e. 0x3FFFFDA7, SP received 0x3FFFFDA4.
The images shows the disassembly,

So what is going on here? Why is Stack pointer Register reading incorrect values?
I am using ARM inline Assembly with C. The IDE is KEIL.
Thanks in Advance.

A: For those who might find this helpful.
Stack-Pointer for armv7 must be 4 bytes aligned. You can write there 0,4,8,12,16 etc but not 9,10,F etc.
So if you want to move any value to Stack-Pointer, make sure it is 4 bytes aligned.


text:
Q: How to remove xarray dimension after adding another without deleting the data variables I have data from ECMWF which when read into xarray looks like this
Dimensions:     (time: 424, step: 12, latitude: 3, longitude: 2)
Coordinates:
    number      int64 0
  * time        (time) datetime64[ns] 1990-03-01T06:00:00 ... 1993-04-22T18:0...
  * step        (step) timedelta64[ns] 01:00:00 02:00:00 ... 11:00:00 12:00:00
    surface     float64 0.0
  * latitude    (latitude) float64 41.0 40.75 40.5
  * longitude   (longitude) float64 -96.92 -96.67
    valid_time  (time, step) datetime64[ns] 1990-03-01T07:00:00 ... 1993-04-2...
Data variables:
    i10fg       (time, step, latitude, longitude) float32 4.876 4.637 ... 3.959
Attributes:
    GRIB_edition:            1
    GRIB_centre:             ecmf
    GRIB_centreDescription:  European Centre for Medium-Range Weather Forecasts
    GRIB_subCentre:          0
    Conventions:             CF-1.7
    institution:             European Centre for Medium-Range Weather Forecasts
    history:                 2022-04-23T22:18 GRIB to CDM+CF via cfgrib-0.9.9...

I've stacked the time and step dimensions to make a new one called forecast. I then added another dimension called valid and set that equal to the coordinate valid_time. Both valid and fcst are the same length, but I now want to drop the fcst dimension. However, when I do this, the data variable also gets deleted. Does anyone know how to fix this? Here is my sample code. There might be a better way to do what I'm doing, but I'm still pretty new to xarray!
ds = ds.stack(fcst=("time", "step")).transpose("fcst", "latitude", "longitude")
ds.expand_dims(valid=ds['valid_time']).drop_dims('fcst')

which leaves me with
<xarray.Dataset>
Dimensions:    (valid: 5088, latitude: 3, longitude: 2)
Coordinates:
  * valid      (valid) datetime64[ns] 1990-03-01T07:00:00 ... 1993-04-23T06:0...
    number     int64 0
    surface    float64 0.0
  * latitude   (latitude) float64 41.0 40.75 40.5
  * longitude  (longitude) float64 -96.92 -96.67
Data variables:
    *empty*

I've tried setting valid as the index then dropping fcst but it still deletes the data variables.
any help would be appreciated!

A: All variables in an xarray Dataset must be indexed by named dimensions. You can use ds.reset_index` drop any labeled coordinates associated with a dimension, but this isn't what you want. You can't simply do away with a dimension without losing the variables which are indexed with this dimension.
From the xarray docs on data structures:

dimension names are always present in the xarray data model: if you do not provide them, defaults of the form dim_N will be created.

Instead, you can swap a non-indexing coordinate for an indexing coordinate using swap_dims. This will swicth valid_time and fcst in your array, such that valid_time becomes the dimension which indexes fcst and any variables previously indexed by fcst (i10fg in your case).
So the answer is, after the stack but without expand_dims or drop:
ds.swap_dims({'fcst': 'valid_time'}).drop('fcst')


text:
Q: dnscrypt-proxy takes long to start at boot SystemD-analyze blame shows 21s.
The issue seems to be here:
sudo systemctl status dnscrypt-proxy
Sep 30 22:18:22 HorniSlezsko systemd[1]: Listening on dnscrypt-proxy listening socket.
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [INFO] + DNS Security Extensions are supported
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [INFO] + Namecoin domains can be resolved
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [INFO] + Provider supposedly doesn't keep logs
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [NOTICE] Starting dnscrypt-proxy 1.6.1
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [INFO] Generating a new session key pair
Sep 30 22:18:24 HorniSlezsko dnscrypt-proxy[1036]: [INFO] Done
Sep 30 22:18:39 HorniSlezsko dnscrypt-proxy[1036]: [ERROR] Unable to retrieve server certificates
Sep 30 22:18:40 HorniSlezsko dnscrypt-proxy[1036]: [INFO] Refetching server certificates
Sep 30 22:18:45 HorniSlezsko dnscrypt-proxy[1036]: [INFO] Server certificate #808464433 received

It can never connect at first and always does so succesfully 15s later.
Only change I've made is in /lib/systemd/system/dnscrypt-proxy.service, in this line:
ExecStart=/usr/sbin/dnscrypt-proxy \
    --resolver-name=soltysiak

I've tried various resolvers and same issue.


text:
Q: Ruby Array Prints as String This piece of code is supposed to loop through an array of IP addresses and checks to see if a port is open.
class Ranger

def initialize(port,file)
    @port = port
    @file = file
    @arr = []
end

def regex(f)
    reg = IO.read(f)
    reg.scan /(?:\d{1,3}\.){3}\d{1,3}/
end

def fileread
        if File.exists?(@file)
            @arr << regex(@file).to_s

            begin
                @arr.each do |ip|
                    sock = Socket.new(:INET, :STREAM)
                    sockaddr = Socket.sockaddr_in(@port, ip.to_i)

                    puts "Host: #{ip}:#{@port} Open" if sock.connect(sockaddr)

                    next

                end

            rescue Errno::ECONNREFUSED
                false
            end
        end
end

end
The code seems to almost completely work, except for one thing. It prints out the success text i.e "Host: #{ip}:#{@port} Open". The problem is that it prints out the entire array where #{ip} is, like this: ["xx.xx.xx.xx","xx.xx.xx.xx","xx.xx.xx.xx"]:22 Open.
It seems to have something to do with the .to_s and .to_i in the script, but it won't work at all without those.

A: From what I can see you are only adding ONE thing to the @arr variable...
@arr << regex(@file).to_s

regex() calls string.scan () which returns an array (presumably your 3 IPs
you're then converting the array to a string and appending the string to @arr.
either you want
@arr = regex(@file) # replace

or
@arr += regex(@file) # concatenate


text:
Q: Databound Windows Forms control does not recognize change until losing focus I use data binding to display values in text boxes in a C# Windows Forms client. When the user clicks Save, I persist my changes to the database. However, the new value in the active editor is ignored (the previous value is saved). If I tab out of the active editor, and then Save, the new value is persisted, as expected.
Is there a way to force the active control to accept its value before persisting?

A: If you can get the Binding instance that corresponds to the input (the TextBox), you can call the WriteValue method to force the value from the control to the object it is bound to.
Also, you can call the EndCurrentEdit method on the BindingManagerBase class (usually a CurrencyManager class instance) to finish the edit, but that requires implementation of the ICancelAddNew or IEditableObject interface on the object that is bound to (and wouldn't require you to fish for the binding).

A: The solution I've used is to call ValidateChildren on the Form from the Save event (call), before actually saving the database records. This forces validation of all fields and thus binding to occur without losing focus of the control currently being edited on the form. It is real handy if the save button is on the Windows menu system and not form itself - plus it returns False if data in any control on the form is invalid and thus can be used to prevent saving errant data.
This also gets around inconsistent updating of the bound field that occurs when OnPropertyChanged is used as a binding method instead of OnValidation. Also, it is critical if the binding method is set to Never with separate WriteValue calls made for each validated event trapped per control.

A: This is kind of a hack, but try setting the focus away from the active editor (by setting the focus to something else, like the save button for example) in the button event before you call save.


text:
Q: How to automatically add extra condition to all Models in Rails? I'm now come to the condition which I need to add some default extra rule to Rails.
eg. when I call :
      Person.first
      Employee.all
    It will automatically do:
      Person.first(:conditions => ['age < ?', 100])
      Employee.all(:conditions => ['age < ?', 100])
In here the condition age < 100 is added to all Models including sub-resources, is there a way to do this in Rails?

A: you may use default_scope like the following
class Person < ActiveRecord::Base
  default_scope :conditions => ['age < ?', 100]
end

You might be interested in this post.
http://archives.ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

A: I recommend not using default scope for conditions, just for ordering.
So I would add a named scope in each model and then use that scope for most queries, e.g.
Rails 3
scope :confirmed, :conditions => { 'age < ?',100 }

Rails 4
Some scopes are moving to be class methods (what they basically are anyway) so you can use something like:
def age_limit
  where :age < 100
end

More info on using scopes at : https://stackoverflow.com/a/5609947/631619
Having the same code in more than model is somewhat undry but this is the routes I would take for less than a dozen models.  You could also create a Constant AGE_LIMIT but then system constant are fraught with issues.  You might be better of creating a model perhaps just for age, then have a model for max_age, then refer to that. Something like that.


text:
Q: Can you switch the order of the determinants when changing variables using the Jacobian? Let say we're changing the variables and we use the Jacobian to do this. Lets say we integrate in respect to $u$ and $v$, does it matter if we set up the integral like $\int\int\,\mathrm{d}u\mathrm{d}v$ or $\int\int\,\mathrm{d}v\mathrm{d}u$ after calculating the Jacobian?

A: What I think you are asking is (relevant to the question)

does the Jacobian change if we consider
  $$
\newcommand{\pwrt}[2]{\frac{\partial #1}{\partial #2}}
J = \left|\det \pmatrix{
\pwrt xu & \pwrt xv\\
\pwrt yu & \pwrt yv}\right|
$$
  as opposed to
  $$
\newcommand{\pwrt}[2]{\frac{\partial #1}{\partial #2}}
J = \left|\det \pmatrix{
\pwrt xv & \pwrt xu\\
\pwrt yv & \pwrt yu}\right|
$$

The answer to this question is no. Switching rows/columns changes the sign but not the magnitude of the determinant of a matrix.


text:
Q: How to connect points with a polyline in ArcMap 10? I have a layer containing a few hundred points representing a survey track. The points are laid out in chronological order in the corresponding attribute table.
How can I have ArcMap 10 automatically "connect the dots" so that I essentially turn the points into a polyline representation of my survey track?
Thanks!
BTW, is there a way for me to specify a few of those points for ArcMap to IGNORE when it makes the polyline?

A: Almost the same answer as Dano - his post references the one on ArcScripts.
It was such a popular download this tool is included in the toolbox at 10.0
Points to Line:
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00170000003s000000.htm
And you asked about doing an ignore.... just use a selection set of the points you actually want. The tool will connect based on a field (if you choose) only your selected points.

A: I just did a quick Google search ("join points in ESRI") and got a hit.  You'll have to do the read up yourself, but at a glance, it looks to me like this will do the trick.  Here ya go:
Points to lines
As for ignoring points, just make a separate file and delete the points you want to ignore before you run the script.  You'll still have them in the original file that way.

A: DNR Garmin can be used to do this sort of task if your points are in order, simply by importing a point shapefile and resaving as a polyline (track) file.
DNR Garmin link
EDIT
I should add that you can import points (or waypoints) in a variety of formats and export to polylines (tracks) or polygons using this program.  It is integrated for ArcMap 9.3 or less and a promise that a version for ArcMap 10 is due this spring.

A: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00170000003s000000.htm
Use Points To Line (Data Management)
You can ignore points using the Line Field option, specifically using a value in one field to calculate the line.  So, for the points you want, add an arbritary value, and another for ones you don't want, and then sort on that:
# Name: PointsToLine_Example2.py
# Description: Convert point features into line features
# Author: ESRI

# Import system modules
import arcpy
from arcpy import env

# Set environment settings
env.workspace = "C:/data"

# Set local variables

inFeatures = "calibration_points.shp"

outFeatures = "C:/output/output.gdb/out_lines"

lineField = "ROUTE1"

sortField = "MEASURE"

# Execute PointsToLine
arcpy.PointsToLine_management(inFeatures, outFeatures, lineField, sortField)

That should work.

A: When using the Point to Line script tool, be sure to first add the following fields if you don't already have something similar set up: Segment (or similarly named): to identify each segment; and Order_ (or similarly named - don't use "Order" as this is a reserved word): to count, in order, the points pertaining to a segment.  Make both fields text with max 10 characters.  Go through the map and identify segments (start at 01) and then identify the order of the points (001, 002, etc.; kind of like "connect the dots").  When using the tool, you can set the "segment" field as the Line option; and set the Order_ field as the point order.  If done correctly, this will create line segments which will follow the ordered points along the proper path.

A: Follow these steps:

*

*Now, carefully by using the Microsoft Excel add 2 field with names of e_end (or as you like for the y axis coordinate) and y_end as well

*The trick is copy your points coordinate without the first point coordinate and paste it in the first point e_end field and y_end field. "This means that the first point will be start point for line and the second point will be end point for the same line

*Repeat the previous step to all number of your point.

*Now, You have 4 field for every one point 2 for the x,y coordinate of the start point an 2 for the end point for each line

*Convert your point in to event feature. File → Add Data → Add x, y Data.

*Export the event x, y table to shape file and save where ever you want.

*By using the tool xy to line. Search for it in ArcMap search wizard

*Follow the required step and apply.


text:
Q: How can I re-invoke a method that is in HUB? asp net core signalr Hello everyone I'm using aspnet core and signalr, and the problem with which I found was that I make a request
to the hub and the first time it enters the method and returns the values, but
and when I call the same method again I do not enter, this warning message comes out "Warning: No client method with the name 'mymethod' found signalr"
How can I solve this?, help please
this is my code
javascript
connection.invoke('mymethod', value1, value2);
event.preventDefault();

Hub
public async Task mymethod(string number, string another)
    {  //my operation
    }


text:
Q: N-Tree Traversal with Scala Causes Stack Overflow I am attempting to return a list of widgets from an N-tree data structure.  In my unit test, if i have roughly about 2000 widgets each with a single dependency, i'll encounter a stack overflow.  What I think is happening is the for loop is causing my tree traversal to not be tail recursive.  what's a better way of writing this in scala?  Here's my function:
protected def getWidgetTree(key: String) : ListBuffer[Widget] = {
  def traverseTree(accumulator: ListBuffer[Widget], current: Widget) : ListBuffer[Widget] = {
    accumulator.append(current)

    if (!current.hasDependencies) {
      accumulator
    }  else {
      for (dependencyKey <- current.dependencies) {
        if (accumulator.findIndexOf(_.name == dependencyKey) == -1) {
          traverseTree(accumulator, getWidget(dependencyKey))
        }
      }

      accumulator
    }
  }

  traverseTree(ListBuffer[Widget](), getWidget(key))
}

A: For the same example as in @dhg's answer, an equivalent tail recursive function with no mutable state (the ListBuffer) would be:
case class Widget(name: String, dependencies: List[String])

val getWidget = List(
  Widget("1", List("2", "5")),
  Widget("2", List("3", "4")),
  Widget("3", List()),
  Widget("4", List()),
  Widget("5", List())).map { w => w.name -> w }.toMap

def getWidgetTree(key: String): List[Widget] = {
  def addIfNotAlreadyContained(widgetList: List[Widget], widgetNameToAdd: String): List[Widget] = {
    if (widgetList.find(_.name == widgetNameToAdd).isDefined) widgetList
    else                                                      widgetList :+ getWidget(widgetNameToAdd)
  }

  @tailrec
  def traverseTree(currentWidgets: List[Widget], acc: List[Widget]): List[Widget] = currentWidgets match {
    case Nil                                => {
      // If there are no more widgets in this branch return what we've traversed so far
      acc
    }
    case Widget(name, Nil) :: rest          => {
      // If the first widget is a leaf traverse the rest and add the leaf to the list of traversed
      traverseTree(rest, addIfNotAlreadyContained(acc, name))
    }
    case Widget(name, dependencies) :: rest => {
      // If the first widget is a parent, traverse it's children and the rest and add it to the list of traversed
      traverseTree(dependencies.map(getWidget) ++ rest, addIfNotAlreadyContained(acc, name))
    }
  }

  val root = getWidget(key)
  traverseTree(root.dependencies.map(getWidget) :+ root, List[Widget]())
}

For the same test case
for (k <- 1 to 5)
  println(getWidgetTree(k.toString).map(_.name).toList.sorted)

Gives you:
List(2, 3, 4, 5, 1)
List(3, 4, 2)
List(3)
List(4)
List(5)

Note that this is postorder not preorder traversal.

A: The reason it's not tail-recursive is that you are making multiple recursive calls inside your function.  To be tail-recursive, a recursive call can only be the last expression in the function body.  After all, the whole point is that it works like a while-loop (and, thus, can be transformed into a loop).  A loop can't call itself multiple times within a single iteration.
To do a tree traversal like this, you can use a queue to carry forward the nodes that need to be visited.
Assume we have this tree:
//        1
//       / \
//      2   5
//     / \
//    3   4

Represented with this simple data structure:
case class Widget(name: String, dependencies: List[String]) {
  def hasDependencies = dependencies.nonEmpty
}

And we have this map pointing to each node:
val getWidget = List(
  Widget("1", List("2", "5")),
  Widget("2", List("3", "4")),
  Widget("3", List()),
  Widget("4", List()),
  Widget("5", List()))
  .map { w => w.name -> w }.toMap

Now we can rewrite your method to be tail-recursive:
def getWidgetTree(key: String): List[Widget] = {
  @tailrec
  def traverseTree(queue: List[String], accumulator: List[Widget]): List[Widget] = {
    queue match {
      case currentKey :: queueTail =>        // the queue is not empty
        val current = getWidget(currentKey)  // get the element at the front
        val newQueueItems =                  // filter out the dependencies already known
          current.dependencies.filterNot(dependencyKey =>
            accumulator.exists(_.name == dependencyKey) && !queue.contains(dependencyKey))
        traverseTree(newQueueItems ::: queueTail, current :: accumulator) //
      case Nil =>                            // the queue is empty
        accumulator.reverse                  // we're done
    }
  }

  traverseTree(key :: Nil, List[Widget]())
}

And test it out:
for (k <- 1 to 5)
  println(getWidgetTree(k.toString).map(_.name))

prints:
ListBuffer(1, 2, 3, 4, 5)
ListBuffer(2, 3, 4)
ListBuffer(3)
ListBuffer(4)
ListBuffer(5)

A: Awesome!  thanks.  I didn't know about the @tailrec annotation.  that's a pretty cool little gem there.  I had to tweak the solution just a little bit because a widget with a self reference was resulting in in an endless loop.  also newQueueItems was an Iterable when the call to traverseTree was expecting a List, so i had to toList that bit.
def getWidgetTree(key: String): List[Widget] = {
  @tailrec
  def traverseTree(queue: List[String], accumulator: List[Widget]): List[Widget] = {
    queue match {
      case currentKey :: queueTail =>        // the queue is not empty
        val current = getWidget(currentKey)  // get the element at the front
        val newQueueItems =                  // filter out the dependencies already known
          current.dependencies.filter(dependencyKey =>
            !accumulator.exists(_.name == dependencyKey) && !queue.contains(dependencyKey)).toList
        traverseTree(newQueueItems ::: queueTail, current :: accumulator) //
      case Nil =>                            // the queue is empty
        accumulator.reverse                  // we're done
    }
  }

  traverseTree(key :: Nil, List[Widget]())
}


text:
Q: "Insert...select" transactions with multiple values and normalized database This question properly explains how to simultaneously insert data in a database for "hierarchical" structures (is-a relationship):

No, you can't insert into multiple tables in one MySQL command. You
  can however use transactions.
BEGIN;
INSERT INTO base_class (data0, data1) VALUES('0', '1');
INSERT INTO derived_class (base_id, data2, data3) VALUES(LAST_INSERT_ID(), '2', '3');
COMMIT;

The solution works well when inserting things one at a time.
I'm, however, in a situation where I need to insert multiple values at the same time using INSERT...SELECT.
BEGIN;
INSERT INTO base_class (data0, data1) SELECT d0, d1 FROM stuff
INSERT INTO derived_class (base_ids, data2, data3) SELECT ???, d2, d3 FROM stuff
COMMIT;

How am I supposed to tell MySQL to "link" every instance of derived_class to the previously created base_class through the base class IDs?
Ideally, I would "loop" through the two tables simultaneously, but that's impossible in MySQL or MariaDB:
# PSEUDOCODE! NOT VALID.
BEGIN;
INSERT INTO
                base_class (data0, data1)
     ALONG_WITH derived_class (base_ids, data2, data3)
     SELECT d0, d1, GET_ALONG_FIELD(base_class, id), d2, d3 FROM stuff
     #      _______ table 1 values
     #              _______________________________________ table 2 values
COMMIT;

How can I solve this issue while maintaining the "hierarchical" design of my tables?

EDIT:
I've opened this question again because I'm curious if it's possible to achieve the behavior I desire without having to resort to procedural-like SQL code (using cursors).
Is there a way of solving this issue without using cursors?

A: Cursors should do the trick. You can loop through the stuff table and perform the inserts one at a time, grabbing the insert IDs as you go. Something like this (untested):
BEGIN;

  DECLARE get_stuff CURSOR FOR SELECT id FROM stuff;
  DECLARE current_id INT;

  OPEN get_stuff;
  insert_stuff: LOOP

    FETCH get_stuff INTO current_id;
    INSERT INTO base_class (data0, data1)
      SELECT d0, d1 FROM stuff WHERE id = current_id
    INSERT INTO derived_class (base_ids, data2, data3)
      SELECT mysql_insert_id(), d2, d3 FROM stuff WHERE id = current_id

  END LOOP insert_stuff;
  CLOSE get_stuff;

COMMIT;

Another possible approach would be to create a view on the two "insert" tables. There may be restrictions on inserting to the view based on how your tables are structured, but something like this might work (also not tested):
CREATE VIEW stuff_view AS
  SELECT b.data0, b.data1, d.data2, d.data3 FROM base_class AS b
  INNER JOIN dervied_class AS d ON (d.base_id = b.id)

INSERT INTO stuff_view (data0, data1, data2, data3)
  SELECT d0, d1, d2, d3 FROM stuff

I'm actually not sure if MySQL will automatically assign appropriate IDs to both the base and derived class tables.

A: I'm not entirely sure I understand your question. I think you're trying to insert d0 and d1 into base_class and base_ids, d2, and d3 into derived_class in the same order so that the nth inserted values in both base_class and derived_class all come from the nth record in stuff. If my understanding is correct, the following transaction will do what you want.
BEGIN;
INSERT INTO base_class (data0, data1)
SELECT d0, d1
FROM stuff
ORDER BY base_ids
INSERT INTO derived_class (base_ids, data2, data3)
SELECT base_ids, d2, d3
FROM stuff
ORDER BY base_ids
COMMIT;