text:
Q: Converting factors with character names to numerics (after import from an .sav file) So after I've imported a data.set via memsci (which worked very nicely btw! :)), I now have the problem that almost all of the data is converted to (non-ordered) factors, but the levels are not 1,2,3,4,5 (which is what it should be for calculations) but rather "fully agree" down to "don't agree at all".
This leads to the problem that I can't use as.numeric(levels(f))[f] to convert the factor into numerics.
To get import my data I used this:
data <- as.data.set(spss.system.file("data.sav"))
dat <- as.data.frame(data)

However: The informations seems to be there.
str(var1)

Factor w/ 5 levels "don't agree at all",..: NA 1 1 1 1 1 1 1 1 1 ...

labels(dat$var1)
  [1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12"
 [13] "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"  "22"  "23"  "24"

levels(dat$var1)
[1] "do not agree at all" ". ."              ". . ."
[4] ". . . ."          "fully agree"

Where are the values stored? I've tried labels(var1) and just var1, but I neither works. However: Using as.numeric(var1) gives me the information I need, BUT I don't think one should apply this as stated in the R help for factors. Also after using dat[,1:ncol(dat)] <- lapply(dat[,1:ncol(dat)], function(x) as.numeric(x))
the variable is still being considered a factor and behaves exactly the same as before.
Edit: Reproducible example thanks to @jakub
var1 <- factor(c(1,2,3,4,5,5,4,3,2,1),
               levels = as.character(1:5),
               labels = c("Fully agree", "....", "...", "..", "Do not agree at all"))

A: You say:

as.numeric(var1) gives me the information I need, BUT I don't think one should apply this as stated in the R help for factors

If you refer to:

In particular, as.numeric applied to a factor is meaningless, and may happen by implicit coercion.

then you are most likely confusing two issues. You either want the labels, or you want the levels.
If you have numerical values that happen to be labels of a factor, then indeed you have to convert to numeric using as.numeric(levels(f))[f]. An example:
var1 <- factor(c(1,2,3,1),
               labels = c("123", "5", "-11"),
               levels = as.character(1:3))
levels(var1)
# [1] "123" "5"   "-11"
as.numeric(var1)
# [1] 1 2 3 1  #this indeed does not make much sense - the values are lost!
as.numeric(levels(var1))[var1]
#[1] 123   5 -11 123

But in your case, this does not apply, because (if I understood correctly), you don't want the labels, but the underlying integers. For you, it makes sense that Fully agree means 1. In such case, as.numeric(var1) is fine.


text:
Q: How can a low quality post can get more than 15 or 20 reviewers? I just went through an item in the Low quality posts review queue in Stack Overflow en español. It sounded strange to me to have it there, since its timestamp was from around September. In any case, I voted to close and then went back to see what others had done, to confirm it wasn't anything weird. The thing is... it was! Not in the sense I thought about, but because I was the 15th person to review the item, as you can see in https://es.stackoverflow.com/review/low-quality-posts/230955

Since this was unexpected, I tried to see what post this happened to, but I cannot get more information. For this, I reviewed another item and the behaviour was the same:

Vote to close and now when I check the page it shows a lot of people in the review list. Apparently I was the 21th to review, but it still shows as 'needs more reviews': https://es.stackoverflow.com/review/low-quality-posts/214264

The question in the review queue has apparently gone through different Close votes, but the links in its timeline doesn't provide further information about them (it just says 'This item is no longer reviewable.' in one case).

A: tl;dr: this appears to be happening because no one is reviewing the item in the Close Votes queue, and not enough people with close voting privileges are reviewing or voting to close the post.
When it comes to reviewing questions in the Low Quality Posts queue, there are three actions one can take: either find that it looks OK, edit it to fix problems with it, or recommend it for closure (maps to a close vote if you have enough rep to cast close votes).
As per When is a review task "completed" or "invalidated"?, the number of Looks OK reviews required to dismiss the task with an outcome of Looks OK is equal to the number of active "very low quality" flags from users (which don't expire), plus 1 (2 on English SO). Also, only a single Edit review is required to dismiss it. But the answer doesn't state anything about the number of Recommend Close reviews required. And that's because those reviews don't actually contribute toward dequeueing the post.1
This is also confirmed by this excellent flowchart published by an employee a while ago, which is still quite accurate to this day (with only one exception for most of the time, and two as of last week's revamps to Triage). I've zoomed in to the relevant part of the flowchart below2:

Notice what the circled box says: if a post there is reviewed as Recommend Close, it "Stays in LQ until final review met, but also sends to Close Review". In other words, it has no effect on its dequeueing from the LQ queue. However, it does have another effect: it puts the post in the Close Votes queue. The option has the effect of casting a standard close flag on behalf of the reviewer. That queue treats it that way as well.
Close flags and votes expire after 14 days, and close review tasks become invalidated if all active close votes and flags expire.
Let's have a look at the second question as an example. We'll examine the question's timeline, and piece the events together with the review task's events. Before continuing, I should mention that due to a bug, the review queue conflates the display of "Recommend Close" and "Close" reviews:

*

*On May 26, someone reviewed the post as Recommend Close. This spawned a Close Votes review for the item.

*14 days later, on June 9, as no one else had cast any close votes or flags, that flag expired, and the review was invalidated. You can see in the LQ review's history that there were no close flags cast within that 14-day period.

*On June 28, the post received a second Close review, which spawned another CV review, which received no reviews.

*The LQ review continued to get more and more close reviews in the LQ queue, along with possibly external close votes or flags, at a rate of at least one every 14 days, enough to keep that second CV review alive and not invalidated. In the meantime, the CV review task didn't receive any reviews from anyone.

*On October 24, the second close review was finally invalidated after a 14-day break in flags.

*One hour ago, you made another Close review, and this should soon spawn a third CV review task.
So, to put it simple, despite the heavy preference toward closure from <3k users, not enough people with 3k+ rep came in and voted to close it, and of the very few who did, their close votes kept expiring. As Recommend Close reviews in Low Quality Posts don't count toward dequeueing the item in any way, the review stretched on indefinitely with nearly two dozen reviewers.
I...think this is a rather rare edge case coming to bite. This definitely shouldn't end up being drawn out like this, and there should be something to stop it. I think there should be a flag to let moderators know if the number of reviews for closure in LQ exceeds a threshold, with no closure.
However, based on the way the system is currently configured, there's no issue here, this is how the queue is designed.
Update: After having looked through the database for other examples of such reviews, I found one example that had been reviewed by 25 people in favor of closure, but received a single Looks OK review at the very end. That single Looks OK review was enough to dismiss the task with a Looks OK outcome, even though there were 25 other people who didn't think so. I'm aware that there's an automatic moderator flag raised if a similar situation happens for answers, but based on the fact that no moderator took any action toward the post, I can't say certainly if the same is raised for questions. If it isn't, that's a massive, gaping flaw, and should be fixed.

1 For a time, that post said that six Recommend Close reviews tasks would dequeue it, but that's not actually the case. I edited that text in back in March 2018, just after I gained the ability to review Low Quality Posts anywhere on the network, and my knowledge of the network was more limited then.
2 This flowchart does oversimplify two details, first, that first posts can also go through that queue in addition to First Posts, and second, that not only questions with low quality score go to the LQ queue, but also questions with high enough score that are flagged as "very low quality" - that's basically telling the system, "hey, you were wrong about judging this as being of good quality enough, this should be treated as not meeting the threshold". But those aren't relevant here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add/remove fields from a form type depending on the action I have two actions that are instantiating a form type.
I need to add/remove fields from the form type depending on the action from which the form type is instantiated.
How can I do this? should I extend the form to get two form types? or use the form events maybe?


text:
Q: Function Sumif in Excel I've got a problem with function SUMIF in Excel.
I want to use this function to calculate the total Q of codes that contain "a" and "b" (ex: ababba, abcab, bac) as in the image.
The code I used is SUMIF(K6:K9;"*a*b*";L6:L9)+SUMIF(K6:K9;"*b*a*";L6:L9). However, codes like ababba, abcab are calculated twice.
Can you help me with this? Thank a lot.

A: Use a simple SUMIFS:
=SUMIFS(L6:L9;K6:K9;"*a*";K6:K9;"*b*")

This will only calculate those that have both.


text:
Q: Registering multiple admin classes with a model in Django admin I've two Admin classes for a single model:
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import *

class ProductSummernoteAdmin(SummernoteModelAdmin):
    summernote_fields = ('description',)

class ProductAdmin(admin.ModelAdmin):
    ...

admin.site.register(Product, ProductSummernoteAdmin)

I want to register both ProductSummernoteAdmin and ProductAdmin with Product model. How to do that? As, i can't register same model twice.

A: I found a quick bypass for registering both SummernoteModelAdmin and admin.ModelAdmin classes using multiple inheritance without Proxy Models:
class ProductAdmin(SummernoteModelAdmin, admin.ModelAdmin):
    summernote_fields = ('description',)

    class Meta:
        model = Product

admin.site.register(Product, ProductAdmin)


text:
Q: Problema con botton de html para modificar un contenido con javascript Estoy programando en js junto con html y css, estoy haciendo un encriptador de mensajes, mi codigo de js tiene una funcion que al recibir un texto de un texttarea cambie las vocales por otras letras, esta función se debe de ejecutar cuando se haga click en un boton llamado "encriptar", a la hora de hacer click, no funciona correctamente.
`

&#9888 Solo letras minúsculas y sin acentos

            <form>
                <textarea cols="50" rows="22" id="mensaje" class="input-mensaje" required placeholder="Pon aquí tu mensaje" ></textarea>

                <button id="encriptar" >Encriptar</button>
                <button id="desencriptar">Desencriptar</button>
            </form>

No se ha encontrado ningún mensaje

hola

var encriptar = document.getElementById("encriptar");
var input = document.getElementById("mensaje");

function imprimir(frase){
    document.write(frase);

}

function cambiaVocal(){

    var letras = input.value;
    var listaLetras = letras.split("");
    var cantidadLetras = letras.length;

    for(var contador = 0; contador < cantidadLetras; contador++)

        if(listaLetras[contador] == "a"){
            document.getElementById("mensaje-encriptado").innerHTML = "ai";
        }
        else if(listaLetras[contador] == "e"){
            document.getElementById("mensaje-encriptado").innerHTML = "enter";
        }
        else if(listaLetras[contador] == "i"){
            document.getElementById("mensaje-encriptado").innerHTML = "imes";
        }
        else if(listaLetras[contador] == "o"){
            document.getElementById("mensaje-encriptado").innerHTML = "ober";
        }
        else if(listaLetras[contador] == "u"){
            document.getElementById("mensaje-encriptado").innerHTML = "ufat";
        }
        else if(listaLetras[contador] == " "){
            document.getElementById("mensaje-encriptado").innerHTML = " ";
    }

}

encriptar.onclick = cambiaVocal

`
Utilice un div con adentro un "hola" para ver que ocurría, me fije que solo muestra si la letra es una "a" la muestra como "ai" por unos milisengundos y vuelve a presentar el mensaje "hola".
Soy nuevo aprendiendo a programar por si no saben como resolverlo o quieren darme recomendaciones acerca de como mejorar el código con términos básicos, estoy más que dispuesto a recibir críticas constructivas,

A: No hace falta que hagas un for ni tampoco esos ifs, podes usar el metodo replaceAll() (replaceAll MDN DOCS) que recibe dos parametros: el patron a reemplazar, y el patron nuevo a colocar. A diferencia de replace(), replaceAll() recorre todo el string y busca cada ocurrencia y reemplaza todas ellas:

let encriptar = document.getElementById("encriptar");
let input = document.getElementById("mensaje");
let msjencriptado = document.getElementById("mensaje-encriptado");

function imprimir(frase){
    document.write(frase);
}

function cambiaVocal(){
    let letras = input.value;
    letras = letras.replaceAll("a","ai")
    letras = letras.replaceAll("e","enter")
    letras = letras.replaceAll("i","imes")
    letras = letras.replaceAll("o","ober")
    letras = letras.replaceAll("u","ufat")
    msjencriptado.textContent = letras
}

document.getElementsByTagName("form")[0].addEventListener("submit",(e) => {
  e.preventDefault(); // esto es para prevenir el comportamiento por defecto de los forms de recargar la pagina cuando se haga submit
})

encriptar.onclick = cambiaVocal

&#9888 Solo letras minúsculas y sin acentos

<form>
    <textarea cols="50" rows="22" id="mensaje" class="input-mensaje" required placeholder="Pon aquí tu mensaje" ></textarea>

    <button id="encriptar" >Encriptar</button>
    <button id="desencriptar">Desencriptar</button>
</form>

No se ha encontrado ningún mensaje


text:
Q: keytool -genkey error: Keystore file does not exist I try to create a new self certified keystore file
The command I use is:
keytool -genkey -selfcert -dname "cn=My Name, ou=Orga unit" -alias selfcertified -keypass somepass -keystore keystore.jks -storepass anotherpass -validity 365

but I always get this annoying error:
keytool error: java.lang.Exception: Keystore file does not exist: keystore.jks

I do not understand why I'm getting this error. The command above should create a new keystore, so why is it complaining about a non existing store?

A: Run command prompt as Administrator and it will be done.

A: Generating a key pair (and a new keystore) has to be done as a separate operation to creating a self-signed certificate for that key.
i.e.
keytool -genkey -alias myKey -keystore store.jks
keytool -selfcert -alias myKey -keystore store.jks

A: First generate the upload key using below command:
keytool -genkeypair -v -keystore my-upload-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

then run
keytool -exportcert -keystore path-to-debug-or-production-keystore -list -v

A: -selfcert option was made obsolete in keytool for Java 6. Check the last section of "Changes" here: Java 6 Keytool
So for Java 6 and onwards, replace -selfcert with -certreq

A: Seems a old link but this is what I tried - Hope this helps someone.
In my case as .keystore file was missing in the below location, I had run the following command;
keytool -genkey -alias mykey -keystore "C:\Users\username.keystore"
This creates a .keystore file in the location, system asks you for information like
What is your first and last name?
What is the name of your organizational unit?
What is the name of your organization?
What is the name of your City or Locality?
What is the name of your State or Province?
What is the two-letter country code for this unit?
Is CN=XXX, OU=XXX, O=XXX, L=XXX, ST=XXX, C=IN correct?
Say "Yes" and the keystore will get created.


text:
Q: Problem with Deploying localized win form app in .net 3.5 C# The Problem in Short:
Localized text works perfect on my development machine(windows 7) but NOT when the app is deployed to some other machine(Win XP).
Details:
I am writing a small, single form app. It must display text in Hindi. Below is my form in the Default Language.

couldnt post image coz im new

Here it is in Hindi:

couldnt post image coz im new

I have the Following code in the constructor of Form1
    public Form1()
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("hi-IN");
        Thread.CurrentThread.CurrentCulture = new CultureInfo("hi-IN");
        InitializeComponent();
    }

It works absolutely fine on my dev machine(Win 7). But when deployed to another machine(win xp) it looks like this. All the text in HINDI is shown as squares:
Form when Run in win XP
Please Guide through this guys.
Thanks in advance.

A: Without seeing the screenshots, it's really difficult to say.  But if you are seeing squares it seems like the Hindi fonts are not installed on the machine.  The squares appear because the character set cannot be found.  Your localized application, I think, is working just fine.


text:
Q: jquery find element by name based on input value and assign its id to another element I have about 9 unordered lists which resemble a color group (red, blue, green etc.). Each color group holds an x amount of list items (light blue, dark blue etc.). When a user clicks a certain list item, it will assign the list item's id (which contains a certain background color) to the previewbox and displays the chosen background color. It also passes the text string of the clicked list item to the input field .numbercheck. I need this text string for further processing.
Example of the HTML markup:
<input type="text" class="numbercheck">

RAL 1000

RAL 1001

RAL 2000

RAL 2001

What I described above works, the text string is passed to the input field and the correct color is displayed in the preview box. But I also want the user to be able to type in a certain number (i.e. 2000), then look for the list item with the same name (this would be
RAL 2000
). If the
 name matches the input value, then the list item's id should be passed to the previewbox like this

. If the name doesn't match the input value, then the id should stay id="nocolor".
Note that I already have a working function which extracts the numbers from the input value, so when "ral 1000" or "abc 1000" etc. is entered, it will extract 1000 from the string.
I've been searching the internet for hours, and at this point I have no clue what kind of code to use to accomplish this. I already tried stuff like:
var colorname = $('.colorpanel li').attr('id');
var inputval = $('input.numbercheck').val();
if (colorname == inputval){
    $('.previewbox').attr('id',colorname);
}

Or:
var inputval = $('input.numbercheck').val();
var listitem = $('.colorpanel li[name='inputval']').attr('id');

The last example doesn't work for me, it gives me an error which says ")" is missing at the line where var listitem is located.
Any help would be appreciated.

A: Since inputval is a variable you need to create selector text properly.
var inputval = $('input.numbercheck').val();
var listitem = $('.colorpanel li[name='+ inputval + ']').attr('id');

A: Try replacing
$('.colorpanel li[name='inputval']').attr('id');
with
$('.colorpanel li[name='+ inputval+ ']').attr('id');


text:
Q: PHP session variables not persisting on new page after form submission I have a quiz site which randomly shuffles and puts together multiple choice questions.  The correct answers (as well as some other data) are stored in session variables, and the students' answers are sent via POST.  On the page that the quiz form submission links to, the correct answers in SESSION are compared to the POST data, and the results of the quiz are displayed.  The site used to work just fine, so I have no idea what happened to make it suddenly stop working.
I have checked to see that the session_id is the same on both pages and it is.  I have made sure that start_session() is placed appropriately above all the HTML (and have even confirmed it by calling var_dump($_SESSION) on the first and second page, user login variables are displayed, but nothing else).
Here is the code from "startquiz.php" which assembles the quiz form.  The session variables in question are just after the end of the "DISPLAY A QUESTION LOOP"
<?php
  require_once('appvars.php');
  require_once('startsession.php');
  require_once('generalauthorize.php');
  $page_title = '10 Question Quiz';
  require_once('header.php');
  require_once('navbar.php');
  require_once('connectvars.php');

//=================MySQL HANDLING====================
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  $quizcount = count($_GET);
  $content_array = [];
  foreach($_GET as $quiz_content){
       $quiz_content = $quiz_content . ' = 1';
       array_push($content_array, $quiz_content);
  }
  $where_clause = implode(' OR ', $content_array);
  $query = 'SELECT * FROM questionbank WHERE ' . $where_clause;
  $data = mysqli_query($dbc,  $query);
  $questions_found = mysqli_num_rows($data);
  mysqli_close($dbc);
//==================MySQL HANDLING=======================

if ($questions_found > 9) {
//==========MAKE A LIST OF POSSIBLE QUESTIONS==================
  $possible_questions_array = [];
  while ($row = mysqli_fetch_array($data)) {
     array_push($possible_questions_array, $row);
  }
//==========MAKE A LIST OF POSSIBLE QUESTIONS=================

// ============DECIDE WHICH 10 QUESTIONS TO USE=================
  $quiz_array = [];
  for($i = 0; $i < 10; $i++) {
      $question_bank_count = count($possible_questions_array);
      $random_question_number = rand(0, ($question_bank_count - 1));
      array_push($quiz_array, $possible_questions_array[$random_question_number]);
      array_splice($possible_questions_array, $random_question_number, 1);
  }
// ============DECIDE WHICH 10 QUESTIONS TO USE=================

//============CREATE QUESTION META DATA ARRAY=================
  $quiz_metadata_array = [];
  for ($i = 0; $i < count($quiz_array); $i++) {
      $question_holder = $quiz_array[$i];
      $metadata_only = array_splice($question_holder, 12);
      array_push($quiz_metadata_array, $metadata_only);
  }
//============CREATE QUESTION META DATA ARRAY=================

echo '
';
echo '
Good Luck!
';
echo '
';
echo '<form role="form" method="post" action="processquiz.php">';

//==============CREATE ARRAYS TO HOLD QUIZ DATA==========
$correct_answers = [];
$question_prompts = [];
//==============CREATE ARRAYS TO HOLD QUIZ DATA==========

//===============DISPLAY A QUESTION LOOP==================
  for($i = 0; $i < (count($quiz_array)); $i++){
  array_push($question_prompts, $quiz_array[$i]['question']);

      //==================ISOLATE THE ANSWERS===============
      $answers_array = [];
      array_push($correct_answers, $quiz_array[$i]['answer']);
      array_push($answers_array, $quiz_array[$i]['answer']);
      array_push($answers_array, $quiz_array[$i]['distractor1']);
      array_push($answers_array, $quiz_array[$i]['distractor2']);
      array_push($answers_array, $quiz_array[$i]['distractor3']);
      //==================ISOLATE THE ANSWERS===============

      //=================SCRAMBLE THE ANSWERS==============
      $scrambled_array = [];
      $answer_count = count($answers_array);
      for ($j = 0; $j < $answer_count; $j++) {
          $random_answer_number = rand(0, (count($answers_array) - 1));
          array_push($scrambled_array, $answers_array[$random_answer_number]);
          array_splice($answers_array, $random_answer_number, 1);
      }
      //=================SCRAMBLE THE ANSWERS==============

      //====================CREATE THE HTML=================
      echo '
Question ' . ($i + 1) . '.
';
      echo '
';
      echo '
' . $quiz_array[$i]['question'] . '
';
             //==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
             for($k = 0; $k < (count($scrambled_array)); $k++) {
                  echo '' . (chr((65 + $k))) . ':   ';
                  echo '<input value="' . $scrambled_array[$k] . '" id="' . $i . $k . '" class="answer_choice" type="radio" name="' . $i . '" required>
 ' . $scrambled_array[$k] . '

';
             }
             //==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
      echo '
';
      echo '
';
      //====================CREATE THE HTML=================
  }
//===============DISPLAY A QUESTION LOOP==================

echo '
';
$_SESSION['correct_answers'] = $correct_answers;
$_SESSION['question_prompts'] = $question_prompts;
$_SESSION['current_quiz'] = $_GET;
$_SESSION['current_quiz_meta'] = $quiz_metadata_array;
echo session_id();
  echo '<button type="submit" class="centered-button">Finished!</button>';
echo '
';
echo '</form>';
echo '
';
} else {
    echo '
';
        echo '
Oh no!
';
        echo '
It looks like there aren\'t enough questions in the database to take a quiz for this category yet!
';
        echo '
Talk to your English teachers about adding some more.
';
        echo '
Sorry about that!

';
        echo ' Okay ';
    echo '
';
}
require_once('bootstrapfooter.php');
?>

And here is the code for the quiz processing page.  When I insert a var_dump($_SESSION) on this page I get the login variables that are in session, but nothing else.
<?php
  require_once('appvars.php');
  require_once('startsession.php');
  require_once('generalauthorize.php');
  $page_title = 'Quiz Results';
  require_once('header.php');
  require_once('navbar.php');
  require_once('connectvars.php');

//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====
$current_quiz = [];
foreach ($_SESSION['current_quiz'] as $key => $value) {
    array_push($current_quiz, $value);
}
$_SESSION['current_quiz'] = "";
//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====

//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========
$increment_these_quizzes = [];
for ($i = 0; $i < count($current_quiz); $i++) {
    if ($current_quiz[$i] == "english_1_1" || $current_quiz[$i] == "english_1_2") {
        if (!in_array('english_1_quiz_taken = english_1_quiz_taken + 1', $increment_these_quizzes)) {
            $array_insert = 'english_1_quiz_taken = english_1_quiz_taken + 1';
            array_push($increment_these_quizzes, $array_insert);
        }
    } elseif ($current_quiz[$i] == "english_2ot_1" || $current_quiz[$i] == "english_2ot_2") {
        if (!in_array('english_2ot_quiz_taken = english_2ot_quiz_taken + 1', $increment_these_quizzes)) {
            $array_insert = 'english_2ot_quiz_taken = english_2ot_quiz_taken + 1';
            array_push($increment_these_quizzes, $array_insert);
        }
    } elseif ($current_quiz[$i] == "english_2pt_1" || $current_quiz[$i] == "english_2pt_2") {
        if (!in_array('english_2pt_quiz_taken = english_2pt_quiz_taken + 1', $increment_these_quizzes)) {
            $array_insert = 'english_2pt_quiz_taken = english_2pt_quiz_taken + 1';
            array_push($increment_these_quizzes, $array_insert);
        }
    } elseif ($current_quiz[$i] == "english_2sw_1" || $current_quiz[$i] == "english_2sw_2") {
        if (!in_array('english_2sw_quiz_taken = english_2sw_quiz_taken + 1', $increment_these_quizzes)) {
            $array_insert = 'english_2sw_quiz_taken = english_2sw_quiz_taken + 1';
             array_push($increment_these_quizzes, $array_insert);
         }
    } else {
        $array_insert = $current_quiz[$i] . '_quiz_taken = ' . $current_quiz[$i] . '_quiz_taken + 1';
        array_push($increment_these_quizzes, $array_insert);
    }
}
$increment_this = implode(', ', $increment_these_quizzes);
$increase_quiz_count_query = "UPDATE memberinfo SET $increment_this WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_quiz_count_query);
mysqli_close($dbc);
//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========

//================GET QUESTION COUNT & SCORE QUIZ===========
  $score = 0;
  $question_count = count($_SESSION['correct_answers']);
  for($i = 0; $i < $question_count; $i++) {
      $switch = 0;
      $keywords = [];
      //==============CORRECT ANSWER HANDLING=====================
      if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
          $generic_array = [];
          $correct_array = [];
          $score++;
          foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
               if ($switch == 1) {
                     if ($value == 1) {
                           if ($key == "english_1_1" || $key == "english_1_2") {
                                 if (!in_array('english_1_correct = english_1_correct + 1', $correct_array)) {
                                      $key = 'english_1_correct = english_1_correct + 1';
                                      array_push($correct_array, $key);
                                 }
                                 if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
                                      $gkey = 'english_1_answers = english_1_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
                                 if (!in_array('english_2ot_correct = english_2ot_correct + 1', $correct_array)) {
                                      $key = 'english_2ot_correct = english_2ot_correct + 1';
                                      array_push($correct_array, $key);
                                 }
                                 if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
                                      $gkey = 'english_2ot_answers = english_2ot_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
                                 if (!in_array('english_2pt_correct = english_2pt_correct + 1', $correct_array)) {
                                      $key = 'english_2pt_correct = english_2pt_correct + 1';
                                      array_push($correct_array, $key);
                                 }
                                 if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
                                      $gkey = 'english_2pt_answers = english_2pt_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
                                 if (!in_array('english_2sw_correct = english_2sw_correct + 1', $correct_array)) {
                                      $key = 'english_2sw_correct = english_2sw_correct + 1';
                                      array_push($correct_array, $key);
                                 }
                                 if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
                                      $gkey = 'english_2sw_answers = english_2sw_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } else {
                           $keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
                           $keyword_correct = $key . '_correct = ' . $key . '_correct + 1';
                           array_push($generic_array, $keyword_generic);
                           array_push($correct_array, $keyword_correct);
                           }
                     }
                     $switch = 0;
               } else {
                     $switch = 1;
               }
          }
          $set_what_generic = implode(', ', $generic_array);
          $set_what = implode(', ', $correct_array);
          $update_query = "UPDATE memberinfo SET $set_what WHERE user_id = $_SESSION[user_id]";
          $update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
          $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
          mysqli_query($dbc, $update_query);
          mysqli_query($dbc, $update_generic_query);
          mysqli_close($dbc);
      //==============CORRECT ANSWER HANDLING=====================

      //==============WRONG ANSWER HANDLING=====================
      } else {
          $generic_array = [];
          foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
               if ($switch == 1) {
                     if ($value == 1) {
                           if ($key == "english_1_1" || $key == "english_1_2") {
                                 if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
                                      $gkey = 'english_1_answers = english_1_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
                                 if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
                                      $gkey = 'english_2ot_answers = english_2ot_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
                                 if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
                                      $gkey = 'english_2pt_answers = english_2pt_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
                                 if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
                                      $gkey = 'english_2sw_answers = english_2sw_answers + 1';
                                      array_push($generic_array, $gkey);
                                 }
                           } else {
                           $keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
                           array_push($generic_array, $keyword_generic);
                           }
                     }
                     $switch = 0;
               } else {
                     $switch = 1;
               }
          }
          $set_what_generic = implode(', ', $generic_array);
          $update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
          $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
          mysqli_query($dbc, $update_generic_query);
          mysqli_close($dbc);
      }
      //===============WRONG ANSWER HANDLING=====================
  }
//================GET QUESTION COUNT & SCORE QUIZ===========

//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================
$update_score_query = "UPDATE memberinfo SET score = total_answers * overall_success_rate WHERE user_id = $_SESSION[user_id]";

$increase_totals_query = "UPDATE memberinfo SET total_quizzes_taken = total_quizzes_taken + 1, total_answers = total_answers + $question_count, total_correct = total_correct + $score WHERE user_id = $_SESSION[user_id]";

$adjust_success_query = "UPDATE memberinfo SET overall_success_rate = (total_correct / total_answers) * 100, phys_con_success = (phys_con_correct / phys_con_answers) * 100, abbr_success = (abbr_correct / abbr_answers) * 100, anatomy_success = (anatomy_correct / anatomy_answers) * 100, society_success = (society_correct / society_answers) * 100, career_success = (career_correct / career_answers) * 100, ment_heal_success = (ment_heal_correct / ment_heal_answers) * 100, tools_success = (tools_correct / tools_answers) * 100, other_success = (other_correct / other_answers) * 100, english_1_success = (english_1_correct / english_1_answers) * 100, english_2ot_success = (english_2ot_correct / english_2ot_answers) * 100, english_2pt_success = (english_2pt_correct / english_2pt_answers) * 100, english_2sw_success = (english_2sw_correct / english_2sw_answers) * 100 WHERE user_id = $_SESSION[user_id]";

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_totals_query);
mysqli_query($dbc, $adjust_success_query);
mysqli_query($dbc, $update_score_query);
      //===============UPDATE THE RANKING CHARTS====================

          //==========FIRS FLUSH ALL RANKINGS TO 0===================
          $flush_rankings = "UPDATE memberinfo SET rank = 0";
          mysqli_query($dbc, $flush_rankings);
          //==========FIRS FLUSH ALL RANKINGS TO 0===================

          //==========NEXT GET ELIGIBLE MEMBERS====================
          $get_eligible_scores = "SELECT user_id FROM memberinfo WHERE total_quizzes_taken > 0 AND overall_success_rate >= 40 ORDER BY score DESC, overall_success_rate DESC, total_correct DESC";
          $eligible_data = mysqli_query($dbc, $get_eligible_scores);
          //==========NEXT GET ELIGIBLE MEMBERS====================

          //==========LOOP THROUGH AND UPDATE THE DATABASE=================
          $rank_number = 1;
          while ($member_data = mysqli_fetch_array($eligible_data)) {
                $rank_update_query = "UPDATE memberinfo SET rank = $rank_number WHERE user_id = $member_data[user_id]";
                mysqli_query($dbc, $rank_update_query);
                $rank_number++;
           }
          //==========LOOP THROUGH AND UPDATE THE DATABASE=================

      //===============UPDATE THE RANKING CHARTS====================
mysqli_close($dbc);
//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================

//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========
echo '
';
echo '
';
  if ($score == 10) {
      echo '
Perfect Score!!!
';
  } else if ($score > 7 && $score < 10) {
     echo '
Well Done!
';
  } else if ($score > 5 && $score < 8) {
      echo '
Good!
';
  } else if ($score > 3 && $score < 6) {
      echo '
Try a little harder!
';
  } else if ($score > 1 && $score < 4) {
      echo '
Oooh.  Not good.
';
  } else if ($score <= 1) {
      echo '
Seriously?  That bad?
';
  } else {
      echo '
How\'d you even get this score??
';
  }
  echo '
You scored ' . $score . '/' . $question_count . '
';
//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========

//================COMPARE AND DISPLAY ANSWERS=================
?>

Correct Answer

Your Answer

<?php
    for ($i = 0; $i < $question_count; $i++) {
        echo '
';
        echo '
Question ' . ($i + 1) . ': ' . $_SESSION['question_prompts'][$i] . '
';
        echo '
';
        echo '
';
        echo '
' . $_SESSION['correct_answers'][$i] . '
';
        if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
            echo '
' . $_POST[$i] . '
';
        } else {
            echo '
' . $_POST[$i] . '
';
        }
        echo '
';
        echo '
';
    }
    echo '
';
//================COMPARE AND DISPLAY ANSWERS=================

//===========CREATE END OF QUIZ LINKS=====================
    $replay_url = 'startquiz.php?';
    $args_array = [];
    for ($i = 0; $i < count($current_quiz); $i++) {
        $arg = 'quiz' . $i . '=' . $current_quiz[$i];
        array_push($args_array, $arg);
    }
    $link_args = "";
    $link_args = implode('&', $args_array);
    $replay_url .= $link_args;
    //=============DISPLAY THE BUTTONS=====================
    echo '
';
    echo '
';
    echo '
';
    echo 'Take This Quiz Again';
    echo '
';
    echo '
';
    echo 'Back to Quiz Select
';
    echo '
';
    echo '

';
    echo '
';
    //=============DISPLAY THE BUTTONS=====================
//===========CREATE END OF QUIZ LINKS=====================
require_once('bootstrapfooter.php');
?>

I apologize for posting the entire code for each page, but I'm not a professional programmer and I'm not sure what is relevant and what isn't.

A: The problem has been resolved.  It turns out the issue was with the php.ini file on the hosting site.  They recently made some changes that I was unaware of and the temporary storage location for session files/variables became undefined.  Once I edited that information in the .ini file, everything worked just fine.


text:
Q: Spring Boot Security error: Encoded password does not look like BCrypt, converting from in memory authentication to database authentication I am getting the error : Encoded password does not look like BCrypt
Here is my Configuration class:
@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
            .csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/h2-console/**", "/createUser")
            .permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .permitAll()
            .and()
            .logout()
            .permitAll();

    http.csrf()
            .ignoringAntMatchers("/h2-console/**");
    http.headers()
            .frameOptions()
            .sameOrigin();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    String userbyUsernameQuery = "select username, password, '1' as enabled from auth_user where username=?;";
    String rolebyUsernameQuery = "SELECT auth_user.username, auth_role.role_name as authority from auth_user\n" +
            "INNER JOIN auth_user_role ON auth_user.auth_user_id = auth_user_role.auth_user_id\n" +
            "INNER JOIN auth_role ON auth_role.auth_role_id = auth_user_role.auth_role_id\n" +
            "WHERE auth_user.username =?";

    auth.jdbcAuthentication()
            .dataSource(dataSource)
            .passwordEncoder(passwordEncoder())
            .usersByUsernameQuery(userbyUsernameQuery)
    .authoritiesByUsernameQuery(rolebyUsernameQuery);

}
@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}

I can post my database if necessary although I don't think it has anything to do with the database.
INSERT INTO auth_user (auth_user_id, first_name, last_name, username, password, enabled)
VALUES (1, 'John', 'Test', 'username', 'password', 'yes');

INSERT INTO auth_role (auth_role_id, role_name, role_desc)
VALUES (1, 'ADMIN', 'Admin role'),
(2, 'USER', 'User role');

INSERT INTO auth_user_role (auth_user_id, auth_role_id)
VALUES (1, 1);

I am submitting this to the database and I am entering username and password as the username and password on my spring boot application however it gives me that error and I cannot figure out what is wrong as the "fixes" I have seen have literally been what I have here.
Need some pointers as to where to go from here or what is specifically wrong.
Thank you.

A: I have found the answer to my question which was adding this
    @Bean
public static NoOpPasswordEncoder passwordEncoder() {
    return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

Since my password is stored as a default string I need to use this.
I changed my AuthenticationManagerBuilder configuration method to include this.
       auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery(userbyUsernameQuery)
    .authoritiesByUsernameQuery(rolebyUsernameQuery)
    .passwordEncoder(passwordEncoder());

A: You should use the same passwordEncoder to encode your password into the DB, here is an example.
    PasswordEncoder passwordEncoder =
        PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("user")
                .password(passwordEncoder.encode("password"))
                .roles("USER")
                .and()
                .passwordEncoder(passwordEncoder)
                .withUser("manager")
                .password("password")
                .credentialsExpired(true)
                .accountExpired(true)
                .accountLocked(true)
                .authorities("WRITE_PRIVILEGES", "READ_PRIVILEGES")
                .roles("MANAGER");
    }


text:
Q: phpmailer & ajax : file attachment with the mail I have a working contact form so a user can email me while not having to refresh the page, using ajax.
I'd like my user to have the option to attach a file with his email, but I'm kind of lost as how to process the data with Ajax.
Here is the contact form :
<form id="contact-form" method="post" action="/handler.php?ajax=contact">

    <input type="email" name="contact-email" id="contact-email" />

    <select name="contact-category" id="contact-category">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

    <input type="text" name="contact-subject" id="contact-subject" />

    <textarea name="contact-message"></textarea>

    <input type="file" name="contact-attachment" id="contact-attachment" />

    <button class="btn-classic btn-orange"> send</button>

</form>

The ajax function :
$(function(contactSubmit) {

    var contactForm = $('#tab-contact #contact-form');
    var contactCallback = $('#tab-contact #contact-callback');

    $(contactForm).submit(function(event) {

        event.preventDefault();
        var contactData = $(contactForm).serialize();

        $.ajax({
            type: 'POST',
            url: $(contactForm).attr('action'),
            data: contactData,
        }).done(function(response) {
            $("#contact-callback").addClass("success");
        }).fail(function(data) {
            $("#contact-callback").addClass("fail");
        });

    });

});

and the 2 php functions to verify the data and send the mail :
<?php

public static function contact() {

    $mail_from_email = filter_var(trim($_POST['contact-email']), FILTER_SANITIZE_EMAIL);
    $mail_from_name = 'User1';
    $mail_to_email = 'webmaster@site.com';
    $mail_to_name = 'Webmaster';
    $mail_subject = '['.$_POST['contact-category'].'] '.trim($_POST['contact-subject']);
    $mail_body = trim($_POST['contact-message']);
    $mail_attachment = $_FILES['contact-attachment'];

    $sendMail = action::sendMail($mail_from_email, $mail_from_name, $mail_to_email, $mail_to_name, $mail_subject, $mail_body, $mail_attachment);

}

public static function sendMail($mail_from_email, $mail_from_name, $mail_to_email, $mail_to_name, $mail_subject, $mail_body, $mail_attachment) {

    require $_SERVER['DOCUMENT_ROOT'].'/phpmailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;

    //$mail->SMTPDebug = 3;                                 // Enable verbose debug output

    $mail->isSMTP();                                        // Set mailer to use SMTP
    $mail->Host = config::get('mail_smtp_host');            // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                                 // Enable SMTP authentication
    $mail->Username = config::get('mail_smtp_username');    // SMTP username
    $mail->Password = config::get('mail_smtp_password');    // SMTP password
    $mail->SMTPSecure = config::get('mail_smtp_security');  // Enable TLS encryption, `ssl` also accepted
    $mail->Port = config::get('mail_smtp_port');            // TCP port to connect to

    $mail->setFrom($mail_to_email, $mail_from_name);
    $mail->addAddress($mail_to_email, $mail_to_name);       // Add a recipient
    $mail->addAddress('');                                  // Name is optional
    $mail->addReplyTo($mail_from_email, $mail_from_name);
    $mail->addCC('');
    $mail->addBCC('');

    $mail->addAttachment($mail_attachment);                 // Add attachments
    $mail->addAttachment('');                               // Optional name
    $mail->isHTML(true);                                    // Set email format to HTML

    $mail->Subject = $mail_subject;
    $mail->Body    = $mail_body;
    $mail->AltBody = '';

    if(!$mail->send()) {
        return $mail->ErrorInfo;
    } else {
        return true;
    }

}

?>

However I've been stuck at step 1 : My php function is unable to retrieve the data from the file input, it seems like ajax isn't sending the informations regarding this input field.
Php returns Undefined index: contact-attachment.
Can anyone guide/help me through this ? What is wrong with my current code ?

A: You form tag doesn't contain all attributes.
Replace
<form id="contact-form" method="post" action="/handler.php?ajax=contact">

with
<form id="contact-form" method="post" action="/handler.php?ajax=contact" accept-charset="utf-8" enctype="multipart/form-data">

$(document).ready(function() {
$('#contact-form').submit( function( e ) {
var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
    });
});

<form id="contact-form" method="post" action="/handler.php?ajax=contact" accept-charset="utf-8" enctype="multipart/form-data">

    <input type="email" name="contact-email" id="contact-email" />

    <select name="contact-category" id="contact-category">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

    <input type="text" name="contact-subject" id="contact-subject" />

    <textarea name="contact-message"></textarea>

    <input type="file" name="contact-attachment" id="contact-attachment" />

    <button class="btn-classic btn-orange"> send</button>

</form>


text:
Q: Android: animate searchview I'm trying to implement an animated searchview (with a simple extend/collapse animation) but all the answers in this forum are not working.
<item
    android:id="@+id/action_search"
    android:orderInCategory="100"
    android:title="@string/action_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:icon="@drawable/ic_search_white_48px"
    app:showAsAction="always"/>

what i've done
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    //Get the ID for the search bar LinearLayout
    int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
    //Get the search bar Linearlayout
    LinearLayout searchBar = (LinearLayout)
            searchView.findViewById(searchBarId);
    //Give the Linearlayout a transition animation.
    searchBar.setLayoutTransition(new LayoutTransition());
    return true;
}

all the error:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.daveslab.wideview, PID: 2459
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setLayoutTransition(android.animation.LayoutTransition)' on a null object reference
                  at com.daveslab.wideview.MainActivity.onCreateOptionsMenu(MainActivity.java:69)
                  at android.app.Activity.onCreatePanelMenu(Activity.java:2846)
                  at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:360)
                  at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:88)
                  at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:331)
                  at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:88)
                  at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
                  at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

errors in values.xml(all the icons are in the project with the correct name):
Error:(1605, 21) No resource found that matches the given name: attr 'searchBackIcon'.

Error:(1602, 21) No resource found that matches the given name: attr 'searchBackground'.
Error:(1604, 21) No resource found that matches the given name: attr 'searchCloseIcon'.
Error:(1606, 21) No resource found that matches the given name: attr 'searchSuggestionBackground'.
Error:(1603, 21) No resource found that matches the given name: attr 'searchVoiceIcon'.
Error:(1605, 21) No resource found that matches the given name: attr 'searchBackIcon'.
Error:(1602, 21) No resource found that matches the given name: attr 'searchBackground'.
Error:(1604, 21) No resource found that matches the given name: attr 'searchCloseIcon'.
Error:(1606, 21) No resource found that matches the given name: attr 'searchSuggestionBackground'.
Error:(1603, 21) No resource found that matches the given name: attr 'searchVoiceIcon'.
Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt.

A: There is an easier approach (in fact, just two more lines of code) and it's bug-free. What you have to do is populating your SearchView in the onCreateOptionsMenu() method like you would have done before, but avoiding the lines of code where you set the transition, as they are not needed anymore.
Next, override onOptionsItemSelected() like this:
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_search:
            TransitionManager.beginDelayedTransition((ViewGroup) getActivity().findViewById(R.id.toolbar));
            MenuItemCompat.expandActionView(item);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

This code prepares a transition and listens for changes in the toolbar layout. When the SearchView appears, the animation starts. It uses the same API as KitKat but it is available starting with ICS. In your build.gradle:
compile 'com.android.support:transition:24.2.1'

You can also customize the transition if you don't like the default one.

A: I am bit late to answer but above answers not worked for me.
     SearchView searchView;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.application_menu, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
        searchBar.setLayoutTransition(new LayoutTransition());
 return super.onCreateOptionsMenu(menu);
        }

And my application_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/app_bar_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="Search"
        app:showAsAction="ifRoom"
         />

</menu>

A: This might be helpful for you.But accept the answer if it solves your problem.So,It will help others too.
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
//Get the ID for the search bar LinearLayout
int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
//Get the search bar Linearlayout
 LinearLayout searchBar = (LinearLayout)
 searchView.findViewById(searchBarId);
 //Give the Linearlayout a transition animation.
 searchBar.setLayoutTransition(new LayoutTransition());

Styles.xml
  <style name="MaterialSearchViewStyle">
    <item name="searchBackground">@color/white_ish</item>
    <item name="searchVoiceIcon">@drawable/ic_action_voice_search</item>
    <item name="searchCloseIcon">@drawable/ic_action_navigation_close</item>
    <item name="searchBackIcon">@drawable/ic_action_navigation_arrow_back</item>
    <item name="searchSuggestionBackground">@color/search_layover_bg</item>
    <item name="android:textColor">@color/black</item>
    <item name="android:textColorHint">@color/gray_50</item>
    <item name="android:hint">@string/search_hint</item>
    <item name="android:inputType">textCapWords</item>
</style>

Use that style in your xml
<item
android:id="@+id/action_search"
android:orderInCategory="100"
android:title="@string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_search_white_48px"
app:showAsAction="always"
 style="@style/MaterialSearchViewStyle"/>


text:
Q: getting only the exception ,not the entire stack trace I want to get only the exception message,not the entire stack trace.A toy example would be as follows:
def div():
    try:
        print(0/0)
    except:
        raise Exception('Divide by zero,please check the input!!!')

def func1():
    try:
        div()
    except:
        raise Exception('Error in func11 try')

func1()

Expected output
Exception: Divide by zero, please check the input!!!
Exception: Error in func11 try

Any help is highly appreciated.

A: Below solution worked for me.
import traceback

def div():
    try:
        print(0/0)
    except:
        raise Exception('Divide by zero,please check the input!!!')

def func2():
    try:
        div()
    except:
        raise Exception('Error in func 2!!!')

def func1():
    exceptions=[]
    try:
        func2()
    except Exception as e:
        msg=traceback.format_exc()
        msg_list= msg.split('\n')
        [exceptions.append(line) for line in msg_list if line.startswith('Exception:')]
        return exceptions

func1()

output
['Exception: Divide by zero,please check the input!!!',
 'Exception: Error in func 2!!!']

A: If you don't want to get the entire stack trace, you can try this:
def div():
    try:
        print(0/0)
    except Exception as e:
        print(e)

A: The answer of @Kairav Parekh works in your condition and it does not prints the entire stack trace, it only prints the error, which is user-friendly in most cases,
you only need to modify his code to match your requirements and you can put a break statement in except such as below,
def div():
    try:
        print(0/a)
    except Exception as e:
        print(e)
        break #break here
div()


text:
Q: How to translate MIPS into C and how to reduce MIPS instructions? Supposing that f, g, h, i are stored in $s0~$s4  respectively and the base addresses of arrays A and B are in  $S6 and $S7.
sll  $t0, $s0, 2
add $t0, $s6, $t0
sll $tl, $sl, 2
add $tl, $s7, $tl
lw $s0, 0($t0)
addi $t2 , $t0, 4
lw $t0, 0($t2)
add $t0, $t0, $s0
SW $t0, 0($tl)

I'm not familiar with MIPS so I Wonder how to translate MIPS into C and how to minimize these MIPS instructions?

A:
how to translate MIPS into C

You recognize the patterns, here for array indexing / array element access.
On a byte addressable machine (all modern hardware), a 4-byte integer occupies 4 bytes in memory, and each of those bytes has a unique memory address.  Because of the way the hardware works, we only use one of those 4 addresses to refer to the whole 4-byte integer, namely we use the lowest address among the 4.  The hardware can load a 4-byte integer from memory given that one address (the lowest).
Since each 4-byte integer in memory occupies 4 addresses, in an array of 4-byte integers, the memory address of the first element and the memory address of the second element are 4 addresses apart even though are sequential index positions (i.e. they are only 1 index position apart).
The formula for indexing a 4-byte integer array, then is to convert the index into a byte offset, then add the byte offset to the base address of the array.  The first part of that: converting an index to a byte offset, is sometimes referred to as "scaling".  Scaling is conceptually done by multiplication, so in A[i], i needs to be scaled by the size of the array elements of A.  If 4-byte integers that means scaling (multiplying) the index  by 4.  A quick way of doing that is shifting by 2 bit positions, which has the same effect as multiplying by 4.
The C language automatically scales when doing array references, whereas assembly language requires explicit scaling.  C can do this because it knows the type of the array, whereas assembly language does not.
In C we can do expressions like A[i].  The C language allows us to break that down somewhat into *(A+i), which separates the pointer arithmetic addition A+i from the dereferencing of that sum, dereferencing with the unary indirection operator, *.  As previously mentioned, C automatically scales, so A+i becomes the equivalent of A+i*4, in which we can substitute shifting for multiplication: A+(i<<2).
Next, we need to know if the dereference is for read or for write.  When A[i] is accessed for its value, we will see it on what we call the "right hand side" of an assignment operator, as in ... = A[i].  When A[i] is access to update/store a value, we will see it on what we call the left hand side of an assignment operator, as in A[i] = ....
So, the sequence for doing A[i] for read (right hand side) in C is the following in assembly:
sll $temp1, $i, 2
addu $temp2, $A, $temp1
lw $temp3, 0($temp1)

Where $tempN is some register (usually a designated temporary) chosen to hold an intermediate value.  Since multiple instructions are needed to accomplish anything, sequences of instructions are interconnected with registers that hold the intermediate states.  And also, in assembly we name registers, not variables, so in my above $i and $A should be a registers names representing those variables rather than variable names directly used.
The pattern for write/store array access is similar but ends with a sw instruction instead, to store some value into memory at the index position.
These instruction sequence are interconnected by the use of these registers, and the sequences can be interrupted or interspersed with other instructions — what we have to follow then is the above pattern by paying attention to to the register usages that interconnect them rather than the specific sequences.
In your sample code:
sll  $t0, $s0, 2     # sourcing an index in $s0, scaling it into temp $t0
add $t0, $s6, $t0    # adding a base array in $s6, putting back into $t0
sll $tl, $sl, 2
add $tl, $s7, $tl
lw $s0, 0($t0)       # accessing the value of $s6[$s0*4], aka A[f]
addi $t2 , $t0, 4
lw $t0, 0($t2)
add $t0, $t0, $s0
SW $t0, 0($tl)

We can see the pattern for a read access to an index in $s0, and an array in $s6, these, we are told, map to f and A, so those three instructions comprise A[f] to read a value from A at index f.
The rest are done similarly.  Your job is to use this knowledge to find the other array indexing patterns in the above sequence.  Find out how the results of the array indexing operations are used and you'll have the complete C code.

NOTE that the sample you've been given incorrectly  uses add and addi when pointer arithmetic should use addu and addiu — we don't want signed integer overflow checking on pointer arithmetic, as pointers are unsigned.
One of the add instructions is not for pointer arithmetic, but should probably still have used addu if this is intended to be replicated in C, because the C language does not have a built in operator to trap on overflow.


text:
Q: Securing a local-only Compojure/Ring Webapp? I want to create a Ring/Compojure webapp that would enable a clojure repl.  All of this is meant to be running on a local machine and the webapp is just a convenient GUI for the local user.  Since it is a enabling a repl, I want it to be secure.  But, I also want it to be convenient.
Here's my idea:

*

*a user would run "lein ring server" to start the app.

*this opens the web-browser and causes it to fetch "/" from the app.

*any session request gets a unique session cookie, but the first session cookie is saved specially on the server

*any requests later check to see the current session cookie == first session cookie

Do you believe this is secure?  I'm concerned with requests to your machine from other hosts and this seems to do the trick.  I'm worried about other users logged into the local machine--could they see that session cookie somehow?  Would I have to enable an https server to really fix this?
I would certainly love to hear if this is a solved problem...
Thanks!


text:
Q: DOMPDF Multiple Documents Generated In One PDF I am using DOMPDF to generate invoices.
1 invoice at time is perfect.
But i want to print (from a while) all invoices between date
all is perfect
But Dompdf print only the last invoice.
The dompdf code
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";

$sql=mysql_query("SELECT * FROM invoices  WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql))
{
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];

// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2))
{
$name = $rows2[name];
//ETC...

// Now we generate the html invoice
$html =
    ''.
//the invoice html
    '';

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
}
}
$dompdf->stream("Invoice.pdf");

I want to get all invoices ( sometimes 5, sometimes 50 ) in 1 pdf file.
How to ?
I close my whiles at end of files, but don't help.
Hope you can help.

A: The way your code is written right now you render your first document then don't do anything with it. So the second pass through the while loop will overwrite the first pass. There are a few ways to achieve what you want, but the easiest would be to compile all your HTML into a single document then render that.
Using your code as a start:
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$invoices = array();

$sql=mysql_query("SELECT * FROM invoices  WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql)) {
  $num=$rows[number];
  $datum=$rows[data];
  $pay=$rows[pay];

  // Need to get the user info from other table
  $Query2 = "SELECT * from user WHERE user='$user'";
  while ($rows2=mysql_fetch_array($Result2)) {
    $name = $rows2[name];
    //ETC...

    // Force page break between invoices
    if ( strlen( $html ) > 0 ) { $html .= '

'; }

    // Now we generate the html invoice
    $invoices[] = '';
  }
}

$html = '' . implode( '

' , $invoices ) . '';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("Invoice.pdf");


text:
Q: android preferred button size what is the the preferred android button size from usability perspective.
I suppose it should be in dp,
I have tried several different size from 50dp to 30dp, each time it looks a little odd, what's the general size used in different android application

A: Put this in your layout for buttons
style="@android:style/ButtonBar"

This are the standard buttons per say.
Hope it helps

A: seems like there is no standard way or , perhaps none documented , I ended up with 40dp


text:
Q: npm failing with error code ETARGET when trying to install dependencies Edit
To anyone coming here from the future, run npm get registry and make sure it's pointing to https://registry.npmjs.com.
Mine was pointing to a Nexus registry that temporarily didn't have the package I needed.

I have a basic project that a Jenkins job clones the repository of and runs,
npm install && npm run build

Eventually, it fails with the below error:
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @typescript-eslint/experimental-utils@4.14.1.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of '@typescript-eslint/eslint-plugin'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:

The version that is being requested exists.
I've tried everything I could think of. I tried,

*

*omitting my yarn.lock file

*switching to package-lock.json to see if that was the issue

*omitting the package-lock.json

*running rm -rf node_modules && rm -rf yarn.lock && npm cache clean --force && npm install && npm run build

*adding @typescript-eslint/experimental-utils@4.14.1 to my dependencies in package.json
What's weird is that locally running yarn && yarn start or npm install && npm run start works just fine.
I honestly have no idea what I'm missing here, I've been pulling my hair out for hours.
I've looked at countless solutions online, but none worked for me.
$ npm -v
v6.13.4

$ node -v
v12.16.1


text:
Q: DNS name for S3 bucket folder Is it possible to assign a unique domain name for an S3 bucket folder - not the entire bucket but just a folder in the bucket?
For example if I have a bucket s3.amazonaws.com/my.domain.tv and a folder Vasilis/ within that bucket I want to point a domain name vasilis.domain.tv at s3.amazonaws.com/my.domain.tv/Vasilis.
I have found how I can do it for an entire bucket but I couldn't find anything for folders.
Also, can I do it with cloudfront, i.e. create a distribution for a specific folder in a bucket?

A: You can create a distribution for a specific folder, was just announced in mid-december:

Amazon CloudFront Now Allows Directory Path as Origin Name- Date:
  December 16, 2014
Details: When you specify the origin for a CloudFront distribution -
  the Amazon S3 bucket or the custom origin where you store the original
  version of content - you can now specify a directory path in addition
  to a domain name. This makes it easier for you to deliver different
  types of content via CloudFront without changing your origin
  infrastructure. Learn more by reading our announcement.

https://aws.amazon.com/about-aws/whats-new/2014/12/16/amazon-cloudfront-now-allows-directory-path-as-origin-name/


text:
Q: Leptonica on Windows + Visual Studio I have followed the following steps for installing Leptonica on Windows with Visual Studio
3. Building on Windows

   (a) Building with Visual Studio

       1. Download the latest SW
              (Software Network https://software-network.org/)
          client from https://software-network.org/client/
       2. Unpack it, add to PATH.
       3. Run once to perform cmake integration:
          sw setup
       4. Run:
          git clone [https://github.com/danbloomberg/leptonica](https://github.com/danbloomberg/leptonica)
          cd leptonica
          mkdir build
          cd build
          cmake ..
       5. Build a solution (leptonica.sin) in your Visual Studio version.

I did everything except for step 5.
My build directory now looks as follows:
ALL_BUILD.vcxproj          LeptonicaConfig.cmake
ALL_BUILD.vcxproj.filters  LeptonicaConfig-version.cmake
cmake_install.cmake        LeptonicaTargets.cmake
cmake_uninstall.cmake      src/
CMakeCache.txt             sw_build_dependencies.vcxproj
CMakeFiles/                sw_build_dependencies.vcxproj.filters
config_auto.h.in           uninstall.vcxproj
INSTALL.vcxproj            uninstall.vcxproj.filters
INSTALL.vcxproj.filters    x64/
lept.pc                    ZERO_CHECK.vcxproj
leptonica.sln              ZERO_CHECK.vcxproj.filters

I cannot seem to find leptonica.sin and how to integrate with visual studio ? I need the steps that are left. I am new to visual studio please mind my question.
I have Visual Studio 2019

A: You probably already figured this out (I'd hope) but if not... Step #5 as you listed has a typo:

*Build a solution (leptonica.sin) in your Visual Studio version.

It's supposed to be leptonica.sLn, as in a Visual Studio Solution file.
In your build directory listing you have leptonic.sln. If you double-click that it should open in Visual Studio (assuming a default/correct install).

A: With Visual Studio 2019 at least you don't actually have to generate a solution file with CMake manually like this as Visual Studio now supports opening folders that contain CMakeLists.txt files as though they are solutions.
You can just do the following to build Leptonica on Windows:

*

*Download sw-master-windows-client.zip  from https://software-network.org/client/.

*Unzip sw.exe to some directory sw_dir.

*Add sw_dir to your path environment variable. Log out and log in to make sure the path is updated.

*Enter power shell etc. and run "sw setup" from a command line.

*Git clone Leptonica to some directory from https://github.com/danbloomberg/leptonica

*Start up Visual Studio.

*Choose "Open local folder" from the intitial dialog VS presents you with. Select the Leptonica folder.

At this point Visual Studio will begin running CMake on the folder and it should succeed assuming it can find sw.exe. This step takes a while. After it completes you can build all from the build toplevel menu.


text:
Q: C# Asp.net MVC on the complier it says error code "CS1061" The tutorial I'm (was) following, they have an option to select "using Microsoft entity framework" but for me, it does not show that potential fix, any advice would be much appreciated.
 services.AddMvc();
            services.AddDbContext<NewContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }

Error message screen shot

A: Your project needs to have the entity framework libraries referenced.
Try adding the "Microsoft.EntityFrameworkCore.SqlServer" nuget package to your project.
Then add the using directive.


text:
Q: how switch in javascript works when it satisfy all cases condition switch (true) {
                case (angle<20):
                    console.log("case1")
                    break;

                case (angle<70):
                    console.log("case2")
                    break;

                case (angle<110):
                    console.log("case3")
                    break;

                case (angle<160):
                    console.log("case4")
                    break;
                ... and so on until 360

}

the given code above is working well.
i just curious how it able to map out that angle 15 is fall on case 1.
while 15 satisfying all case condition
unable to find any clue in google.. so im asking here
another topic been raise before. but i dont really get it still
some clue here

A: A switch statement executes the block for the first case that it matches (as per the order the case statements are listed top to bottom).
If that case contains a break, then no other case statements are matched as execution will resume after the switch block.

A: Because of break; the switch case will break after the angle variable encounters the first case which satisfies the condition.

A: switch case follow top to bottom approach.
So Try reverse condition
switch (true) {
   case (angle>300):
       console.log("case1")
       break;

   case (angle>250):
       console.log("case2")
       break;

   case (angle>200):
       console.log("case3")
       break;

   ... and so on
}

A: The magic is on the use of the optional break statement, remember this:

The optional break statement associated with each case label ensures
  that the program breaks out of switch once the matched statement is
  executed and continues execution at the statement following switch. If
  break is omitted, the program continues execution at the next
  statement in the switch statement.

What happens if you delete the break statements on each case clause?
I think that this quote solve your doubt.


text:
Q: Angular 11 : Template not updating on http request subscription even with changedetector() I'm stuck into this problem
my template is not beeing updated with the new values from the subscription even it's updated when I console Log it
In service :
getExam(teacherUsername:string,courseCode:string,examID:number){
    return this.http.post<{error:boolean,message:string,exam?:Quiz}>('https://the url goes here',
    {
      teacherUsername:teacherUsername,
      courseCode:courseCode,
      examID:examID
    })}

in the component :
    quiz!:Quiz;
    loadQuiz(){
    this.courseService.getExam("getTeachernameFromLocalStorage","getCourseIDFromLocalStorage",this.retrieveTheQuiz()).subscribe(
           res =>{
             if(res.error == false){
              this.quiz = res.exam!;
               this.changeDetectorRef.detectChanges();
                console.log(this.quiz);
              }}
ngOnInit(){
this.loadQuiz();
}

in template :
{{quiz.quizSetup?.quizTitle}}

I'm calling also detectChanges() and nothing happens the templatae is not updated !

A: @Component({
    selector: 'app-selector',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `...`
})

set changeDetection onPush for your componente, and then use inside the subscription how you already made.
or, you can use a boolean and ngIf inside your template:
loadData = false;

ngOnInit(): void {
  this.loadData = true;
  this.courseService.getExam().substribe(res => {
    // do stuff
    this.loadData = false; // set if to false when data is loaded
  });
}

template:
<div *ngIf="!loadData">
  your content
</div>

this will force the page to be rendered again. I prefer first option.


text:
Q: Permanent redirect 301 with /?lang=de I need to redirect a multilingual website to a new domain and will use an .htaccess file for it. I redirect all old pages to their respective new ones on the new domain.
OLD URLS
Englisch
    Main page: www.olddomain.com
    Sub pages: www.olddomain.com/bike-rental

Spanish
    Main: www.olddomain.com/?lang=es
    Sub pages: www.olddomain.com/bike-rental?lang=es

German
    Main: www.olddomain.com/?lang=de
    Sub pages: www.olddomain.com/bike-rental?lang=de

NEW URL's
Englisch
    Main page: www.new-domain.com
    Sub pages: www.new-domain.com/bike-rental

Spanish
    Main: www.new-domain.com/es
    Sub pages: www.new-domain.com/es/alquiler-de-bicis
German
    Main: www.new-domain.com/de
    Sub pages: www.new-domain.com/de/fahrradvermietung

I realized it does not work with a normal redirect in the .htaacces file
    such as:
    Redirect 301 /?lang=de http://www.new-domain.com/de/
    Redirect 301 /bike-rental?lang=de http://www.new-domain.com/de/fahrradvermietung

Any ideas how to redirect those old URL's to the new ones?
Thanks

A: Since php 5.3.0 This variable was added:
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale; // returns "en_US"
$localeshort = substr($locale, -2);
echo $localeshort; // returns "US"

If you use this, you can make a redirect with something like:
Header("Location: index.php?lang=".$localeshort);

A: OR use: this tool to create a redirect, repeat this until you have all languages. IMAGE

A: See my previous message:
Since php this function was added:
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale; // returns "en_US"
$localeshort = substr($locale, -2);
echo $localeshort; // returns "US"

Use in your .htacces
RewriteEngine on

RewriteRule ^(.*)$ /index.php [R=permanent,L]

Now it will be redirected to the page on the begin.
This is the only solution i know.

A: You can do something like this in htaccess:
RewriteCond %{REQUEST_URI} !^/bike-rental$
RewriteCond %{QUERY_STRING} ^lang=(.*)$
RewriteRule ^(.*)/ /bike-rental?lang=%1 [L,R=301]

(Tested and added condition to avoid circular rewrite)


text:
Q: How to set the state of a past TaskInstance to success and continue the pipeline inside a airflow DAG? I'm trying to make a DAG with params that can be triggered with a dag_id/task_id. The goal of this DAG is to set the state of the last executed task to "success" and to continue the pipeline from this point.
exemple of pipeline:

In my dag I want to be able to set "run_that" to success and automatically run "run_them" as a result of the new state change.
Here is what I did from now:
import airflow
from airflow.models import DagRun, TaskInstance, DagBag

from airflow.operators.dagrun_operator import TriggerDagRunOperator
from airflow.utils.trigger_rule import TriggerRule
from airflow.utils.state import State

from airflow.operators.python_operator import PythonOperator

import pendulum

from wrapper import ScriptLauncher, handleErrorSlack, handleErrorMail

from datetime import timedelta, datetime

default_args = {
  'owner': 'tozzi',
  'depends_on_past': False,
  'start_date': pendulum.datetime(2022, 12, 19, tz='Europe/Paris'),
  'retries': 0,
  'retry_delay': timedelta(minutes=5),
  'xcom_push': True,
  'catchup': False,
  'params': {
    'dag_id': 'my_dag',
    'task_id': 'run_that',
  }
}

def last_exec(dag_id, task_id, session):
    task_instances = (
        session.query(TaskInstance)
        .filter(TaskInstance.dag_id == dag_id, TaskInstance.task_id == task_id)
        .all()
    )
    task_instances.sort(key=lambda x: x.execution_date, reverse=True)
    if task_instances:
        return task_instances[0]
    return None

def set_last_task_success(**kwargs):
    dag_id = kwargs['dag_id']
    task_id = kwargs['task_id']

    session = airflow.settings.Session()
    task_instance = last_exec(dag_id, task_id, session)

    if (task_instance is not None):
      task_instance.state = 'success'
      # task_instance = TaskInstance(task_id=task_id, execution_date=last_task_instance.execution_date)
      task_instance.run(session=session, ignore_ti_state=True, ignore_task_deps=True)
      session.commit()
      session.close()

doc_md=f"""## Set the given task_id to success of the given dag_id"""

# launched remotely
launcher = ScriptLauncher(default_args, "@once", 'set_task_to_success', ['airflow'], doc_md)

dag = launcher.dag;

set_to_success = PythonOperator(
    task_id='set_to_success',
    provide_context=True,
    python_callable=set_last_task_success,
    dag=dag,
    op_kwargs={
        'dag_id': '{{ params.dag_id }}',
        'task_id': '{{ params.task_id }}',
    }
)

The task_instance.run(...) call fail here with this error : "AttributeError: 'TaskInstance' object has no attribute 'task'", the state change is correctly working tho. What should I change so it rerun the "run_them" task when I change the state of the "run_that" task?

A: As of Airflow 2.5.0 you can update the state of any existing task via the Airflow REST API.

A: Using @TJaniF answer, I made this little reusable failure function task on_failure_send_force_success_mail, this function send a mail with a link to a custom API that call the patch task instance request using a get, it works as expected:
def on_failure_send_force_success_mail(task_id):
    def send_mail(**context):
        result = requests.post('mailing_api_url', json={
            "from": "foobar@mail.com",
            "to": "tozzi@mail.com",
            "subject": "Airflow task failed",
            "html": f'Airflow task test failed: click here',
        })
    return send_mail

def run_this_func_failed(**context):
    raise Exception('FAILED')

def run_this_func(**context):
    print('COMPLETED')

run_that = PythonOperator(
    task_id='run_that',
    provide_context=True,
    python_callable=run_this_func_failed,
    dag=dag,
)

run_this = PythonOperator(
    task_id='run_this',
    provide_context=True,
    python_callable=run_this_func,
    trigger_rule="all_success",
    dag=dag,
)

on_failure = PythonOperator(
    task_id='on_failure',
    provide_context=True,
    python_callable=on_failure_send_force_success_mail('run_that'),
    trigger_rule="all_failed",
    dag=dag,
)

run_that >> on_failure
run_that >> run_this


text:
Q: Drop TSQL temp tables In the report Command, I use this code before populating a temp table:
IF OBJECT_ID('tempdb..#GROUPERS') IS NOT NULL
    BEGIN
        DROP TABLE #GROUPERS;
    END;

When I save and run the command, I get this error message:

How can I resolve this?

A: When I run this I get 'It does not exist
create table #GROUPERS(i1 int)
IF OBJECT_ID('tempdb..#GROUPERS') IS NOT NULL
    BEGIN
        DROP TABLE #GROUPERS;
    END;

if OBJECT_ID('tempdb..#GROUPERS') IS NOT NULL
    print 'It exists'
else
    print 'It does not exist'

This means that the logic works. I am willing to bet that there is a unprintable character (invisible character) on the line where the if statement is. Did you cut and paste this code from somewhere? Try clicking on the error message. It may take you to where the error is. There may be strange characters at the end of the line....

A: Taking out all the CTEs in the code helped. Not sure why


text:
Q: Remove the gray border above the arrow for Bootstrap tooltip Does anyone know why this thin border appears on ALL my Bootstrap tooltips? I have searched and searched and cannot find anyone else who seems to experience this. The border is there in all of our MVC projects, and we have not altered the Bootstrap CSS in any way. We are using Bootstrap 3.3.7. The image shows the thin border above the stem/arrow.
Thanks!

A: Change Css Of below classes which is use for tooltip in bootstrap.
.tooltip.top .tooltip-arrow,
.tooltip-inner {
    border:none;
    box-shadow:none;
    outline:none;
}


text:
Q: Relationship between Liouvile's theorem and Diffusion equation Consider a Hamiltonian system. According to the Liouville's theorem there exists a probability density function $\rho(q^a,p_a,t)$ in the phase space whose evolution is given by
$$
\frac{\partial \rho }{\partial t} + \{\rho, H\} = 0 \, .
$$
Now, assume that the Hamiltonian system is a sort of Lorentz gas that presents a diffusive behavior, i.e. its evolution satisfies the Diffusion equation,
$$
\frac{\partial \tilde{\rho} }{\partial t} = D \nabla^2  \tilde{\rho} \, ,
$$
being $D$ the diffusion coefficient, $\nabla^2$ the Laplacian operator and $\tilde{\rho}(\bf{r},t)$ the probability density in the physical (configuration) space.
Does anyone know some works where a relationship between $\rho$ and $\tilde{\rho}$ is set up? Any bibliography will be appreciated.


text:
Q: How to limit the number of characters read by StreamReader.ReadLine() in .NET? I am writing a web server application in C# and using StreamReader class to read from an underlying NetworkStream:
 NetworkStream ns = new NetworkStream(clientSocket);
 StreamReader sr = new StreamReader(ns);
 String request = sr.ReadLine();

This code is prone to DoS attacks because if the attacker never disconnects we will never finish reading the line. Is there any way to limit the number of characters read by StreamReader.ReadLine() in .NET?

A: You might need one of StreamReader.Read overload:
Taken from http://msdn.microsoft.com/en-us/library/9kstw824.aspx
    using (StreamReader sr = new StreamReader(path))
    {
        //This is an arbitrary size for this example.
        char[] c = null;

        while (sr.Peek() >= 0)
        {
            c = new char[5];
            sr.Read(c, 0, c.Length);
            //The output will look odd, because
            //only five characters are read at a time.
            Console.WriteLine(c);
        }
    }

Focus on the sr.Read(c, 0, c.Length) line. This reads only 5 character from stream and put in into c array. You may want to change 5 to value you want.

A: Here is my own solution based on the solution by Marc Gravell:
using System;
using System.IO;
using System.Text;

namespace MyProject
{
    class StreamReaderExt : StreamReader
    {

        public StreamReaderExt(Stream s, Encoding e) : base(s, e)
        {
        }

        /// <summary>
        /// Reads a line of characters terminated by CR+LF from the current stream and returns the data as a string
        /// </summary>
        /// <param name="maxLineLength">Maximum allowed line length</param>
        /// <exception cref="System.IO.IOException" />
        /// <exception cref="System.InvalidOperationException">When string read by this method exceeds the maximum allowed line length</exception>
        /// <returns></returns>
        public string ReadLineCRLF(int maxLineLength)
        {
            StringBuilder currentLine = new StringBuilder(maxLineLength);

            int i;
            bool foundCR = false;
            bool readData = false;

            while ((i = Read()) > 0)
            {

                readData = true;

                char c = (char)i;

                if (foundCR)
                {
                    if (c == '\r')
                    {
                        // If CR was found before , and the next character is also CR,
                        // adding previously skipped CR to the result string
                        currentLine.Append('\r');
                        continue;
                    }
                    else if (c == '\n')
                    {
                        // LF found, finished reading the string
                        return currentLine.ToString();
                    }
                    else
                    {
                        // If CR was found before , but the next character is not LF,
                        // adding previously skipped CR to the result string
                        currentLine.Append('\r');
                        foundCR = false;
                    }
                }
                else // CR not found
                {
                    if (c == '\r')
                    {
                        foundCR = true;
                        continue;
                    }
                }

                currentLine.Append((char)c);
                if (currentLine.Length > maxLineLength)
                {
                    throw new InvalidOperationException("Max line length exceeded");
                }
            }

            if (foundCR)
            {
                // If CR was found before, and the end of the stream has been reached, appending the skipped CR character
                currentLine.Append('\r');
            }

            if (readData)
            {
                return currentLine.ToString();
            }

            // End of the stream reached
            return null;

        }
    }
}

This piece of code is provided "AS IS" with NO WARRANTY.

A: You would have to use the Read(char[], int, int) overload (which does limit the length) and do your own end-of-line detection; shouldn't be too tricky.
For a slightly lazy version (that uses the single-characted reading version):
static IEnumerable<string> ReadLines(string path, int maxLineLength)
{
    StringBuilder currentLine = new StringBuilder(maxLineLength);
    using (var reader = File.OpenText(path))
    {
        int i;
        while((i = reader.Read()) > 0) {
            char c = (char) i;
            if(c == '\r' || c == '\n') {
                yield return currentLine.ToString();
                currentLine.Length = 0;
                continue;
            }
            currentLine.Append((char)c);
            if (currentLine.Length > maxLineLength)
            {
                throw new InvalidOperationException("Max length exceeded");
            }
        }
        if (currentLine.Length > 0)
        {
            yield return currentLine.ToString();
        }
    }
}

A: You can always use ".Read(...)" and MSDN recommends doing so for a situation like yours.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx


text:
Q: How do I use external applications to scrape data from a mobile app? I am trying to scrape data from a mobile application (Pokemon HOME). The app shows usage statistics and other useful statistics that I want to scrape. I want to scrape this on my computer using python.
I am having trouble determining how to scrape data from a mobile application. I tried using Fiddler and an Android emulator to intercept server data but I am unfamiliar with the software to be able to understand what exactly to do.
Any help would be very beneficial. Even just suggestions for resources where I can learn how to do this on my own. Thank you!

A: It's possible but it's really a hard nut to break. There's a huge difference between Mobile app and web app
Web app is accessible through WAN ,v.i.z World area network. Scraping is fairly and squarely easier.
In Python, you can bs4 to do it.
But in Mobile app, essentially and effectively, it's more about LAN.
It's installed locally.
Install an app to remote control your device from another device (usually required root)
However, whole data might not be available.


text:
Q: Application with session management in the server side I need to create a server based (php) application with iOS client with authintication "login" mechanisim but i dont known about session in iOS. My application needs login to my website (PHP based website) to get data. I dont known a is the session for the iPhone client is keept in the server?
Details:
After sending the login request from iPhone client to my web application, I think here a session is created in my webapp (right?), what about my next request? can I access the same session created for the first request.. In another word : can I share data in the web session (in the server) to be accessible in each request sent by iOS client after login?

A: Sessions are a server-side concept - there is no session on the client side.
What normally happens is that the server sets a cookie in the response headers after you log in, and that cookie contains the session ID so that on subsequent requests, the server knows that the client is using that session because it matches up the cookie.
Cookies work automatically on iOS, so you shouldn't have to do anything at all. NSURLRequests have a property HTTPShouldHandleCookies that defaults to YES, so everything should just work by default.
If it's not working (or if you just want to see what's going on), you can gain access to the cookies in iOS using the NSHTTPCookieStorage APIs. Take a look inside the [NSHTTPCookieStorage sharedHTTPCookieStorage], which works a bit like an NSDictionary. That's where the session cookie should be set after you log in.


text:
Q: Use an output variable as a global variable in Azure yaml pipeline I got an Azure yaml pipeline in which there's an input of a name of an output variable:
- task: QueryAzureDevOpsExtensionVersion@3
  displayName: 'Query Extension Version'
  inputs:
    ...
    outputVariable: 'Task.Extension.Version'
    ...

I noticed that I can access this output variable only in the same stage it was defined so I declared a variable to the entire pipeline so I can use it in multiple stages:
variables:
  - name: TaskExtensionVersion
    value: initialValue

How can I set the value of Task.Extension.Version to variabls.TaskExtensionVersion?

A: UPDATE
I've just released a verion of the Azure DevOps Extension Tasks that can set the flag on the output variable (version 3.1.123), I'll make this the default in v4, since it's a breaking change.
steps:
- task: QueryAzureDevOpsExtensionVersion@3
  displayName: 'Query Extension Version: jessehouwing.jessehouwing-vsts-variable-tasks'
  name: Query
  inputs:
    connectedServiceName: Marketplace
    publisherId: jessehouwing
    extensionId: 'jessehouwing-vsts-variable-tasks'
    versionAction: Patch
    setOutputFlag: true

Version 4 removed the need to set anything and always registers an output variable:
steps:
- task: QueryAzureDevOpsExtensionVersion@4
  displayName: 'Query Extension Version: jessehouwing.jessehouwing-vsts-variable-tasks'
  name: Query
  inputs:
    connectedServiceName: Marketplace
    publisherId: jessehouwing
    extensionId: 'jessehouwing-vsts-variable-tasks'
    versionAction: Patch

You can then reference the variable using Query.Extension.Version in the same job or with: dependencies.JobA.outputs['Query.Extension.Version'] across jobs.

Before
You can try my Variables Tasks:
- task: VariableSetTask@2
  name: SetVersion
  displayName: 'Set variable: TaskExtensionVersion to: ''$(Task.Extension.Version)'''
  inputs:
    variableName: TaskExtensionVersion
    Value: '$(Task.Extension.Version)'
    IsOutput: true

Or use a Powershell script:
- powershell: |
   $value = $env:version
   Write-Host "##vso[task.setvariable variable=TaskExtensionVersion;isoutput=true]$value"
  displayName: 'PowerShell Script'
  name: SetVersion
  env:
    version: $(Task.Extension.Version)

I don't think the extension tasks currently register the variable as an output variable across stages.
Then make sure you reference the variable using the correct syntax:
$(dependencies.JobA.outputs['SetVersion.TaskExtensionVersion'])

Be sure to add the name: parameter to your Job and your Task so the output variable can be referenced. The naming of tasks and jobs and declaring dependencies is required to make this work. See the docs on this topic:

*

*In the same job

*Across jobs.