text:
Q: Why if the set of values of the sequence terms is finite then the sequence is eventually a constant? I am reading a proof of theorem that states that the sequence is Cauchy only if it's convergent. At the beginning of the proof it is stated that if the set of the values of sequence is finite then the sequence is ultimately a constant so from there it is convergent as well. For example a sequence ${(-1)^n}$ forms a finite set of values, but for a sequence to be Cauchy, shouldn't inequality $|a_n-a_m|<\epsilon$ be true for whatever epsilon? I don't see how this sequence is ultimately constant it if every second term is opposite of the first one.

A: There are sequences with only finitely many values that aren't eventually constant, as $(-1)^n$ shows.
But Cauchy sequences with only finitely many values are eventually constant. Indeed let $(u_n)$ be such a Cauchy sequence and let $x_1,...,x_k$ be the values it takes, we take the $x_i$ to be distinct. Let $e= \min_{i\neq j} |x_i-x_j|>0$ and $\epsilon = e/2$.
Then by Cauchy-ness, there is $N$ such that for $n,m\geq N$, $|u_n-u_m|<\epsilon$.
Let $i$ be such that $u_N = x_i$. Then for $n\geq N$, $|u_n - u_N|< \epsilon < e$. Let $k$ be such that $u_n = x_k$. Then if $k\neq i$, $|u_n-u_N| = |x_k-x_i| \geq e > |u_n-u_N|$, a contradiction. Therefore $x_k = x_i$. Therefore for all $n\geq N, u_n = x_i$ : $(u_n)$ is eventually constant.


text:
Q: Generate random numbers based on row and colum totals I would like populate the blue area with random numbers.
sum of C3 to R3 should be equal to B3 value: 124
also;
sum of C3 to C26 should be equal to C2 value: 705
I tried to achieve it with the following code:
(this code was originally posted here: Code by @Mech
Sub RandomNumbersArray()
    ' dim your variables. this tells vba what type of variable it is working with
    Dim lRow As Long
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
    ' find the last row in column b (2) in the above defined ws
    lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    ' loop through rows 3 to last row
    For i = 3 To lRow
        ' generate a random number between 0 and the row contents of column B (5)
        ws.Cells(i, 3).Value = Int(Rnd() * (ws.Cells(i, 2).Value + 1))

        ' generate a random number between 0 and the difference between column B and colum C
        ws.Cells(i, 4).Value = Int(Rnd() * (ws.Cells(i, 2).Value - ws.Cells(i, 3).Value))

        ' subtract the difference between column B and the sum of column C and column D
        ws.Cells(i, 5).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value)

        ' subtract the difference between column B and the sum of column C and column D and column E
        ws.Cells(i, 6).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value)

        ' subtract the difference between column B and the sum of column C and column D and column E and column F
        ws.Cells(i, 7).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value + ws.Cells(i, 6).Value)
    Next i

    ' sum column C (column 3) and place the value in C2
    ws.Cells(2, 3).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 3), Cells(lRow, 3)))
    ' sum column D (column 4) and place the value in D2
    ws.Cells(2, 4).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 4), Cells(lRow, 4)))
    ' sum column E (column 5) and place the value in E2
    ws.Cells(2, 5).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 5), Cells(lRow, 5)))
    ' sum column F (column 6) and place the value in F2
    ws.Cells(2, 6).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 6), Cells(lRow, 6)))
    ' sum column G (column 7) and place the value in F2
    ws.Cells(2, 7).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 7), Cells(lRow, 7)))
End Sub

EDIT: Just to clarify, no negative numbers.

A: Here is something to try:
Set all cells to 0. Create a list of all cells (some kind of reference to each cell).
Now, randomly choose a cell from your list, and add 1 to that cell. The very first time, all cells will be 0, except for one, which will now be 1.
For this cell that you just incremented, add up the row and column and see if the sums have been reached. If either the row or the column sum has been reached, remove this cell reference from the list.
Repeat (randomly choose a cell from those remaining on the list) until the list is empty.
At each iteration you are randomly choosing one of the remaining cells in the reference list (not choosing from all the cells) and this list is getting smaller and smaller as column or row sums are reached.
It should be the case that random cells will increment, and if the columns and sums can in fact be calculated by values without logical inconsistencies, you should fairly quickly reach that point when the reference list falls empty.

A: I have a solution.
Answers so far have mostly been about finding values which are random, then fixing them to fit the totals.
I tried finding a calculated (non random) solution that fits the totals, then made a separate sub to randomize it. This way you can prevent the randomization from introducing negative values.
There are two procedures, This sub will call them both on the same Range.
Sub Call_Random_Array
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
Dim RangeToFill as Range: Set RangeToFill = ws.Range("C3:R26") 'Edit this line to select whatever range you need to fill randomly

'Proportionately fill the array to fit totals:
Call ProportionateFillArray(RangeToFill)

'Randomize it x times
For x = 1 to 10 'increase this number for more randomisation
    Call RandomizeValues(RangeToFill)
Next

End Sub

Proportionately fill the array to fit totals:
Sub ProportionateFillArray(rngAddress As Range)
Dim ws As Worksheet: Set ws = rngAddress.Worksheet

'Horizontal and Vertical target values as ranges:
Dim hTarg As Range, vTarg As Range
Set hTarg = rngAddress.Rows(1).Offset(-1, 0)
Set vTarg = rngAddress.Columns(1).Offset(0, -1)

'Check the totals match
If Not WorksheetFunction.Sum(hTarg) = WorksheetFunction.Sum(vTarg) Then
    'totals don't match
    MsgBox "Change the targets so both the horizontal and vertical targets add up to the same number."
    Exit Sub
End If

With rngAddress

    'Now fill rows and columns with integers
    Dim Row As Long, Col As Long
    For Row = 1 To .Rows.Count
        For Col = 1 To .Columns.Count
            .Cells(Row, Col) = Int( _
                hTarg.Cells(Col) * vTarg.Cells(Row) / WorksheetFunction.Sum(hTarg) _
                )
        Next
    Next

    'Correct rounding errors
    For Row = 1 To .Rows.Count
        For Col = 1 To .Columns.Count
            If Row = .Rows.Count Then
                'Last row, so this column must be corrected come what may
                .Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Columns(Col)) + hTarg.Cells(Col)
            ElseIf Col = .Columns.Count Then
                'Last column, so must be corrected come what may
                .Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Rows(Row)) + vTarg.Cells(Row)
            ElseIf _
                (WorksheetFunction.Sum(.Rows(Row)) - vTarg.Cells(Row)) * _
                (WorksheetFunction.Sum(.Columns(Col)) - hTarg.Cells(Col)) > 0 Then
                'both row and column are incorrect in the same direction
                .Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Max( _
                    WorksheetFunction.Sum(.Rows(Row)) - vTarg.Cells(Row), _
                    WorksheetFunction.Sum(.Columns(Col)) - hTarg.Cells(Col))
            End If
        Next
    Next

End With
End Sub

Randomize an array without changing row or column totals:
Sub RandomizeValues(rngAddress As Range)
Dim ws As Worksheet: Set ws = rngAddress.Worksheet
Dim rngIncrease(1 To 2) As Range, rngDecrease(1 To 2) As Range, lDiff As Long

With rngAddress
    'Select two cells to increase at random
    For a = 1 To 2
        Set rngIncrease(a) = .Cells(RndIntegerBetween(1, .Rows.Count), RndIntegerBetween(1, .Columns.Count))
        rngIncrease(a).Select
    Next

    'Corresponding cells to decrease to make totals the same:
    Set rngDecrease(1) = ws.Cells(rngIncrease(1).Row, rngIncrease(2).Column)
    Set rngDecrease(2) = ws.Cells(rngIncrease(2).Row, rngIncrease(1).Column)

    'Set the value to increase/decrease by - can't be more than the smallest rngDecrease Value, to prevent negative values
    If Not WorksheetFunction.Min(rngDecrease) > 1 Then
        'Don't decrease a value below 1
        Exit Sub
    Else
        lDiff = RndIntegerBetween(1, WorksheetFunction.Min(rngDecrease)-1)
    End If

    'Now apply the edits
    For a = 1 To 2
        rngIncrease(a) = rngIncrease(a) + lDiff
        rngDecrease(a) = rngDecrease(a) - lDiff
    Next
End With
End Sub

'The below is the Random Integer function, I also used it in my other answer
Function RndIntegerBetween(Min As Long, Max As Long) As Long
RndIntegerBetween = Int((Max - Min + 1) * Rnd + Min)
End Function

A: This code is for what you were trying to do, not exactly how you explained it though (see comments). If this is what you were looking for, then your explanation was a bit off, otherwise let me know what you did mean.
Sub RandomNumbersArray()
    Dim lRow As Long, lColumn As Long, remainingValue As Long
    Dim wb As Workbook: Set wb = ActiveWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")

    lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    lColumn = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column

    For i = 3 To lRow 'loop through the rows
        remainingValue = ws.Cells(i, 2).Value2
        For j = 3 To lColumn 'loop through all the columns per row
            ' generate a random number between 0 and the row contents of column B - previous column
            If j = lColumn Then 'last cell can't be random unless you want to extend the columns until the sum in B-column is met
                ws.Cells(i, j).Value2 = remainingValue
            Else
                ws.Cells(i, j).Value2 = Int((remainingValue + 1) * Rnd)
            End If
            remainingValue = remainingValue - ws.Cells(i, j).Value2
        Next j
    Next i
    For j = 3 To lColumn 'loop through the columns to set the sum
        ws.Cells(2, j).Value2 = Application.WorksheetFunction.Sum(Range(Cells(3, j), Cells(lRow, j)))
    Next j

End Sub

I'm yet to get past the O-column with any value above 0 however

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run `mvn appengine:set_default_version` without rebuilding? Our build takes a long time, even when nothing has changed. When I run mvn appengine:set_default_version it does a full build, which takes a few minutes.
Is there an easier way to call set_default_version, bypassing the build?

A: As requested by @Alex :)
I do believe you could build a custom flow to just to call set version. But seems like a complete overkill.
Since you should be changing the default version every once in a while and not on every build (I hope), would't the UI on the cloud Console suffice? You just go to Compute > App Engine > versions and setup the default.
Be advised some people reported issues with the new UI where default version was not changed, so if that fails you might need to use the old app engine console.


text:
Q: Creating drop down menu in html and css (strange error) Before you read: please do not judge me on every little thing.  I am a beginner to this sort of thing and I am just trying to get some practice.  Only comment my mistakes if they are either relevant to the conversation or truly helpful.
I've looked over and over at my code and stackoverflow answers but nothing has what I need.  I want to create a dropdown menu (you hover on a button and multiple links appear in a vertical line below it).  I have been having trouble because the links are horizontal instead of vertical when I hover.  I have no idea why.  I thought this may be because the display style on my nav bar is set to inline, but I used id's in my css, so that should override the navbar classes.  I'm very confused.  Someone please help.  Here is the relevant code (yes, I am using django):

    Home
    Create Post
    {% if user.is_authenticated %}
    My Profile
    {% else %}
    My Profile
    {% endif %}
    {% if not user.is_authenticated %}
    Login
    Register
    {% else %}

    Logout

    {{ user.username }}

        Link 1
        Link 2
        Link 3

    {% endif %}

Edit:  Is the best way to do this just to take a few weeks to learn javascript?

A: You have 2 things going on here:
The horizontal links on hover are popping up because you are basically floating the a tag to the right and not fixing the #dropdown with it so it gets left behind.
in order to get the submenus to show below, you have a number of methods for me I usually use display: flex your code would look something like this:

    Home
    Create Post
    {% if user.is_authenticated %}
    My Profile
    {% else %}
    My Profile
    {% endif %}
    {% if not user.is_authenticated %}
    Login
    Register
    {% else %}

    Logout

    {{ user.username }}

        Link 1
        Link 2
        Link 3

    {% endif %}

you can refer here to more explanation  about css flex here
Edit Code

    Home
    Create Post
    {% if user.is_authenticated %}
    My Profile
    {% else %}
    My Profile
    {% endif %}
    {% if not user.is_authenticated %}
    Login
    Register
    {% else %}

    Logout

    {{ user.username }}

        Link 1
        Link 2
        Link 3

    {% endif %}


text:
Q: Android - How to extract data between tags in xml I have a res/xml/myxmlfile which looks something like this (sorry for the screenshot, I am unsure how to display the xml file properly in the stackoverflow editor):
<Food>
    <Pizza>
        <type>Salami</type>
        <type>Pepperoni</type>
        <type>Hawaiian</type>
    </Pizza>
    <Burger>
        <type>Chicken</type>
        <type>Bacon</type>
        <type>Cheese</type>
    </Burger>
    <Soup>
        <type>Pumpkin</type>
        <type>Sweet Corn</type>
        <type>Vegetarian</type>
    </Soup>
</Food>

I want to write a function that takes the type of food as a parameter (e.g. Burger) and loads all the items between the  tags into a string[i].
So function would be something like this:
public string[] GetAllSubFoodTypes (string foodtype)
{
    string[] contents;

    //--- pseudocode as I don't know how to do this
    Loadxmlfile
    Find the <foodtype> tag in file
    Load all data between <type> and </type> into the string[] contents
    return contents;
}

Example of how you'd call the function from main:
string[] subFoodType;

subFoodType = GetAllSubFoodTypes("Burger")

Contents of subFoodType will then be:
subFoodType[0] will be "Chicken", subFoodType[1] will be "Bacon" and so on.

A: You can use xml parsing like pull parser,DOM parser and SAX parser

A: you can use DOM API, for example:
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse("input.xml");

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/Food/Pizza/type[1]"; // first type
Node pizza = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

if (pizza== null)
    System.out.println("Element pizza type not exists");
else
    System.out.println(pizza.getTextContent());


text:
Q: Inject header in HAProxy redirect function I have HAProxy 1.5.8.
I have this basic 301 rule :
frontend http_frontend
  bind *:80
  mode http
  redirect location https://xxxx.com code 301

The response looks like this :
HTTP/1.1 301 Moved Permanently
Content-length: 0
Location: https://xxxx.com
Connection: close

I need to add a date in the header, like a regular webserver would do.
respadd function doesn't seems to affect the redirect.
Is it possible ?

A: It is possible to do this, Willy from HaProxy identified the solution here:
https://www.mail-archive.com/haproxy@formilux.org/msg25061.html
http-request redirect location "https://blah..\r\nDate: xyz"

The problem I was wanting to solve was to add a HSTS header, but I guess you could use it for a date.
It isn't pretty, but does work, and I have just implemented it, for us we also wanted to render a header identifying the box that was generating the redirect, as we have multiple HaProxy boxes.
This was tested by me in HaProxy 1.6, I can't vouch for other versions.

A: It's not possible for any browser that has ever seen the redirect. It is cached indefinitely. A 301 redirect should only be used when you are retiring a site permanently, and even then it's a bad idea - you loose visibility of the traffic still hitting the old site.
So change it to a 302 redirect before you do anything else.
Haproxy is not a webserver. It has no means to generate a header contains dynamic data - if you really want a date header, use a webserver. There are several lightweight ones capable of this task.
Alternatively tell us why you need such a header and we might be able to advise on a more apposite solution.

A: I found in github issue discussion it is possilbe since Haproxy 2.2
https://stackoverflow.com/a/72830822/1849577
http-after-response set-header Cache-Control max-age=3600 if {condition}


text:
Q: seguridad al hacer upload de imagenes de documentos de identidad tengo este código con el que subo las imágenes de documento de identidad al servidor, por ahora me sube todo sin problema pero me gustaría saber si tengo que agregarle algún parámetro de seguridad adicional y si los valores que estoy colocando en size están bien? adicional quisiera saber si es seguro almacenar esto en una carpeta abierta? pregunto por el tema de los hackers que quieras robar la información de los documentos de identidad o algo, existe algún parámetro para darle seguridad a esto?
y si los valores que subo por ejemplo el nombre del archivo, cuando lo subo a la base de datos, le estoy colocando unos caracteres adicionales que se generan pero seria mejor codificar eso? o solo se le deja el nombre de la imagen y ya? ejemplo imagen1_qwdqdqwdqwd.jpg?
$archivo_subir1 = $_FILES["archivo_subir1"]["name"];
$archivo_subir2 = $_FILES["archivo_subir2"]["name"];
$archivo_subir3 = $_FILES["archivo_subir3"]["name"];
$archivo_subir4 = $_FILES["archivo_subir4"]["name"];
$archivo_subir5 = $_FILES["archivo_subir5"]["name"];

if (!empty($Nom_empresa)) { // <= false
    $Nombre_emp=$Nom_empresa;
    }

    $fecha_hora=time() - (1*60*60);
    $fecha=date("Y/m/d",$fecha_hora);
    $fechaRestada=date("H:i:s",$fecha_hora);
$caracteres = '0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$caractereslong = strlen($caracteres);
$clave = '';
$clave2 = '';
$clave3 = '';
$clave4 = '';
$clave5 = '';

for($i = 0; $i < 20; $i++) {
  $clave .= $caracteres[rand(0, $caractereslong - 1)];
  $clave2 .= $caracteres[rand(0, $caractereslong - 1)];
  $clave3 .= $caracteres[rand(0, $caractereslong - 1)];
  $clave4 .= $caracteres[rand(0, $caractereslong - 1)];
  $clave5 .= $caracteres[rand(0, $caractereslong - 1)];
}
    foreach ($Dat_per_consulta as $item){
        if ($item[$array_validacion_ident]==1){

    $Idperfil_admin =$item[$array_idperfil_admin];
        }
        }
  if ($_SESSION['idtipo']==4) {
if(empty($Doc_front_consult) or empty($Doc_post_consult) or empty($Doc_sost_consult)){
if (empty($Doc_front_consult)) {
if ($archivo_subir1=="") {
}else{
if (($_FILES["archivo_subir1"]["size"] < 100000000 and $_FILES["archivo_subir1"]["name"] !=="" and $_FILES["archivo_subir1"]["type"]=="image/jpeg" or $_FILES["archivo_subir1"]["size"] < 100000000 and $_FILES["archivo_subir1"]["name"] !=="" and  $_FILES["archivo_subir1"]["type"]=="image/png"))
{
$patch='identidades';
        $nombrearchivo=strip_tags($_FILES['archivo_subir1']['name']);
        $nombrearchivo=str_replace(' ', '', $nombrearchivo);
$nombrearchivo=$Empleados.'_'.$clave.'_'.$nombrearchivo;
        if(move_uploaded_file($_FILES['archivo_subir1']['tmp_name'], $patch."/".$nombrearchivo)){
    update_documentos_emp($nombrearchivo, 1);
        }else{
    echo "
Solo se permiten archivos JPG y PNG para la imagen frontal del documento.

";
    }
}else{
echo "
Solo se permiten archivos JPG y PNG para la imagen frontal del documento.

";
$NArch1=="";
}
}
}


text:
Q: Error on getting the result of FolderBrowserDialog Here's my code on my button. I get error on the if statement on the DialogResult. Please see the picture for reference.
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();

if (result == DialogResult.OK)
{

}

A: The System.Windows.Forms.FolderBrowserDialog returns a System.Windows.Forms.DialogResult. Use the fully qualified name:
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();

if (result == System.Windows.Forms.DialogResult.OK)
{

}


text:
Q: how to get the userdefined field in payumoney paymentgetway by using codeigniter? I am developing a online shopping application . for payment getway i am using the payumoney.
in that, i am passing the user defined fields like, $udf1,$udf2,$udf3,$udf4,$udf5,$udf6,$udf7 in PaymentGetway_Controller check method. i am getting the value $udf1 to $udf5 ,
          but not getting the $udf6 , $udf7 in status controller after the payment is successful.
below is my code:
public function check()
{
    $amount = $this->input->post('payble_amount');
    $product_info = $this->input->post('product_info');
    $customer_name = $this->input->post('customer_name');
    $customer_emial = $this->input->post('customer_email');
    $customer_mobile = $this->input->post('mobile_number');
    $customer_address = $this->input->post('customer_address');
    $udf1 = $this->input->post('udf1');
    $udf2 = $this->input->post('udf2');
    $udf3 = $this->input->post('udf3');
    $udf4 = $this->input->post('udf4');
    $udf5 = $this->input->post('udf5');
    $udf6 = $this->input->post('udf6');
    $udf7 = $this->input->post('udf7');

        $MERCHANT_KEY = "jFoMrF"; //change  merchant with yours
        $SALT = "L9butXEG";  //change salt with yours

        $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);

        $udf1 = $udf1;
        $udf2 = $udf2;
        $udf3 = $udf3;
        $udf4 = $udf4;
        $udf5 = $udf5;
        $udf6 = $udf6;
        $udf7 = $udf7;

         $hashstring = $MERCHANT_KEY . '|' . $txnid . '|' . $amount . '|' . $product_info . '|' . $customer_name . '|' . $customer_emial . '|' . $udf1 . '|' . $udf2 . '|' . $udf3 .'|' . $udf4 .'|' . $udf5 . '||||||' . $SALT;
        $hash = strtolower(hash('sha512', $hashstring));
        $success = site_url() . 'Status';
        $fail = site_url() . 'Status';
        $cancel = site_url() . 'Status';

         $data = array(
            'mkey' => $MERCHANT_KEY,
            'tid' => $txnid,
            'hash' => $hash,
            'amount' => $amount,
            'name' => $customer_name,
            'productinfo' => $product_info,
            'mailid' => $customer_emial,
            'phoneno' => $customer_mobile,
            'address' => $customer_address,
            'action' => "https://secure.payu.in", //for live change action  https://secure.payu.in
            'sucess' => $success,
            'failure' => $fail,
            'cancel' => $cancel,
            'udf1' => $udf1,
            'udf2' => $udf2,
            'udf3' => $udf3,
            'udf4' => $udf4,
            'udf5' => $udf5,
            'udf6' => $udf6,
            'udf7' => $udf7
        );

      $data['menues'] =  $this->user_model->menusubmenudata();
      $data['viewcartdata'] =  $this->user_model->viewcartdata();
      $data['billshiprows'] =  $this->user_model->billshipfetchdata();
      $data['alldata'] = $data;
      $data['template'] = 'confirmation';
      $data['title'] = 'confirmation';
      $this->userlayout($data);
}

/*Status controller */
public function index() {

   $status = $this->input->post('status');
  if (empty($status)) {
        redirect(site_url().'User/PaymentGetway_Controller/product_form');
    }

    $firstname = $this->input->post('firstname');
    $amount = $this->input->post('amount');
    $txnid = $this->input->post('txnid');
    $posted_hash = $this->input->post('hash');
    $key = $this->input->post('key');
    $productinfo = $this->input->post('productinfo');
    $email = $this->input->post('email');
    $salt = "L9butXEG"; //  Your salt
    $add = $this->input->post('additionalCharges');
    If (isset($add)) {
        $additionalCharges = $this->input->post('additionalCharges');
        $retHashSeq = $additionalCharges . '|' . $salt . '|' . $status . '|||||||||||' . $email . '|' . $firstname . '|' . $productinfo . '|' . $amount . '|' . $txnid . '|' . $key;
    } else {
        $retHashSeq = $salt . '|' . $status . '|||||||||||' . $email . '|' . $firstname . '|' . $productinfo . '|' . $amount . '|' . $txnid . '|' . $key;
    }

      $data['hash'] = hash("sha512", $retHashSeq);
      $data['amount'] = $amount;
      $data['txnid'] = $txnid;
      $data['posted_hash'] = $posted_hash;
      $data['status'] = $status;

      if($status == 'success'){
          $this->load->view('success', $data);
     }
     else{
          $this->load->view('failure', $data);
     }
}


text:
Q: Recalculate sum of select option on change I have this selector with calculation on select change based on option sum id attribute and input number,
the problem is when im selecting option 1 and increase the input number is working just fine, but when i select option 2 or 3 and incrase the input number again the calculation of total sum is messing up. Im trying when i select different options if a change was made the total price to be again the one from option id.

// Input number
 $('input[name=\'cantitate\']').on('change', function() {
      var cant  = $('#cantitate').val();
      var price = $(this).children(":selected").attr("id");
    $('#total').text(price * cant + ' USD');

  });
// Select box
 $('#variantacurs').on('change', function() {
       var cant  = $('#cantitate').val();
       var price = $(this).children(":selected").attr("id");
     $('#total').text(price * cant + ' USD');

  });

60

  <select class="form-control" id="variantacurs" name="variantacurs">
    <option value="">---SELECT---</option>
     <option id="100" value="Option 1">Option 1</option>
     <option id="210" value="Option 2">Option 2</option>
     <option id="300" value="Option 3">Option 3</option>
  </select>

 <input type="number" name="cantitate" id="cantitate" placeholder="1" min="1" value="1" >

A: Typo, use .form-control selected input/select value.
$(".form-control").children(":selected")
$("input[name='cantitate']").on("change", function () {
  var cant = $("#cantitate").val();
  var price = $(".form-control").children(":selected").attr("id");
  console.log(price)
  $("#total").text(price * cant + " USD");
});

I will recommend not to use id for value, use value as value. Some
  clean can be done as below.

(function ($) {
  // Input number
  const input = $("input[name='cantitate']");
  const select = $(".form-control");
  input.on("change", function () {
    calculate($(this).val(), select.children(":selected").val());
  });
  // Select box
  select.on("change", function () {
    calculate(input.val(), $(this).val());
  });
  function calculate(input, selected) {
    var cant = Number(input);
    var price = Number(selected);
    $("#total").text(`Total: ${price * cant + " USD"}`);
  }
})($);
.as-console {
  min-height: 100% !important;
}

.as-console-row {
  color: blue !important;
}

Total: 0

    <select class="form-control" id="variantacurs" name="variantacurs">
        <option value="">---SELECT---</option>
        <option value="100">Option 1</option>
        <option value="200">Option 2</option>
        <option value="300">Option 3</option>
    </select>
    <input type="number" name="cantitate" placeholder="1" min="1" value="1">

A: There are a number of things wrong with this code:

*

*The id tag is not a good way to store values. The values can be stored in the value attribute itself, whilst the label is the actual content of the <option> element. This makes it easier to retrieve values as well.

*You can just define a function (eg. calc() in my example), and assign it's reference to onchange of the inputs instead of repeating code.

*Use the Number() to convert the string input from val() into proper numbers.

Example:

// Input number
$('input[name=\'cantitate\']').on('change', calc);
$('#variantacurs').on('change', calc);

function calc() {
      var cant = Number($('#cantitate').val());
      var price = Number($('#variantacurs').val());
      $('#total').text(cant * price + ' USD');
}

60

<select class="form-control" id="variantacurs" name="variantacurs">
  <option value="60" disabled selected>---SELECT---</option>
  <option value="100">Option 1</option>
  <option value="210">Option 2"</option>
  <option value="300">Option 3"</option>
</select>

<input type="number" name="cantitate" id="cantitate" placeholder="1" min="1" value="1">


text:
Q: is a sata DVD burner really worth the extra cash  My computer has a old school PATA (ide) DVD burner that works fast and great, really it is the only thing I've not updated over the years. is there any advantage to upgrading to a Sata DVD drive.

A: If you are happy with your old one, the way it looks, and if fits into your new computer connector-wise, then the answer if that it is fine, and you could spend the money better elsewhere.


text:
Q: Help Implement Tags in PHP In my recent PHP project, I need to implement Tags (searchable) separated by comma (similar to this site or something like in WordPress). What is the smart way to detect and remove unnecessary characters or tags? Putting the XSS concern aside, first of all I need to clean and extract only text if user inputs HTML(or other tags) instead of the plain text.
For example:
If user inputs sdfasdf, sdfsdfsdf, <sdfsdfsdf
It should strip out all the unnecessary characters and tags and only plain text should be saved in database.

I have tried it in WordPress and it is very smart to figure out this plus automatically extracts text only.
My question:
Is there an open source library available for this task, which I can integrate in my project. I have done some homework regarding this but *htmlentities(), strip_tags(), HTML Purifier* etc. doesn't seem suitable for this task. Or do need to build my own library combined with this?
Can somebody guide me on this?
Thanks!

A: In addition to removing "complete" tags (markup language elements) such as found in sdfasdf, sdfsdfsdf,
you can also remove "forbidden" characters such as "<", ">", and "&" (using preg_replace and the like), and collapse multiple spaces into a single space (also using preg_replace).
Remember, they're used only as tags (keywords), so it's acceptable here to use a somewhat restricted character set.  In Stack
Overflow, for instance, only letters, numbers, and hyphens are allowed in tags.

A: I would look at this the other way around. What input is legal? Which characters are allowed in tag names? Ones those questions are answered I would build a server-side whitelist of legal characters using regex, state the rules in the UI, and simply reject input that does comply.
Massaging invalid inpu into valid, is rarely a good idea.
Characters allowed in tags are usually alphanumeric + dashes and underscores. Some sites also allow spaces.


text:
Q: jQuery access Ajax Response from PHP function I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.
<?php
 function dateRangeTimeFrame($var1){
  ...

  $date['startDate'] = $startDate;
  $date['endDate'] = $endDate;

  return $date;
 }
?>

I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:
if (isset($_POST['dateFunction'])) {
  print_r(dateRangeTimeFrame($_POST['dateFunction']));
}

My jQuery code is as follows:
$.ajax({
    url: 'includes/functions.php',
    type: 'post',
    data: { "dateFunction": theDate},
    success: function(response) {
        console.log(response['startDate']);
        console.log(response.startDate);
    }
});

My issue is that I do not know how to access the response that the php function is returning.
Here is the response I am getting from the PHP function:
Array
(
  [startDate] => 2015/01/17
  [endDate] => 2015/02/16
)

How would I go about getting these 2 vars from the PHP response?

A: You need to use JSON. Your Javascript natively understands and can parse it
if (isset($_POST['dateFunction'])) {
   echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}

And your jQuery (note I added dataType)
$.ajax({
    url: 'includes/functions.php',
    dataType: 'json',
    type: 'post',
    data: { "dateFunction": theDate},
    success: function(response) {
        console.log(response.startDate);
    }
});

A:     <?php
     function dateRangeTimeFrame($var1){
      ...

      $date['startDate'] = $startDate;
      $date['endDate'] = $endDate;

      return json_encode($date);
     }

?>

jQuery
$.ajax({
    url: 'includes/functions.php',
    type: 'post',
    data: { "dateFunction": theDate},
    dataType: "json",
    success: function(response) {
       console.log(response.startDate);
    }
});

A: <?php
function dateRangeTimeFrame($var1) {
   // ...

   $date['startDate'] = $startDate;
   $date['endDate'] = $endDate;

   echo json_encode($date);
}
?>

Ajax
$.ajax({
   url: 'includes/functions.php',
   type: 'post',
   data: { "dateFunction": theDate },
   success: function(response) {
      for (var i = 0; i < response.length; i++) {
         alert(response[i].startDate);
      }
   }
});


text:
Q: clickable css menu without JS i want to create an HTML5 menu with CSS which works with click instead of hover.
I saw examples on the web where its done with JS.
I was wondering if it's possible to do it without JS. one way maybe is to add
 <input type='checkbox' />

before each parent and according to if its checked to show the sub items
what do you think?

A: :checked
Yes you can do it using a checkbox, it isn't that well supported currently though. It uses the next sibling + and general sibling ~ selectors along with :checked.
jsFiddle
HTML
<input id="menu-button" type='checkbox' />

Menu item 1

Menu item 2

Menu item 3

CSS
/* hide the checkbox */
 #menu-button {
    position:absolute;
    left:-9999px;
    top:-9999px;
}
#menu-button + label:after {
    display:block;
    content:"v";
}
#menu-button:checked + label:after {
    content:"^";
}
#menu {
    display:none;
}
#menu-button:checked ~ #menu {
    display:block;
}

:target
Another way is to use  tags and :target, this is also not that well supported.
jsFiddle
HTML
Show menu

Menu item 1

Menu item 2

Menu item 3

    Hide menu

CSS
#menu {
    display:none;
}
#menu:target {
    display:block;
}


text:
Q: Beamer notes printed in the same page right under each bullet points I understand that Beamer can print notes in a separate page. It also has the capability of displaying the notes in the computer screen while displaying the content of the frame in the projected screen. But my need is a little different. I usually write voluminous notes with each slide and I would like to see them before or after each of bullet points in the slide. After incorporating notes in such a way, I would like to have two versions of the slide. One version will be without the notes which will be beamed in the screen. I would like to keep the other version with all the notes printed and notes must have to be in the same page where the contents are.
The reason I want this is that when the first bullet in a new frame starts, I would just like to take a glance in my printed presentation slide and get an idea on how I am planning to present the content of that bullet point. With the notes separated from the content, it becomes quite difficult to track down which bullet point is referred to which note. If notes are right below or above the bullet points in a frame, then only those can be easily related.
I understand Beamer prints the notes in a different page so that contents remain intact. But for me that does not work. I would like to have the notes in the same page as the content. I understand it may increase the size of the frame which may not contain in the same page. In that I would like Beamer to automatically switch the content of a frame into the next frame whenever it is required. Then when I compile the slides with notes option switched off, the frames should shrink back to original number and size.
I don't know whether Beamer has this capability at all, if not please feel free to suggest other alternatives in TeX.

A: Would something like this fulfil your needs? If you remove handout from the document class options, you will get a version without the note.
\documentclass[handout]{beamer}

\begin{document}

    \begin{frame}
        \begin{itemize}[<+->]
            \item bla
            \mode<handout>{\newline\textcolor{red}{notetext}}
            \item blub
        \end{itemize}
    \end{frame}

\end{document}

for automatic framebreaks you can use the allowframebreak option. But this won't work together with automatic uncovering of the items
\documentclass[
handout
]{beamer}

\begin{document}

    \begin{frame}[allowframebreaks]
        \begin{itemize}
            \item bla
            \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}
                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

                        \item bla
                        \mode<handout>{\newline\textcolor{red}{notetext}}

            \item blub
        \end{itemize}
    \end{frame}

\end{document}


text:
Q: /bin/sh: 1: python: not found Недавно с винды перешел на Убунту (20.04.2.0) и в vscode теперь не могу код запустить. Через терминал не пробовал (ибо неудобно), установил Code runner и выходит такая ошибка
/bin/sh: 1: python: not found

A: *

*Проверь прописан ли путь к python в PATH:

echo $PATH

Если нет используй export для добавления в PATH

*Открой терминал и напиши: python. Должно вывести:

Python 2.7.18 (default, Mar  8 2021, 13:02:45)
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Если вывел:
Command 'python' not found, did you mean:

command 'python3' from deb python3
command 'python' from deb python-is-python3

или
python not found, try

apt-get install python

Тогда пропиши:
sudo apt-get update
sudo apt-get install python

A: sudo apt install python-is-python3


text:
Q: Apache Ignite - Cassandra persistence issue This question is strictly related to my previous one.
Quick summary: I am struggling to configure Cassandra as persistence layer for my Ignite 2.0 cache. It fails with write-behind operations because of:
java.lang.IllegalArgumentException: object is not an instance of declaring class

I tried to play with the schema on Cassandra, fields configuration in the persistence settings, cache properties etc. but I am not able to overcome that. The following is last configuration I tried:
Persistence settings:
<persistence keyspace="ignite" table="odbc_test" ttl="86400">
    <keyspaceOptions>
        REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1}
        AND DURABLE_WRITES = true
    </keyspaceOptions>
    <tableOption>
        comment = 'Cache test'
        AND read_repair_chance = 0.2
    </tableOption>
    <keyPersistence class="java.lang.String" strategy="PRIMITIVE" column="key"/>
    <valuePersistence class="com.riccamini.ignite.ValueClass" strategy="POJO"/>
</persistence>

ValueClass:
public class ValueClass implements Serializable{
    @QuerySqlField
    private int numberOne;
    @QuerySqlField
    private int numberTwo;

    public int getNumberOne(){ return numberOne;}

    public int getNumberTwo(){ return numberTwo;}

    public void setNumberOne(int value){
        numberOne = value;
    }

    public void setNumberTwo(int value){
        numberTwo = value;
    }
}

Cassandra's table:
CREATE TABLE ignite.odbc_test (
    key text PRIMARY KEY,
    numberone int,
    numbertwo int);

Ignite's configuration:
boolean persistence = true;

IgniteConfiguration cfg = new IgniteConfiguration();
CacheConfiguration<String, ValueClass> configuration = new CacheConfiguration<String, ValueClass>();

configuration.setName("test-cache");
configuration.setIndexedTypes(String.class, ValueClass.class);

if(persistence){
    //  Configuring Cassandra's persistence
    DataSource dataSource = new DataSource();
    dataSource.setContactPoints("172.17.0.2");
    RoundRobinPolicy robinPolicy = new RoundRobinPolicy();
    dataSource.setLoadBalancingPolicy(robinPolicy);
    dataSource.setReadConsistency("ONE");
    dataSource.setWriteConsistency("ONE");
    String persistenceSettingsXml = FileUtils.readFileToString(new File(persistenceSettingsConfig), "utf-8");
    KeyValuePersistenceSettings persistenceSettings = new KeyValuePersistenceSettings(persistenceSettingsXml);
    CassandraCacheStoreFactory cacheStoreFactory = new CassandraCacheStoreFactory();
    cacheStoreFactory.setDataSource(dataSource);
    cacheStoreFactory.setPersistenceSettings(persistenceSettings);
    configuration.setCacheStoreFactory(cacheStoreFactory);
    configuration.setWriteThrough(true);
    configuration.setReadThrough(true);
    configuration.setWriteBehindEnabled(true);
    configuration.setStoreKeepBinary(true);
    }

//  Setting cache configuration
cfg.setCacheConfiguration(configuration);

//  Configuring ODBC
OdbcConfiguration odbcConfig = new OdbcConfiguration();
odbcConfig.setMaxOpenCursors(100);
cfg.setOdbcConfiguration(odbcConfig);

//  Starting Ignite
Ignite ignite = Ignition.start(cfg);

Complete stack trace:
SEVERE: Failed to process 1 of 1 elements, during BULK_WRITE operation with Cassandra
class org.apache.ignite.IgniteException: Failed to execute Cassandra BULK_WRITE operation
    at org.apache.ignite.cache.store.cassandra.session.CassandraSessionImpl.execute(CassandraSessionImpl.java:266)
    at org.apache.ignite.cache.store.cassandra.CassandraCacheStore.writeAll(CassandraCacheStore.java:333)
    at org.apache.ignite.internal.processors.cache.store.GridCacheWriteBehindStore.updateStore(GridCacheWriteBehindStore.java:804)
    at org.apache.ignite.internal.processors.cache.store.GridCacheWriteBehindStore.applyBatch(GridCacheWriteBehindStore.java:720)
    at org.apache.ignite.internal.processors.cache.store.GridCacheWriteBehindStore.access$2400(GridCacheWriteBehindStore.java:75)
    at org.apache.ignite.internal.processors.cache.store.GridCacheWriteBehindStore$Flusher.flushCacheCoalescing(GridCacheWriteBehindStore.java:1135)
    at org.apache.ignite.internal.processors.cache.store.GridCacheWriteBehindStore$Flusher.body(GridCacheWriteBehindStore.java:1006)
    at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110)
    at java.lang.Thread.run(Thread.java:748)
Caused by: class org.apache.ignite.IgniteException: Failed to get value of the field 'numberOne' from the instance  of 'class org.apache.ignite.internal.binary.BinaryObjectImpl' class
    at org.apache.ignite.cache.store.cassandra.persistence.PojoField.getValueFromObject(PojoField.java:165)
    at org.apache.ignite.cache.store.cassandra.persistence.PersistenceController.bindValues(PersistenceController.java:450)
    at org.apache.ignite.cache.store.cassandra.persistence.PersistenceController.bindKeyValue(PersistenceController.java:203)
    at org.apache.ignite.cache.store.cassandra.CassandraCacheStore$4.bindStatement(CassandraCacheStore.java:347)
    at org.apache.ignite.cache.store.cassandra.CassandraCacheStore$4.bindStatement(CassandraCacheStore.java:333)
    at org.apache.ignite.cache.store.cassandra.session.CassandraSessionImpl.execute(CassandraSessionImpl.java:230)
    ... 8 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.ignite.cache.store.cassandra.persistence.PojoField.getValueFromObject(PojoField.java:147)
    ... 13 more

Thank you for all the help provided so far.

A: This happens because you set this:

configuration.setStoreKeepBinary(true);

Set it to false (which is default), deploy POJO classes on server nodes and it will work. Current implementation can't work with binary objects directly, this will be improved in the scope of this ticket: https://issues.apache.org/jira/browse/IGNITE-5270


text:
Q: Grub2-reboot # not working on FreePBX Distro 7 - Based on CentOS 7 I have used the same configuration to successfully add a second menu entry and boot to it via "grub2-reboot # && reboot" in CentOS 7 but nothing I do seems to change the menu entry selection for next boot in the FreePBX Distro 7.
Any ideas on what to try to troubleshoot/test/fix?
Configs:
cat /etc/default/grub
[root@freepbx ~]# cat /etc/default/grub
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="gfxterm"
GRUB_CMDLINE_LINUX="crashkernel=auto biosdevname=0 net.ifnames=0 rhgb quiet"
GRUB_DISABLE_RECOVERY="true"
GRUB_BACKGROUND=/boot/splash.png

cat /boot/grub2/grub.cfg
[root@freepbx ~]# cat /boot/grub2/grub.cfg
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub2-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
set pager=1

if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="${saved_entry}"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_msdos
insmod ext2
set root='hd0,msdos2'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos2 --hint-efi=hd0,msdos2 --hint-baremetal=ahci0,msdos2 --hint='hd0,msdos2'  5820774d-3fcf-44fb-86b9-972fab5de985
else
  search --no-floppy --fs-uuid --set=root 5820774d-3fcf-44fb-86b9-972fab5de985
fi
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=en_US
  insmod gettext
fi
terminal_output gfxterm
insmod part_msdos
insmod ext2
set root='hd0,msdos1'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1'  0123444f-dbb6-421e-ad8a-6f6bfb0a0901
else
  search --no-floppy --fs-uuid --set=root 0123444f-dbb6-421e-ad8a-6f6bfb0a0901
fi
insmod png
background_image -m stretch /splash.png
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/00_tuned ###
set tuned_params=""
### END /etc/grub.d/00_tuned ###

### BEGIN /etc/grub.d/01_users ###
if [ -f ${prefix}/user.cfg ]; then
  source ${prefix}/user.cfg
  if [ -n "${GRUB2_PASSWORD}" ]; then
    set superusers="root"
    export superusers
    password_pbkdf2 root ${GRUB2_PASSWORD}
  fi
fi
### END /etc/grub.d/01_users ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Sangoma Linux (3.10.0-514.2.2.el7.x86_64) 7 (Core)' --class sangoma --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.2.2.el7.x86_64-advanced-5820774d-3fcf-44fb-86b9-972fab5de985' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_msdos
        insmod ext2
        set root='hd0,msdos1'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1'  0123444f-dbb6-421e-ad8a-6f6bfb0a0901
        else
          search --no-floppy --fs-uuid --set=root 0123444f-dbb6-421e-ad8a-6f6bfb0a0901
        fi
        linux16 /vmlinuz-3.10.0-514.2.2.el7.x86_64 root=UUID=5820774d-3fcf-44fb-86b9-972fab5de985 ro crashkernel=auto biosdevname=0 net.ifnames=0 rhgb quiet
        initrd16 /initramfs-3.10.0-514.2.2.el7.x86_64.img
}
if [ "x$default" = 'Sangoma Linux (3.10.0-514.2.2.el7.x86_64) 7 (Core)' ]; then default='Advanced options for Sangoma Linux>Sangoma Linux (3.10.0-514.2.2.el7.x86_64) 7 (Core)'; fi;
### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/20_ppc_terminfo ###
### END /etc/grub.d/20_ppc_terminfo ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
menuentry "Parted Magic 64-bit LiveISO" {
set root=(hd0,msdos2)
set isofile="/home/isos/pmagic.iso"
loopback loop $isofile
linux (loop)/pmagic/bzImage64 iso_filename=$isofile load_ramdisk=1
initrd (loop)/pmagic/initrd.img /pmagic/fu.img /pmagic/m64.img
}
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

I've also tried the following and get the same results:
sudo rm /boot/grub2/grub.cfg
sudo rm /etc/grub.d/* -R
sudo rm /etc/sysconfig/grub
yum reinstall -y grub2-tools
grub2-mkconfig -o /boot/grub2/grub.cfg
grub2-install /dev/sda

So FreePBX Uses there own Repo, so I followed the above code, but manually downloaded grub2-tools, now I get the follow error:
[root@freepbx grub]# grub2-install --target=x86_64
grub2-install: error: /usr/lib/grub/x86_64/modinfo.sh doesn't exist. Please specify --target or --directory.
[root@freepbx grub]# grub2-install /dev/sda
grub2-install: error: /usr/lib/grub/i386-pc/modinfo.sh doesn't exist. Please specify --target or --directory.

A: For some reason, FreePBX Distro has a /boot/efi/ folder even on an MBR install.
Tree: (I removed extra stuff)
[root@freepbx ~]# tree /boot/
/boot/
├── efi
│   └── EFI
│       ├── BOOT
│       │   ├── BOOTX64.EFI
│       │   └── fallback.efi
│       └── centos
│           ├── BOOT.CSV
│           ├── fonts
│           │   └── unicode.pf2
│           ├── gcdx64.efi
│           ├── grubenv
│           ├── grubx64.efi
│           ├── MokManager.efi
│           ├── shim-centos.efi
│           └── shim.efi
├── grub
│   └── splash.xpm.gz
├── grub2
│   ├── grub.cfg
│   ├── grubenv -> /boot/efi/EFI/centos/grubenv

The Issue :
/boot/grub2/grubenv is a softlink to /boot/efi/EFI/centos/grubenv
Check MBR vs UEFI:
[root@freepbx ~]# sudo parted -l | grep Table
Partition Table: msdos

sudo rm /boot/efi -R
sudo rm /boot/grub2/grubenv*
sudo rm /boot/grub2/grub.cfg
sudo rm /etc/grub.d/* -R
sudo rm /etc/sysconfig/grub
yum reinstall -y grub2-tools

nano /etc/grub.d/40_custom

grub2-mkconfig -o /boot/grub2/grub.cfg
grub2-install /dev/sda
grub2-reboot 'Parted Magic 64-bit LiveISO'
reboot


text:
Q: ec2 out of memory from apache random spike Over the past year, we had consistently random spikes which caused apache to use all the memory and swap out.
Server Uptime

I have an example of the latest crash (5:30AM - 12:00PM UTC).
OOM Kernel Dump

EC2 Logs

RDS Logs

404 Errors Before Crash

I don't want to increase the ec2 instance resources, since under normal circumstances it is enough to handle the traffic.
What can I put in place to log the source of these spikes, and also put in a solution to prevent these spikes from bringing down the website?
Update
I can confirm that the previous two crashes happened immediately after a considerable amount of 404 requests from a group of IP addresses belonging to ChinaNetCenter Ltd.
Update 2:
Solved the issue by reducing the memory needed to serve 404 pages.

A: A look into the Apache logs around the time of the crash would be insightful. You could have something as simple as a cron job executing that is causing the apache service to crash or you could have apache enabled to only accept a specified amount of concurrent connections and your user base influxes during different times of the day causing this limit to be reached.
You could even have a log rotation that is running that is causing the resources to spike. It is not possible to tell for certain without the apache error log but these are some possibilities to check into.


text:
Q: How to trigger an uncaught exception in React, for Sentry testing? I need to trigger an error in a React app to make sure that my Sentry.io has been configured correctly.
Here is what the Sentry docs is asking me to do:
You can trigger your first event from your development
environment by raising an exception somewhere within
your application. An example of this would be rendering
a button whose onClick handler attempts to invoke a method
that does not exist:

return <button onClick={methodDoesNotExist}>Break the world</button>;

However, even if I disable eslint for the file, React itself will not let me define an element whose onClick is an undefined method.
How else can I generate such an error?

A: Simply add:
<button onClick={()=>{
throw 'oh no an error'`
}}> Err </button>

Thanks to @omnikron


text:
Q: How we open link starting with www I am newer in iOS. I want to open  link starting with www. i am trying to appending http.But it s not work.I am clicking link starting with http is open but not with www Please Help.I am very thankful to any help.....
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (webView==myWebView) {
        if ([request.URL.absoluteString rangeOfString:@"http://"].location != NSNotFound) {
            [[UIApplication sharedApplication] openURL:request.URL];
            return NO;
        }

        else if([request.URL.absoluteString rangeOfString:@"www."].location != NSNotFound) {
                      [request.URL.absoluteString stringByReplacingOccurrencesOfString:@"www." withString:@"http://www."];

            [[UIApplication sharedApplication] openURL:request.URL];
            NSLog(@"%@",request.URL);
            return NO;
        }

        else {
            return YES;
        }
    } else {
        if ([request.URL.absoluteString rangeOfString:@"http://"].location != NSNotFound) {
            NSString *tempString=[request.URL.absoluteString stringByReplacingOccurrencesOfString:@"http://" withString:@""];
            NSArray *itemArray = [tempString componentsSeparatedByString:@","];
            NSDictionary *dict;
            NSString *title=@"";
            if ([[itemArray objectAtIndex:0] integerValue]==0) {
                dict=[toArray objectAtIndex:[[itemArray objectAtIndex:1] integerValue]];
                title=@"Recipient";
            } else if ([[itemArray objectAtIndex:0] integerValue]==1) {
                dict=[ccArray objectAtIndex:[[itemArray objectAtIndex:1] integerValue]];
                title=@"Cc";
            } else if ([[itemArray objectAtIndex:0] integerValue]==2) {
                dict=[bccArray objectAtIndex:[[itemArray objectAtIndex:1] integerValue]];
                title=@"Bcc";
            }
            [appDelegate.navigationController setNavigationBarHidden:NO];
            [self showUnknownPersonViewController:[dict objectForKey:@"address"] :[dict objectForKey:@"name"]:title];
            return NO;
        } else {
            return YES;
        }
    }
}

A: You are using 'stringByReplacingOccurrencesOfString', however not using the return value of that function. Use the returned value to create a new URL:
NSString *newURLString = [request.URL.absoluteString stringByReplacingOccurrencesOfString:@"www." withString:@"http://www."];
NSURL *newURL = [NSURL URLWithString:newURLString];
[[UIApplication sharedApplication] openURL:newURL];
NSLog(@"%@",newURL);
return NO;


text:
Q: Слишком много файлов в каталоге При выполнении поиска похожих изображений с помощью команды
findimagedupes -t 85 Папка_1 Папка_2

выскакивает ошибка:

findimagedupes: Argument list too long

Как решить эту пролему?

A: согласно man findimagedupes, программа умеет вести базу данных с «отпечатками» (fingerprints) изображений (и, конечно, именами файлов, в которых изображения хранятся).
указать файл базы данных можно с помощью опции -f файл. если он не существует, то будет создан. для общей информации: база данных — в формате berkeley db.
если указана база данных, поиск дубликатов будет производиться и в ней тоже, а сигнатуры всех файлов, переданных аргументами (точнее, изображений, хранящихся в этих файлах), будут добавлены в базу данных.
несколько баз данных можно слить в одну (в этом случае опцию -f файл можно использовать многократно) с помощью опции -M файл:
$ findimagedupes -n -M /путь/к/объединённой.бд -f /путь/к/первой.бд -f /путь/ко/второй.бд

есть ещё несколько опций для манипуляций с базой данных. см. man-страницу.

собственно о проблеме:

*

*файлы (с отпечатками) можно добавлять в базу данных последовательно:
$ findimagedupes -f /путь/к/бд -R -n /путь/к/первому/каталогу
$ findimagedupes -f /путь/к/бд -R -n /путь/ко/второму/каталогу
...
$ findimagedupes -f /путь/к/бд

опция -n — не искать дубликаты (только подсчёт отпечатков и сохранение в бд), опция -R — просматривать каталоги рекурсивно.

*если файлов в одном каталоге очень много и возникает упомянутая ошибка, можно выбирать файлы «пачками»: /путь/к/[a-f]* — файлы, начинающиеся с a, b, … f.

*если предыдущий вариант не подходит, можно вызывать программу, используя связку find+xargs. эта связка подставит максимально возможное количество файлов, запуская требующуюся программу несколько раз (если потребуется):
$ find /путь/к/каталогу -type f | xargs findimagedupes -f /путь/к/бд


text:
Q: Is there an equivalent function of mysqli_fetch_assoc for ldap I have done a directory that enable the user to search for other user if they are on the Active Directory. I actually  use ldap to make this possible. The problem is i want to export the result of the search via TCPDF (https://tcpdf.org/).
If i'm right i have to do the research again and then read my entries but i don't know how to proceed. i saw some exemple of tcpdf with mySql db but none with ldap
so i don't have [enter image description here][1]a clue of wich function i have to use to read my entries


text:
Q: WiFi Extender - increase HotSpot number of connections All, need some help with a Wireless Networking Issue.
I need to increase number of connections that my Hotspot device supports (without rooting or changing current config of the device).
My Current Setup

*

*HotSpot Device -> Android phone that supports upto 8 connections

*WiFi Extender -> Netgear EX6150, which connects to Android phone via WiFi, and then extends WiFi to other devices in the household

*Devices -> Then I have 10+ devices in the household that connect to WiFi extender, and in turn access the internet. Note, none of these devices is a laptop or computer. They are all either smartphones or smart devices e.g. TV, wifi enabled electrical devices, xbox etc.
Problem
Although all devices connect to the wifi extender, the hotspot device still detects all the connections, and blocks the 9th device from internet access.
As the hotspot device (a mobile phone) can only support up to 8 devices, remaining devices in my household cannot access the internet.
What I want to know
1 - If my devices connect to WiFi extender, which then accesses the hotspot, why does the hotspot still detect other devices as direct connections?
Is there a way to hide the additional connections to the wifi extender, so that the hotspot only sees 1 device connected to it, the wifi extender.
2 - If above is not possible, then is there any other way to somehow increase max connections ? (sharing USB connection to a computer, and then share wifi is not an option, as I have no access to a spare computer which can serve as internet distribution point)
Appreciate any help you can offer.

A: Get a WiFi extender or a client bridge device (something that can connect to WiFi and allows connections via an ethernet port), and connect it to your phone's hotspot.
Then, disable the access point (repeating/extending function) on the WiFi extender and plug an ethernet cable from a LAN port on the extender to the WAN port of a router.
You can usually find old routers on Craigslist for about $15 to $25. Connect all your devices to the access point broadcasted from the router, and that should do. The router, is given one IP, and then splits it up for other devices.
WiFi extenders do not have routing functionality. The reason for this, is because it would be more expensive to build it that way, and... Traditionally it would cause less issues because it connects to one LAN network pool. Aka, the devices on the main access point can still initiate connections with devices connected to the repeater.

A: Additionally and/or alternatively to @Brad's answer you could look at a wireless router that has wireless WAN connectivity so you can still have your wireless hotspot (phone, for example) but the router will connect to your hotspot as a client to get an internet connection (a "public" IP).
The router will also have a wireless transmitter to create your "private" LAN and it'll do all the routing for you between the devices and your hotspot.
Your hotspot will only see "one" device connected.
As an example DrayTek's Vigor 2860 does exactly this.

You may be able to do it much more cheaply using, for example, a DD-WRT router but it must be capable of having the multiple modes so that you can connect to a hotspot and be a hotspot.

A: You can use a windows PC that has WiFi. The PC (e.g., Win 10 or 11) will have its own WiFi hotspot with a max of 8 WiFi connections to the PC allowed. Very easy to configure the Win hotspot.


text:
Q: Performance problem with upsert in mysql Aurora I am posting here a performance problem which we are dealing with Upsert statement in MySQL Aurora database. The details are mentioned below.
Background Details:
Suppose if there is a schema db1 with a table called tab1(col1,col2,col3,col4,col5,col6). There is unique index being created on col5 and col6.
We created a unique view in the schema db1 with the same structure as tab1 which has the latest data from tab1. And also there is a schema called db2 in which a table tab2 is created with the same
structure of tab1 and unique index. The data from the unique view is inserted/updated into tab2 of schema db2 by using upsert statement. This process is followed on each and every day such that tab2 will have the latest data from tab1.
Problem:
For the first time, as there was no data available in tab2, the upsert statement executed very fast as expected. The second time when delta load has come to the unique view from the tab1 of schema db1. This incremental/delta data should be inserted and updated in the tab2 of schema db2 using upsert statement. The following upsert statement is taking very long time to execute. Not sure, why it is taking very long time. The syntax is as follows.
INSERT INTO tab2 SELECT v.*,CURDATE()
 FROM db1.uniqueview AS v ON DUPLICATE KEY UPDATE
col1=v.col1,col2=v.col2, col3=v.col3, col4=v.col4;
Tab1 has around 2 million rows currently. This data is easily inserted into tab2 when we ran the above command, For the next incremental loads, upsert operation is very slow.
Please help in resolving the issue or your thoughts.
Thanks in Advance


text: Q: Autoregression Model I am new to statistics and math in general as I started at such a late age. I am trying to come up with a model that can predict future numbers using past numbers based on multiple time series that fit into one another. Each time series should operate somewhat independently of the other but also should be dependent on one another. How can I set up a model that will encompass this information that has boundaries. For instance. If I used a time series of 1 hour with the number of data points being 20 with boundaries of 2 standard Deviations above and below the moving average. Now use a time series of a half hour that also uses 20 data points with boundaries of 2 std dev.above and below, how could I build a model that will run that will try to bring these systems into equilibrium? Keeping in mind that the 20 data points in the hourly series is equal to twenty hours but the 20 data points in the half hour series is only 10 hours. Any and all help would be appreciated. Thanks.


text:
Q: C - Fourier transform series for a sawtooth wave I am building an iOS synth, using Audio Unit, basically built around this.
I already support a simple ASR envelope, and sine, triangle and square waves.
Sine are simply,
 sin(theta) * amplitude

Squares are
 sgn(sin(theta)) * amplitude

Now triangles use a non-looped FFT, as follows:
((8 / pow(M_PI,2)) * (sin(theta) - sin(3*theta)/9 + sin(5*theta)/25)) * amplitude

But I can't figure out the sawtooth waves,
I have tried 2*(theta - floor(theta) - 0.5) but it came out aliased and distorted(not from clipping).
I now I should build it with a Fourier transform series, but I can't figure out how to implement it in C.
Any help anyone?

A: You can use a truncated Fourier series for sawtooth waves just like you did for triangle waves, except for including the even harmonic terms as well the odd harmonic terms in the summation, and using a divisor equal to the harmonic number of each term instead of the square of such.
The more terms you use, the more the series approximation will look like a sawtooth, but the more high frequency content it will include.


text:
Q: lebesgue measure in $[0,1]\setminus \mathbb{Q}$ I found this in an old exam and I am not sure if what I've done is correct.
Let $E=[0,1]\setminus\mathbb{Q}$ find a closed set $F$ such that the Lebesgue measure is at least 3/4
Should I suppose that closed here means closed in the subspace topology in $E$ or it is in the usual topology of $\mathbb{R}$?
here what I've done:
Consider $\lbrace q_n\rbrace_{n\geq 1}$ the rational numbers in $[0,1]$ and take $\varepsilon=\frac{1}{4}$. For each $q_n$ we can consider the open interval $I_n$ whose Lebesgue measure is given by $m(I_n)=\frac{\varepsilon}{2^n}$.  Now, let $\tilde{I_n}=I_n \cap E$, it is clear that $m(\tilde{I_n})\leq \frac{\varepsilon}{2^n}$ and consider $U = \bigcup_{n\geq 1}\tilde{I_n}\subseteq E$.Now,   $U$ is open in $E$ with the subspace topology, and since $m(U)\leq \varepsilon$ we are done if we take $F=U^c$.
What do you think about it?

A: Your argument accomplishes more than just making a set $F$ closed in the subspace topology of $E$. It creates a subset $F\subset E$ which is closed in $\mathbb R$ (and so certainly also in the subspace topology).
Namely, a countable union $U\subset [0,1]$ of smaller-and-smaller open intervals around rationals is open in $\mathbb R$, and can be made to have arbitrarily small measure. Its complement in $[0,1]$ is closed in $\mathbb R$, and has measure as close to $1$ as you'd like.

A: It is not to be understood has "a closed subset in the subset topology" but has "find a closed subset that contains no rational number such that its Lebesgue measure is greater that $\frac{3}{4}$". Otherwise, the answer is trivia : take $[0,1]\setminus \mathbb{Q}$.
Let $\{q_n\}_{n\geqslant 1}$ be the sequence of all rational numbers in $[0,1]$, and let $\varepsilon >0$ small. Let $I_n = [0,1] \cap (q_n - \frac{\varepsilon}{2n^2},q_n +\frac{\varepsilon}{2n^2})$. Then $U(\varepsilon)=\cup_{n\geqslant 1} I_n$ is open in $[0,1]$ as a union of open subsets. Moreover, its Lebesgue measure is lesser than $\sum_{n\geqslant 1} \frac{\varepsilon}{n^2} = \frac{\pi^2\varepsilon}{6}$. Let $F(\varepsilon) = [0,1]\setminus U(\varepsilon)$. It is a close subset of $[0,1]$ that does not contain any rational number, and has Lebesgue measure greater than $1 - \frac{\varepsilon\pi^2}{6}$. Chose $\varepsilon$ small enough so that it has measure greater than $\frac{3}{4}$. For example, $F\left(\frac{2}{3\pi^2 } \right)$ is an answer.


text:
Q: how to consider modification time (mtime) by mod_rewrite Is it possible to consider modification time (mtime) of file by mod_rewrite?
What I want to do is:

*

*when accessed to '*.html':

*

*return '*.html' when it exists and is newer than '*.html.eruby'.

*rewrite into '*.html.eruby' when '*.html' doesn't exist or is older than '*.html.eruby'.

my .htaccess:
## inhibit direct access to *.eruby
RewriteRule \.eruby$ - [R=404,L]

## rewrite *.html into *.html.eruby when *.html.eruby exists
## (TODO: rewrite only when *.html.eruby is newer than *.html)
RewriteCond %{REQUEST_FILENAME}.eruby -s
RewriteRule ^(.*)$  $1.eruby

A: Of course there's a solution. I sell it $100 000 000 (close friend's price). Just kidding.
To solve this, use RewriteMap directive that executes an external "filter". See here.
From the website, with emphasis on what you may look:

External Rewriting Program
MapType: prg, MapSource: Unix filesystem path to valid regular file Here the source is a program, not a map file. To create it you can
  use a language of your choice, but the result has to be an executable
  program (either object-code or a script with the magic cookie trick
  '#!/path/to/interpreter' as the first line).
This program is started once, when the Apache server is started, and
  then communicates with the rewriting engine via its stdin and stdout
  file-handles.

So my advice: make a very simple program in python that compares timestamps of the two files.
See here for a sample in Perl.


text:
Q: Filter Crossfilter dimension by date How does one filter a range of dates using Crossfilter? The below does not work when I know for a fact records exist between that time period.
Var myDimension = CrossFilterObj.dimension(function(d) { return new Date(d.insertDate) });

myDimension.filterRange([new Date('December 30, 2014'), new Date('January 1, 2014')]);

A: I think because of the primitive type restriction of dimension you need to use valueOf on Date or simply getTime()
var myDimension =
  CrossFilterObj.dimension(function(d) { return new Date(d.insertDate).getTime() })

myDimension.filterRange([
  new Date('December 30, 2014').getTime(), new Date('January 1, 2014').getTime()
])


text:
Q: Return the AVG of the Top 5 Values in Query Results Question: How would I return the AVG of the Top 5 values in the Payment Ranking query below.
Database: Oracle 11g
Current Query
select distinct pye.payeeid, pay.value,
dense_rank() over (partition by bu.name order by pay.value DESC) as "Payment Ranking"

from cs_period per, cs_payee pye, cs_payment pay, cs_businessunit bu

where per.name = 'August 2014'
and pye.payeeseq = pay.payeeseq
and pay.businessunitmap = bu.mask
and pye.effectiveenddate = to_date('01/01/2200','dd/mm/yyyy')
and pye.removedate = to_date('01/01/2200','dd/mm/yyyy')
and per.periodseq = pay.periodseq
order by pay.value DESC

Results

A: select avg(payment)
from
(
    <your query here>
)
where rownum <= 5

Assumed you keep the ordering as shown in your query.

A: I'm assuming you want the top 5 according to "Payment Ranking" (for which you used DENSE_RANK() instead of RANK() or ROW_NUMBER()):
SELECT AVG(value) FROM (
    select distinct pye.payeeid, pay.value
         , dense_rank() over (partition by bu.name order by pay.value DESC) as payment_ranking
     from cs_period per, cs_payee pye, cs_payment pay, cs_businessunit bu
    where per.name = 'August 2014'
      and pye.payeeseq = pay.payeeseq
      and pay.businessunitmap = bu.mask
      and pye.effectiveenddate = to_date('01/01/2200','dd/mm/yyyy')
      and pye.removedate = to_date('01/01/2200','dd/mm/yyyy')
      and per.periodseq = pay.periodseq
) WHERE payment_ranking <= 5

Note that all I did was take your query and use it as a subquery, adding a WHERE clause to restrict to the top 5 ranked payments.


text:
Q: How to update instances synchronously in Django models? I have 2 models:
class TranslatedLesson(models.Model):
 created_at = models.DateTimeField(auto_now_add=True)
 updated_at = models.DateTimeField(auto_now=True)
 amount_steps = models.IntegerField(default=0)

class TranslationStep(models.Model):
 lesson = models.ForeignKey(TranslatedLesson, on_delete=models.CASCADE, related_name="steps")
 created_at = models.DateTimeField(auto_now_add=True)
 updated_at = models.DateTimeField(auto_now=True)

@receiver(post_save, sender=TranslationStep,
 dispatch_uid="update_lesson_date")
 def update_lesson_date(sender, instance, **kwargs):
  lesson = instance.lesson
  lesson.update_date = instance.updated_at
  lesson.save()

Every time I update TranslationStep model, I wanna update updated_at time, which TranslatedLesson has. But the code above gives me different results, as lesson is saved futher a little bit. Even if I delete auto_now=True and override .save method it doesn't give desired result.
 >>> step.updated_at
     datetime.datetime(2017, 7, 27, 7, 59, 24, 912420, tzinfo=<UTC>)
 >>> lesson.updated_at
     datetime.datetime(2017, 7, 27, 7, 59, 24, 919461, tzinfo=<UTC>)

How to perform update synchronously?

A: Since you want TranslatedLesson.save() to automatically update_date, you cannot use TranslatedLesson.save() here.  The solution is to bypass the call to TranslatedLesson.save() by using QuerySet.update() instead:
receiver(post_save, sender=TranslationStep, dispatch_uid="update_lesson_date")
def update_lesson_date(sender, instance, **kwargs):
    qs = TranslatedLesson.objects.filter(id=instance.lesson_id)
    qs.update(updated_at=instance.updated_at)


text:
Q: Compile Ceylon Js Code with Google Closure Compiler in Advanced Mode What is the recommended way to optimally minimize the size of ceylon javascript code?

A: I passed the language module through a minifier once (can't remember which one, some online service) and some tests failed after that. But this was before splitting the model from the code, and IIRC the errors were related to the model being minified; so maybe it can work for you if you only minify the code, but leave the model alone.


text:
Q: Django: how to load a Queryset with a specific field of a foreign key? I have 2 models, Painting and Painter.
 class Painting(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    painter = models.ForeignKey(Painter)

 class Painter(models.Model):
    name = models.CharField(max_length=200)
    code = models.CharField(max_length=200)

In reality, Painting has 30 columns and Painter has 3.
How can get a QuerySet of paintings so that instead of each object having a painter_id it has painter_name?
I've tried many variations of:
paintings = Painting.objects.prefetch_related('painter_set__name').all()

but can't seem to get it right.
My ultimate goal is to use pandas to export a CSV, so I want each object in the QuerySet to have all the fields I'm interested in.
I want to do something like
paintings = Painting.objects....
df = pandas.DataFrame(list(paintings.values()))
df.to_csv('blah.csv')

A: One way to support this is to annotate each row with the related painter name using F expressions like this:
from django.db.models import F

paintings = Painting.objects.annotate(painter_name=F('painter__name')).all()

Each painting instance in the paintings list will have a painter_name attribute based on the related painter's name field.


text:
Q: Ruby : how to import contact to salseforce from a yaml file I need to parse a yaml file and import it to salseforce contacts... I know how to create new users using the databasedotcom gem, but i don't want to create new users from a rails generated html form...i want to import the contacts from a yaml rather...
As salseforce allows to import contacts from csv files...so is it that i can convert the yaml file to csv and then push it to salseforce...
I searched for some gems at github...but not much of any help...or do i need to do it from the scratch...
Also i didn't find any gem to push contacts to salseforce even if the file format is csv...
I don't want to use dataloader or apex-code or something...i've a developer edition account, and a rails console...just that...
maybe...i'ld try to first parse the yaml file to a hash or something and the push it to a csv file using yaml gem and csv gem...but then i don't have any clues to push that csv file to salsforce...i don't want to use dataloader or apex-code or something
Any help is appreciated...
Thank

A: If you don't want to use dataloader or do it through the import wizard in salesforce directly I think you're going to have to use one of the Salesforce APIs - your best bet is the Bulk API which is designed for larger data sets. The databasedotcom gem works off of the REST API which is more for smaller transactions.  I found this salesforce_bulk_api gem that should work with the Bulk API if you don't want to start from scratch but I know nothing about it.
The Bulk API doesn't support YAML so you will have to convert to either CSV or XML - the documentation will explain the format you need better. It may be that the gem can handle that for you, I'm not sure.

A: If you have rails console, the best way to get started is with https://github.com/heroku/databasedotcom. You can do pretty much everything with that


text:
Q: C# cannot convert from "Gameserver.Client.TCP" to "Sytem.Net.Sockets.TcpClient" I am trying to set up a test server for a simple Game and I am following a tutorial (https://www.youtube.com/watch?v=uh8XaC0Y5MA). The problematic bit of code is:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace GameServer
{
    class Client
    {
        public static int dataBufferSize = 4096;
        public int id;
        public TcpClient tcp;

        public Client(int _clientId)
        {
            id = _clientId;
            tcp = new TCP(id);
        }

        public class TCP
        {
            public TcpClient socket;

            private readonly int id;
            private NetworkStream stream;
            private byte[] receiveBuffer;

            public TCP(int _id)
            {
                id = _id;
            }
        }
    }
}

Whenever I try to run the program I get the error from the title because of this block of code(precisely the "new TCP(id)" Part):
public Client(int _clientId)
{
    id = _clientId;
    tcp = new TCP(id);
}

From my understanding the problem is that I cant convert from the Self written code to the standard library but I don't see where that would be a problem.
So my question is: is there a conversion I can use or some other solution to my problem.
Thank you in advance.
PS. If you need more of the source code please write a Comment.

A: Looks like your field tcp is defined as the type TCPClient, not as type TCP.  There's a type mismatch.  Which type did you want it to be?
You need to fix either the type behind new, or the type in the definition of your field.  Based on the structure (that type TCP contains a TCPClient inside), you wanted the field tcp to be of type TCP.  So change public TCPClient tcp; to public TCP tcp;.


text:
Q: What's the best way to completely remove everything from a computer, without re-installing? I have a friend who wants to sell their computer, but obviously all personal information and software that it is on it needs to be removed before doing so.
Usually I would format and reinstall it, but I cannot easily get hold of the required XP DVDs and I'm not 100% sure the serial number is stuck on the case as usual so getting hold of it will probably require more effort than I'm prepared to spend.
So, what's the best and quickest way to remove and uninstall everything from the PC without reinstalling it?
Thanks.
EDITS: I'm looking to remove things like Internet History and all installed programs, too. I know how to remove the history and each individual program, but that could take hours.
The machine is not branded and therefore there is no website I can go to download recovery software. There is no recovery partition on the computer and I'm not aware of any recovery DVDs for it either. I can only assume it was installed from a retail copy, and therefore there is no way to recover it to factory settings.
It needs to have XP installed, not any distribution of Linux. Like most average people, the person getting the computer will not understand what to do with a computer that doesn't have Windows installed, and software like Office does not work on Linux either.
Buying another licence is not really an option either. She has just brought a laptop to replace the computer, so buying another licence for a computer that she's getting rid of doesn't really make sense.
Thanks for all the help so far!

A: couple of options

*

*just wipe the entire hard drive with a utility like Darik's Boot & Nuke (http://www.dban.org/) which will effectively blank the entire drive.  Then allow the new owner to install whatever operating system they'd prefer.

*create a new user, assign it admin rights, and then remove the contents of the folder(s) located under C:\Documents and Settings{all user EXCEPT the new ADMIN} for example, remove C:\Documents and Settings\administrator.  This in effect removes all the personalized data for the users.  Then you'd have to get some sort of registry cleaner, or as I've done in the past - manually walk through all the registry keys and remove them within REGEDIT.  Painfully cumbersome, but effective.

In reality - the safest way to dispose of a system is to WIPE it using a software disc eraser.  Any software method can leave fragments of files behind since the file is really NOT removed, that is, anyone with time and a little knowledge can RECOVER deleted data.

A: You're not going to be able to clean a computer to any degree that is secure without wiping and re-installing the OS. However it doesn't have to be painful.

*

*Download and install to a CD Darik's Boot And Nuke.

*Get hold of a copy on CD of the version of Windows your friend is using.

*Download and run Double Driver. Use it to back up your drivers onto a USB stick.

*Use Magical Jelly Bean KeyFinder to find out what the Windows XP serial is.

Once you've done all that, then you're ready to go:

*

*Run Dariks Boot and Nuke to erase the hard-drive. As noted by M.M this could take many hours, so run overnight.

*Boot the Windows XP CD and go through the installer. Ensure that Windows Updates are turned off (as otherwise you'll find yourself wading through hundreds of them) during the install.

*Use the CD key you got previously to re-register Windows.

*Let Windows go online and validate your CD key.

*Unplug the network cable.

*Point Windows at the USB stick for any drivers that are missing. No need to download anything.

*Turn on Windows Update to the recommended settings.

*Power off the computer.

Job done. If you're feeling benevolent, then you could also:

*

*Turn on Windows Update and download all high priority packages

*Install Microsoft Security Essentials.

*Use Ninite to pre-install a bunch of useful applications really quickly and unattended (eg. FireFox, VLC, Picasa, Adobe Reader, Flash, SilverLight and CDBurnXP if you have a CD/DVD writer on the computer)

A: This is what I have done in the past before donating an old computer to a friend or a relative.

*

*Uninstall everything that isn't shipped with windows using an uninstall tool that also cleans the registry and deletes leftover files. (I like Revo Uninstaller Free)

*Delete all bookmarks in IE

*Use a tool to remove private data from the computer (browser history, cookies, recently opened files ..) Again I recommend Revo, It has a Tracks Cleaner on the Tools tab

*Delete all files on the desktop and in my documents and anywhere else you know there is data

*Empty Recycle bin
If you have more than one user, repeat 2-5 for each user

*Create a new Admin user, with a blank (no) password log on as that user

*Delete all other accounts

*Delete the folders for the old/removed users in C:\Documents and Settings

*Delete C:\Documents and Settings\All Users\Dokument and all files on any other partitions/hard-drives beside C:

*Do a full computer search for media files and documents to see if you missed anything interesting and delete those

*Get a "free space" scrubber and run that to make undeleting files impossible (I use Eraser)
After this the computer should be safe to sell.

A: Short answer, no easy way to do what you suggest. Cleaning personal info from XP is a manual job that takes time, and no way to guarantee you got it all.
Best advice is to use the restore partition (if it has one) or clean Install of XP and then when it is done restoring or the clean install is done, overwrite all the free space on the drive with "Eraser 5.8", this guarantee's all info has been overwritten and is not recoverable by anyone.
Posting your Make and exact Model may prompt us for more suggestions.
Since reinstalling is definitely Not an option.
Back up data you want to save.

*

*Create a new user account.

*Log into that new account and delete any other user accounts (do not delete the admin or guest accounts)

*Uninstall any software you don't want to pass on. then search the hard drive for those names of software and remove any folders left behind.

*Delete any folders on the C drive that may have been created manually by the user.

*Do a IE7-8-9 reset, then delete browsing history (select all the boxes)

*Use index.dat suite to delete any dat files it finds,(requires selecting them to be deleted on a reboot)  http://support.it-mate.co.uk/?mode=Products&p=index.datsuite

*At the command prompt type these 3 commands one at a time hitting enter each time, the erase tmp command may take time to complete.
cd\
erase *.tmp /s
erase *.bak /s

*Empty the Recycle Bin

*Use eraser version 5.8.8 to erase the free space on the hard drive, install eraser,   then right click on the C drive and select "erase unused space". (it may take quite some time if the hard drive is large) http://sourceforge.net/projects/eraser/files/

A: The brand name machines usually come with a disk that will reset the box back to default, maybe you can download an image of the disk?  Some also have a "restore" partition on the hard drive of the box, check for that. The last HP Pavillion we had was equipped with such a partition, the docs were available from HP, which allowed up to re-install everything fresh starting with a wipe of the hard drive.

A:
I have a friend who wants to sell
  their computer, but obviously all
  personal information and software that
  it is on it needs to be removed before
  doing so.

There are 3rd party applications (mostly paid/not free) that will be able to traverse your registry and obtain any serial/license keys. There's really no easy way to "copy" software in the Windows world from one computer to another. Installation is the only way. The key is the more important item. Google alone can point you to many utilities that might meet your requirements. I'd also look around lifehacker.com. They might have some utilities that may work for this specific scenario.

Usually I would format and reinstall
  it, but I cannot easily get hold of
  the required XP DVDs and I'm not 100%
  sure the serial number is stuck on the
  case as usual so getting hold of it
  will probably require more effort than
  im prepared to spend.

Maybe this would be an opportunistic time to upgrade to Windows 7 OEM and add some of the cost onto the price? If not, getting an XP CD is one thing, but the license is quite another. XP has many different versions both for home and professional. There's Home OEM and Home Retail. Profession OEM and Pro Retail, etc. etc. Your key if it's on the computer itself (like on a sticker or something) may not be usable if you use a different XP CD/DVD. I've run into this several times. The key you have may be for retail or OEM version. If this is a brand name computer like HP/Dell/Compaq/whatever, then there may be a recovery disc available for purchase online (usually pretty cheap - $5-$10).
It sounds like you want to maximize your money earned rather than spend money to sell the machine with a clean Windows XP install. That's totally fine and it makes sense. I'd say, your best bet is to look for a recovery disc from the manufacturer and try reinstalling Windows that way. If you can't find it, you may have to manually remove all the software.

So, what's the best and quickest way
  to remove and unstall everything from
  the PC without reinstalling it?

'Best' way? Reinstall the OS. 'Quickest' way? Reinstall the OS. But it's looking like that may or may not be an option. If the computer is a brand name machine, hunt down the manufacturer's website for any hint of a recovery CD and see if that'll do the trick. If not, it looks like your only option is to manually remove everything.

A: First since time spent and security are issues not to mention that when done it's still going to have a 10 yr old OS on it I would personally consider two things (assuming there isn't a really easy way like the restore partition).
First if everything went wrong I would be willing to just scrub the disk and sell it as is. Many times I buy older PC's with the idea of blasting what's there and installing Linux, for most of the older boxes I've looked at the price differential is only about $25 for a clean disk vs an XP install.
Now the part that will probably get criticized and probably isn't even that good an answer but because I wouldn't be willing to spend more than about 30 minutes to preserve that $25 I would do the following.
Clone the disk if possible to some old drive laying around using Clonezilla.  Or at least the back up the Program Files.
Then I would just start deleting directories out of the Program Files directory.
Then run a couple decent registry cleaners that would scan for useless and unreferenced keys as well as shortcuts that don't point anywhere. (there are discussions with regard to registry cleaners on SU).
Finally with regard to personal data, not knowing where and how you organize things, it's just a matter of tracking it all down, deleting it, and defraging, or to be really safe delete it with a file scrubbing software of which plenty of free ones are available.
Which is why if you don't have a restore partition, and don't want to track down a CD, I would personally consider selling a blank box.

A: A supplemental answer that improves upon other answers listed here.
Be aware that tools like Eraser can only wipe the 'cluster tips' (the slack space at the end of any file smaller than a multiple of the cluster size) of files that are not in use or protected.  This means that a small amount of personal information can remain behind.
To mitigate this, you can boot from a CD, so that those files are not in use. Hiren's Boot CD can do this, and comes with Data Shredder and CCleaner, both of which can wipe cluster tips and free space.
Note also that Eraser also handles alternate data streams, and so does CCleaner.


text:
Q: How to get row Index from cellEdited:function(cell)? - Tabulator I have a typical tabulator setup with  keybindings:{"navUp" :"38","navDown" :"40","navLeft" :"37","navRight" :"39"} enabled.
When edit a cell it updates data successfully and moves programmatic in the next cell bellow
    cellEdited:function(cell){

         let updateValue = updateValueQuery(columnIndex,rowIndex,cell.getValue()).then(function(done){
         cell.nav().down();
         });
    }

When in a new cell down, the rowId doesn't change (its behavior is not like rowClick)
What i'm trying to figure out is:  How to get row.getIndex(); inside of cellEdited:function(cell){}
    cellEdited:function(cell){

         // ->> How i can obtain rowIndex = row.getIndex(); here or if there is another more optimal way.

         let updateValue = updateValueQuery(columnIndex,rowIndex,cell.getValue()).then(function(done){
         cell.nav().down();
         });
    }

I've tried to put row attribute in cellEdited:function(cell,row) but without luck.
Any help will be appreciated!
thank you for your time!

A: I'm not sure I understand your question but you can access the row through the cell component methods
var row = cell.getRow();

And you can also just get the data without going through the row:

Get Data
The getData function returns the data for the row that contains the
cell.

var dataID = cell.getData().id;
// the name of the property you are using for the index

Or use getIndex

Get Index
The getIndex function returns the index value for the row. (this is
the value from the defined index column, NOT the row's position in the
table)

var rowIndex = row.getIndex();

If you want to get the next or previous logical row, you can use the methods of the row component:

Get Next Row
The getNextRow function returns the Row Component for the next visible
row in the table, if there is no next row it will return a value of
false.

var nextRow = row.getNextRow();
var prevRow = row.getPrevRow();

And finally:

Get Position
Use the getPosition function to retrieve the numerical position of a
row in the table. By default this will return the position of the row
in all data, including data currently filtered out of the table.
If you want to get the position of the row in the currently
filtered/sorted data, you can pass a value of true to the optional
first argument of the function.

var rowPosition = row.getPosition(true);
//return the position of the row in the filtered/sorted data


text:
Q: Find the current shell of the user using a shell script I am trying to write a file that a user will source in order to modify their ld_library path. This will be different for each shell so I need to find theirs before I do this.
I have tried:
$SHELL

Unfortunately this will give the users shell but not necessarily the shell that they are in. If my normal shell is BASH but I swap into sh, it will return /bin/bash.
readlink -f /proc/$$/exe

This looked promising unfortunately a shell script actually spawns a new instance of bash, or whatever you put with the #! at the start.
Finally:
$0

This actually returns the name of the executable, rather than the shell. Which makes sense but it works as a shell command.
Any suggestions?
EDIT: So all of the suggestions from a similar thread will either return what is the users preferred shell, they will return the name of the executable itself, or they will return the path for the #! at the start of the code. None of these are particularly helpful.


text:
Q: How to solve the Rope Bridge problem with an algorithm? I was wondering if this rope bridge problem could be solved with a graphing algorithm search:
My gut feeling says DFS but how should I define the states?  (That is if DFS is even the way to go.)
Rope Bridge

A: This task is supposed to be solved without a computer.
However, if you generalize the case, then, I suppose, you can do it with graph searching, but you should take the size of the graph into account.  If each vertex is the "state", then the number of this states estimates as 2N⋅L, where N is the number of people, and L is the length of the flashlight.  Each state contains information, which side is each person at, and of remaining flashlight duration.  If there's a path from initial state to one of those states where everyone's on the camp's side, then this path is the solution.
That's the most obvious way to create states, but maybe you can do it in a more efficient way (current number of states, hence the runtime, is exponential to the input size).
However, for the sizes that small as in the sample you provided, exponential runtime (with graphs) is acceptable.  The interviewer may even like it, if you suggest programmatic solution instead of doing it by hand.

A: You might want to look at EWD 1255.


text:
Q: How do you efficiently apply a numeric operation to an array in lua? Say, I have an array
a = { 1, 2, 10, 15 }

I would like to divide each element by 3 and store the result in a new array. Is there a more efficient / elegant way of doing that than this:
b = { }
for i,x in pairs(a) do
  b[i] = x / 3
end

In R, I would simply do b <- a/3. Is there anything like that in lua, or maybe a way of applying a function to each element of a table?

A: Lua is lightweight, so there is no ready-made functions, but you can create a similar function with metatable.
local mt_vectorization = {
    __div = function (dividend, divisor)
        local b = {}
        for i,x in pairs(dividend) do
            b[i] = x / divisor
        end
        return b
    end
}

a = setmetatable({ 1, 2, 10, 15 }, mt_vectorization)

b = a / 3

A: In addition to the answer by shingo, I found in the meanwhile that writing an R-style mapping function is very easy in lua:
function map(x, f)
  local ret = { }
  for k, v in pairs(x) do
    ret[k] = f(v)
  end
  return ret
end

This makes some operations easy, for example
a = { 1, 2, 3, 5, 10 }
map(a, function(x) return x * 2 end)