text:
Q: React Chakra UI Modal bug I'm developing in ReactTS in VS Code.
In the navbar there is a menu in which there is a logut button.
when clicked user logged out etc. but at the end the sign in modal appears and I cant figure out why.
The sign in button doesn't trigger neither does the variable turns true which controls the sign in modal.
I fixed it by setting isLogin to false but it never had turned to true anyway.
Menu Component:
export default function UserMenu() {

    const navigate = useNavigate();
    const user = useAppSelector(state => state.auth.user);
    const dispatch = useAppDispatch();
    const [isLogin, setIsLogin] = useState(false);

    if (user) return (
        <Menu>
            <MenuButton>
                Account
            </MenuButton>
            <MenuList>
                <MenuGroup title={user.name}>
                    <MenuItem onClick={() => {
                        dispatch(logout());
                        dispatch(setMovie(null));
                        navigate("/");
                        //Login bug
                        Had to set this here so it works but don't know why
                        setIsLogin(false);

                    }} >Logout</MenuItem>
                </MenuGroup>
            </MenuList >
        </Menu >
    )
    else return (
        <Fragment>
            <Button onClick={() => setIsLogin(true)}>Sign in</Button>

            THIS IS THE LOGIN MODAL THAT APPEARS RIGHT AFTER LOGOUT
            <Login isOpen={isLogin} onClose={() => setIsLogin(false)} />
            isLogin variable is never true.

        </Fragment>
    )
}

(removed code for better readibility)
Login:
export default function Login({ isOpen = false, onClose, forwardto }:
{
isOpen: boolean,
onClose: () => void,
forwardto?: string
}) {

    return{(
        <Modal
            isOpen={isOpen}
            onClose={() => {
                onClose()
            }}
        >
            <ModalOverlay />
            <ModalContent>
                ...doesnt affect result
            </ModalContent>
        </Modal>
    )}


text:
Q: WINAPI methods with nonzero return value at success For a lot of WINAPI methods, the return value is either 0 (failure) or nonzero (success). For example:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682565(v=vs.85).aspx

Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero.

My question is, for such a method, is it correct to test the return value with TRUE (which is a BOOL value equal to 1)? Or is it more correct to test if the return value is !FALSE instead?
Another nonrelated question is, when the return value is non-zero, what exactly is it? Can it be any value or from a set of values?

A: The signature of the method you mentioned is:
BOOL WINAPI DeleteTimerQueue(_In_ HANDLE TimerQueue);

In the Windows headers the type BOOL is defined as an int. This is for historical reasons, since in the days before C99 there was no bool type that we are now familiar with, and WinAPI have kept using the BOOL definition for many of the methods introduced later on.
Further, the Windows headers look very similar to this, if we take the liberty to simplify a bit,
typedef int   BOOL
#define FALSE 0  // < note that #define <number> introduces an integer constant
#define TRUE  1

Thus your question can be interpreted as whether testing for !<integer> is equivalent to testing against a boolean value. The answer is yes, with C++ testing !0 == true and !n == false for any integral n > 0.

Another nonrelated question is, when the return value is non-zero, what exactly is it? Can it be any value or from a set of values?

It will be different for different WinAPI methods. Generally it can be any value, but since the return type is conceptually a boolean, it is okay to test it as a boolean.

so to sum up I should check it as …

The idiomatic way to check is:
if(!DeleteTimerQueue(handle)) {
    /* handle the error case */
    /* call GetLastError() where applicable */
}
/* otherwise proceed, the call succeeded */

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL 'LIKE' query with spaces I have a MySQL database with postcodes in it, sometimes in the database there are spaces in the postcodes (eg. NG1 1AB) sometimes there are not (eg. NG11AB). Simlarly in the PHP query to read from the database the person searching the database may add a space or not. I've tried various different formats using LIKE but can't seem to find an effective means of searching so that either end it would bring up the same corresponding row (eg. searching for either NG11AB or NG1 1AB to bring up 'Bob Smith' or whatever the corresponding row field would be).
Any suggestions?

A: SELECT *
FROM MYTABLE
WHERE REPLACE(MYTABLE.POSTCODE, ' ', '') LIKE '%input%'

Make sure your PHP input is trimmed as well

A: I wouldn't even bother with LIKE or regex and simply remove spaces and compare the strings:
SELECT *
FROM mytable
WHERE LOWER(REPLACE(post_code_field, ' ', '')) = LOWER(REPLACE(?, ' ', ''))

Note that I also convert both values to lower case to still match correctly if the user enters a lower-case post code.

A: Assuming your column has more than just the postcode in it: Remove all spaces before doing the like test:
where replace(postcode, ' ', '') like '%NG11AB%'

If your columns has just the postcode in it:
where replace(postcode, ' ', '') = 'NG11AB'

or
where postcode like 'N%G%1%1%A%B'

Regex will work for both cases. The following regex allows optional spaces between each letter:
where postcode rlike 'N ?G ?1 ?1 ?A ?B' -- use regex

A: You can use "*" metacharacter who matches 0 or more char, e.g.
   LIKE "NG1*1AB"
matches NG11AB and NG1 1AB
More examples: http://www.shayanderson.com/mysql/mysql-regex-metacharacters.htm


text:
Q: Problema al insertar datos en base de datos Este es el codigo de mi formularo , cuando selecciono las variables que luego serviran para hacer el select individual de cada tabla , luego debo insertarlas en una tabla final , basicamente lo que necesito es tomar los datos de 3 tablas diferentes y luego insertarlos en una tabla final
                        <?php
                        // incluye la conexión
                        include_once('connection.php');

                        $database = new Connection();
                        $db = $database->open();
                        try {
                            $sql = 'SELECT * FROM certificado';
                            foreach ($db->query($sql) as $row) {
                        ?>

                            <?php echo $row['id_certificado']; ?>
                            <?php echo $row['nom_estudiante']; ?>
                            <?php echo $row['curso']; ?>
                            <?php echo $row['entrenador']; ?>
                            <?php echo $row['expedicion']; ?>

                                        <a href="#edit_<?php echo $row['id_certificado']; ?>" class="btn btn-success btn-sm" data-toggle="modal"> Editar
                                        <a href="#delete_<?php echo $row['id_certificado']; ?>" class="btn btn-danger btn-sm" data-toggle="modal"> Eliminar

                                    <?php include('edit_delete_modal.php'); ?>

                        <?php
                            }
                        } catch (PDOException $e) {
                            echo "There is some problem in connection: " . $e->getMessage();
                        }
                        //cerrar conexión
                        $database->close();
                        ?>

<?php include('add_modal.php'); ?>

aqui se reciben los datos del formulario y se guardan en variables para luego utilizarlas ,
es mi duda  , se puede reslizar las consultas asi o debo usar otro comando para hacer las consultas en un solo ciclo
<?php
session_start();
include_once('connection.php');

if (isset($_POST['add'])) {
    $name = $_POST['nombre'];
    $trainer = $_POST['trainer'];
    $curso = $_POST['curso'];
    $expe = $_POST['expedicion'];

$query_estudiante = "SELECT * FROM nacional where nombre_completo ='$name'";
$query_entrenador = "SELECT * FROM entrenador where nombre_entrenador ='$trainer'";
$query_curso = "SELECT * FROM curso where nombre_curso ='$curso'";

$ejecutar_est= mysqli_query($conexion,$query_estudiante);
$ejecutar_tra= mysqli_query($conexion,$query_entrenador);
$ejecutar_cur= mysqli_query($conexion,$query_curso);

while ($rowe = mysqli_fetch_array($ejecutar_est)) {
    while ($rowt = mysqli_fetch_array($ejecutar_tra)) {
        while ($rowc = mysqli_fetch_array($ejecutar_cur)) {
            $query = "INSERT INTO certificados
            (id_certificado,duracion_curso, expedicion, nivel, nom_estudiante, cedula, entrenador, firma, resolucion, curso,cargo_profe) VALUES
        ('5'
        ,$rowc[duracion]',
        '$_POST[fecha]',
         'alto',
        '$rowe[nombre_completo]',
        '$rowe[cedula]',
        '$rowt[nombre_entrenador]',
        '$rowt[firma]',
        '$rowt[resolucion]',
        '$rowc[nombre_curso]',
            '$rowt[cargo_entrenador]')";

        }
    }
}


text:
Q: After contact form 7 mail sent need to submit another hidden form I have a form made by contact form 7. After the form data successfully sent i need to submit another hidden form to external CRM. My code is below
add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function( $contact_form ) {
$title = $contact_form->id;
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
    $posted_data = $submission->get_posted_data();
}
if ( 12 == $title ) {
$firstname = $posted_data['firstname'];
echo '<form name="bntWebForm" id="bntWebForm" method="post"action="https://www.bntouchmortgage.net/account5/webform/" style="display:none;">
<input class="form-control" type="text" name="name_1" value="'.$firstname.'" />
<input type="submit" value="Submit">
</form> ';
?>
<script>document.getElementById("bntWebForm").submit();</script>
<?php
}
}

But whenever i ran the code it is not working and the ajax loaded endlessly spining. Can anyone please help me how can i do it.

A: I think that your approach is basically incorrect.
The wpcf7_mail_sent action occurred in the server side and it cannot be used to add DOM element to the page. The form you try to echo out together with the javascript code will never be added to the page and run on the client side environment you're expecting.
To send a post with data to the external endpoint you want, you can still use the wpcf7_mail_sent hook using PHP curl functions to send a HTTP post request.
An example can be found below:
add_action('wpcf7_mail_sent', function() {
   $endpoint_url = 'https://www.bntouchmortgage.net/account5/webform/';
   $data_to_post = ['name_1' => $firstname];

   // Sets our options array so we can assign them all at once
   $options = [
       CURLOPT_URL        => $endpoint_url,
       CURLOPT_POST       => true,
       CURLOPT_POSTFIELDS => $data_to_post,
   ];

   $curl = curl_init();
   curl_setopt_array($curl, $options);

   // Executes the cURL POST
   $results = curl_exec($curl);

   curl_close($curl);
});


text:
Q: De Morgan's rules explained Could you please explain the De Morgan's rules as simply as possible (e.g. to someone with only a secondary school mathematics background)?

A: It is just a way to restate truth statements, which can provide simpler ways of writing conditionals to do the same thing.
In plain English:
When something is not This or That, it is also not this and not that.
When something is not this and that, it is also not this or not that.
Note: Given the imprecision of the English language on the word 'or' I am using it to mean a non-exclusive or in the preceding example.
For example the following pseudo-code is equivalent:
If NOT(A OR B)...
IF (NOT A) AND (NOT B)....
IF NOT(A AND B)...
IF NOT(A) OR NOT(B)...

A: Overview of boolean algebra
We have two values: T and F.
We can combine these values in three ways: NOT, AND, and OR.
NOT
NOT is the simplest:

*

*NOT T = F

*NOT F = T
We can write this as a truth table:
when given.. | results in...
============================
           T | F
           F | T

For conciseness
x | NOT x
=========
T | F
F | T

Think of NOT as the complement, that is, it turns one value into the other.
AND
AND works on two values:
x y | x AND y
=============
T T | T
T F | F
F T | F
F F | F

AND is T only when both its arguments (the values of x and y in the truth table) are T — and F otherwise.
OR
OR is T when at least one of its arguments is T:
x y | x OR y
=============
T T | T
T F | T
F T | T
F F | F

Combining
We can define more complex combinations. For example, we can write a truth table for x AND (y OR z), and the first row is below.
x y z | x AND (y OR z)
======================
T T T | ?

Once we know how to evaluate x AND (y OR z), we can fill in the rest of the table.
To evaluate the combination, evaluate the pieces and work up from there. The parentheses show which parts to evaluate first. What you know from ordinary arithmetic will help you work it out. Say you have 10 - (3 + 5). First you evaluate the part in parentheses to get
10 - 8

and evaluate that as usual to get the answer, 2.
Evaluating these expressions works similarly. We know how OR works from above, so we can expand our table a little:
x y z | y OR z | x AND (y OR z)
===============================
T T T | T      | ?

Now it's almost like we're back to the x AND y table. We simply substitute the value of y OR z and evaluate. In the first row, we have
T AND (T OR T)

which is the same as
T AND T

which is simply T.
We repeat the same process for all 8 possible values of x, y, and z (2 possible values of x times 2 possible values of y times 2 possible values of z) to get
x y z | y OR z | x AND (y OR z)
===============================
T T T | T      | T
T T F | T      | T
T F T | T      | T
T F F | F      | F
F T T | T      | F
F T F | T      | F
F F T | T      | F
F F F | F      | F

Some expressions may be more complex than they need to be. For example,
x | NOT (NOT x)
===============
T | T
F | F

In other words, NOT (NOT x) is equivalent to just x.
DeMorgan's rules
DeMorgan's rules are handy tricks that let us convert between equivalent expressions that fit certain patterns:

*

*NOT (x AND y) = (NOT x) OR  (NOT y)

*NOT (x OR  y) = (NOT x) AND (NOT y)
(You might think of this as how NOT distributes through simple AND and OR expressions.)
Your common sense probably already understands these rules! For example, think of the bit of folk wisdom that "you can't be in two places at once." We could make it fit the first part of the first rule:
NOT (here AND there)

Applying the rule, that's another way of saying "you're not here or you're not there."
Exercise: How might you express the second rule in plain English?
For the first rule, let's look at the truth table for the expression on the left side of the equals sign.
x y | x AND y | NOT (x AND y)
=============================
T T | T       | F
T F | F       | T
F T | F       | T
F F | F       | T

Now the righthand side:
x y | NOT X | NOT Y | (NOT x) or (NOT y)
========================================
T T | F     | F     | F
T F | F     | T     | T
F T | T     | F     | T
F F | T     | T     | T

The final values are the same in both tables. This proves that the expressions are equivalent.
Exercise: Prove that the expressions NOT (x OR  y) and (NOT x) AND (NOT y) are equivalent.

A: Looking over some of the answers, I think I can explain it better by using conditions that are actually related to each other.
DeMorgan's Law refers to the fact that there are two identical ways to write any combination of two conditions - specifically, the AND combination (both conditions must be true), and the OR combination (either one can be true).  Examples are:
Part 1 of DeMorgan's Law
Statement: Alice has a sibling.
Conditions: Alice has a brother OR Alice has a sister.
Opposite: Alice is an only child (does NOT have a sibling).
Conditions: Alice does NOT have a brother, AND she does NOT have a sister.
In other words: NOT [A OR B] = [NOT A] AND [NOT B]
Part 2 of DeMorgan's Law
Statement: Bob is a car driver.
Conditions: Bob has a car AND Bob has a license.
Opposite: Bob is NOT a car driver.
Conditions: Bob does NOT have a car, OR Bob does NOT have a license.
In other words: NOT [A AND B] = [NOT A] OR [NOT B].
I think this would be a little less confusing to a 12-year-old.  It's certainly less confusing than all this nonsense about truth tables (even I'm getting confused looking at all of those).

A: "He doesn't have either a car or a bus." means the same thing as "He doesn't have a car, and he doesn't have a bus."
"He doesn't have a car and a bus." means the same thing as "He either doesn't have a car, or doesn't have a bus, I'm not sure which, maybe he has neither."
Of course, in plain english "He doesn't have a car and a bus." has a strong implication that he has at least one of those two things.  But, strictly speaking, from a logic standpoint the statement is also true if he doesn't have either of them.
Formally:

*

*not (car or bus) = (not car) and (not bus)

*not (car and bus) = (not car) or (not bus)

In english, 'or' tends to mean a choice, that you don't have both things.  In logic, 'or' always means the same as 'and/or' in English.
Here's a truth table that shows how this works:
First case: not (cor or bus) = (not car) and (not bus)
 c | b || c or b | not (c or b) || (not c) | (not b) | (not c) and (not b)
---+---++--------+--------------++---------+---------+--------------------
 T | T ||    T   |      F       ||    F    |    F    |        F
---+---++--------+--------------++---------+---------+--------------------
 T | F ||    T   |      F       ||    F    |    T    |        F
---+---++--------+--------------++---------+---------+--------------------
 F | T ||    T   |      F       ||    T    |    F    |        F
---+---++--------+--------------++---------+---------+--------------------
 F | F ||    F   |      T       ||    T    |    T    |        T
---+---++--------+--------------++---------+---------+--------------------

Second case: not (car and bus) = (not car) or (not bus)
 c | b || c and b | not (c and b) || (not c) | (not b) | (not c) or (not b)
---+---++---------+---------------++---------+---------+--------------------
 T | T ||    T    |       F       ||    F    |    F    |        F
---+---++---------+---------------++---------+---------+--------------------
 T | F ||    F    |       T       ||    F    |    T    |        T
---+---++---------+---------------++---------+---------+--------------------
 F | T ||    F    |       T       ||    T    |    F    |        T
---+---++---------+---------------++---------+---------+--------------------
 F | F ||    F    |       T       ||    T    |    T    |        T
---+---++---------+---------------++---------+---------+--------------------

A: If you're a police officer looking for underage drinkers, you can do one of the following, and De Morgan's law says they amount to the same thing:
FORMULATION 1 (A AND B)

If they're under the age
  limit AND drinking an alcoholic
  beverage, arrest them.

FORMULATION 2 (NOT(NOT A OR NOT B))

If they're over
  the age limit OR drinking a
  non-alcoholic beverage, let them go.

This, by the way, isn't my example. As far as I know, it was part of a scientific experiment where the same rule was expressed in different ways to find out how much of a difference it made in peoples' ability to understand them.

A: Draw a simple Venn diagram, two intersecting circles. Put A in the left and B in the right. Now (A and B) is obviously the intersecting bit. So NOT(A and B) is everything that's not in the intersecting bit, the rest of both circles. Colour that in.
Draw another two circles like before, A and B, intersecting. Now NOT(A) is everything that's in the right circle (B), but not the intersection, because that's obviously A as well as B. Colour this in. Similarly NOT(B) is everything in the left circle but not the intersection, because that's B as well as A. Colour this in.
Two drawings look the same. You've proved that NOT(A and B) = NOT(A) or NOT(B). T'other case is left as an exercise for the student.

A: DeMorgan's Law allows you to state a string of logical operations in different ways. It applies to logic and set theory, where in set theory you use complement for not, intersection for and, and union for or.
DeMorgan's Law allows you to simplify a logical expression, performing an operation that is rather similar to the distributive property of multiplication.
So, if you have the following in a C-like language
if !(x || y || z) { /* do something */ }

It is logically equivalent to:
if (!x && !y && !z)

It also works like so:
if !(x && !y && z)

turns into
if (!x || y || !z)

And you can, of course, go in reverse.
The equivalence of these statements is easy to see using something called a truth table. In a truth table, you simply lay out your variables (x, y, z) and list all the combinations of inputs for these variables. You then have columns for each predicate, or logical expression, and you determine for the given inputs, the value of the expression. Any university curriculum for computer science, computer engineering, or electrical engineering will likely drive you bonkers with the number and size of truth tables you must construct.
So why learn them? I think the biggest reason in computing is that it can improve readability of larger logical expressions. Some people don't like using logical not ! in front of expressions, as they think it can confuse someone if they miss it. The impact of using DeMorgan's Law on the gate level of chips is useful, however, because certain gate types are faster, cheaper, or you're already using a whole integrated circuit for them so you can reduce the number of chip packages required for the outcome.

A: Not sure why I've retained this all these years, but it has proven useful on a number of occasions. Thanks to Mr Bailey, my grade 10 math teacher. He called it deMorgan's Theorem.
!(A || B) <==> (!A && !B)
!(A && B) <==> (!A || !B)

When you move the negation in or out of the brackets, the logical operator (AND, OR) changes.


text:
Q: Simplest, easiest way for 2 Python scripts on 2 computers over local network to share data Computer A: Has a script which, when run, will return the content of a iMessage sent to the computer (from the Messages.app)
Computer B: Has a script which will display the content of the iMessage received on Computer A
This is the desired result. Currently the way I have it working is all on one machine, so the computer that receives the message is able to display it. I have tried running the script on Computer B with the script pointing to the path of the message file from Computer A via Mac file sharing. The problem with this is the file sharing seems very intermittent, it often disconnects or doesn't grab the up to date information. When it's all running on one machine, it's instant, no delays.
What alternatives are there for transferring the data between the 2 computers. Can Computer B trigger Computer A to run the script that gets the data, and then somehow have it sent to the script on Computer B?
Thanks for any help!
If it's not clear, let me know and I'll try to elaborate more

A: I suggest you look into the 'pika' module and RabbitMQ message broker. More info on their tutorial page.
https://www.rabbitmq.com/tutorials/tutorial-one-python.html
A free and simple RabbitMQ server can be found here:
https://www.cloudamqp.com/


text:
Q: Uncaught Reference Error: validateform is not definded The code is very simple. But this is the first thing off this kind that I am doing, and I simply do not understand what it is that I am doing wrong.
Also this is the raw code straight from OCR.
This is GCSE computing coursework. I don't have to fix it, but I don't know how I'm supposed to test the stuff I'm going to add without the base code working.

    <title>Exam entry</title>

Exam Entry Form

    <form name="ExamEntry" method="post" action="success.html">

                Name

                    <input type="text" name="name" />

                Subject

                    <input type="text" name="subject" />

                    <input type="submit" name="Submit" value="Submit" onclick= return "validateForm()";  />

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

    </form>

A: Your code has couple of syntax errors. I have removed that.
here is the fiddle link

Exam Entry Form

    <form name="ExamEntry" method="post" action="success.html">

                Name

                    <input type="text" name="name" />

                Subject

                    <input type="text" name="subject" />

                    <input type="submit" name="Submit" value="Submit" onclick= " return validateForm();"  />

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

    </form>


text:
Q: Move an OpenLayer point I want to draw a rectangle and be able to move it by moving its corners. I want it to remain a rectangle all the time. I drew the rectangle and its corners, and I know how to erase its sides.
I would like to put an EventListener on its corners, and be able to erase or move its corners. Do you know how to do that ? Thank you.
<!doctype html>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css" type="text/css">

    <title>OpenLayers example</title>

My Map

A: You can have a look at ol-ext transform interaction.

 https://viglino.github.io/ol-ext/examples/interaction/map.interaction.transform.html


text:
Q: What can I do with this Error downloading PyAudio? What can I do with this Error?
C:\Users\hp laptop\AppData\Local\Programs\Python\Python39>pip install PyAudio-0.2.11-cp310-cp310-win_amd64.whl
ERROR: PyAudio-0.2.11-cp310-cp310-win_amd64.whl is not a supported wheel on this platform.
I already try installing the latest version but it always come up with this


text:
Q: How can i open a link in my webbrowser application?

Hi i want to do like this. i'm writing a  webbrowser application in c# and i will set as default browser.but i have one problem if i set it won't open clicked link from other program or html file on desktop.
how can i do that ?
it should be like this photos.
i hope you understand my english.sorry for my english. :)
    private void Form1_Load(object sender, EventArgs e)
    {
        panel3.BackColor = Doga_Rhodonit.Properties.Settings.Default.themebg;

        ((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(what should i write or what event should i write??);

A: If your  browser is set to the default when a link is pressed the OS will send the URL as a argument
   string URL = null;

   public static void Main(string[] args)
        {
            Console.WriteLine(args[0]);
            URL = args[0];
        }

private void Form1_Load(object sender, EventArgs e)
    {
        panel3.BackColor = Doga_Rhodonit.Properties.Settings.Default.themebg;

        ((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(URL);


text:
Q: Guessing the salt of a known password in Meteor My goal is to store the hash and salt of meteor password on another database. So far I've managed to know the hash but not the salt....
Is there a way to deduce the salt used by bcrypt ?
Or is there a way to know the salt used ?
And does Meteor create a new salt each time a password is hashed ?
A "solution" could be the creation of one well known password and deduce the salt out of it if Meteor doesn't change the salt each time.
Any ideas ?


text:
Q: Jquery form submit button (chrome issue) I'm trying to prevent a form from being submitted twice. I'm doing that by catching clicks on a submit button and disabling it while the form submit goes on in the background.
Here's a very basic example of the code I'm using:
$("button").click(function(){
    $(this).attr("disabled","true").html("Wait here while posted...");
});

Working example:
http://jsfiddle.net/t93Vw/
This works perfectly in firefox and IE, but in chrome the form is not submitted.
Why is this different behaviour, and does anyone have a quick fix?

A: If you want to submit a form then you should use onsubmit event:
$("form").submit(function () {
    $(':submit', this).prop("disabled", true).html("Wait here while posted...");
});

onclick is for click, form has a special event for submission. Advantage is that it will properly behave on Enter key submit.
Demo: http://jsfiddle.net/t93Vw/1/

A: Try .prop( propertyName, value ) and don't wrap true in quotes

value Type: String or Number or Boolean A value to set for the property.

$("button").click(function (e) {
    e.preventDefault(); //stop default behavior of form submit
    $(this).prop("disabled", true) // disable button
        .text("Wait here while posted...") //change text of button
        .closest('form').submit();//find closest form and submit it
});

.closest()
event.preventDefault()

Fiddle Demo

A: The type of the button may be the reason ... try this
<form action="/test" method="post">
    <input type="text" name="somefield"/>
    <button id="submitbutton">Send</button>
</form>

$("button").click(function(){
    $(this).prop("disabled",true).html("Wait here while posted...")
       .parent().get(0).submit();
    e.preventDefault();
});

A: Not quite sure what's the error but maybe this will help?
$("button").click(function(e){
    e.preventDefault();
    $(this).attr("disabled","true").html("Wait here while posted...");
});

A: For it to work on chrome, do the following updates in your codes:
(1) your form
<form action="/test" method="post" id="myForm">
  <input type="text" name="somefield"/>
  <button id="submitbutton" type="submit">Send</button>
</form>

(2) Use jquery to submit the form:
$("button").click(function(){
  $('form#myForm').submit();
  $(this).attr("disabled","true").html("Wait here while posted...");
});


text:
Q: Multiple radio buttons to show/hide div I have 4 radio buttons and I need to show a specific div based on which is clicked and make sure the other 3 remain hidden, etc for all 4. I can only find code to make 2 work but not 4.
Does anyone have an example how to do this?
Just as a test I have

 1

 2

 3

 4

but cannot find something to sort out doing it with all of them.
Buttons are just basic in place to test right now:

<input value="12" id="option_2624" name="signup[optionid]" type="radio" checked="checked">
<var class="" ref=""> 12

<input value="6" id="option_2429" name="signup[optionid]" type="radio">
<var class="" ref=""> 6

<input value="3" id="option_1554" name="signup[optionid]" type="radio" >
<var class="" ref=""> 3

<input value="1" id="option_1697" name="signup[optionid]" type="radio">
<var class="" ref=""> 1

A: You can do this by jQuery like the following
I added a custom attribute to the radio that is connected to the div and this will only show one div per click
HTML Code

1

2

3

4

5

<input type="radio" data-target-id="1" name="radio" class="radioBtn">
<input type="radio" data-target-id="2" name="radio" class="radioBtn">
<input type="radio" data-target-id="3" name="radio" class="radioBtn">
<input type="radio" data-target-id="4" name="radio" class="radioBtn">
<input type="radio" data-target-id="5" name="radio" class="radioBtn">

JS Code
$(document).ready(function(){
     $('.radioBtn').click(function(){

         var target = $(this).data('target-id');
         $('.my-div').hide();
         $('.my-div[data-target="'+target+'"]').show();
     });

});

And here is a working example
http://jsfiddle.net/JU7Nw/70

A: Here's a sample code that does what you want. I am not using any javascript library but plain old javascript.

        <input type="radio" onclick="showDiv ('1')" name="selectme">1</input>
        <input type="radio" onclick="showDiv ('2')" name="selectme">2</input>
        <input type="radio" onclick="showDiv ('3')" name="selectme">3</input>
        <input type="radio" onclick="showDiv ('4')" name="selectme">4</input>

Hey, its me, 1

Hey, its me, 2

Hey, its me, 3

Hey, its me, 4


text:
Q: Majority Element Failing to close cycles I'm trying to figure out why this keeps printing the "majority element" candidate in every cycle.
The code I've been trying to make work is a Majority Element search (to find an element that is repeated more than half of the length of a list).
I can't separate the processes of finding the candidate and testing against the array because my input is a text file that has an indeterminate number of arrays. It's an exercise from rosalind.info that has different inputs every time you try to solve it.
An example of the input would be
-5 5 5 5 5 5 5 5 -8 7 7 7 1 7 3 7 -7 1 6 5 10 100 1000 1 -5 1 6 7 1 1 10 1

Here's what I've written so far.
foreach my $currentrow (@lists) {

    my @row = ();
    @row = split( /\s/, $currentrow );

    my $length = $#row;
    my $count  = 0;
    my $i      = 0;

    for $i ( 0 .. $length - 1 ) {

        if ( $count == 0 ) {
            $candidate = $row[$i];
            $count++;
        }

        if ( ( $count > 0 ) and ( $i = $length - 1 ) ) {

            my $counter2 = 0;

            for my $j ( 0 .. $length - 1 ) {
                if ( $row[$j] == $candidate ) {
                    $counter2++;
                }
            }

            if ( $counter2 <= ( $#row / 2 ) and ( $i = $length - 1 ) ) {
                $candidate = -1;
                print $candidate, " ", $i, " ";
            }

            if ( $counter2 > ( $#row / 2 ) and ( $i = $length - 1 ) ) {
                print $candidate, " ", $i, " ";
            }

        }

        if ( $candidate == $row[$i] and $count > 0 ) {
            $count = $count + 1;
        }

        if ( $candidate != $row[$i] and $count > 0 ) {
            $count = $count - 1;
        }
    }
}

A: Do you have use strict and use warnings 'all' in place?
I imagine that your problem may be because of the test $i = $length - 1, which is an assignment, and should be $i == $length - 1

A: To find a majority element I would use a hash:
perl -nae '%h=(); $h{$_}+=2 for @F; $h{$_}>@F and print for keys %h; print "\n"'

Each line of input is treated separately. Each line of output matches a line of input and presents its majority element or is empty if there is no such element.
Edit: Now the solution uses autosplit (-a), which is shorter and work not only for numbers.


text:
Q: Firebird sends all events in .NET Is it normal firebird server sends all registered event counts on raising any of registered event?
By example on firebirds site I do this:
class FirebirdListenerTest
{
    public FirebirdListenerTest()
    {
        try
        {
            FbConnectionStringBuilder cs = new FbConnectionStringBuilder();
            cs.DataSource = "localhost";
            cs.Database = "C:\\FIREBIRD\\TEST.GDB";
            cs.UserID = "SYSDBA";
            cs.Password = "masterkey";
            cs.Charset = "NONE";

            FbConnection connection = new FbConnection(cs.ToString());
            connection.Open();

            FbRemoteEvent revent = new FbRemoteEvent(connection);
            revent.AddEvents(new string[] { "text_changed", "text_inserted", "justtest_event" });

            // Add callback to the Firebird events
            revent.RemoteEventCounts += new FbRemoteEventEventHandler(EventCounts);

            // Queue events
            revent.QueueEvents();

            Console.ReadLine();
            connection.Close();
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

    static void EventCounts(object sender, FbRemoteEventEventArgs args)
    {
        Console.WriteLine("Event {0} has {1} counts.", args.Name, args.Counts);
    }
}

In such code, if any of events is raised, I always get counts for all events. Is it how it should works?

A: Yes it is. You can filter it base on Counts property, it can be 0-n.


text:
Q: Protocol not being executed I'm trying to implement light and dark theme throughout the entire app. My problem is that it's not working properly. I have a ContainerVC that contains 2 ContainerViews - SidebarMenuVC and DashboardVC. SidebarMenuVC is offset so initially, the user is being displayed DashboardVC.
The ContainerVC is embedded in a UINavigationController and there's a hamburger type menu. When the user taps on that menu button, SidebarMenuVC is being displayed. It all works just fine.
SidebarMenuVC contains an image that is responsible for changing the theme of the app. When the user taps on the image it goes from light to dark or vice versa. The moment of tap changes the theme of SidebarMenuVC but when you hide the menu (via swipe), DashboardVC's theme is not being applied. I tried to do that with protocol but I think I'm not doing it correctly (well, its not working so I KNOW i've messed up somehow).
protocol ReloadTheme {
    func reload()
}

class ContainerVC: UIViewController, SidebarDelegate {

    var delegateReloadTheme: ReloadTheme?
    func hideMenu() {
        sideBarMenuLeadingConstraint.constant = -300
        applyTheme()
        animateConstraint()
        delegateReloadTheme?.reload() // when I put a breakpoint here, it shows it's nil
    }
}

extension DashboardVC : ReloadTheme {
    func reload() {
        applyTheme()
    }
}

So, the big picture is: when the user swipe right to hideMenu() (which is in ContainerVC, it somehow needs to access DashboardVC and call applyTheme()
Protocols/Delegates always confuse me, so a little bit of help is welcome.
Okay, so as requested, here's how the sidebarMenu is connected:
protocol SideBarDelegate: class {
      func showMenu()
      func hideMenu()
}
class DashboardVC: UIViewController {
   static weak var delegateSideBar: SideBarDelegate?

    @IBAction func sideMenuButtonPressed(_ sender: UIBarButtonItem) {
         Dashboard.delegateSideBar?.showMenu()
     }
}

And then in the ContainerVC :
class ContainerVC: UIViewController, SideBarDelegate {
  override func viewDidLoad() {
    super.viewDidLoad()
    DashboardVC.delegateSideBar = self
  }

 func hideMenu() {
    sideBarMenuLeadingConstraint.constant = -300
    dimView.isHidden = true
    applyTheme()
    animateConstraint()
  //  delegateReloadTheme?.reloadTheme()
}
func showMenu() {
    sideBarMenuLeadingConstraint.constant = 0
    dimView.isHidden = false
    applyTheme()
    animateConstraint()
}

func animateConstraint() {
    UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
    }
  }
}

And that's how the swipe menu works and it's connected.

A: You need to assign your delegate somewhere - it is optional type.
For instance, in viewDidLoad you can say item.delegateReloadTheme = self.
You need to show more code regarding DashboardVC.
Basically, when you create delegate, you are creating interface for the work that needs to be delegated, and you delegate it to other class. Because you can implement delegate almost anywhere in the code, you need to tell who is in charge of the implementing that delegate(interface).
for example:
protocol RefresherDelegate {
    func refreshUI()
}

Here we define what function(s) will be delegate.
class MyView : UIView {
    var delegate: RefresherDelegate?
}

Here, we create variable that will hold object that actually confroms RefresherDelegate.
class MyObject : RefresherDelegate {
    var myView = MyView()

Here you say that MyObject will implement RefresherDelegate and create simple MyView instance (won't show on UI, just simple example)
func assignDelegate() {
    myView.delegate = self
}

This is crucial part - assign delegate to implementation of it - in this case MyObject.
After assignDelegate(), when you actually call refreshUI() it will be get called in MyObject.


text:
Q: How can I filter products to show only those belonging to selected category in Django Admin? I am trying to filter the options shown in a foreignkey field within Django Admin inline. Using formfield_for_foreignkey I'm able to show products with category_id = 4 but instead of the 4 I would like to filter based in the category field in the inline. Using kwargs["queryset"] = Product.objects.filter(category=F('order_line__category')) does not get the category field value.
class Order_lineInline(admin.StackedInline):
    model = Order_line

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "product":
            kwargs["queryset"] = Product.objects.filter(category=4)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    class Category(models.Model):
        name = models.CharField(max_length=255)

    class Product(models.Model):
        part_number = models.CharField(max_length=255)
        category = models.ForeignKey('Category')
        price = models.DecimalField(max_digits=10, decimal_places=2)

    class Order(models.Model):
        customer = models.CharField(max_length=255)

    class Order_line(models.Model):
        order = models.ForeignKey('Order', on_delete=models.CASCADE)
        category = models.ForeignKey('Category', on_delete=models.CASCADE)
        product  = models.ForeignKey('Product', on_delete=models.CASCADE)
        price    = models.DecimalField(max_digits=10, decimal_places=2)

A: Maybe this is what you want:
Product.objects.filter(category__name='xxxxxx')


text:
Q: sed found lines with set articles (a, an, the) I should find lines with articles i set by myself. Search among first 10 lines.
sed -n '/the/p' file.txt | sed -n '/ a /p' file.txt

will show only output from the last command. Also
sed -n '1,10 /the/p' file

or
sed -n 1,10p '/the/p' file

dont work, i found usage of range only with patterns like
[range]/s/pattern/pattern/p

How can i combine several conditions and range of lines?
Example of file:
For the first time since early February
the top three films at the weekend
box office were all new releases
and leading the way was
Fox's Bohemian Rhapsody
with a $50 million
chart-topping performance
well above expectations.
That said, the weekend isn't all about
new releases as the holdovers

Output should be:
 For the first time since early February
 the top three films at the weekend
 and leading the way was
 with a $50 million
 That said, the weekend isn't all about
 new releases as the holdovers

A: *

*To get lines containing the
sed -n '1,10{/\<the\>/p}' file

*To get lines containing the or a or an
sed -n '1,10{/\<\(the\|a\|an\)\>/p}' file


text:
Q: Downgrade rails gem with Rubber I have a rails gem that I need to downgrade to an older version due to an issue with the newer version: aws-sdk
I've updated my local Gemfile and pushed to my git server to:
gem 'aws-sdk', '< 2.0'
Now, I need to get my production server updated with the downgraded gem, instead of the newer version that it currently has.
I tried cap deploy, but am getting this error:
 ** [out :: app01-myserver.com] You are trying to install in deployment mode after changing
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com] your Gemfile. Run `bundle install` elsewhere and add the
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com] updated Gemfile.lock to version control.
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com] You have added to the Gemfile:
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com] * aws-sdk (< 2.0)
 ** [out :: app01-myserver.com]
 ** [out :: app01-myserver.com] You have deleted from the Gemfile:
 ** [out :: app01-myserver.com] * aws-sdk

So, is there a cap or rubber command that I can run from the command line that will update the Gemfile?

A: As described in error message, you should add your Gemfile.lock to git. After it just run bundle update aws-sdk, commit changes in Gemfile.lock, push it and deploy to the production server using cap.


text: Q: How to download facebook user profile pic and upload it to my rails3 app I have tried to retrieve user profile pic from facebook using omniauth. But it is providing an auth_hash which has a link in form of http://graph.facebook.com/id/picture?type=normal. Please tell me how to download the image from the retrieved link and upload it to the signup page of my rails3 app.


text:
Q: Joining tables with different number of rows without duplicates I have an already complicated SQL statement that creates a table of users who have the rights CONNECT, APPUSER, or both:
(SELECT  b.grantee AS "Username", A.granted_role AS "Connect", b.granted_role AS "APPUSER" FROM
    (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'CONNECT')  A
    RIGHT OUTER JOIN
    (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'APPUSER') b
    ON A.grantee=b.grantee)
UNION
(SELECT  A.grantee, A.granted_role, b.granted_role FROM
    (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'CONNECT')  A
    LEFT OUTER JOIN
    (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'APPUSER') b
    ON A.grantee=b.grantee)

This produces something like:
Username        Connect        APPUSER
---------      ---------      ---------
Sue             CONNECT        APPUSER
Bob             (null)         APPUSER
Joe             CONNECT        (null)

I wish to use the all_users table, to also show users who have neither rights.  The all_users table shows every user in the database.
I have tried adding several types of joins to the end of my SQL statement to achieve this.  The closest I got was adding:
UNION
(SELECT username, NULL, NULL FROM all_users)

This would produce a list where each user is shown twice, but shows users without either right:
Username        Connect        APPUSER
---------      ---------      ---------
Amy             (null)         (null)
Sue             CONNECT        APPUSER
Sue             (null)         (null)
Bob             (null)         APPUSER
Bob             (null)         (null)
Joe             CONNECT        (null)
Joe             (null)         (null)

I tried adding a where username = a.grantee, but that won't work with Unions.  If I try replacing UNION with any JOINs, like adding:
FULL OUTER JOIN
SELECT username, NULL, NULL FROM ALL_USERS
on username = a.grantee;

I get the error:

"SQL command not properly ended"

A: Your query seems way more complicated than necessary.  Here is one approach:
select grantee,
       max(case when granted_role = 'CONNECT' then granted_role end) as "connect",
       max(case when granted_role = 'APPUSER' then granted_role end) as "appuser"
from dba_role_privs
group by grantee;

If there are users that have no roles at all, then you will need the all_users table.
EDIT:
Just use a left join:
select au.userName,
       max(case when granted_role = 'CONNECT' then granted_role end) as "connect",
       max(case when granted_role = 'APPUSER' then granted_role end) as "appuser"
from all_users au join
     dba_role_privs rp
     on au.userName = rp.grantee
group by au.userName;

A: I'm not quite sure I understand the first query. It seems like you're doing something really complex when you could use a PIVOT. However, if it's working right, then you should be able to just do:
SELECT username
FROM ALL_USERS
WHERE username NOT IN (
(SELECT DISTINCT b.grantee AS "Username", A.granted_role AS "Connect", b.granted_role AS "APPUSER" FROM
        (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'CONNECT')  A
        RIGHT OUTER JOIN
        (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'APPUSER') b
        ON A.grantee=b.grantee)
    UNION
    (SELECT  A.grantee, A.granted_role, b.granted_role FROM
        (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'CONNECT')  A
        LEFT OUTER JOIN
        (SELECT grantee, granted_role FROM dba_role_privs WHERE granted_role = 'APPUSER') b
        ON A.grantee=b.grantee)
)

A: use the below query. Let me know if this works. You need to add dp1.granted_role is null and dp2.granted_role is null at the where clause.
select     au.username,
           dp1.granted_role,
           dp2.granted_role

    from all_users au
    left join dba_role_privs drp1 on drp1.grantee=au.username and drp1.granted_role='CONNECT'
    left join dba_role_privs drp2 on drp2.grantee=au.username and drp2.granted_role='APPUSER'


text:
Q: WSO2 IS SCIM user schema extension. How to define and map multi-valued attributes We are using WSO2 IS 5.1 and I'd like to define multi-valued attribute:
....
{
"attributeURI":"urn:scim:schemas:extension:wso2:1.0:wso2Extension.vultPerson.mailAlternateAddress",
"attributeName":"mailAlternateAddress",
"dataType":"string",
"multiValued":"true",
"multiValuedAttributeChildName":"null",
"description":"Some attribute",
"schemaURI":"urn:scim:schemas:extension:wso2:1.0",
"readOnly":"false",
"required":"false",
"caseExact":"false",
"subAttributes":"null"
},
...

I mapped this attribute in urn:scim:schemas:core:1.0 dialect to LDAP (primary user store) atrribute mailAlternateAddress (my LDAP has this attribute in one of UserEntryObjectClass'es). I tried to provision user by SCIM API. User was created, all simple attributes from extension were created too, only mailAltrernateAddress not. I tried to send this attribute as:
....
"mailAlternateAddress": [
        {
          "type": "work",
          "value": "a.a"
        }
....

and as:
...
"mailAlternateAddress": ["a.a","b.b"]
...

I received good responses to SCIM requests.
I tried mappings:
urn:scim:schemas:extension:wso2:1.0:wso2Extension.vultPerson.mailAlternateAddress -> mailAlternateAddress
and
urn:scim:schemas:extension:wso2:1.0:wso2Extension.vultPerson.mailAlternateAddress.work -> mailAlternateAddtress

Both with the same result.
BTW, according to core SCIM schema, emails attribute is mapped to LDAP mail attribute (this mapping is in WSO2 IS destribution) but this mapping  doesn't work too, mail attribute isn't created.
What am I doing wrong?
One more question. Could I define canonical values for multi-valued attribute in scim-user-schema-extension?

A: The problem is in class
org.wso2.carbon.identity.scim.common.utils.AttributeMapper

There are strange limitations. At first I rewrote method getClaimsMap and now it works as expected.
I'm sorry for my English.


text:
Q: Open subset of the large plane which isn't formed from Borel sets Some background. I was looking for a product of two Borel $σ$-algebras which is not Borel. I know that the two topological spaces mustn't be second-countable. I then googled an example of such a space and found the long line on Wikipedia.
Now the problem. The large plane is the topological product of two long lines. The disjoint union of uncountably many unit squares, let's say
$$A:=\bigcup_{α∈ω_1} \bigl] (α,0),(α,1) \bigr[^2,$$
seems (until I'm proved wrong...) a reasonable bet for an open set which is not in the product of the Borel $σ$-algebra of the long line with itself. However, I'm still not able to prove it. Should I give up? Is my conjecture true?

A: I don't know if the product of two long lines works, but here is a somewhat simpler and more straightforward counterexample.
Let $X$ be any set whose cardinality is greater than that of the continuum (for example, the power set of $\mathbb R$). Endow it with the discrete topology. Let $D\equiv\{(x,x)\mid x\in X\}$ be the diagonal of $X\times X$. Then, $D$ is clopen (as is any subset of $X\times X$) in the product topology, so it lies in $\mathscr B_{X\times X}$ (which is, of course, the discrete $\sigma$-algebra on $X\times X$).
However, $D\notin\mathscr B_X\otimes\mathscr B_X$. If $D$ were in the product of the Borel $\sigma$-algebras, then there would exist a $\sigma$-subalgebra $\mathscr M\subseteq\mathscr B_X\otimes\mathscr B_X$ that is generated by a countable class of measurable rectangles and $D\in\mathscr M$. It follows that there exists a countably generated $\sigma$-subalgebra $\mathscr N\subseteq\mathscr B_X$ with $D\in\mathscr N\otimes\mathscr N$. Then, since $\{x\}$ is a coordinate projection of $D$ for every $x\in X$, one would have that $\{x\}\in\mathscr N$. This is impossible, given that $\mathscr N$ is countably generated, so that its cardinality cannot be greater than that of $\mathbb R$.
For more details, see Folland (1999), in particular: Exercise 7.29 (page 231), Exercise 1.5 (page 24), and Proposition 1.23 (page 40).


text:
Q: Laravel Rotating Eloquent Models I have a Laravel Project where I aggregate data on each 30m from different REST APIs and on the flow I build up the relational model based on the fetched Data. Before fetching the Data I clean up the main table and the related tables too. Sometimes this can take long till data is getting repopulated, up to 1-2m which would mean that I have a gap on production.
I'm searching for a workaround to keep the previously populated data live till the new data is getting aggregated and saved in the database.
Are there any good practices for this kind of Logic? Or the the idea behind is wrong

A: Why don't you put column like revision and instead of removing everything from tables you create new revision? Then app can display always latest revision and you can delete data after import is finished or at any time you want because when you finish import you will have new revision so app will automatically display newest revision data.


text:
Q: Writing a line in a file when finding a keyword I am trying to make a function which writes a line when it finds some text inside a file.
Example: it finds "hello" in a .txt file so then writes "Hi!" in the following line. There is something else, i want it to write "Hi!" not the first time it finds "hello" but the second.
Here is what i have been trying, but i don't know if the idea is right. Any help?
def line_replace(namefilein):
    print namefilein
    filein=open(namefilein, "rw")
    tag="intro"
    filein.read()
    for line in filein:
        if tag=="second" or tag=="coord":
            try:
                filein.write("\n\n %s" %(text-to-be-added))
                print line
            except:
                if tag=="coord":
                    tag="end"
                else:
                    tag="coord"

        if "           text-to-find" in line:
            if tag=="intro":
                tag="first"
            elif tag=="first":
                tag="second"
    filein.close()

A: You can use this code:
def line_replace(namefilein):

    new_content = ''
    first_time = False
    with open(namefilein, 'r') as f:
        for line in f:
            new_content += line
            if 'hello' in line:
                if first_time:
                    new_content += 'Hi!' + '\n'
                else:
                    first_time = True

    with open(namefilein, 'w') as f:
        f.write(new_content)

Look that I am using the with statement that in Python is a context manager, so it means, in this case, when the block of code has executed, then the file will be closed automatically.
Let's supposed you have a file my_file.txt which contents is:
hello
friend
this
is
hello

And let's say your file is in the same directory than the python file that has your code, so calling:
line_replace('my_file.txt')

will produce the following output:
hello
friend
hello
Hi!
is


text:
Q: How to get GesturDetector.onSingleTapConfirmed() return value inside onTouch method? I have the following code, which is just setting a onTouchListener with GestureDetector on a button.
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.btn);

    final GestureDetector gd = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return true;
        }
    });

    btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            boolean res = gd.onTouchEvent(event);
            Log.i("res", "res = " + res);
            return res;
        }
    });
}

}
However, the log shows that the res value is always false and never true, meaning that my onSingleTapConfirmed callback never pass its return value back to onTouch() method.  Any way to get onSingleTapConfirmed's return value inside onTouch method?


text:
Q: WebAPI 2 - CORS not working with contentType application/json I've got an Asp.net WebApi 2 project, with a Booking controller
If I try to post this from my client-side js:
$.ajax({
            url: 'http://localhost:57517/api/booking',
            type: 'POST',
            crossDomain:true,
            data: {AdultPaxCount:1},
            contentType: "application/json"
        });

I get a not-allowed error (and the Post action on my BookingController is not hit)
However;
If I remove the

contentType: "application/json"

section, it 'works' (it is sent to the controller)
Am I missing something in my setup?

A: With that content-type, the browser will preflight the request.  This means that the browser will send an OPTIONS request initially, and will only send the underlying request if your server responds appropriately to the preflight.  So, the error is caused by your server rejecting the preflight (OPTIONS) request.  You will either need to handle the preflight request server-side, or ensure the browser does not preflight the request by only sending a "simple" cross-origin request.  More in the preflighting section of the MDN article on CORS.

A: You can either add an Options method to your controller which always just returns without error, or add the
[HttpOptions]
[AcceptVerbs("POST", "OPTIONS")]

attributes to the PostXXX Method of your controller.

A: The only Content-type values that won't trigger a CORS preflight request are text/plain, multipart/form-data, application/x-www-form-urlencoded.


text:
Q: --with-arch-32 =? I tried to build the gcc 4.8 trunk on ubuntu 12.04 (64 bit).
When I use the configuration
../gcc-trunk/configure -v --with-pkgversion='ubuntu12.04-64' --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu

I get the following error:
In file included from /usr/include/fenv.h:58:0,
                 from ../../../../gcc-trunk/libquadmath/math/ccoshq.c:23:
../../../../gcc-trunk/libquadmath/math/ccoshq.c: In function 'ccoshq':
/usr/include/bits/fenv.h:116:4: error: impossible constraint in 'asm'
    __asm__ __volatile__ ("divss %0, %0 " : : "x" (__f));
    ^
/usr/include/bits/fenv.h:116:4: error: impossible constraint in 'asm'
    __asm__ __volatile__ ("divss %0, %0 " : : "x" (__f));

But after I delete "--with-arch-32=i686", things are alright.
My cpu is Intel(R) Core(TM)2 Quad CPU Q9400.
So, what should I use with the "--with-arch-32" option?
Thanks.

A: The constraint x means an SSE registter. The architecture i686 does not implement SSE insns. The oldest you can use is pentium3.
It depends on where do you intend to run the binaries, generated from this compiler. If it's only for your own use you can configure simply with core2.


text:
Q: Rails: Find or initialize and then merge in params I use find_or_initialize_by in my controller and then would like to apply the additional params to the record, whether new or existing.  Is this possible to do in a Railsy way or do I have to loop through the parameters?
def create
  re_evaluation = @client.re_evaluations.find_or_initialize_by(program_id: re_evaluation_params[:program_id], check_in_id: re_evaluation_params[:check_in_id])

  # apply remaining re_evaluation_params here

  if re_evaluation.save
    render json: re_evaluation, status: :created
  else
    render json: re_evaluation.errors.full_messages, status: :unprocessable_entity
  end
end

A: You should be able to assign the parameters as you'd do normally.
re_evaluation.assign_attributes(re_evaluation_params)

if re_evaluation.save
  ...


text:
Q: Is this the best way to script my Kantu macro? Using Kantu 2.5.2 on Chrome Version 64.0.3282.186
My script needs to do this for me:
1. Push the search button on the page
2. if something pops up, Click button A, B, then C.
It does this on a constant loop until A B and C pop up.
This is my script:

{
  "CreationDate": "2018-2-26",
  "Commands": [
    {
      "Command": "click",
      "Target": "id=btnSearchTrade",
      "Value": ""
    },
    {
      "Command": "waitForPageToLoad",
      "Target": "",
      "Value": ""
    },
    {
      "Command": "store",
      "Target": "true",
      "Value": "!Errorignore"
    },
    {
      "Command": "click",
      "Target": "id=UPDOWN1013612",
      "Value": ""
    },
    {
      "Command": "click",
      "Target": "id=btnCreatePickup",
      "Value": ""
    },
    {
      "Command": "click",
      "Target": "/html/body/div[8]/div[3]/div/button[1]/span",
      "Value": ""
    }
  ]
}

The problem:  Kantu gets very slow after it goes through this about 5 times.  It should only take about 2 seconds each step but ends up taking 30 seconds per step and just gets even more slow each time.
Is there a better way I can script this in Kantu?  I don't think I can use if/then logic with the free version.

A: Try update to the latest version.
You should be able to accomplish this with a combination of if/else, while and pause.


text:
Q: Error reading XML via JaxB This is my class structure:
@XmlRootElement(name="System")
public class SystemDTO () {

  @XmlElement(name="ID")
  public void setId(String id) {
      this.id = id;
  }

  @XmlElement(name="Source")
  public void setSource(SourceDTO source) {
      this.source = source;
  }
}

@XmlRootElement(name="Source")
class SourceDTO {
  @XmlElement(name="Name")
  public void setName(String name) {
      this.name = name;
  }
}

This is my XML File:
<System>
   <ID>e5b160d0</ID>
   <Source>
     <Name>Kron</Name>
   </Source>
</System>

The problem is the Source is always null.  I do not get a exception, it just comes out null.  I've attempted to use just the Source tag and it picks up Name just fine, but when I add it as part of the System class it does not seem to work.
Additionally I attempted to do this and have a string member variable in System for name:
@XmlElementWrapper(name="Source")
@XmlElement(name="Name")

But that causes an exception.  Any ideas?

A: The Test Class
    public class JaxbTest {
        public static void main(String[] args) {

            String xml = "<System>\n" +
                    "   <ID>e5b160d0</ID>\n" +
                    "   <Source>\n" +
                    "     <Name>Kron</Name>\n" +
                    "   </Source>\n" +
                    "</System>";
            SystemDTO systemDTO;
            try {

                JAXBContext jaxbContext = JAXBContext.newInstance(SystemDTO.class);

                StringReader reader = new StringReader(xml);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                systemDTO = (SystemDTO) jaxbUnmarshaller.unmarshal(reader);
                System.out.println(systemDTO.getSource().getName());

            } catch (JAXBException e) {
                e.printStackTrace();
            }
        }

    }

Source DTO
    @XmlRootElement(name = "Source")
    class SourceDTO {
        private String name = null;

        public String getName() {
            return name;
        }

        @XmlElement(name = "Name")
        public void setName(String name) {
            this.name = name;
        }

    }

System DTO
    @XmlRootElement(name = "System")
    public class SystemDTO {

        private String id;
        private SourceDTO source;

        public String getId() {
            return id;
        }

        public SourceDTO getSource() {
            return source;
        }

        @XmlElement(name = "ID")
        public void setId(String id) {
            this.id = id;
        }

        @XmlElement(name = "Source")
        public void setSource(SourceDTO source) {
            this.source = source;
        }

    }

A: One possible problem that I see is that you have declared 2 "Root" elements in your XML. Try @XmlType on your Source class:
    @XmlType(name="Source")
    class SourceDTO {
       ...
    }


text:
Q: MariaDB 10.1 JsonGet_string In one of our columns we store this example json string:
[{"Name":"Pay Amount","Value":"0.00"},{"Name":"Period","Value":"3"},{"Name":"Client","Value":"TestClient"},{"Name":"Our Reference","Value":""},{"Name":"Pay Type","Value":"Test"}]

We repeat the Names through out and the values will differ.
I've tried querying this data using JsonGet_string :
SELECT
    JSONGET_string(Header, "Name") Name
FROM tbl

but what it does it selects the first one i.e PayAmount and it only displays a list of payamount it doesn't select anything for Period, Client etc.
The result that it returns looks like this:
|  Name    |
|----------|
|          |
| PayAmount|
| PayAmount|

And it should return this:
|    Name     |
|-------------|
|             |
| PayAmount   |
| Period      |
| Client      |
| OutReference|
| Pay Type    |

Any ideas?


text:
Q: Get the http headers from current request in PHP Is it possible to get the http headers of the current request with PHP? I am not using Apache as the web-server, but using nginx.
I tried using getallheaders() but I am getting Call to undefined function getallheaders().

A: Taken from the documentation someone wrote a comment...
if (!function_exists('getallheaders'))
{
    function getallheaders()
    {
       $headers = array ();
       foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
           }
       }
       return $headers;
    }
}

A: This issue was finally addressed in PHP 7.3.0, check release notes.

Fixed bug #62596 (getallheaders() missing with PHP-FPM).

A: You can upgrade your server to PHP 5.4 thereby giving you access to getallheaders() via fastcgi or simply parse what you need out of $_SERVER with a foreach loop and a little regex.

A: Combined getallheaders() + apache_request_headers() for nginx
    function get_nginx_headers($function_name='getallheaders'){

        $all_headers=array();

        if(function_exists($function_name)){

            $all_headers=$function_name();
        }
        else{

            foreach($_SERVER as $name => $value){

                if(substr($name,0,5)=='HTTP_'){

                    $name=substr($name,5);
                    $name=str_replace('_',' ',$name);
                    $name=strtolower($name);
                    $name=ucwords($name);
                    $name=str_replace(' ', '-', $name);

                    $all_headers[$name] = $value;
                }
                elseif($function_name=='apache_request_headers'){

                    $all_headers[$name] = $value;
                }
            }
        }

        return $all_headers;
}

A: Improved @Layke his function, making it a bit more secure to use it:
if (!function_exists('getallheaders'))  {
    function getallheaders()
    {
        if (!is_array($_SERVER)) {
            return array();
        }

        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

(wished I could just add this as a comment to his answer but still building on that reputation thingy -- one of my first replies)

A: This should work:
<?php

print_r(
  array_intersect_key(
    $_SERVER,
    array_flip(
      preg_grep(
        '/^HTTP_/',
        array_keys($_SERVER),
        0
      )
    )
  )
);


text:
Q: Composer Install/Update stopped working Suddenly my Composer has stopped working.
Whenever I run composer update, it doesn't progress after this:

Loading composer repositories with package information
      Updating dependencies (including require-dev)

I tried another Laravel project, that project's Composer was working
I cleared the cache, and also ran this command rm -rf ~/.composer/cache
Nothing seems to happen. I moved composer.lock to a different folder, deleted from the current project and ran the commands again, but no luck
Here is my composer.json file:
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "nesbot/carbon": "~1.14",
        "venturecraft/revisionable": "~1.8",
        "doctrine/dbal": "v2.4.2",
        "zizaco/entrust": "dev-laravel-5",
        "aws/aws-sdk-php-laravel": "~3.0",
        "guzzlehttp/guzzle": "~5.2",
        "league/flysystem-aws-s3-v2": "~1.0",
        "sofa/revisionable": "~1.0@dev",
        "maatwebsite/excel": "~2.0.0",
        "monolog/monolog": "^1.15",
        "jenssegers/agent": "^2.2",
        "php-mime-mail-parser/php-mime-mail-parser": "^2.1",
        "messaged/php-mime-mail-parser": "^1.0",
        "willdurand/email-reply-parser": "^2.4",
        "barryvdh/laravel-debugbar": "~2.0.2"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "Validations\\": "app/Validations"
        },
        "files": [
            "app/Support/helpers.php"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php -r \"copy('.env.example', '.env');\"",
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

A: I made some Tests and it looks like these two packages in combination cause the problem:
"aws/aws-sdk-php-laravel": "~3.0",
"league/flysystem-aws-s3-v2": "~1.0",

They install properly each for itself but not together. I used a fresh Laravel 5.1 install for testing (composer create-project laravel/laravel --prefer-dist). After adding only these two packages to the composer.json Composer is stuck at

Updating dependencies (including require-dev)

If you remove one of them your composer update runs fine. I don't know anything about these two packages but the combination definitely crashes Composer even in -verbose mode.

The crashing composer.json as minimal example:
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "aws/aws-sdk-php-laravel": "~3.0",
        "league/flysystem-aws-s3-v2": "~1.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "Validations\\": "app/Validations"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}


text:
Q: Need help in $_GET I have a php page like this
if($_GET){
    if($_GET['name'] && $_GET['number']){
        $name = $_GET['name'];
        $number = (int) $_GET['number'];
        echo "Got it!";
    } else {
        echo "Please give input!";
    }
} else {
    echo "Please give input!";
}

Now it works fine when there is no input is given. But if i give one input like page.php?name=Something&number=0 it gives error Undefined index: number
And the value of number also can be 0.
This error doesn't look good. Now how can I get rid from this? Please help!

A: use isset to check
also check it explicitly like $_GET['name']!='' and dont print or store whatever you get from get and post etc.. if you are storing to database using mysli_real_escape_string.  and if you are outputting to browser use htmlspecialchars
    if(isset($_GET)){
        if(isset($_GET['name']) && $_GET['name']!='' && isset($_GET['number']) && $_GET['number']!=''){
            $name = $_GET['name'];
            $number = (int) $_GET['number'];
            echo "Got it!";
        } else {
            echo "Please give input!";
        }
    } else {
        echo "Please give input!";


text:
Q: grunt-contrib-cssmin: css source map appears empty in dev tools I am using grunt with cssmin to minify and concatenate css files.
Css files are well concatenated and minified but when I try to watch the non minified files in chrome dev tools under 'Sources' tab, files appears empty.
Here is my cssmin task:
cssmin: {
    options: {
        report: 'gzip',
        keepSpecialComments: 0,
        sourceMap: true,
        outputSourceFiles: true
    },
    target: {
        files: {
            'web/assets/dist/css/vendors.min.css': [
                'bower_components/bootstrap/dist/css/bootstrap.min.css',
                'bower_components/chosen/chosen.min.css',
                'bower_components/slabText/css/slabtext.css',
                'bower_components/video.js/dist/video-js.css',
                'bower_components/video.js/dist/video-js.css'
            ],
            'web/assets/dist/css/app.min.css': [
                'app/Resources/assets/css/jumbotron-narrow.css',
                'app/Resources/assets/css/custom.css',
            ],
        }
    }
},

Source map setting is enabled under chrome.
web/assets/dist/css/app.min.css.map looks like this:
{
    "version":3,
    "sources":["app/Resources/assets/css/jumbotron-narrow.css","app/Resources/assets/css/custom.css"],
    "names":[],
    "mappings":"AAeA,QAdA,KAeI,eAAgB,KADpB,QA6BA,WAEI,cAAe,IAAI,MAAM,QA7C7B,KACI,YAAa,KCUb,YAAa,eAAkB,WDHnC,QAFA,QACA,WAEI,cAAe,KACf,aAAc,KASlB,WACI,WAAY,EACZ,cAAe,EACf,YAAa,KAIjB,QACI,YAAa,KACb,MAAO,KACP,WAAY,IAAI,MAAM,QAI1B,yBACI,WACI,UAAW,OAGnB,qBACI,OAAQ,KAAK,EAIjB,WACI,WAAY,OAGhB,gBACI,QAAS,KAAK,KACd,UAAW,KAIf,WACI,OAAQ,KAAK,EAEjB,gBACI,WAAY,KAIhB,oCAII,QAFA,QACA,WAEI,cAAe,EACf,aAAc,EAGlB,QACI,cAAe,KAGnB,WACI,cAAe,GC3EvB,WACI,YAAa,eACb,IAAK,iCAAkC,mBAG3C,WACI,YAAa,YACb,IAAK,8BAA+B,mBAOxC,GACI,WAAY,KACZ,eAAgB,UAChB,YAAa,EACb,YAAa,YAAe,WAC5B,YAAa,EAAI,EAAI,IAAI,KAG7B,4BACI,QAAS,MACT,YAAa,KACb,aAAc,KACd,cAAe,IAGnB,UACI,UAAW,MACX,WAAY,KAIhB,oBACI,MAAO,IAGX,sBACI,gBAAiB,KACjB,YAAa,EAGjB,cACI,aAAc,QAIlB,iCACI,QAAS"
 }

Version from my package.json:
 "grunt-contrib-cssmin": "^0.12.0",

What am I doing wrong?

A: Edit: Firstly, try specifying a root in your options of the Gruntfile.js as follows:
// ...
cssmin: {
  options: {
    // ...
    root: 'web/assets/dist/css/' // <-- Add this too.
  },
  target: {
    // ...
  }
  /...

The Issue
The sourceMap file that grunt-contrib-cssmin is generating is incorrectly specifying the paths in the sources Array. The resultant sourceMap should be as follows:
app.min.css.map
{
  "version":3,
  "sources":[
    "../../../../app/Resources/assets/css/jumbotron-narrow.css",
    "../../../../app/Resources/assets/css/custom.css"
  ],
  "names":[],
  "mappings":"AAeA,QAdA,KAeI,eAAgB,KADpB,QA6BA,WAEI,cAAe,IAAI,MAAM,QA7C7B,KACI,YAAa,KCUb,YAAa,eAAkB,WDHnC,QAFA,QACA,WAEI,cAAe,KACf,aAAc,KASlB,WACI,WAAY,EACZ,cAAe,EACf,YAAa,KAIjB,QACI,YAAa,KACb,MAAO,KACP,WAAY,IAAI,MAAM,QAI1B,yBACI,WACI,UAAW,OAGnB,qBACI,OAAQ,KAAK,EAIjB,WACI,WAAY,OAGhB,gBACI,QAAS,KAAK,KACd,UAAW,KAIf,WACI,OAAQ,KAAK,EAEjB,gBACI,WAAY,KAIhB,oCAII,QAFA,QACA,WAEI,cAAe,EACf,aAAc,EAGlB,QACI,cAAe,KAGnB,WACI,cAAe,GC3EvB,WACI,YAAa,eACb,IAAK,iCAAkC,mBAG3C,WACI,YAAa,YACb,IAAK,8BAA+B,mBAOxC,GACI,WAAY,KACZ,eAAgB,UAChB,YAAa,EACb,YAAa,YAAe,WAC5B,YAAa,EAAI,EAAI,IAAI,KAG7B,4BACI,QAAS,MACT,YAAa,KACb,aAAc,KACd,cAAe,IAGnB,UACI,UAAW,MACX,WAAY,KAIhB,oBACI,MAAO,IAGX,sBACI,gBAAiB,KACjB,YAAa,EAGjB,cACI,aAAc,QAIlB,iCACI,QAAS"
}

Note the sourceRoot prefixes ../../../../ added to each path in the sources Array.
In the SourceMap Specification a section reads:

Resolving Sources
If the sources are not absolute URLs after prepending of the "sourceRoot", the sources are resolved relative to the SourceMap (like resolving script src in a html document).

If specifying a root path, (as initially mentioned), does not resolve the issue then it indicates that this part of the specification is not being honoured by grunt-contrib-cssmin.

Alternate Solution
If the initial suggested fix does not work then consider adding a custom Task to invoke a Function which fixes each sources path after the sourceMap(s) have been created by grunt-contrib-cssmin.
You could do something like this:
Gruntfile.js
module.exports = function (grunt) {

  grunt.initConfig( {
    cssmin: {
      options: {
        report: 'gzip',
        keepSpecialComments: 0,
        sourceMap: true,
        outputSourceFiles: true
      },
      target: {
        files: {
          'web/assets/dist/css/vendors.min.css': [
            'bower_components/bootstrap/dist/css/bootstrap.min.css',
            'bower_components/chosen/chosen.min.css',
            'bower_components/slabText/css/slabtext.css',
            'bower_components/video.js/dist/video-js.css'
          ],
          'web/assets/dist/css/app.min.css': [
            'app/Resources/assets/css/jumbotron-narrow.css',
            'app/Resources/assets/css/custom.css'
          ]
        }
      }
    }
  });

  /**
   * Helper function prefixes sources paths in sourceMap files with a sourceRoot.
   *
   * `grunt-contrib-cssmin` does not apply the correct sourceRoot for each
   * path in the `sources` Array. See github issue #248 for further info:
   * (https://github.com/gruntjs/grunt-contrib-cssmin/issues/248)
   *
   * @param {String} filePath - The path to the sourceMap to fix.
   * @param {String} sourceRootPrefix - The sourceRoot prefix e.g. ../../
   */
  function prefixSourceMap(filePath, sourceRootPrefix) {
    var json = grunt.file.readJSON(filePath);
    json.sources = json.sources.map(function (_path) {
      return sourceRootPrefix + _path;
    });
    grunt.file.write(filePath, JSON.stringify(json));
  }

  // Register Task to invoke function for fixing paths in each sourceMap file.
  grunt.registerTask('fixSourceMaps', 'Fix paths in each sourceMap', function () {
    prefixSourceMap('web/assets/dist/css/vendors.min.css.map', '../../../../');
    prefixSourceMap('web/assets/dist/css/app.min.css.map', '../../../../');
  });

  grunt.loadNpmTasks('grunt-contrib-cssmin');

  grunt.registerTask("default", [
    'cssmin',
    'fixSourceMaps' // <-- Must be after cssmin tasks.
  ]);
};

Notes

*

*The the custom grunt.registertask named fixSourceMaps invokes the prefixSourceMap function for each sourceMap file to fix.

*Two arguments are passed to the prefixSourceMap function, namely:

*

*filePath - The path to the sourceMap to fix.

*sourceRootPrefix - The sourceRoot prefix e.g. ../../

*For fixing both sourceMap files (vendors.min.css.map and app.min.css.map) the sourceRootPrefix argument is specified as ../../../../ - This is specified as four levels due to the relationship between the resultant .min.css file and it's location to the original unminified source .css file within your directory structure.
If you were to add another set of .css files to minify to your cssmin.target.files Task, in which the relationship between the resultant .min.css file and the unminified source .css file was not four levels, you will need to specify a different sourceRootPrefix value.
For example, lets say in cssmin.target.files the following css is to be minified:
// ...
target: {
  files: {
    //...
    'web/assets/quux.min.css': [ // <-- Two levels deep
      'path/to/file/foo.css',
      'path/to/file/baz.css'
    ],
    // ...
  }
}
// ...

As the resultant quux.min.css is saved in the directory two levels deep then the sourceRootPrefix argument is passed to the prefixSoureMap functions as '../../'. For example:
//...
grunt.registerTask('fixSourceMaps', 'Fix paths in each sourceMap', function () {
  prefixSourceMap('web/assets/quux.min.css.map', '../../');
  //...
});
//...

A: as explained in comment above, there was 2 issues in my Gruntfile :

*

*missing root directive as explained by @RobC

*original assets were not accessible by the webserver, so I moved them in a location under the web root  of my virtualhost. In my case web/assets. Here is my cssmin task that is now working:
cssmin: {
    options: {
        root: 'web/assets/dist/css/',
        report: 'gzip',
        keepSpecialComments: 0,
        sourceMap: true,
        outputSourceFiles: true
    },
    target: {
        files: {
            'web/assets/dist/css/app.min.css': [
                'web/assets/css/jumbotron-narrow.css',
                'web/assets/css/custom.css',
            ],
        }
    }
},


text:
Q: Swift: Checking UIImage failable init I want to check if an image exists, but in the failable init... I can do it ugly, but really I want to know if self == nil is possible...
extension UIImage {

    convenience init?(_ name:String) {
        let image = UIImage(named:name)
        guard image != nil else { Assert("image \(name) missing yo"); return nil }
        self.init(named: name)
    }
}

cleaner but doesn't compile
extension UIImage {

    convenience init?(_ name:String) {
        self.init(named: name)
        if self == nil { Assert("image \(name) missing yo") }
    }
}

static func isn't as fun as init
extension UIImage {

   static func with(_ name:String) -> UIImage? {
        let image = UIImage(named:name)
        if image == nil { Assert("image \(name) missing yo") }
        return image
   }
}

Thanks in advance for your time
** EDIT **
perhaps I need both?
extension UIImage {
    convenience init?(_ name:String) {
        self.init(named:name)
   }
}

extension Optional where Wrapped == UIImage {
    init?(_ name:String) {
        self.init(name)
        if self == nil {
            Assert("image \(name) missing yo")
        }
   }
}

A: I am not 100% sure if i get your question correct. But i think you want something like that: (let me know if it helps or why not)
extension Optional where Wrapped == UIImage {

    init?(_ name:String) {
        self.init(name)
        if self == nil {
            Assert("image \(name) missing yo")
        }
    }
}


text:
Q: installing vlc-tar.bz2 and gcc.tar I need to install vlc player in fedora which is a tar.bz2 file. How can i install it ?
Someone told me that gcc is needed to install this software. How do install gcc-4.6.2.tar ?
Please list the steps needed to install vlc.tar.bz2 and also gcc.tar .

A: gcc can be installed via the yum package manager, which handles all the software management in the system. Try:
yum install gcc

or
yum search gcc

But you should always try to go with a premade package; for VLC you can get it by adding the RPM Fusion repository. The instructions for configuring it are available on their configuration page.

A: Never install anything from sources, if you don't know how to do it. Use package for your distro and version and package-manager of your system


text:
Q: Interpreting scipy.stats: ks_2samp and mannwhitneyu give conflicting results I've encountered conflicting results between ks_2samp and mannwhitneyu while trying to compare two empirical distributions, particularly when specifying the "alternative" keyword argument. Per their respective docstrings, my understanding is that both share the same definition of alternative hypothesis. For example, given two samples X and Y, alternative='greater' denotes the alternative hypothesis that X is greater than Y, and the returned p-value represents the likelihood of the resultant test statistic if both distributions were the same. Unless I'm misunderstanding something, the toy example below suggests this definition is reversed for the mannwhitneyu test.
Generating two different samples:
import numpy as np

N = 100000
x = np.exp(np.random.normal(np.log(1), size=N))
y = np.exp(np.random.normal(np.log(3), size=N))

Sample distributions
Running the two tests:
from scipy.stats import ks_2samp, mannwhitneyu

print(ks_2samp(x, y, alternative='greater'))
print(mannwhitneyu(x, y, alternative='greater'))

Yields:

Ks_2sampResult(statistic=0.41866, pvalue=0.0)
MannwhitneyuResult(statistic=2188790813.0, pvalue=1.0)

And the opposite:
print(ks_2samp(x, y, alternative='less'))
print(mannwhitneyu(x, y, alternative='less'))

Yields:

Ks_2sampResult(statistic=-0.0, pvalue=1.0)
MannwhitneyuResult(statistic=2188790813.0, pvalue=0.0)

Given the wisespread usage of these functions I assume this comes down to my own misunderstanding. If someone could help clarify why they results are reversed I would very much appreciate it. Thank you!

A: The KS test will (assuming less) test for the $H_1$ that the CDF of x lies below that of y. On the other hand, the MW  (assuming less) will test for the $H_1$ that the location shift is less than 0. The results reported are perfectly aligned with that as they indeed suggest that "$x$ is smaller than $y$". The KS fails to reject its null hypothesis in favour of the alternative that the CDF of x lies below that of y, while MW does reject it in favour of the alternative that x is shifted to the left of y.


text:
Q: lateinit property ApplicationContext has not been initialized Hello I relatively new to the programming world and I'm having a problem with my project.
I have a simple counter that counts how many birds you saw and then changes the color of the TextView (that displays counter) depending on what button you pressed.
I'm using viewModel with live data and data binding for this and it works. Now when I try to add Shared Preferences to store my data so that they can survive application being shut down. When I try to use 'userDataProvider' I get a error that I dont know how to fix.
//Error
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property ApplicationContext has not been initialized
at com.example.lv4_birdscounter.BirdsCounterApp$Companion.getApplicationContext(BirdsCounterApp.kt:11)
at com.example.lv4_birdscounter.PrefsManager.setCounter(PrefsManager.kt:53)
at com.example.lv4_birdscounter.PrefsManager.setBirdCounter(PrefsManager.kt:19)
at com.example.lv4_birdscounter.BirdsCounter.onCreate(BirdsCounter.kt:52)
//BirdsCounter.kt
package com.example.lv4_birdscounter

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.lv4_birdscounter.databinding.ActivityMainBinding

class BirdsCounter : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    lateinit var viewModel: BirdsCounterViewModel

    private val userDataProvider: UserDataProvider by lazy { PrefsManager }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(this).get(BirdsCounterViewModel::class.java)

        binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).apply {
            this.setLifecycleOwner(this@BirdsCounter)
            this.viewmodel=viewModel
        }

        viewModel.birdsSeen.observe(this, Observer {
            //display new data
            binding.tvCounter.text = it.toString()
        })

        viewModel.birdsColor.observe(this, Observer {
            //display new data
            binding.tvCounter.setBackgroundColor(Color.parseColor(it))

            //Make number more visible by changing the colour of the text
            when(it){
                viewModel.GREEN -> binding.tvCounter.setTextColor(Color.BLACK)
                viewModel.WHITE -> binding.tvCounter.setTextColor(Color.BLACK)
                else -> binding.tvCounter.setTextColor(Color.WHITE)
            }
        })

        //Crashes
        userDataProvider.birdCounter = 5

        setContentView(binding.root)
    }

}

//BirdsCounterApp.kt
codpackage com.example.lv4_birdscounter

import android.app.Application
import android.content.Context

class BirdsCounterApp : Application(){

    companion object {
        lateinit var ApplicationContext: Context
    }

    override fun onCreate() {
    super.onCreate()
    ApplicationContext = this
    }

}

//PrefsManager.kt
    package com.example.lv4_birdscounter

import android.content.Context

interface UserDataProvider{
    var birdCounter: Int
    var tvColor: String
}

object PrefsManager: UserDataProvider{

    private val PREFS_FILE = "preferences"
    private val COUNTER_ID = "counter_id"
    private val COLOR_ID = "color_id"

    override var birdCounter: Int
        get() = getCounter()
        set(value) = setCounter(value)

    override var tvColor: String
        get() = getColor()
        set(value) = setColor(value)

    //for color
    private fun getColor(): String {
        return BirdsCounterApp.ApplicationContext.getSharedPreferences(
                PREFS_FILE,
                Context.MODE_PRIVATE
        ).getString(COLOR_ID, "#4A6572")?: "#4A6572"
    }

    private fun setColor(value: String){
        BirdsCounterApp.ApplicationContext.getSharedPreferences(
                PREFS_FILE,
                Context.MODE_PRIVATE)
                .edit()
                .putString(COLOR_ID, value)
                .apply()
    }

    //for counter
    private fun getCounter(): Int {
        return BirdsCounterApp.ApplicationContext.getSharedPreferences(
                PREFS_FILE,
                Context.MODE_PRIVATE
        ).getInt(COUNTER_ID, 0)?:0
    }

    private fun setCounter(value: Int){
        BirdsCounterApp.ApplicationContext.getSharedPreferences(
                PREFS_FILE,
                Context.MODE_PRIVATE)
                .edit() // dobivamo Editor instancu koja se koristi za izmjenu SharedPreferences-a
                .putInt(COUNTER_ID, value)
                .apply() // pohranjujemo promjene
    }
}

//BirdsCounterViewModel
    package com.example.lv4_birdscounter

import android.graphics.Color
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class BirdsCounterViewModel() : ViewModel() {

    val RED = "#D82929"
    val BLUE = "#2121E1"
    val WHITE = "#FFFFFFFF"
    val GREEN = "#2DF62D"
    val LIGHT_GRAY = "#4A6572"

    private val _birdsSeen: MutableLiveData<Int> = MutableLiveData<Int>(0)
    val birdsSeen: LiveData<Int> = _birdsSeen

    private val _birdsColor: MutableLiveData<String> = MutableLiveData<String>("#4A6572")
    val birdsColor: LiveData<String> = _birdsColor

    fun onButtonPressed(color: String){
        _birdsSeen.value?.let { _birdsSeen.postValue(it + 1) }
        _birdsColor.value?.let { _birdsColor.postValue(color) }
    }

    fun onResetButtonPressed(){
        _birdsSeen.value?.let { _birdsSeen.postValue(0) }
        _birdsColor.value?.let { _birdsColor.postValue(LIGHT_GRAY) }
    }

}

//mainActivity XML
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewmodel"
            type="com.example.lv4_birdscounter.BirdsCounterViewModel" />

    </data>
    <androidx.constraintlayout.widget.ConstraintLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/dark_gray"
        tools:context=".BirdsCounter">

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guide_vertical_center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <TextView
            android:id="@+id/tvCounter"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/tvMargin"
            android:background="@color/light_gray"
            android:textAlignment="center"
            android:textColor="@color/white"

            android:textSize="@dimen/tvTextSize"
            app:layout_constraintLeft_toLeftOf="parent"

            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="@string/tvCounterDefaultValue" />

        <Button
            android:id="@+id/btnRed"
            android:layout_width="0dp"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/btnMargin"
            android:backgroundTint="@color/red"
            android:text="@string/btnRedText"

            android:textColor="@color/white"
            app:layout_constraintEnd_toStartOf="@id/guide_vertical_center"

            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tvCounter"
            app:strokeColor="@color/black"

            app:strokeWidth="@dimen/btnStrokeWidth"
            android:onClick="@{()->viewmodel.onButtonPressed(viewmodel.RED)}"/>

        <Button
            android:id="@+id/btnBlue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/btnMargin"
            android:backgroundTint="@color/blue"
            android:text="@string/btnBlueText"

            android:textColor="@color/white"
            app:layout_constraintEnd_toEndOf="parent"

            app:layout_constraintStart_toStartOf="@id/guide_vertical_center"
            app:layout_constraintTop_toBottomOf="@id/tvCounter"
            app:strokeColor="@color/black"

            app:strokeWidth="@dimen/btnStrokeWidth"
            android:onClick="@{()->viewmodel.onButtonPressed(viewmodel.BLUE)}"/>

        <Button
            android:id="@+id/btnWhite"
            android:layout_width="0dp"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/btnMargin"
            android:backgroundTint="@color/white"
            android:text="@string/btnWhiteText"

            android:textColor="@color/black"
            app:layout_constraintEnd_toStartOf="@id/guide_vertical_center"

            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btnRed"
            app:strokeColor="@color/black"

            app:strokeWidth="@dimen/btnStrokeWidth"
            android:onClick="@{()->viewmodel.onButtonPressed(viewmodel.WHITE)}"/>

        <Button
            android:id="@+id/btnGreen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/btnMargin"
            android:backgroundTint="@color/green"
            android:text="@string/btnGreenText"

            android:textColor="@color/black"
            app:layout_constraintEnd_toEndOf="parent"

            app:layout_constraintStart_toStartOf="@id/guide_vertical_center"
            app:layout_constraintTop_toBottomOf="@id/btnBlue"
            app:strokeColor="@color/black"

            app:strokeWidth="@dimen/btnStrokeWidth"
            android:onClick="@{()->viewmodel.onButtonPressed(viewmodel.GREEN)}"/>

        <Button
            android:id="@+id/btnReset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="@color/black"
            android:text="@string/btnResetText"

            android:textColor="@color/white"

            app:layout_constraintLeft_toLeftOf="@id/guide_vertical_center"
            app:layout_constraintRight_toRightOf="@id/guide_vertical_center"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btnWhite"

            android:onClick="@{()->viewmodel.onResetButtonPressed()}"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

A: You do not need to initialise the ApplicationContext in your application class. Android will provide it for you. You just need to access it from where ever you need. ApplicationContext is basically an instance that is singleton and can be accessed in activity via getApplicationContext(). This context is tied to the lifecycle of an application.
And rather than accessing the application context via companion object. Inject the context to the respective file where it needs to be used via constructor and use that instance. You can also use dependency injection libraries like Dagger to help you inject dependencies.
You could do something like PrefsManager constructor (val context:Context)
to do constructor injection of context manually from your birds counter activity into PrefsManager and then use that context to save to sharedpreferences