text:
Q: Updating a state in React leads to auto-updation of another state I have two local states, UserList and ModifiedUsers in my App function. The UserList is supposed to capture an array of user objects from an API, and ModifiedUsers will operate on a copy of the array of objects to reverse/sort the list.
const APIURL = "https://jsonplaceholder.typicode.com/users";
function App() {
  const [UserList, setUserList] = useState([]);
  let [ModifiedUsers, setModifiedUsers] = useState([]);

This getUsers method is used for fetching data from the API and storing it in a local variable users. Which I am then passing to both the UserList array and ModifiedUsers array.
const getUsers = async () => {
    let response = await fetch(APIURL);
    let users = await response.json();
    let modifiedUsers = users;
    setUserList(users);
    setModifiedUsers(modifiedUsers);
   };

This sortList method is called on a button click to sort the array. Even though in this method I am only updating the ModifiedUsers array, it is somehow updating the UserList array as well.
 const sortList = () => {

    let temp = 0;

    for (let i = 0; i < ModifiedUsers.length - 1; i++) {
      if (
        ModifiedUsers[i].name.trim().length >
        ModifiedUsers[i + 1].name.trim().length
      ) {
        temp = ModifiedUsers[i];
        ModifiedUsers[i] = ModifiedUsers[i + 1];
        ModifiedUsers[i + 1] = temp;
      }
    }
    setModifiedUsers(ModifiedUsers);
    if (click % 2 === 0) {
      ModifiedUsers.reverse();
      setModifiedUsers(ModifiedUsers);
    }

    setClick(++click);
     };

When I console log the UserList Array, I see that it has captured the modified values of ModifiedUsers array, even though I am nowhere updating the original UserList Array.
I am unable to retain the original array of objects no matter what I try. Please help.
Here is the code live on a codepen- https://codesandbox.io/s/api-forked-ie57j4?file=/src/App.js
I have tried creating multiple states, but all of them get updated similarly. I was expecting only the ModifedUsers array to get updated, but all of them did.

A: Essentially, you are modifying your UserList — not only because it obviously behaves the same like your ModifiedUsers but because of the way you created it.
In JavaScript, all object variables (meaning everything except for primitives like string and boolean) are stored and copied by reference. This means: the value of users is only a pointer, pointing to the location of your actual array. When you copy this into your ModifiedUsers, you are only copying the pointer, which in turn leads to using the same array. And by sorting this one, the same change (hence the same array) is visible in UserList.
To modify the two arrays independently, you have to clone them, in order to create an exact copy with new pointers. For example, you can use the JavaScript spread syntax:
let modifiedUsers = [...users]

Keep in mind that this will only clone 1 level, so all the object pointers inside the array remain the same. (It only makes a shallow copy, as pointed out in the answer by @BikramKarki) If you need to change them independently as well, you have to deep clone your array. You can find some more inspiration on this here or on the web.

A: Addition to the answer by @Janik
This happens when the objects inside of an array or objects are still referencing the original object.
And we should be mindful of the use of the spread operator while copying an object or array. The spread operator only makes a copy of primitive data types and not objects (makes a shallow copy of the objects). Nested objects will still be referenced to the old object.
const personA = {
  name: "A",
  age: 5,
  address: {
    city: "City A",
    country: "Country A"
  }
}

const personB = {...personA};
personB.name = "B";
personB.address.city = "City B"

console.log(personA.name); // "A"
console.log(personA.address.city); // "City B" cause address object in "personB" is still referencing the address object in "personA"

Thus, the following is only make a shallow copy.
const modifiedUsers = [...users] // only makes shallow copy

So, we should instead make a deep copy of the objects/arrays with:
const modifiedUsers = JSON.parse(JSON.stringify(users));

NB: This method can only be used with serializable objects for eg.: if your objects or array has functions then it won't work.
More on Shallow vs Deep copy: https://www.freecodecamp.org/news/copying-stuff-in-javascript-how-to-differentiate-between-deep-and-shallow-copies-b6d8c1ef09cd/#:~:text=A%20deep%20copy%20means%20that,into%20how%20JavaScript%20stores%20values.


text:
Q: java smack 4.0.3 library facebook login error Connect to Facebook using smack 4.0.3 java api I want to. There was an error "login" function
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.enabled);
config.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(config);
connection.connect();
connection.login("aaaaa", "passss");

output:

Ağu 27, 2014 9:40:34 PM org.jivesoftware.smack.filter.IQReplyFilter accept
  WARNING: Rejected potentially spoofed reply to IQ-packet. Filter settings: packetId=hR95T-0, to=null, local=null, server=chat.facebook.com. Received packet with from=aaaaa@chat.facebook.com
  Ağu 27, 2014 9:40:39 PM test.main login
  SEVERE: null
  org.jivesoftware.smack.SmackException$NoResponseException
      at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:177)
      at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:161)
      at org.jivesoftware.smack.XMPPConnection.bindResourceAndEstablishSession(XMPPConnection.java:530)
      at org.jivesoftware.smack.tcp.XMPPTCPConnection.login(XMPPTCPConnection.java:260)
      at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:442)
      at test.main.login(main.java:135)
      at test.main.main(main.java:62)

A: You can not login to Facebook with Smack. Smack is used to connect to public XMPP servers or a local server. To login Facebook you need to use its API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't refer to files in different directory I'm having trouble making the files to be found by each others. Let's say I have the Login_Success.php, which has the logout button
<form name="lgt" action="Logout.php" method="post">

    <?php
if(isset($_SESSION['username']))
{
    echo "Welcome ".$_SESSION['username']."";
}
?>

    <input type="submit" name="lgout" value="Logout"></form>

</form>

I put this file into root/action directory; I also place another file named Logout in the same directory.  This is my Logout.php file (I put my index.php in root directory)
<?php session_start();
session_destroy();
header("location:/index.php");
?>

Now I'm facing with a problem that when I login successfully, I can easily logout from Login_Success and go back to the index.php for another login session.  But when I stand there, I go back to the index.php (NOT logout yet, just type index.php to the navigation bar) and I can't logout anymore.  It says:

Object not found!
The requested URL was not found on this server. The link on the
  referring page seems to be wrong or outdated. Please inform the author
  of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.15

I know the problem is that my Logout.php can't be found, just because the index.php and the Logout.php are not in the same directory, unlike these 2.
The index I wrote very simple for I am new to PHP language, I just want the User Information to be replaced the login form when I successfully login.  So I wrote like this
<?php session_start() ?>
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

<?php
if(!isset($_SESSION['username']))
{
include "pc/LoginForm.php";
}
else
{
include "pc/ProfileInfo.php";
}
?>

I'm stuck with this for a couple of days. Now I want to logout at index.php either. Hope to hear from you support very soon.
Sincerely,

A: I'm not seeing the creation of a $_SESSION variable for the username, simply checking if it exists.
Generally log in scripts are a 3-part affair.

*

*Display log in form for user to fill

*Link to login-checker.php(you should have another file that verifies username, password,
  permission,etc) that compares user input from the form to the user info in the database
      -> this is where you set your VERIFIED input as your $_SESSION variables

*Logout.php file to kill the session when you're done (don't change anything there, that's right!)

Seems to me like you should revisit steps one and two.


text:
Q: Bar chart with wrong bar height There are three data series, two of them are bar type series (Insolation Duration and Power Duration).
When I import data (from Striped Table) to the Highcharts, the bar chart height doesn't display properly.
It doesn't fit the scale of the chart's value, like this:
e.g. 2018/05/01
The Insolation value is less than the Power value, but the height of Power Duration bar chart is higher than Insolation Duration.

Here are the chart options I use:
var ChartObj =
{
    type: "chart",
    value:
    {
        "chart": { "alignTicks": false, "zoomType": "xy" },
        "title": { "text": " ", "floating": false, "align": "center" },
        "xAxis":
        [
        {
            "categories": [],   //PUT LABEL IN HERE
            "crosshair": true, "index": 0, "isX": true
        }
        ],
        "tooltip": { "shared": true },
        "legend":
        {
            "layout": "horizontal",
            "align": "right",
            "x": 0,
            "verticalAlign": "top",
            "y": 0,
            "floating": false,
            "backgroundColor": "#FFFFFF"
        },
        "yAxis":
        [
        {
            "gridLineColor": "transparent",
            "labels":
            {
                "format": "{value}",
                "style": { "color": "#7cb5ec" },
                "enabled": false
            },
            "title": { "text": null, "style": { "color": "#7cb5ec" } },
            "opposite": false,
            "index": 0,
        },
        {
            "gridLineColor": "transparent",
            "labels":
            {
                "format": "{value}",
                "style": { "color": "#90ed7d" },
                "enabled": false
            },
            "title":
            {
                "text": null,
                "style": { "color": "#90ed7d" }
            },
            "opposite": true,
            "index": 1,
        },
        {
            "gridLineColor": "transparent",
            "labels":
            {
                "format": "{value}",
                "style": { "color": "#f7a35c" },
                "enabled": false
            },
            "title": { "text": null,
            "style": { "color": "#f7a35c" } },
            "opposite": true,
            "index": 2,
        }
        ],
        "series":
        [
        {
            // Insolation
            "name": " ",
            "color": "#90ed7d",
            "tooltip":
            {
                "valueSuffix": "",
                "pointFormat": "● {series.name}: {point.y:,.2f}
"
            },
            "yAxis": 0,
            "type": "column",
            "data": [],
            "_symbolIndex": 0
        },
        {
            // Power
            "name": " ",
            "color": "#f7a35c",
            "tooltip":
            {
                "valueSuffix": "",
                "pointFormat": "● {series.name}: {point.y:,.2f}
"
            },
            "yAxis": 1,
            "type": "column",
            "data": [],
            "_symbolIndex": 1
        },
        {
            // PR
            "name": " ",
            "color": "#7cb5ec",
            "tooltip":
            {
                "valueSuffix": "",
                "pointFormat": "● {series.name}: {point.y:,.2f}
"
            },
            "yAxis": 2,
            "type": "line",
            "data": []
        }
        ]
    }
};

A: You will need to set a max to the 2 first column axis like this
{
        "gridLineColor": "transparent",
        "labels":
        {
            "format": "{value}",
            "style": { "color": "#7cb5ec" },
            "enabled": false
        },
        "title": { "text": null, "style": { "color": "#7cb5ec" } },
        "opposite": false,
        "index": 0,
        max:12 // The value to set
    },

Or change the index of your series to use the same yAxis
Demo Fiddle


text:
Q: How can I write arrays to a file with one column of int values and another float I've written code to plot the average of two spectra, but I also need to write the average to a text file. I use the following command to do so (x3 and y3 are arrays containing the average x and y values):
np.savetxt('averaged_spectra.txt', np.transpose([x3,y3]))

This works well, however the values in the array x3 are actually four and five-digit integers, and the 18 digit float output I'm getting looks bad and is somewhat incongruous with the spectra files I began with. How can I write the elements of the x3 array as integer values while keeping the elements of y3 as float?

A: A quick way is to add the argument fmt="%g" to the savetxt call:
np.savetxt('averaged_spectra.txt', np.transpose([x3,y3]), fmt="%g")

That tells savetxt to use "%g" as the format for each number.  It will print an integer-valued floating point number as an integer.
You can also use a format string containing two field specifications.  This gives you control of the format of each column.  For example,
np.savetxt('averaged_spectra.txt', np.transpose([x3,y3]), fmt="%6d  %26.18e")


text:
Q: Jcrop change parent div for thumbnail preview I'm using Jcrop plugin for cropping a picture with preview thumbnail.
Jcrop plugin creates preview image with inside jcrop-active div. So how it will be possible to change preview div layer inside other div?
Working example on https://jsfiddle.net/cuwfpo45/
Here HTML:

  <img src="<?php echo $image; ?>" id="target" />

<form id="" class="s-form" method="POST" action="test3.php" onsubmit="return checkCoords();">
  <input type="hidden" id="x" name="x" />
  <input type="hidden" id="y" name="y" />
  <input type="hidden" id="w" name="w" />
  <input type="hidden" id="h" name="h" />
  <input type="hidden" name="image" value="<?php echo $image; ?>" />
  <input type="submit" value="Submit" />
</form>

Here my JS code:
$(function(){
    var box_width = $('#form-photo').width();

    $('#target').Jcrop({
        setSelect: [ 100, 100, 500, 500 ],
        aspectRatio: 1,
        onSelect: updateCoords,
        onChange: updateCoords,
        boxWidth: box_width
    },function(){
        var jcrop_api = this;
        thumbnail = this.initComponent('Thumbnailer', { width: 330, height: 320 });
    });
});

function updateCoords(c)
{
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
};

function checkCoords()
{
    if (parseInt($('#w').val())) return true;
    alert('Please select a crop region then press submit.');
    return false;
};

Thank you for helping!

A: Edit: I have made required adjustment to show preview in a separate div.

$(function(){
    var box_width = $('#form-photo').width();
    var $preview = $('#preview');

    $('#target').Jcrop({
  onChange: showPreview,
  onSelect: showPreview,
    onRelease: hidePreview,
  aspectRatio: 1
 });

  function hidePreview()
{
    $preview.stop().fadeOut('fast');
};

function showPreview(c)
{
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);

    var rx = 100 / c.w;
 var ry = 100 / c.h;

    $('#preview').css({
  width: Math.round(rx * 500) + 'px',
  height: Math.round(ry * 370) + 'px',
  marginLeft: '-' + Math.round(rx * c.x) + 'px',
  marginTop: '-' + Math.round(ry * c.y) + 'px'
 });
};

});
#form-photo{width:500px;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/2.0.4/css/Jcrop.min.css" rel="stylesheet"/>

    <form id="" class="s-form" method="POST" action="act/test3.php" onsubmit="return checkCoords();">
      <input type="hidden" id="x" name="x" />
      <input type="hidden" id="y" name="y" />
      <input type="hidden" id="w" name="w" />
      <input type="hidden" id="h" name="h" />
      <input type="hidden" name="image" value="<?php echo $image; ?>" />
      <input type="submit" value="Submit" />
    </form>


text:
Q: Using table locking to prevent multiple users from updating at a given time I am building a simple shopping cart. Currently, to ensure that a customer can never purchase a product that is out of stock, when processing the order I have a loop for each product in their cart:
-- Begin a transaction --
Loop through each product in the cart and

*

*Select the stock count from the products table

*

If it is in stock:

*

*I will reduce the stock count from the product

*Add the product to the order items table

Otherwise, I call a rollback and return an error
-- (If there isn't a call for rollback, everything ends off with a commit --
However, if at any given time, the stock count for a product is updated AFTER it has checked for that particular product, there may be inconsistencies.
Question: would it be a good idea to lock the table from writes whenever I am processing an order? So that when the 'loop' above occurs, I can be assured that no one else is able to alter the product count and it will always be accurate.
The idea is that the product count/availability will always be consistent, and there will never be an instance where the stock count goes to -1 (which would be unfulfillable).
However, I have seen so many posts on locks being inefficient/having bad effects. If so, what is the best way to accomplish this?
I have seen alternatives like handling it in an update + select query, but have seen that it may also not be suitable in some cases.

A: You have at least three strategies:
1. Pessimistic Locking
If your application will experience low activity then you can lock the tables (or single rows) to make sure no other thread changes the values during the processing of a purchase. It works, but it has performance limitations.
2. Optimistic Locking
If your application/web site must serve a high load then you can opt for the "optimistic locking" strategy. In this case you add a version number column to your critical tables and then you use it when reading/writing it.
When updating stock you check the version number you are updating must be the same that you read. If it's not the case anymore (another thread modified it) you roll back the transaction and can retry again a couple of times until you succeed.
It requires more development effor since you need to identify the bad case and implement retry logic (if you want to).
3. Processing Queues
You can implement processing queues. When a thread wants to "purchase an order" it can submit it to a processing queue for purchase orders. This queue can be implemented by one or more threads dedicated to this task; if you choose multiple threads they can be divided by order types, regions, categories, etc. to distribute the load.
This requires more programming effort since you need to manage asynchronous processing, but can sustain much higher levels of load.
You can use this strategy for multiple different tasks: purchasing orders, refilling stock, sending notifications, processing promotions, etc.


text:
Q: El proceso no puede obtener acceso al archivo porque está siendo utilizado en otro proceso. C# Cuando imprimo un documento, y trato de eliminarlo despues, me sale el siguiente error:
El proceso no puede obtener acceso al archivo C:\T33F9472.pdf porque está siendo utilizado en otro proceso.
El codigo que uso es el siguiente:
String pathTmp = "C:\\" + "T33F9472.pdf"+ ".pdf";
        using (FileStream fs = new FileStream(pathTmp, FileMode.Create))
        {
            fs.Write(renderedBytes, 0, renderedBytes.Length);
            fs.Close();
            SendToPrinter(pathTmp);
            if (System.IO.File.Exists(pathTmp))
            {
                System.IO.File.Delete(pathTmp);
            }
            file_name = fileContentResult.FileDownloadName;
        }

 private void SendToPrinter(String filePath)
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.Verb = "print";
        info.FileName = filePath;
        info.CreateNoWindow = true;
        info.WindowStyle = ProcessWindowStyle.Hidden;

        using (Process p = new Process())
        {
            p.StartInfo = info;
            p.Start();
            p.WaitForInputIdle();
            System.Threading.Thread.Sleep(3000);
        }
        //if (p.CloseMainWindow()==false) Esta linea esta comentada, porque me salia error, no me servia.
        //    p.Kill();

    }

Además, me gustaría saber si el ProcessStartInfo puede leer archivo binario, en vez de ruta de un archivo fisico.
Como podría solucionar este problema.Desde ya, gracias.

A: Creo que tú problema radica en que estas tratando de eliminar el archivo estando aún dentro del using que lo está creando, intenta lo siguiente:
String pathTmp = "C:\\" + "T33F9472.pdf"+ ".pdf";
using (FileStream fs = new FileStream(pathTmp, FileMode.Create))
{
   fs.Write(renderedBytes, 0, renderedBytes.Length);
   fs.Close();
   SendToPrinter(pathTmp);
   file_name = fileContentResult.FileDownloadName;
}

if (System.IO.File.Exists(pathTmp))
{
   System.IO.File.Delete(pathTmp);
}

A: el problema se me soluciono utilizando el código siguiente
try

       { tu codigo }

   Exit Function

Catch ex As Exception

         MsgBox(ex.Message & "...problemas CON GENERAR SELLO DIGITAL ")
End Try


text:
Q: Trouble creating a SELECT to make a VIEW I'm trying to make a VIEW but first I want to have the SELECT correct. I'm working with tables of SugarCRM and can't make it. I tried making it part by part and the firs time I got all the rows but everytime i add an INNER JOIN the rows I get are less and less .
This are my tables
hu35p_huespedes_cstm hdata, /*TABLA DE HUESPEDES - GUEST TABLE*/
hu35p_reservas_cstm rdata, /*TABLA DE RESERVAS - RESERVATION TABLE*/
hu35p_visitas_cstm vdata, /*TABLA DE VISITAS - VISIT TABLE*/
lvr_libro_reclamaciones_cstm ldata, /*TABLA DEL LIBRO DE RECLAMACIONES - COMPLAINS TABLE*/
es_encuesta_satisfaccion_cstm edata, /*TABLA DE ENCUESTA DE SATISFACCION - POLL TABLE*/

hu35p_huespedes_hu35p_reservas_1_c hr, /*RELACIONA RESERVAS CON HUESPEDES - LINKS GUEST WITH RESERVATION*/
hu35p_huespedes_hu35p_visitas_1_c hv, /*RELACIONA HUESPEDES CON VISITAS - LINKS GUEST WITH VISIT*/
hu35p_huespedes_lvr_libro_reclamaciones_1_c hl, /*RELACIONA HUESPEDES CON LIBRO DE RECLAMACION - LINKS GUEST WITH COMPLAINS*/
hu35p_huespedes_es_encuesta_satisfaccion_1_c he, /*RELACIONA HUESPEDES CON ENCUESTA DE SATISFACCION - LINKS GUEST WITH POLL*/
hu35p_reservas_hu35p_visitas_1_c rv /*RELACIONA RESERVAS CON VISITAS - LINKS RESERVATION WITH VISIT*/

This is the query I'm trying
SELECT

hdata.numero_documento_c as Numero_Documento, hdata.nombres_c as Nombres,
hdata.apellido_paterno_c as Apellido_Paterno, hdata.apellido_materno_c as Apellido_Materno,
DATE_FORMAT(rdata.fecha_reserva_c, "%d-%m-%Y") as Fecha_Visita, rdata.numero_habitacion_c as Numero_Habitacion,
ldata.tipo_reclamacion_c as Tipo_Reclamacion,
edata.valor_c as Indice_Satisfacción,
vdata.importetotal_c as Importe_Total_Visita, vdata.importealojamiento_c as Alojamiento, vdata.importebar_c as Bar, vdata.importecomunicaciones_c as Comunicaciones,
vdata.importeconvenciones_c as Convenciones, vdata.importedeportes_c as Deportes, vdata.importefrigobar_c as Frigobar, vdata.importelavanderia_c as Lavanderia,
vdata.importeninos_c as Ninos, vdata.importerestaurante_c as Restaurante,
vdata.importetodoincluido_c as Todo_Incluido, vdata.importevarios_c as Varios, vdata.importewellness_c as Wellness

FROM        hu35p_huespedes_cstm hdata
INNER JOIN  hu35p_huespedes_hu35p_reservas_1_c hr
ON          hdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_huespedes_ida
INNER JOIN  hu35p_reservas_cstm rdata
ON          rdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_reservas_idb
INNER JOIN  hu35p_huespedes_lvr_libro_reclamaciones_1_c hl
ON          hdata.id_c = hl.hu35p_huespedes_lvr_libro_reclamaciones_1hu35p_huespedes_ida
INNER JOIN  lvr_libro_reclamaciones_cstm ldata
ON          ldata.id_c = hl.hu35p_hues9aa7aciones_idb
INNER JOIN  hu35p_huespedes_es_encuesta_satisfaccion_1_c he
ON          hdata.id_c = he.hu35p_huespedes_es_encuesta_satisfaccion_1hu35p_huespedes_ida
INNER JOIN  es_encuesta_satisfaccion_cstm edata
ON          edata.id_c = he.hu35p_huesb4bffaccion_idb
INNER JOIN  hu35p_reservas_hu35p_visitas_1_c rv
ON          rdata.id_c = rv.hu35p_reservas_hu35p_visitas_1hu35p_reservas_ida
INNER JOIN  hu35p_visitas_cstm vdata
ON          vdata.id_c = rv.hu35p_reservas_hu35p_visitas_1hu35p_visitas_idb

When I do this
SELECT

hdata.numero_documento_c as Numero_Documento, hdata.nombres_c as Nombres,
hdata.apellido_paterno_c as Apellido_Paterno, hdata.apellido_materno_c as Apellido_Materno,
DATE_FORMAT(rdata.fecha_reserva_c, "%d-%m-%Y") as Fecha_Visita, rdata.numero_habitacion_c as Numero_Habitacion

FROM        hu35p_huespedes_cstm hdata
INNER JOIN  hu35p_huespedes_hu35p_reservas_1_c hr
ON          hdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_huespedes_ida
INNER JOIN  hu35p_reservas_cstm rdata
ON          rdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_reservas_idb;

I got this (500 ROWS LIMIT)

But the moment I add more lines to the query (like this):
SELECT

hdata.numero_documento_c as Numero_Documento, hdata.nombres_c as Nombres,
hdata.apellido_paterno_c as Apellido_Paterno, hdata.apellido_materno_c as Apellido_Materno,
DATE_FORMAT(rdata.fecha_reserva_c, "%d-%m-%Y") as Fecha_Visita, rdata.numero_habitacion_c as Numero_Habitacion,
ldata.tipo_reclamacion_c as Tipo_Reclamacion

FROM        hu35p_huespedes_cstm hdata
INNER JOIN  hu35p_huespedes_hu35p_reservas_1_c hr
ON          hdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_huespedes_ida
INNER JOIN  hu35p_reservas_cstm rdata
ON          rdata.id_c = hr.hu35p_huespedes_hu35p_reservas_1hu35p_reservas_idb
INNER JOIN  hu35p_huespedes_lvr_libro_reclamaciones_1_c hl
ON          hdata.id_c = hl.hu35p_huespedes_lvr_libro_reclamaciones_1hu35p_huespedes_ida
INNER JOIN  lvr_libro_reclamaciones_cstm ldata
ON          ldata.id_c = hl.hu35p_hues9aa7aciones_idb;

it gets wrong and got this (155 rows even with the limit of 500 rows)

A: The bit about creating a view is extraneous. The crux is the results returned from the  SELECT statement, either fewer rows or more rows that expected.
Most likely explanation for "missing" rows is that one of the tables does not have rows that match. In that scenario, the JOIN operation will exclude rows that don't have matches. When we want to return unmatched rows, we can use an outer join. An outer join will return rows when there isn't matching row in the outer joined table.
For a guest that has zero rows in the complaint table, then this query
SELECT ...
  FROM guest     g
  JOIN visit     v  ON v.guest_id = g.id
  JOIN complaint c  ON c.guest_id = g.id

would return zero rows for that guest.
If we want rows returned for a guest that has no rows in the complaint table, we can use an outer join. We specify that by including the LEFT keyword. For example:
SELECT ...
  FROM guest     g
  JOIN visit     v  ON v.guest_id = g.id
  LEFT
  JOIN complaint c  ON c.guest_id = g.id

Note that this query can return "duplicates", e.g. multiple copies of the same visit row if that is matched to more than one complaint row.
For example, a guest with 4 visits that has 2 complaints, that could produce 8 rows. Each complaint wil lbe matched to each visit.
That's how the set operations in SQL work.


text:
Q: Approachs to load thousands of records into MySQL I have been developing a php application in symfony1 that loads thousands of records from a excel file and evaluates them in the script, and finally inserts them in the MySQL database. I saw that the script is taking to much to load. Im using doctrine 1 to insert the data with transactions.
My questions are:
should I use an ORM or should I use raw SQL for inserting task? is there any performance related between them?
Should I convert the excel file in a CSV, to consume less memory?
Should I use anything else to load the files like other scripting language specifically for this task? files sizes are between 10MB and 50MB
Thanks.

A: Mauro, you can still create a friendly interface in your application to import the records into your database. However using raw sql is definitely the best way to do so. Through PHP you can manipulate your system's resources. Once you've got the file's path (I'd recommend to use CSV) you can issue any command in your system such as:
<?php
shell_exec("mysql -uUSER -pPASSWORD -e 'YOUR SCRIPT TO IMPORT THE DATA HERE'");
...
OR
<?php
shell_exec("mysqlimport -uUSER -pPASSWORD 'YOUR CRITERIA HERE'");
...

I believe it is the best approach for that. Let us know how you sort it out!


text:
Q: Android - Cannot receive C2DM Registration Intent I am attempting to register my device with C2DM and am having major issues. I have followed several tutorials, all of which are very similar. I believe the issue has to do with the registration intent that it sends to the C2DM server. Does anyone have any suggestions. The following is the relevant code:
Manifest: The permissions (outside my application tag):
<!-- Used for C2DM -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.companyname.parade.permission.C2D_MESSAGE" />

This is the Intent registration (inside my application tag):
<receiver
    android:name=".C2DMReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <!-- Receive the actual message -->
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />

        <category android:name="com.companyname.parade" />
    </intent-filter>
    <!-- Receive the registration id -->
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="com.companyname.parade" />
    </intent-filter>
</receiver>

The following is what I call to register my device to the C2DM server (it starts the service that contacts the C2DM servers that is suppose to send back a registration Intent with my registartionID in it). It is located in a file called C2DMessaging:
public static void register(Context context) {
    Intent registrationIntent = new Intent(REQUEST_REGISTRATION_INTENT);
    registrationIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT,
            PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    registrationIntent.putExtra(EXTRA_SENDER, SENDER_ID);
    ComponentName name = context.startService(registrationIntent);
    if(name == null){
        // FAIL!
        Log.d(TAG, "FAIL");
    }else{
        // SUCCESS
        Log.d(TAG, "Success");
    }
}

The ComponentName info is the following:
com.google.android.gsf/com.google.android.gsf.gtalkservice.PushMessagingRegistrar

There is no logcat output. My receiver (named C2DMReceiver) is the following:
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (C2DMessaging.INTENT_REGISTRATION_CALLBACK.equals(action)) {
        // Registration Intent
        Log.w(TAG, "Registration Receiver called");
        handleRegistration(context, intent);
    } else if (action.equals(C2DMessaging.INTENT_RECEIVED_MESSAGE_CALLBACK)) {
        Log.w(TAG, "Message Receiver called");
        handleMessage(context, intent);
    } else if (action.equals(C2DMessaging.INTENT_C2DM_RETRY)) {
        C2DMessaging.register(context);
    }
}

This does not get called at all.
Edit: This whole thing was a stupid mistake on my part. I simply forgot a step somehow in the tutorials I read. I need to add this to my permissions:
<permission android:name="com.companyname.parade.permission.C2D_MESSAGE" android:protectionLevel="signature" />

Thanks to MisterSquonk for the response.

A: From the Google docs for C2DM for Creating the Manifest, the manifest needs a <permission> entry to complement the <uses-permission> entry for C2D_MESSAGE.
Something like this...
<permission android:name="com.companyname.parade.permission.C2D_MESSAGE" android:protectionLevel="signature" />

A: This tutorial worked for me in getting me up to speed:
http://www.vogella.com/articles/AndroidCloudToDeviceMessaging/article.html
I'm not sure why you have two intent filters. I only needed one - com.google.android.c2dm.intent.REGISTRATION (see tutorial above for a complete example manifest)
I'd check your manifest is correctly referencing the receiver class - perhaps try a fully-qualified reference to the class. I had an issue at one point where I moved receiver class in my project structure and all messages stopped.
I'd also check that the C2DM account is set up right, and with the right package name.
I'd also try it on another device, as in my experience some Android devices fall off C2DM and just don't receive messages for a period of time. I find sometimes flicking to airplane mode and back sorts it out, but I found testing on several devices essential to rule out problems with a specific device.


text:
Q: Forgotten user password for Ubuntu 12.04 I recently found my old Lenovo which has Ubuntu 12.04 LTS and I've forgotten my user login. My dad is the registered admin but he's no longer here and I've tried holding the shift key when I restart like so many people have said but nothing notable really happens?
I'd really appreciate it if someone could help me and explain it as if they're talking to a toddler because computer talk really confuses me.
Thank you :)

A: Boot the LiveCD and mount the root partition of your main system, enter the chroot session and use the passwd command to set the new password. Exit chroot, unmount the root partition and reboot. :)


text:
Q: Parameters in R lines Function I want to plot the 97% confidence interval and prediction interval into my other plot using different colours and legends. I want them to be represented by just straight lines across the scatter plot graph.
Please forgive me as I'm new to R so any tips also on how to phrase this question would be helpful!
I'm confused what to put in as the x and y coordinates in the lines function
I tried to put in a and m to match but it creates a very weird complicated graph that I'm sure is not correct, would you mind explaining what I should be putting inside the place where I put HELP in the code below?
attach(my_data)
plot(a, m,
     xlab="a", ylab = "m",
     main = "Confidence intervals and prediction intervals",
     ylim = c(10,50))
abline(lm.fit,lwd=5,col='pink')

p_pred <- predict(lm.fit,data.frame(a=c(14.50)),interval="prediction",level=0.97)
p_conf <- predict(lm.fit,data.frame(a=c(14.50)),interval="confidence",level=0.97)
lines(HELP,p_conf[,"lwr"], col="red", type="b", pch="+")
lines(HELP,p_conf[,"upr"], col="red", type="b", pch="+")
lines(HELP,p_pred[,"upr"], col="blue", type="b", pch="*")
lines(HELP,p_pred[,"lwr"], col="blue", type="b", pch="*")
legend("bottomright",
       pch=c("+","*"),
       col=c("red","blue"),
       legend = c("confidence","prediction"))

I'm sure for this problem the solution is very simple, so I apologize as I am not that familiar with R if I am asking an easy question!

A: If you want just plot you don't need to calculate predicitons yourself but you can use geom_smooth from ggplot2 library. As in the example below:
library(ggplot2)
ggplot(mtcars, aes(mpg,cyl))+
  geom_point()+
  geom_smooth(method = "lm", level =0.97)

A: Thank you for the suggestions on the page! I actually ended up fixing the problem by creating a new variable that took the min and max value of the x variable and then the lines fitted on the graph.


text:
Q: GraphQL error: Internal server error when accessing graphQL I am using GraphQL with wpgraphql inside a WP setup. I have been using the service without any problems until I updated a Custom Post Type and it stopped working.
message: "Internal server error", category: "internal",
But what is odd is that it still returns the data, along with the error.
Doing the same query in graphiQL works without any flaws. Looking at the request, the only difference is no cookies are sent with the failing request.
I have enabled: define( 'WP_DEBUG', true ); but no new errors are displayed.
The query is rather simple:
{
  rankings {
    edges {
      node {
        rankingId
        id
        commentStatus
        content
        date
        title
        uri
        link
      }
    }
  }
}

A: Use define( 'GRAPHQL_DEBUG', true ); to get the full error message from WPGraphQL


text:
Q: Libgit2 - Failed to authenticate SSH session: Unable to open public key file I'm trying to do a very simple git clone using ssh over a network with Libgit2 -- getting the error in the title in the process. I am not sure what I'm doing wrong -- it is not a network issue as I can clone the repo via the command line. The keys are also in the specified path.
Also the keys are already set up such that if I wanted to ssh to the machine I'm trying to clone from I just need to supply a password, so not really sure why I need to redefine it here.
#include <git2.h>
#include <iostream>

// Callback function
int cred_cb(git_cred **out, const char *url, const char *username_from_url,
     unsigned int allowed_types, void *payload) {

  // https://libgit2.github.com/libgit2/#HEAD/group/cred/git_cred_ssh_key_new
  return git_cred_ssh_key_new(out, "username",
        "~/.ssh/id_rsa.pub", "~/.ssh/id_rsa", "password");
}

int main() {
  // Start up libgit2
  git_libgit2_init();

  // Test clone setup
  git_repository *repo = NULL;
  const char *url = "ssh://username@66.66.66.666/home/git_repo_to_clone";
  const char *path = "tmp";

  // Test clone
  git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
  clone_opts.fetch_opts.callbacks.credentials = cred_cb;
  int error = git_clone(&repo, url, path, &clone_opts);

  // Prints the last error message
  std::cout << giterr_last()->message << std::endl;

  // Clean up
  git_libgit2_shutdown();

  return 0;
}

Printing allowed_types in cred_cb says 22, and so if you try to return a different type of git_cred (for example, git_cred_userpass_plaintext) the library complains that callback returned unsupported credentials type, and also if no callback is specified (by calling git_clone with NULL as the third parameter) then it says that authentication required but no callback set. I might be missing something obvious, I would appreciate any help, thanks.
Edit
I instead tried with git_cred_ssh_key_from_agent(out, "username") and it seems to have done something (the git folder gets cloned), albeit with missing files. Although now the problem is it becomes an endless loop between cred_cb and git_clone (seems to be called back and forth).

A: The path to the key files should be the full path without ~. Libgit2 doesn't expand ~ like the shell would.
Also, the password should be the passphrase used to encrypt your private key, not the password you use to authenticate with the remote.


text:
Q: Does filling your reputation bar with paragon prevent you from filling it with renegade? If I have played through the game and done a good job of responding to all the opportunities to gain reputation and paragon points then my bar will probably be fairly full and I might have 2 or 3 tick mark levels of Paragon points.
Let's assume that when I play through again in new game+ I want to try the renegade path.  My reputation is transferred from the last play through, does this mean I will still have a full Paragon bar?  If so, will I be restricted from filling my renegade bar somehow or will I encounter more "+reputation" opportunities to that I could have both the P&R bars full simultaneously?

A: Yes your bar will update accordingly.
It's because even though it's hidden, you actually have points (like 100 paragon points etc.) and the bar is just the ratio of Paragon:Renegade:Neutral (the neutral part doesn't appear on the bar, just increases its size).
So you might end a game with 1000 paragon points and 100 renegade points.
Starting a new game plus will keep those scores. If you then finish the game gaining 1000 renegade and 100 paragon, you'll have 1100 of each and be split perfectly.

A: You only have 1 reputation bar, and it is used for both paragon and renegade checks. Some of it will be red and some of it will be blue, the ratio will be different depending on which type of reputation you acquire more. If your bar is maxed out, only the ratio will change when you gain paragon/renegade points.
You will have more success while charming/intimidating with a full reputation bar, regardless of whether you're predominantly paragon or renegade. Some interrupts, however, are determined by which (paragon/renegade) reputation is higher, so your Shepard me be more of a pacifict than you'd like if your second playthrough is renegade, but your first was paragon.

A: You can change the ratio of Renegade to Paragon. I maxed my bar as 99% Paragon in a first playthrough and I've been playing a New Game + as Renegade, my bar is now at 20% Renegade and I've just reached Tuchanka.
You do keep your full rep bar, and the + neural rep opportunities maintain your rep bar's current ratio, but Paragon/Renegade points will change the balance. Just do every Renegade Interrupt (they still appear even if you're pure paragon) and every Renegade dialog option and you should see your Renegade bar rise.


text:
Q: prove that flat shape minimizes a functional The following functional arises in an information theoretic problem that I work on currently.
$I(G(\omega)) = \int\limits_{-\kappa\pi}^{\kappa\pi}d\omega \frac{A}{G(\omega)+A}-\frac{| \int\limits_{-\kappa\pi}^{\kappa\pi}d\omega \frac{A}{G(\omega)+A}\exp(-i\omega)|^2}{ \int\limits_{-\kappa\pi}^{\kappa\pi}d\omega \frac{A}{G(\omega)+A}}$,
where $\kappa<1$, $A>0$, and $G(\omega)\geq 0$.
Now I would like to minimize $I(G(\omega))$ under the constraint of unit area of $G(\omega)$, i.e., $\int\limits_{-\kappa \pi}^{\kappa \pi}d\omega\, G(\omega)=1$.
My hypothesis is that a flat $G(\omega)=\frac{1}{2}\kappa\pi$ is optimal, but I cannot prove that (Matlab hints towards it).

A: This hypothesis is not right. The first integral alone $\int {A\over G(\omega) +A } d\omega$ has a local minimum at the constant function (and a global minimum too), so that it's first variation is zero, but the numerator of the second term doesn't have a vanishing variational derivative, so it isn't extremal for a constant, so there are easy counterexamples close to a constant function.
To see that a constant locally minimizes the first integral, you can expand in a Taylor series in G
$$ \int 1 - {G\over A} + {G^2\over 2A^2} d\omega $$
The first two terms are constant (since you have a constraint on the total integral), and the last term is positive definite quadratic form, so the constant is a local minimum. You can show it's a global minimum too using convexity arguments (the second variation of the function is everywhere positive definite).
Knowing this, the first variation of the numerator near the constant function is all you need to check. This variation is proportional to
$$2\mathrm{Re} (\int e^{i\omega'-i\omega} \delta G(\omega) d\omega'd\omega)  $$
which is not zero for general $\delta G$. If you want an explicit counterexample, use a little positive bump for $\delta G$ anywhere that $\cos(\omega)$ is negative, or a little negative bump where $\cos(\omega)$ is positive (the real part can be taken inside the integral, so you can see what a $\delta G$ perturbation does explicitly).
The solution to your extremization problem can be given as a nonlinear integral equation using the method of Lagrange multipliers. Add the term
$$ \int \lambda G $$
to your functional, and minimize the sum. The equation doesn't simplify very much, and should be solved numerically, and for this purpose, you can just make a grid and minimize the values by steepest decent, starting from the constant. You can also solve the integral equation from the calculus of variations by iterations, starting from a constant, and this is roughly equivalent.


text:
Q: how to convert column of object datatype to int64 datatype in python pandas I merged two tables and hence a column has a dtype object, I need to convert it to int, where I am getting a type error.
I used astype function, but the object is not converted to string, getting the following type error:

TypeError: int() argument must be a string, a bytes-like object or a
  number, not 'method'

A: I think that in your dataframe you have some NaN values, Check that first with
df.isnull().sum()

Then fill the NaN values or drop them, and after that you can you convert your values.
if it's not the problem, can you try something like that :
df['col']=df['col'].apply(lambda x : int(x))


text:
Q: check radio button with jquery I have this code snippet to check/uncheck radiobutton with jquery.
 $.each(options, function (index, item) {
                $optionli.find("li").eq(index)
                                    .find("input[type='radio']")
                                    .attr("checked", item.IsAnswer);

            });

The item.IsAnswer returns "true" or "false", however the radio button is not checked though in its html view, the "checked" attribute is set to "checked"

What could be the reason for something like that to happen?
Thanks

A: Try this:- Use prop instead of attr
Checked as an attribute does not take true or false. Presence of checked it is implicit that it is checked.
$.each(options, function (index, item) {
                $optionli.find("li").eq(index)
                                    .find("input[type='radio']")
                                    .prop("checked", item.IsAnswer);

            });

A: checked is a property, you should use prop method, when a boolean attribute like disabled or checked is set to an element, the value is mapped to the relevant DOM property of the element(browsers do this) and attr and removeAttr methods do not change the properties of an element, as of jQuery 1.6 for modifying properties, prop() method should be used instead of attr.
$('input[type=radio]').prop('checked', function(i, state){
        return !state;
    });


text:
Q: Question about class and methods- create a object of the class inside a method I am confusing when create an object inside a method.
For example in this coding; I am not sure why I am putting public void copiar(Ventana w) , why put this?? in the second method it's obvious because we are going to set this values to variables, but in the first method I don't have any idea what I am trying to do.
I hope someone can help me.
Class Ventana
{
    public void copiar(Ventana w) {
    }
    public void copiar(String p, int xx, int y) {
    }
}

Thanks in advance!

A: It is like Elliott commented above.
With this method with Ventana as parameter it is more practical to duplicate a Ventana.
eg.:
Class Ventana{

    private String style;
    private int height;
    private int wide;

    public void copiar(Ventana w) {
       this.style = w.getStyle();
       this.height = w.getHeight();
       this.wide = w.getWide();
    }

    public void copiar(String style, int height, int wide) {
       //...
    }
}

Probably, better to have the adequate constructor:
public Ventana (String style, int height, int wide){
       this.style = style;
       this.height = height;
       this.wide = wide;
}

And then have the copy method as:
public Ventana copiar(Ventana w) {
       return new Ventana(w.getStyle(), w.getHeight(), w.getWide());
    }

A: Reading between the lines, as it looks like you've not provided the full code, maybe you're trying to do this?
Class Ventana
{
   string p;
   int xx;
   int y;

   public static Ventana(Ventana w)
   {
      Ventana copy = new Ventana();
      copy.p = w.p;
      copy.xx = w.xx;
      copy.y = w.y;
      return copy;
   }
}


text:
Q: Right align ComponentRenderer in a Vaadin TreeGrid It is possible to align text content in a Vaadin TreeGrid column using setTextAlign(ColumnTextAlign.END), however this does not work if the column is using a ComponentRenderer, in my case it is rendering a MenuBar component.
Does anyone know if it is possible to right align a ComponentRenderer without resorting to a template or wrapping it in a HorizontalLayout?


text:
Q: Get dynamic page title for the value  I am trying to implement an ActiveCampaign form in Wordpress site. The same form will be using on a different page but I would like to know which page the contacts are coming from. So, I use a hidden filed where the value will be updated dynamically using Javascript I believe but can't figure out how to use javascript to get that. Can anyone help me with this?

value=" " would be change dynamically with the page title.

A: For page title
const titleEL = document.getElementByTagName('TITLE'); // Get the title html tag
const hiddenInputEl = document.getElementById('hidden'); // Get hidden input
hiddenInputEl.value = titelEl.textContent // Set input value to the content of the title-tag

or if you want the url.
hiddenInputEl.value = window.location.href

You could also use document.title see the documentation here.

A: To get the title from the document via JavaScript (check out the docs for more details),
var docTitle = document.title;
To more easily access your input field from JavaScript side, I would suggest you add an ID to your input field:
<input type="hidden" name="field[46]" value="" id="title_field" />
So what you can now do is to change the value of your input field as such:
document.getElementById('title_field').value = document.title;
EDIT:
On another note, why do you need to have a hidden field specially for obtaining the title, when you would have obtained the document's title using document.title?
EDIT 2: Snippet

document.addEventListener('DOMContentLoaded', allContentLoaded, false);

function allContentLoaded() {
  var docTitle = document.title;
  document.getElementById('title_field').value = docTitle;
  console.log(docTitle);
}
<input type="text" name="field[46]" value="" id="title_field" />

<!--For the sake of visibility, I changed the type of your input to text.-->


text:
Q: Google Analytics CID in Cookie POST request I'm currently working on cookies that I console-send using a POST method to a sign up page.
I manage via GET method (asking the sign up) to get the cookie information, but I see that in the POST method, the cookie is sent with a CID (Client ID) information to the server (CID comes from a Google Analytics function)
My question is : if I want to do a POST request to the server, the problem is that I don't have the Client ID, does that matter?

A: see this, http://www.ietf.org/rfc/rfc4122.txt
I think you have to create your own clientId or &cid param, because the order hand you will need put script
<!-- Google Analytics -->

    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];
    a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXX-Y','auto');
    ga('send', 'pageview');

</script>
<!-- End Google Analytics -->

in your index.jsp and take the cid of the cookie value of _ga....
A greeting.


text:
Q: Editing & Repackaging a packaged Lightning Community Template I have created a managed package which contains a lightning community template which was created by exporting it from the lightning community.
Now, I would like to make some modification to the template which was package, but there appears to be no way of updating it.
Need some guidance on how to update a lightning community template??
There is a similar question but it hasn't been answered yet. How to update an exported Lightning Community Template

A: This is a limitation currently in communities packaging. There is no way to update the whole template. You will have to again export everything as a new template.
Note if you already have a client that has installed it, you might just want to make the change in sandbox and push to pros via changesets.
For new clients you will have to build a new one.
These limitations are listed here


text:
Q: Overleaped heatmap doesn't show correctly I have a heatmap plotted above an image (as shown on image link 1), with gaussian filter and normalize data. The main issue is that there is no value under 92 on the y axis, so the plot doesnt start on (0,0), instead start on (0,92). So, when I put together both pictures (heatmap and background image), there is an abrupt cut on the graph (as shown on 2nd link, where is the heatmap without background).
So, how can I extend the axis on the heatmap so it start on (0,0)?
Below is the code that I'm currently using to plot both images. Thanks!
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy.ndimage.filters import gaussian_filter
import matplotlib.colors as mcolors
from sklearn.preprocessing import normalize

x = df['x_data']
y = df['y_data']

heatmap, xedges, yedges = np.histogram2d(x, y, bins = [800,600])

extent = [0, xedges[-1], yedges[0], yedges[-1]]
heatmap = normalize(heatmap)
heatmap = gaussian_filter(heatmap, 16)

colors = [(1,1-c,0,c) for c in np.linspace(0,1,100)]
cmapred = mcolors.LinearSegmentedColormap.from_list('mycmap', colors, N=5)

map_img = mpimg.imread('dir/to/background/image.png')

fig, ax = plt.subplots(figsize=(16.1, 9.1))

plt.imshow(map_img, extent=[0, 800, 0, 600], cmap = 'Greys_r')
plt.imshow(heatmap.T, extent = extent, origin = 'lower', cmap = cmapred, alpha = 0.7)

plt.ylim([0,600])
plt.xlim([0,800])
plt.show()

Image of heatmap + background: https://imgur.com/2vX6Bw6
Image of only heatmap: https://imgur.com/axMe7K7

A: You could add rows to your heat map manually.  Maybe easier is to try setting the histogram bins explicitly?
bins=[np.arange(0, 800, 1), np.arange(0, 600, 1)]
heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)


text:
Q: JavaScript - Can you detect wether an event was triggered by the user or the app? I know that this is possible with for mouse events using the MouseEvent constructor.
For example, with the MouseEvent constructor, you can simulate mouse clicks easily. With this approach, I can add additional fields to my "fake" mouse event such as
var event = new MouseEvent(type, mouseEventInit)'
event.fake = true

that allows me to detect in the listener wether this event was triggered by the user or the app.
I would like to do something similar with a html video when it is played/paused/seeked. The video can either be controlled by my app (calling video.play(), video.pause() or setting video.currentTime = x) or the user (using the video controls normally) at any given time. When the event listeners I added are fired I do not have a way to know who or what was the source (the user or my app).
So basically, I don't want to listen to events triggered by my app but I do want to listen to user actions (the user clicked on the play button or seeked in the video by clicking somewhere on the progress bar).
My current approach is to remove the listeners and add them back afterwards like so:
video.removeEventListener('play', playListener)
video.play()
// I have to wait until the video actually plays
setTimeout(function() {
  video.addEventListener('play', playListener)
}, 100)

It works fine, but when I do this for seeking, it's harder to select a good time for settimeout because of video buffering (it seems like the seeked event is triggered after the video finished buffering). So I'm exploring different methods.
I know about the CustomEvent() constructor, but I doubt I could use this to actually play or seek. I need to create an event that will trigger the appropriate actions (play, pause or seek). Feel free to correct me if I'm wrong.
Any other ideas I could detect events triggered by my app and/or the user?

A: You can attach a Boolean to object passed to event handler to determine if event was dispatched in response to user action or application action.

var button = document.querySelector("button");
var div = button.nextElementSibling;

var app = {
  config: "def",
  userAction: "abc",
  setApp: function setApp(duration) {
    this.timeout = setTimeout(function() {
      button.dispatchEvent(appEvent)
    }, duration || 3500);
  },
  timeout: null
}

// dispatch `app` event
app.setApp(0);

function handleEvent(event) {
  // check `event.detail.app` object `Boolean` value
  if (event.detail.app) {
    div.textContent = app.config;
  } else {
    div.textContent = app.userAction;
    // dispatch `app` event in 3500ms
    app.setApp();
  }
}

button.onclick = handleEvent;

// set plain object having `Boolean` value at `event.detail` `{app:true}`
var appEvent = new CustomEvent("click", {
  detail: {
    app: true
  }
});
<button>click</button>


text:
Q: Adding and removing events in one method, c# Sometimes I need to add and remove events from bunch of controls. And I always do that with one method for adding events:
private void AddEvents(){
    textBox.TextChanged += TextChanged;
    integerUpDown.ValueChanged += ValueChanged;
    colorPicker.SelectedColorChanged += ColorChanged;
    //... and so on
}

And same one for removing events:
private void RemoveEvents(){
    textBox.TextChanged -= TextChanged;
    integerUpDown.ValueChanged -= ValueChanged;
    colorPicker.SelectedColorChanged -= ColorChanged;
    //... and so on
}

I'm using different types of controls and different types of EventArgs. I'd like to compress it to one method, something like:
private void RemoveEvents(bool add){
    textBox.TextChanged add ? += : -= TextChanged;
    integerUpDown.ValueChanged add ? += : -= ValueChanged;
    //or method approach
    ManageEvent(colorPicker.SelectedColorChanged, ColorChanged, add);
    //... and so on
}

But that's not possible with ? operator. Is there a way to do it?

A: I think this is neat.
First, define the following interface and class:
public interface IEventHolder
{
    void Attach();
    void Detach();
}

public class EventHolder<H> : IEventHolder
{
    private Action<H> _add;
    private Action<H> _remove;
    private H _handler;

    public EventHolder(Action<H> add, Action<H> remove, H handler)
    {
        _add = add;
        _remove = remove;
        _handler = handler;
    }

    public void Attach() { _add(_handler); }

    public void Detach() { _remove(_handler); }
}

Now you can define this private field:
    private List<IEventHolder> _eventHolders = new List<IEventHolder>();

In the Form_Load event I've written this code:
    private void Form1_Load(object sender, EventArgs e)
    {
        _eventHolders.Add(new EventHolder<EventHandler>(h => textBox1.TextChanged += h, h => textBox1.TextChanged -= h, textBox1_TextChanged));
        _eventHolders.Add(new EventHolder<EventHandler>(h => numericUpDown1.ValueChanged += h, h => numericUpDown1.ValueChanged -= h, numericUpDown1_ValueChanged));
        _eventHolders.Add(new EventHolder<MouseEventHandler>(h => textBox2.MouseMove += h, h => textBox2.MouseMove -= h, textBox2_MouseMove));

        _eventHolders.ForEach(eh => eh.Attach());
    }

Notice that the line _eventHolders.ForEach(eh => eh.Attach()); attaches all events.
My handlers look like this:
    private void textBox1_TextChanged(object sender, EventArgs e)
    { }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        this.textBox1.Text = numericUpDown1.Value.ToString();
    }

    private void textBox2_MouseMove(object sender, MouseEventArgs e)
    {
        _eventHolders.ForEach(eh => eh.Detach());
    }

The textBox2_MouseMove handler detaches all of the events in one go.
I've tested this and it works like a treat.

A: The conditional operation returns a value based on the statement's result. Returning "+=" is definitely not valid, since you are basically subscribing to the event. https://msdn.microsoft.com/en-us/library/ty67wk28.aspx
However, why don't you take the simpler approach?
private void AddOrRemoveEvents(bool add)
{
    if (add)
    {
        AddEvents();
    }
    else
    {
        RemoveEvents();
    }
}

A: One line if statement to the rescue! There will be a little bit of repetition but none the less it is a one liner
if (add) textbox.TextChanged += TextChanged; else textbox.TextChanged -= TextChanged;

A: As you want to avoid having to specify both adding and removing a handler, there is only reflection left.
private static void ManageEvent(object target, string evnt, EventHandler handler, bool add)
{
    var ei = target.GetType().GetEvent(evnt);
    if(add)
    {
        ei.AddEventHandler(target, handler);
    }else{
        ei.RemoveEventHandler(target, handler);
    }
}

This method finds the target event info on a given instance, and based on a condition invokes either the add or remove method. You can also make this generic, but then you would have to specify the type of the delegate. This assumes EventHandler, which is quite common.
ManageEvent(textBox, "TextChanged", TextChanged, add);

In C# 6, you can also use nameof(textBox.TextChanged) instead of "TextChanged" which makes your code easier to refactor.
Please note that reflection performs mostly slow, so consider using the approach shown in other answers if you have to call this method a lot.
This all is necessary because the events are located in another class, and you cannot thus access directly their backing field. However, if the event is located in your class, you can pass it as a reference to a similar helper method:
private static void ManageEvent<TDel>(ref TDel source, TDel value, bool add) where TDel : class
{
    if(add)
    {
        source = (TDel)(object)Delegate.Combine((Delegate)(object)source, (Delegate)(object)value);
    }else{
        source = (TDel)(object)Delegate.Remove((Delegate)(object)source, (Delegate)(object)value);
    }
}

This does exactly what normal event methods do, either combine or remove events.
ManageEvent(ref MyEvent, MyEventHandler, add);


text:
Q: jQuery show/hide element when hovering another element I have the following HTML as an example:

and the following jQuery which should hide the pagination by default but then fade it in when a user hovers the header and then fades it back out when they move off the header:
            $(".pagination").hide();
            $("#header").mousemove(function()
            {
                $(".pagination").fadeIn(1500);
            });
            $("#header").mouseleave(function()
            {
                $(".pagination").fadeOut(1500);
            });

The problem I have is that it will run through the code the same number of times a user hovers the header so for example if I hovered 5 times in a row the pagination would fade in and out 5 times. This is not the function I want, rather a simple fade in and out when a user is hovering the header.
Can anyone help? Thanks.

A: Edited: Added some code to avoid repeated fading in and out.
     var running = false;

     $("#header").hover(function()
        {
            if(!running){
               $(".pagination").fadeIn(1500);
               running = true;
            }
        }, function()
        {
            $(".pagination").fadeOut(1500, function(){
                running = false;
            });
        });

Now, the hover effect only kicks in if it is not already running.

A: well than instead of fadeIn - fadeOut just use .fadeTo like in my
JSFiddle DEMO
And to stop the issue you are talking about use .stop()
Good Luck!


text:
Q: How to implement separate functionality in instances of child component in Angular? I am developing an Angular application based on PrimeNG UI library. It implements several pages which contain tables, for example UsersComponent, AccountsComponent, TweetsComponent, etc.
I am using PrimeNG's Table component to display the data in table form. In order to achieve component reusability, I have created a generic TableComponent class which implements PrimeNG table, and have added custom functionality to this table component like filters, sorting, etc.
I can pass data from UsersComponent, AccountsComponent, and TweetsComponent to this TableComponent and the data from these parent components is displayed nicely like I want.
<UsersComponent>
    <TableComponent [data]="usersArray"></TableComponent>
</UsersComponent>

<AccountsComponent>
    <TableComponent [data]="accountsArray"></TableComponent>
</AccountsComponent>

<TweetsComponent>
    <TableComponent [data]="tweetsArray"></TableComponent>
</TweetsComponent>

However, the issue is that I want to add some methods that are specific to each component. For example, when the TableComponent is displaying list of users, I want to be able to call methods addUser(), deleteUser() and updateUser() that add, delete or update a user record, respectively. Similarly, AccountsComponent should have its own functionality and separate, independent API calls.
How can I achieve this in Angular?
I can pass down data from parent to child component but how can I pass multiple specific methods to the child? Where will I create these methods and how shall I call them in the child component?

A: From my point of view this sounds like you should implement some abstract interface (or multiple, if you want to split up logic), which will be implemented by services and then passed to the child component as an input property.
export interface CrudService<T> {
  addItem(item: T): Observable<T>;
  updateItem(item: T): Observable<T>;
  removeItem(item: T): Observable<void>;
}

Now you can implement services specific for your use case like so:
@Injectable()
export class UserService implements CrudService<User> {
  addItem(item: User): Observable<User> {
    // logic specific to user
  }
  updateItem(item: User): Observable<User> {
    // logic specific to user
  }
  removeItem(item: User): Observable<void> {
    // logic specific to user
  }

}

and pass it to your TableComponent
export class Tableomponent<T>  {
  @Input()
  crudService: CrudService<T>;

}

Now you are able to generically call add, update or remove methods on this service. If not all entities support all CRUD operations, you should split this interface up into different interfaces.

A: I have something like this on my app (really small version to get the idea)
https://stackblitz.com/edit/angular-ivy-jj5jbt?file=src/app/hello.component.ts
I Use the table on lot of parent components but the edit, add functions are different on all the parent components, that's why i keep the functions on the parent to avoid haven lot of different function on the child component. and then pass them to the child. Also I add a parameter (id) that can be pass beetween them
export class ConfigButtons {
  icon: string;
  buttonText: string;
  functionName: Function;
}

that's the model and then
     config: ConfigButtons[] = [
    {
      icon: 'edit-icon',
      buttonText: 'Edit User',
      functionName: (userId) => this.editUser(userId),
    },
  ];

  editUser(userId: string) {
    console.log('editUser', userId);
  }

The full example is on the stackblitz project

A: In your case, I would add a custom "actions" columns at the end of my array, where I would put my custom actions (and hide it if there's none).
Then, to give them the actions I want, I would use ng-content so that I can call my component like this :
<UsersComponent>
    <TableComponent [data]="usersArray">
      <ng-template let-item>
        <button (click)="deleteUser(item)">
          <icon>delete</icon>
        </button>
      <ng-template>
    </TableComponent>
</UsersComponent>


text:
Q: sending input field data to php script in angular 4 I am trying to build an angular app and i am fairly new to the technology. I have successfully been able to take values from the input field and view them in the console but i want to take those values and send it to the php script where the backend processing can be done. Basically its a simple mail function. Below are my codes.
My backend.php file
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

  @$rand = $_POST['rand'];
    @$captcha = $_POST['captcha'];
    @$email = $_POST['email'];
    @$msg = $_POST['msg'];
    @$to = "contact@ixoraa.in";
  @$subject = $_POST['name'];
    @$headers = "From:" . $email . "\r\n";
  @$header .= "MIME-Version: 1.0\r\n";
    @$header .= "Content-type: text/html\r\n";
if($rand == $captcha)
{

    $retval =mail($to, $subject, $msg, $headers);

if( $retval == true )

{

echo '';

echo '<meta http-equiv="refresh"
content="0;url=http://www.ixoraa.in/new">';

}

else
{

echo '';
}
   }

        else{

echo '';
        }

?>

Here goes my component.html
<form class="" [formGroup] = "form" (ngSubmit)="onSubmit(form.value)">

                <input  name="name" type="text" formControlName='name' class="form-control" placeholder="Name" style="background-color: rgba(60, 144, 155, 0.10); color: white;"/>

                <input  name="email" formControlName='email' type="text" class="form-control" placeholder="Email" style="background-color: rgba(60, 144, 155, 0.10); color: white;" />

               <textarea  name="msg" formControlName='msg' type="text" rows="5" class="form-control" placeholder="Message" style="background-color: rgba(60, 144, 155, 0.10); color: white;"></textarea>

   <input name="rand" formControlName='rand'  class="text-center" style="background-color: antiquewhite; text-decoration: line-through;" size="3" type="text" value="{{randomNumber}}" readonly>

        <input formControlName='captcha'  onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off name="captcha" id="captcha" type="text" class="form-control" placeholder="Enter Code Here" style="background-color: rgba(60, 144, 155, 0.10); color: white;" />

   <input style="padding-left: 20px; font-weight: 600; padding-right: 20px; background-color: #00aee7;margin-bottom: 40px; color: white;" type="submit" name="submit" value="Send" class="btn">
</form>

and here goes my component.ts file
import { Component, OnInit } from '@angular/core';
import {Http} from '@angular/http';
import {FormGroup, FormControl, FormControlName} from '@angular/forms';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {

  form;

  randomNumber;
  constructor(private http: Http) {
    this.randomNumber = Math.floor((Math.random() * 10000) + 1);

  }

  onSubmit = function(user) {
      console.log(user);
      this.http.post('http://localhost/ixoraa/backend.php', user).subscribe();

  };

  ngOnInit() {
    this.form = new FormGroup({
      name: new FormControl(),
      email: new FormControl(),
      msg: new FormControl(),
      captcha: new FormControl(),
      rand: new FormControl(this.randomNumber)
    });
  }

}

thanks in advance!!!

A: I believe yours may be a CORS problem: your are probably starting your angular app with default configuration, which means it will be hosted on localhost:4200, while your http post request is sent on localhost:80, which is not the same origin as you application.
Here is an nice article about CORS:
Cross-Origin Resource Sharing Article
And here is a nice answer explaining how to deal with them.


text:
Q: When editing a table, it updates the last entry in the DB instead of the selected one I have a table that can have multiple posts, let's say that I go to edit any random post.
It shows me with the correct information about said post, however once I change the data and click on my button to save the information and update the post, it updates the last post that was created instead of the chosen one.
Posts would be the table with the column id as my primary key using an auto_increment for identification.
HTML:
{{Form::open(['url'=> 'employer/jobs', 'method' => 'POST'])}}
{{csrf_field()}}

Title *

<input type="text" class="form-control" name="title" placeholder="Name" required value="{{old('title')}}">

<button type="submit" class="btn btn-jobs-post job-employee">Save changes</button>

{{Form::close()}}

Controller:
 /**
 * return view for edit current post by id
 */

public function show($id){
    $company = Companies::where('user_id', Auth::id())->first();
    if(count($company)){

        $jobEdit = Posts::find($id);
        $categories = Categories::where('status','active')->get();
        $cities = Cities::all();
        $job_types = JobTypes::where('status','active')->get();

        return view('employer.edit_job', compact('jobEdit', 'categories', 'cities', 'job_types', 'company')); }
        else{
        return Redirect::to('employer/company/add');
    }
}

 /**
 * update post detail in database
 */

public function updateJob(Request $request, $id){

    $this->validate($request, [
        'title' => 'required|max:50',
        'category' => 'required|numeric',
        'last_date' => 'required',
        'description' => 'required|min:20',
        'city' => 'required',
        'vacancies' => 'nullable|numeric',
    ]);

    $job = Posts::find($id);

    $job->title             = $request->title;
    $job->description       = $request->description;
    $job->type              = $request->type;
    $job->cat_id            = $request->category;
    $job->experience        = $request->experience;
    $job->city_id           = $request->city;
    $job->total_vacancies   = $request->vacancies;
    $job->job_type_id       = $request->job_type;
    $job->salary            = $request->salary;
    $job->last_date         = Carbon::createFromFormat('d/m/Y', $request->last_date);
    $job->shift             = $request->shift;
    $job->status            = 'active';

    $job->save();

    if($request->add_type == 'option2'){
        Session::flash('job_id', $job->id);
         return redirect()->route('theoption2')->with( 'job', $job );
    } else {
        return redirect()->back()->withSuccess('Updated.');
    }
}

If changed Posts::findOrFail($id) does not display any error.
Any help on why it's always updating the information on the last entry would be greatly appreciated!
Thank you in advance.

A: the problem is with the id you are sending to the post, please where is the id coming from? i would have saved each comment with its id to be saved and return it when posting, if you can post your html or where the id is coming from, that will help check your program


text:
Q: Why does my web page render differently coming from my web server vs VS2010's web server?
I am using IE11 on Widnows 7. The server is 2008, IIS v7.0.6...
As you can see by the picture the dropshadow doesn't show up on the banner and the border on the calendar is not as dark.
Same code, same browser, different server.
Any suggestions as to what causes this and how I can fix it?
Any ideas on where to look?

A: Try this tag in the head section of your file
 <meta http-equiv="X-UA-Compatible" content="IE=edge">

maybe the browser is rendering you page with a lower version than it has, this forces to IE to render the page with the last version posible
Also after adding that press ctrl + F5 in the browser to request all from server and no from cache


text:
Q: PHP mysqli insert only works once I've got a script that I needed to change since the data which is going to be inserted into the db got too big to do it at once. So I created a loop, that splits up the array in blocks of 6000 rows and then inserts it.
I don't know exactly if the data is to big for the server to process at once or if it's too big to upload, but atm I got both steps split up in these 6000s blocks.
Code:
for ($j = 0; $j <= ceil($alength / 6000); $j++){

    $array = array_slice($arraysource, $j * 6000, 5999);

    $sql = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ";

    foreach($array as $a=>$value){

        //transforming code for array

        $ra = $array[$a][0];
        $na = str_replace(",", ",", $array[$a][1]);
        $na = str_replace("\", "\\\\", $na);
        $na = str_replace("'", "\'", $na);
        $sc = $array[$a][2];
        $kd = $array[$a][3];
        $wi = $array[$a][4];
        $ki = $array[$a][5];
        $de = $array[$a][6];
        $sh = $array[$a][7];
        $ti = $array[$a][8];
        $sp = $array[$a][9];
        $sql .= "('$ra',' $na ','$sc','$kd','$wi','$ki','$de','$sh','$ti','$sp'),";
    }

    $sql = substr($sql, 0, -1);
    $conn->query($sql);
}
$conn->close();

Right now it only inserts the first 5999 rows, but not more as if it only executed the loop once. No error messages..

A: Don't know if this'll necessarily help, but what about using array_chunk, array_walk, and checking error codes (if any)? Something like this:
function create_query(&$value, $key) {
    //returns query statements; destructive though.
    $value[1] = str_replace(",", ",", $value[1]);
    $value[1] = str_replace("\", "\\\\", $value[1]);
    $value[1] = str_replace("'", "\'", $value[1]);

    $queryvalues = implode("','",$value);
    $value = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ('".$queryvalues."');";
}

$array = array_chunk($arraysource, 6000);

foreach($array as $key=>$value){
    array_walk($value,'create_query');
    if (!$conn->query($value)) {
        printf("Errorcode: %d\n", $conn->errno);
    }
}

$conn->close();

Secondly, have you considered using mysqli::multi_query? It'll do more queries at once, but you'll have to check the max allowed packet size (max_allowed_packet).
Another tip would be to check out the response from the query, which your code doesn't include.

A: Thanks for the tips but I figured it out. Didn't think about this ^^
it was the first line after the for loop that i didnt include in my question:
array_unshift($array[$a], $a + 1);

this adds an additional value infront of each user, the "rank". But the numbers would repeat after one loop finishes and it can't import users with the same rank.
now it works:
array_unshift($array[$a], $a + 1 + $j * 5999);


text:
Q: Postfix header checks multiple actions I want to make a header check rule to add a reply-to and change From to a no-reply.
I use it for sort of diffusion list adress
I have tried this regexp code but it is not working:
if !/^From:(.+@myserver\.fr)/
/^From:(.*)$/ PREPEND Reply-To:$1
/^From:(.*)$/ REPLACE From: no-reply@myserver.fr
endif

Only the first action is use.
Can someone explain me what I am doing wrong?

A: The problem is with your match regex. You are matching the same header twice and thats not possible with header checks.
if you can set the reply to in the email client you can just replace the from address with header checks and the case is solved.
if !/^From:(.+@myserver\.fr)/
/^From:(.*)$/ REPLACE From: no-reply@myserver.fr
endif

A: The easy way that I found to fix something similar like this was, creating two files with regex sentences, to do this I edited the main.cf and I added these two files:
smtp_header_checks = regexp:/etc/postfix/header_checks
header_checks = pcre:/etc/postfix/add_original_rcpt.pcre

and I put one regex sentence in each file, and it works for me.

A:
Replace From header

The above syntax looks wrong try as below,enable header_checks with postfix main.cf
Append the lines as below in header_checks file,Next if u want to add Reply_To header next to From header,do as below
/^From:[[:space:]]+(.*)/ REPLACE From:  noreply@domain.com,

Prepend or Add new Header .* explains next to

/^From:.*/ PREPEND Reply_To: xyz@domain.com
If you want to set return path set using canonical_maps


text:
Q: Linear combination of powers of a function I'm looking for a reference that studies this. Consider a function $f:\mathbb{R}^n\rightarrow\mathbb{R}$. Is there a name for the set of functions spanned by the powers of $f$? I.e.,
$$
\left\{\sum_{k=0}^{\infty}c_kf^k(x)|\ c_k\in\mathbb{R},\forall k\geq 0\right\}.
$$
I assume $f$ to be real analytic.
It looks like a generalization of Fourier series, but $f^k$ may not be orthogonal.
How about in general,
$$
\left\{\int_0^{\infty}g(s)f^s(x)ds|\ g(s):\mathbb{R}_+\rightarrow\mathbb{R}\right\}?
$$


text:
Q: How can I determine the eigenvalue of a given eigenvector? I was wondering if there was a good way to determine the eigenvalue of a particular given eigenvector. I was thinking of starting out with the equation $(A-\lambda I)\hat{x}=\hat{0}$ and solving for $\lambda$, but I am a little unsure how to do this.

*

*Simple Example: Let A =$\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix}$ and eigenvector $\hat{v_{1}} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}$. So this would yield: $ (\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} - \lambda \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}) \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \hat{0}$. How would I solve for $\lambda$ in this case?

A: Just use the definition of eigen vectors: $v$ is an eigen vector if $Av={\lambda}v$, (and $v~!=\hat{0}$). So if you're sure that $v$ is an eigen vector, just compute $Av$ and see how many times it is $v$, this is your lambda.
Hope it helps!
EDIT: to solve the example you provided:
$ (\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} - \lambda \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}) \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \hat{0}$
leads to the two same equations:
$3-\lambda =0$ and
$3-\lambda =0$ which is equivalent to $\lambda =3$

A: To solve $A\vec {v_1}=\lambda \vec{v_1}$ for $\lambda, $
can you solve $$ \begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix}  \begin{bmatrix} 1 \\ 1 \end{bmatrix}=   \lambda \begin{bmatrix} 1 \\ 1 \end{bmatrix}$$ for $\lambda?$
Note that $$ \begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix}  \begin{bmatrix} 1 \\ 1 \end{bmatrix}=  \begin{bmatrix} 3 \\ 3 \end{bmatrix},$$
so you must solve  $$\begin{bmatrix} 3 \\ 3 \end{bmatrix}=\lambda  \begin{bmatrix} 1 \\ 1 \end{bmatrix}$$
for $\lambda$.

A: In this particular case we may observe that
$\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \begin{bmatrix} 3 \\ 3 \end{bmatrix} = 3 \begin{bmatrix} 1 \\ 1 \end{bmatrix}, \tag 1$
so if in addition we have
$\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \lambda \begin{bmatrix} 1 \\ 1 \end{bmatrix}, \tag 2$
then
$\lambda \begin{bmatrix} 1 \\ 1 \end{bmatrix}  = 3 \begin{bmatrix} 1 \\ 1 \end{bmatrix}, \tag 3$
or
$\begin{bmatrix} \lambda  \\ \lambda  \end{bmatrix}  = \begin{bmatrix} 3  \\ 3  \end{bmatrix}, \tag 4$
from which it is readily seen that
$\lambda = 3. \tag 5$
More generally, if $\vec v \ne 0$ is an eigenvector of some $n \times n$ matrix $A$, then since
$A \vec v = \lambda \vec v, \tag 6$
every entry of $A \vec v$ is the same multiple, $\lambda$, of the corresponding entry of $\vec v$; since $\vec v \ne 0$ we have
$\exists i, 1 \le i \le n, \; \vec v_i \ne 0; \tag 7$
then
$(A\vec v)_i = \lambda \vec v_i, \tag 8$
whence
$\lambda = \dfrac{(A\vec v)_i}{\vec v_i}, \tag 9$
and thus $\lambda$ is determined by the eigenvector $\vec v$.


text:
Q: Image not loading through Glide after picking from gallery I create an intent to let the user pick an image from their gallery:
Intent intent  = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICK_IMAGE);

Then, after the user picks an image, I handle it here:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == REQUEST_PICK_IMAGE) {
        final Uri uri = intent.getData();

        Glide.with(context)
            .load(new File(uri.getPath()))
            .into(myImageView);
    }
}

The URI looks something like this:
content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F43/ORIGINAL/NONE/image%2Fpng/2098318161

But it's not loading the image into the ImageView, and I don't know why.

A: you can load it in to the imageView like this;
myImageView.setImageURI(uri);

A: First thing, If you pass an Uri instance, In normal case it will start like this (file://) but in yours it doesn't have a correct schema .
You can check how Uri, String and File models are loaded.
Second thing, If your using a testing device whose api level is >= 29 then you have to add a flag in manifest to access the storage.
requestLegacyExternalStorage=true

Also check your result code if it's returning 0 or -1


text:
Q: How can edit an already issued invoice? How I can edit an already issued invoice? I want to edit the shipping address of order "XYZ" and send the email to the customer. How can we do that? If that is possible, Please comment "Yes" or "No".
Thank you...

A: No you won't be able to as far as I'm aware, you'd need to re-issue the invoice with the updated details I believe.


text:
Q: pip3 install mysql ERROR I get this error
pi@teambaboy:~ $ pip3 install mysql

Collecting mysql

Downloading https://www.piwheels.org/simple/mysql/mysql-0.0.1-py3-none-any.whl
Collecting MySQL-python (from mysql)

Using cached MySQL-python-1.2.5.zip

 Complete output from command python setup.py egg_info:

Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-k38v3y9c/MySQL-python/setup.py", line 13, in <module>
        from setup_posix import get_config
      File "/tmp/pip-build-k38v3y9c/MySQL-python/setup_posix.py", line 2, in <module>
        from ConfigParser import SafeConfigParser
    ImportError: No module named 'ConfigParser'

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-k38v3y9c/MySQL-python/

A: Use mysqlclient instead. It's the modern drop-in replacement.
$ pip install mysqlclient


text:
Q: How to get the current url in xslt I'm programing in sharepoint and I need to get the current url in my Content Query WebPart's Sytle file(ItemStyle.xsl or ContentQueryMain.xsl) in order to add the querystring to the url of a link in my pages.

Is it possible to get the URL of the page in XSL similar to javascript's location.href ?

A: try This
We will be adding this namespace to your XSL file, you can add it to either Main CQWP xsl or ItemStyle.xsl, incase you add it to Main XSL pass it down to Item Template as parameter.  I usually add to Item Style XSL .
Add NameSpace xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" at top
Add a parameter "PageUrl "   right below your namespace definitions

*

*Concat this parameter as part in your Display URL as part Source query string parameter

Thanks


text:
Q: duplicate panGestureRecognizer? Let's say I have a custom view and I want to add gesture recognizer to it.
    UIPanGestureRecognizer* y  = a.panGestureRecognizer;
    y.minimumNumberOfTouches = 2;
    y.maximumNumberOfTouches = 2;
    [self addGestureRecognizer:y];

After adding the panGestureRecognizer of a to self, a would no longer have the panGestureRecognizer.
What should I do such that even after adding the  UIPanGestureRecognizer to self, a would still have it with itself (such as duplicating it)?
I tried this as suggested by meronix but get exception.
 UIPanGestureRecognizer* y  = [a.panGestureRecognizer copy]; //I'm using ARC so I didn't add autorelease.
 [self addGestureRecognizer:y];

-[UIScrollViewPanGestureRecognizer copyWithZone:]: unrecognized selector sent to instance 0x1c5c2460

A: If you merely want to duplicate that gesture recognizer with its current state, then something like:
UIPanGestureRecognizer *r = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                    action:action];
r.minimumNumberOfTouches = a.panGestureRecognizer.minimumNumberOfTouches;
r.maximumNumberOfTouches = a.panGestureRecognizer.maximumNumberOfTouches;
[self addGestureRecognizer:r];

If however, you want to make sure that any changes that happen to r and a.panGestureRecognizer, you can set up a helper class to handle this for you.
For example something like this:
@interface GestureHandler: NSObject
// ...
- (void)setNewMinTouches(unsigned int)num;
// Weak references to a and r (for example)
@property (nonatomic, weak) UIPanGestureRecognizer *gestureRecognizerFromA;
@property (nonatomic, weak) UIPanGestureRecognizer *gestureRecognizerR;

@end

@implementation GestureHandler
// ...
- (void)setNewMinTouches(unsigned int)num {
    self.gestureRecognizerFromA.minimumNumberOfTouches = num;
    self.gestureRecognzierR.minimumNumberOfTouches = num;
}
// ... and so on.
@end

You'd then have to be careful you only interact with the two gesture recognisers through the GestureHandler class (unless you specifically want them out of sync).
As katzenhut points out, you could also use this class to generate gesture recognisers as you need them. The standard -initWithTarget:action: is really quite useful by itself though.

Incidentally, the reason [gestureRecogniser copy] doesn't work is because UIGestureRecognizer does not implement -copy. Therefore, when the message is sent to the gesture recogniser, NSObject's -copy method is called which is designed to throw an exception as it is an override point for subclasses.

A: Apple does not provide to make duplicate the instance of gesture. Just because of the gesture is associated to the view and the selector method.
You always have to make new instance for every view with selector method or you can used same method for more gesture.


text:
Q: Why does my encoding add \0 efter decoding? So I am sending a simple string from my TCP Client to my server and then when I receive it it decodes the bytes and prints out what it got.. However I am sending
Client connecting..
and I receive
Client connecting..\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
Why is that?
The buffer seems to be the same, 18 bytes with the empty ones being 0
is this due to the Encoding method? I've tried different ones likes Default and UTF8 but it seems to do the same still.
    _listener.Start();
    Console.WriteLine("Waiting for connection..");

    //Assign our client the value of the first accepted request.
    _client = _listener.AcceptTcpClient();
    Console.WriteLine("Client connected.");

    //Set the stream to listen for incoming requests.
    _stream = _client.GetStream();

    //Build the package
    byte[] buffer = new byte[128];

    var bufferLength = _stream.Read(buffer, 0, buffer.Length);
    return buffer;

And it passes the byte array to this
    public void SendPacket(byte[] buffer)
            {
                TcpClient client = new TcpClient(hostName, portNum);

                NetworkStream ns = client.GetStream();

                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"Received from remote client: {Encoding.UTF8.GetString(buffer, 0, buffer.Length)}");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Relaying to the remote server: {Encoding.UTF8.GetString(buffer, 0, buffer.Length)}");

                ns.Write(buffer, 0, buffer.Length);

        }

And then
Console.WriteLine("Data Received..");
var data = Encoding.UTF8.GetString(buffer, 0, length);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received: " + data);

A: According to your code
var bufferLength = _stream.Read(buffer, 0, buffer.Length);
return buffer;

bufferLength is dropped on the floor.
var data = Encoding.UTF8.GetString(buffer, 0, length);

I don't know where length came from, but I suppose it's the buffer's length. Since the receive didn't fill up the whole buffer but only part of it, you must use bufferLength to know how many bytes to work with.
Same problem here:
var eh = ns.Read(newBuffer, 0, newBuffer.Length);
var received = Encoding.ASCII.GetString(newBuffer, 0, newBuffer.Length);

Use eh!
var eh = ns.Read(newBuffer, 0, newBuffer.Length);
var received = Encoding.ASCII.GetString(newBuffer, 0, eh);

A: \0 is the "empty" value for a char object, so most likely it is reading the chars.


text:
Q: Find the indices in a vector efficiently in matlab I have this vector something like this
1
2
2
2
3
3
3
3
.
.
.

What I want to know is in how many rows the individual numbers appeared something like this
1 1
2 3
3 4
. .
. .

I can loop through each element and use
index = find(vector == element)
length(index)

But that is very inefficient. What is the most efficient way  to do it in matlab?

A: From the documentation of histc:

bincounts = histc(x,binranges) counts the number of values in x that
  are within each specified bin range.

If you combine histc with unique, you can get what you want:
a =
     4
     2
     3
     3
     1
     2
     1
     1
     2
     3

uni = unique(a);
[uni, histc(a,uni)]
ans =
     1     3
     2     3
     3     3
     4     1


text:
Q: How do I write a Unicode string to the console screen buffer? Given a handle (hStdOut here) to the standard output device, I use the following 2 procedures to write an arbitrary string from a console application:
Excerpt:
procedure Send(const s: string);
var
  len: cardinal;
begin
  len:=Length(s);
  WriteFile(hStdOut,s[1],len,len,nil);
end;

procedure SendLn(const s: string);
begin
  Send(s + #13#10);
end;

My trouble:
This statement doesn't render correctely the string as I expected:
SendLn('The harder they come...');

My Question:
Is there a "WideString" overload of WriteFile or should I consider another Unicode-aware function that access the console screen buffer?

A: One problem is that you need to specify the length in bytes rather than characters. So use ByteLength rather than Length. At the moment what you are passing in len is half the byte size of the buffer.
I also believe that you should not use the same variable for the nNumberOfBytesToWrite and lpNumberOfBytesWritten parameters.
procedure Send(const s: string);
var
  NumberOfBytesToWrite, NumberOfBytesWritten: DWORD;
begin
  NumberOfBytesToWrite := ByteLength(s);
  if NumberOfBytesToWrite>0 then
    WriteFile(hStdOut, s[1], NumberOfBytesToWrite, NumberOfBytesWritten, nil);
end;

The above is fine if your stdout is expecting UTF-16 encoded text. If not, and if it is expecting ANSI text then you should switch to AnsiString.
procedure Send(const s: AnsiString);
var
  NumberOfBytesToWrite, NumberOfBytesWritten: DWORD;
begin
  NumberOfBytesToWrite := ByteLength(s);
  if NumberOfBytesToWrite>0 then
    WriteFile(hStdOut, s[1], NumberOfBytesToWrite, NumberOfBytesWritten, nil);
end;

Exactly what you need to send to the standard output device depends on what text encoding it is expecting and I don't know that.
Finally, if this is a console that you are writing to then you should simply use WriteConsole.


text:
Q: Python: change color of nodes in graph I have a  and I need to change color of nodes.
I know, that I can specify that in draw_networkx_nodes with node_color.
But is any way to change color with some probability? I don't need to change color to all nodes? only specify a probability 0.3