text:
Q: Serial readBytes - Arduino Loop I have a loop that reads the serial port for 1 byte. When it finds a valid byte it calls other functions.
This works but it also seems to run the else statement as well.
void loop() {
byte rx_byte[1];
byte input[2];

if (a_Serial.available() > 0) {
    a_Serial.readBytes(rx_byte,1);

    debug_Serial.println(rx_byte[0],HEX);

    if (rx_byte[0] == 0xaa){

             debug_Serial.println("aa Running");

            }

    if (rx_byte[0] == 0xbb){
            debug_Serial.println("bb Running");

            }

    if (rx_byte[0] == 0xcc){
              a_Serial.readBytes(input,2);
              rawcmd(input);

              }

    else {
      a_Serial.println("Error");
      debug_Serial.println("Command Invalid");}

     memset(rx_byte, 0, sizeof(rx_byte));

A: Use else if instead of if. If your rx_byte[0] isn't equal to 0xcc then it can also be 0xaa or 0xbb.
if (rx_byte[0] == 0xaa){

         debug_Serial.println("aa Running");

        }

else if (rx_byte[0] == 0xbb){
        debug_Serial.println("bb Running");

        }

else if (rx_byte[0] == 0xcc){
          a_Serial.readBytes(input,2);
          rawcmd(input);

          }

else {
...


text:
Q: Applying three different background colors to three divs with the same class using LESS HI I am completely new to LESS.I need to do the following task,
Applying three different background colors to three divs with the same class using LESS

A: Check out CSS's sibling selectors. https://www.w3schools.com/css/css_combinators.asp
Note that this is a general CSS feature, not something specific to LESS

redpajama_set_name: RedPajamaStackExchange


text:
Q: footer overlap content when break page. how to fix it? When I print html, the content is overwritten by the footer and I print it on firefox 42
image description here

 this is my css

@media print {
    table {
        page-break-inside:auto
    }
    tr {
        page-break-inside:avoid;
        page-break-after:auto;
    }
    .header-TQ {
        position: fixed;
        left: 0;
        right: 0;
        margin-top: -15px;
    }
    .content-TQ {
        text-align: center;
        margin-top: -5px;
        padding-bottom: 20px;
        line-height: 1.42857 !important;
        position: relative;
        top: 65px;
  }


text:
Q: Taskkill a Process present in a specific path using WMIC and a Environment Variable I am trying to close an exe process located in a specific directory, using the %appdata% variable, but it doesn't work.
WMIC Process Where "ExecutablePath='%APPDATA%\\Adobe\\screenrecorder.exe'" Call Terminate

If I try to close the process without %appdata% it works as intended.
WMIC Process Where "ExecutablePath='C:\\Users\\Admin\\AppData\\Roaming\\Adobe\\screenrecorder.exe'" Call Terminate

It is essential that it must work using %appdata%, does someone know how to close an exe file using %appdata%?

A: With a Batch file ,you can try like this way :
@echo off
Title Kill Application using WMIC
Set Application=%AppData%\Adobe\screenrecorder.exe
Call :Add_backSlash %Application%
echo %Application%
pause
WMIC Process Where "ExecutablePath='%Application%'" Call Terminate
pause
EXIT
::---------------------------------------------------------------------
:Add_backSlash <String>
Rem Subroutine to replace the simple "\" by a double "\\" into a String
Set "Application=%1"
Set "String=\"
Set "NewString=\\"
Call Set "Application=%%Application:%String%=%NewString%%%"
Exit /b
::---------------------------------------------------------------------

A: You should have noted that backward slashes in a path require escaping in the WHERE clause of WMIC, so you simply need to expand the environment variable, and substitute the backward slashes for escaped backward slashes. The general method of doing that is %VariableName:CharToSubstitute=SustitutionChars%
WMIC Process Where "ExecutablePath='%AppData:\=\\%\\Adobe\\screenrecorder.exe'" Call Terminate

Or more robustly
%SystemRoot%\System32\wbem\WMIC.exe Process Where "ExecutablePath='%AppData:\=\\%\\Adobe\\screenrecorder.exe'" Call Terminate


text:
Q: C# XDocument stuck in memory Basically, I'm reading multiple xml files, recovering some items from it then next file, until all files are done and then I do my thing on collected items.
Problem is each file is ~50mb and I may have up to 70 to take on a single operation, plus on every loop memory usage (in visual studio's inspector) bumps ~180mb (around 800mb RAM usage for 5 files) so I might never have enough RAM to handle it, memory exceeded errors and all that...
I thought of using a yield return to work on every item as it appears but I need to get them all sorted before working on it.
Here is some sample code if it helps, tried setting my doc to null as found on some answers on SO but to no success...
class MyClass
{
    List<string> sourceFiles // All my XML input files
    List<XElement> listItem  // items to get from XML files

    /...

    static void FillListItem()
    {
        bool found = false;
        foreach (var sourceFile in sourceFiles)
        {
            XDocument xdoc = XDocument.Load(sourceFile);
            foreach (var inventory in xdoc.Descendants("INVENTORY"))
            {
                if (/*Checks if current item is valid*/)
                {
                    try
                    {
                        //...
                        listItems.Add(inventory);
                        found = true;
                    }
                    catch (Exception e)
                    {
                        Logs.LogReject(Filenames.rejectInvalid, inventory, e);
                        continue;
                    }
                }
                else Logs.LogReject(Filenames.rejectConfig, inventory);
            }
            xdoc = null; //doesn't seem to change anything...
            if (!found)
                Logs.LogInfo("No corresponding field in " + sourceFile);
        }
    }
}


text:
Q: php function that has a definable function when called How do I compose a function with a section that is able to be defined when the function is called?
<?php
class MyClass {
        function doSomething() {
        $conn = $this->connectToDatabase("database");
        $rows = $conn->query($query);

        if ($rows->num_rows > 0) {
            while($row = $rows->fetch_assoc()) {
                $col_value = $row['name'];
                function defineMe() {
                   //i need to be defined when called
                }
}
        } else {
            echo "0 results";
        }

        $conn->close();
    }
}
?>

That way, say I wanted to pull data from a database, I can change defineMe() to match the layout of the info that its spitting out.  How can I override this function and still access the data from the doSomething() function?
Like
$myClass = new MyClass;
$myClass->doSomething(){
    function defineMe() {
       echo $col_value;
    }
};

A: You can just pass a callback to your function:
<?php
class MyClass
{
    function doSomething(callable $callback)
    {
        $conn = $this->connectToDatabase("database");
        $rows = $conn->query($query);

        if ($rows->num_rows > 0)
        {
            while($row = $rows->fetch_assoc())
            {
                $col_value = $row['name'];
                $callback($col_value);      // Call callback
            }
        } else {
            echo "0 results";
        }

        $conn->close();
    }
}

$myClass = new MyClass;
$myClass->doSomething(function($col_value) {
    echo "Inside callback: ".$col_value;
});
?>


text:
Q: How to write to local JSON file using jQuery Please note; everything I'm doing here is local.
I've been looking for and testing ways to write to a JSON from a JS file using jQuery. I've found ways that use PHP, but I'm not fluent in PHP and would rather stay away from it for now.
Is there any function in jQuery, or JavaScript, that can let me easily write to JSON files?
Thanks in advance,
Benjamin.

A: If you are going with browser then it will not work in any way. If you are using nodejs on local system then you can do it with nodejs. With only remote side script it is not possible. With javascript running in browser you can only perform browser based task.


text:
Q: Can't find the "app.js" file when attempting to work on a project with React Native I am trying to start working in React Native.
After having the device connected by the expo app, it says in the "Getting Started" site:

"Now that you have successfully run the app, let's modify it. Open App.js in your text editor of choice and edit some lines."

I downloaded Sublime Text 3, but I don't see there any app.js file.
Is that a file that i should create somewhere or is it suppose to be in the code editor? How do I get it connected with React Native?

A: Checking the tutorial you mention it states this command should be run:
expo init AwesomeProject

If so, then I believe that app.js file should be in that directory. Just open it up like any other file and you should be good to go!


text:
Q: javascript warning message for value field I want to make a javascript that will show a warning message for some specific words from a textfield. I mean if a user write http:// and / in a textfield and click on the Submit button of my form then a javascript will show a error message to the user. So how I can do it for this textfield:
<input type="text" name="attn" size="35" />

How I should edit it?

A: Give the input some id
Then you could do:
var the_input = document.getElementById('inputID');
the_input.onkeyup = function(){
    if(the_input.value == 'http://' || the_input.value.indexOf('http://') > 0) {
       alert('AHHH!');
       the_input.value = '';
    }
}

Demo: http://jsfiddle.net/maniator/rdZAZ/
Try typing http:// into the input.

A: When the user submits the form, you could perform the following:
//Grab the value of your textbox
var textValue = document.getElementsByName("myInput").value;

//Checks if the textbox contains 'http://' or '/'
if(textValue.indexOf('http://') || textValue.indexOf('/'))
{
    alert("Please check your input and try again...");
    return false;
}


text:
Q: Pass a table and return a table to a stored procedure or function? I would like to pass a table to either a UDF or stored procedure and then have it process the data and return the sensitivity, specificity and 95% Upper/Lower Confidence Intervals (for each) from the table I pass to it.
Basically, from a table I need to calculate and return six values.
I have to do this a bunch of times so automation would be awesome but I have not created a UDF or SP.  I have read up on them (stackoverflow and elsewhere but am stuck on how to proceed.
I created the SQL part to calculate the parameters of interest but I am really befuddled on how to pass a table to it and get a table back out.
DECLARE @R_MODS TABLE(
  SUBJECTID varchar(max),
  ResultCall varchar(max)
)

INSERT INTO @R_MODS VALUES ('11-0001','TP');
INSERT INTO @R_MODS VALUES ('11-0002','TP');
INSERT INTO @R_MODS VALUES ('11-0003','TP');
INSERT INTO @R_MODS VALUES ('11-0004','TP');
INSERT INTO @R_MODS VALUES ('11-0005','TP');
INSERT INTO @R_MODS VALUES ('11-0006','I');
INSERT INTO @R_MODS VALUES ('11-0007','TP');
INSERT INTO @R_MODS VALUES ('11-0008','TP');
INSERT INTO @R_MODS VALUES ('11-0009','I');
INSERT INTO @R_MODS VALUES ('11-0010','TP');
INSERT INTO @R_MODS VALUES ('11-0011','TP');
INSERT INTO @R_MODS VALUES ('11-0012','TN');
INSERT INTO @R_MODS VALUES ('11-0013','TP');
INSERT INTO @R_MODS VALUES ('11-0014','I');
INSERT INTO @R_MODS VALUES ('11-0015','TP');
INSERT INTO @R_MODS VALUES ('11-0016','TP');
INSERT INTO @R_MODS VALUES ('11-0017','TN');
INSERT INTO @R_MODS VALUES ('11-0018','TP');
INSERT INTO @R_MODS VALUES ('11-0019','FP');
INSERT INTO @R_MODS VALUES ('11-0020','FP');

DECLARE @TP float, @TN float, @FP float, @FN float, @SEN float, @SPE float, @M1 float,
        @M2 float, @Sen95 float, @SpeL float , @SpeU float, @SenU float, @SenL float

SET @TP = (SELECT COUNT(SUBJECTID) FROM @R_MODS WHERE ResultCall='TP')
SET @TN = (SELECT COUNT(SUBJECTID) FROM @R_MODS WHERE ResultCall='TN')
SET @FP = (SELECT COUNT(SUBJECTID) FROM @R_MODS WHERE ResultCall='FP')
SET @FN = (SELECT COUNT(SUBJECTID) FROM @R_MODS WHERE ResultCall='FN')

SET @SEN = @TP/(@TP + @FN)
SET @M1 = @TP + @FN

SET @SPE = @TN/(@TN + @FP)
SET @M2 =  @FP + @TN

SET @SenL = ( 2*@M1*@SEN + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2)
    - 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) + 1)))/(2*(@M1+POWER(1.96,2)))
SET @SenU = ( 2*@M1*@SEN + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2)
    + 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) - 1)))/(2*(@M1+POWER(1.96,2)))

SET @SpeL = ( 2*@M2*@SPE + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2)
    - 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) + 1)))/(2*(@M2+POWER(1.96,2)))
SET @SpeU = ( 2*@M2*@SPE + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2)
    + 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) - 1)))/(2*(@M2+POWER(1.96,2)))

SELECT @SEN, @SenL, @SenU, 1-@SPE, 1-@SPEL, 1-@SpeU

A: Since your code just does calculations on data (i.e. no side-effects or updates of tables) and isn't coupled to tables, what you can do is to can create a table valued function to do these calculations - the function can take in the table of inputs  (R_MODS)as a table type and also return a table of outputs (Sen etc).
Here's a SqlFiddle example.
In detail:
You'll need to create a table type for the inputs, e.g.
CREATE TYPE R_MODS_TYPE AS TABLE(
  SUBJECTID varchar(max),
  ResultCall varchar(max)
);

And define the function as such:
CREATE FUNCTION dbo.DoCalcs(@TheRMods R_MODS_TYPE READONLY)
RETURNS @Result TABLE
(
    [SEN] DECIMAL(10,4),
    [SenL] DECIMAL(10,4),
    [SenU] DECIMAL(10,4),
    [1-SPE] DECIMAL(10,4),
    [1-SPEL] DECIMAL(10,4),
    [1-SpeU] DECIMAL(10,4)
)
AS
BEGIN
    DECLARE @TP float, @TN float, @FP float, @FN float, @SEN float, @SPE float,
            @M1 float, @M2 float, @Sen95 float, @SpeL float , @SpeU float,
            @SenU float, @SenL float;

    SET @TP = (SELECT COUNT(SUBJECTID) FROM @TheRMods WHERE ResultCall='TP')
    SET @TN = (SELECT COUNT(SUBJECTID) FROM @TheRMods WHERE ResultCall='TN')
    SET @FP = (SELECT COUNT(SUBJECTID) FROM @TheRMods WHERE ResultCall='FP')
    SET @FN = (SELECT COUNT(SUBJECTID) FROM @TheRMods WHERE ResultCall='FN')

    SET @SEN = @TP/(@TP + @FN)
    SET @M1 = @TP + @FN

    SET @SPE = @TN/(@TN + @FP)
    SET @M2 =  @FP + @TN

    SET @SenL = ( 2*@M1*@SEN + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2)
          - 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) + 1)))/(2*(@M1+POWER(1.96,2)))
    SET @SenU = ( 2*@M1*@SEN + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2)
          + 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) - 1)))/(2*(@M1+POWER(1.96,2)))

    SET @SpeL = ( 2*@M2*@SPE + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2)
      - 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) + 1)))/(2*(@M2+POWER(1.96,2)))
    SET @SpeU = ( 2*@M2*@SPE + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2)
      + 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) - 1)))/(2*(@M2+POWER(1.96,2)))

    INSERT INTO @Result ([SEN], [SenL], [SenU], [1-SPE], [1-SPEL], [1-SpeU])
        SELECT @SEN, @SenL, @SenU, 1-@SPE, 1-@SPEL, 1-@SpeU;
    RETURN;
END

You then invoke the table function by declaring an instance of the table type, populating it, and passing it to your function:
DECLARE @TestData R_MODS_TYPE;

INSERT INTO @TestData VALUES ('11-0001','TP'),
('11-0002','TP'),
('11-0003','TP'),
('11-0004','TP'),
... etc.

SELECT * FROM dbo.DoCalcs(@TestData);

Result:
SEN       SenL     SenU    1-SPE   1-SPEL  1-SpeU
--------- -------- ------- ------- ------- -------
1.0000    0.7166   0.9929  0.5000  0.9081  0.0919

A: Here is another approach using a Stored Procedure
You need a user-defined table data type for your input parameter.
CREATE TYPE R_MODS_TBL AS TABLE(
    SUBJECTID VARCHAR(MAX),
    ResultCall VARCHAR(MAX)
)

And the stored procedure:
Notice the change on the assignment of variables @TP, @TN, @FP, and @FN to use a single SELECT statement instead of four separate ones.
CREATE PROCEDURE  dbo.YourStoredProcedure(
    @R_MODS R_MODS_TBL READONLY
)
AS

DECLARE
    @TP FLOAT, @TN FLOAT, @FP FLOAT, @FN FLOAT,
    @SEN FLOAT, @SPE FLOAT, @M1 FLOAT, @M2 FLOAT, @Sen95 FLOAT,
    @SpeL FLOAT, @SpeU FLOAT, @SenU FLOAT, @SenL FLOAT

SELECT
    @TP = COUNT(CASE WHEN ResultCall='TP' THEN SUBJECTID END),
    @TN = COUNT(CASE WHEN ResultCall='TN' THEN SUBJECTID END),
    @FP = COUNT(CASE WHEN ResultCall='FP' THEN SUBJECTID END),
    @FN = COUNT(CASE WHEN ResultCall='FN' THEN SUBJECTID END)
FROM @R_MODS

SET @SEN = @TP/(@TP + @FN)
SET @M1 = @TP + @FN

SET @SPE = @TN/(@TN + @FP)
SET @M2 =  @FP + @TN

SET @SenL = (2*@M1*@SEN + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2) - 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) + 1)))/(2*(@M1+POWER(1.96,2)))
SET @SenU = (2*@M1*@SEN + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2) + 2 -(1/@M1)+ 4*@SEN *(@M1*(1-@SEN) - 1)))/(2*(@M1+POWER(1.96,2)))

SET @SpeL = (2*@M2*@SPE + POWER(1.96,2) - 1 - 1.96 * SQRT(POWER(1.96,2) - 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) + 1)))/(2*(@M2+POWER(1.96,2)))
SET @SpeU = (2*@M2*@SPE + POWER(1.96,2) + 1 + 1.96 * SQRT(POWER(1.96,2) + 2 -(1/@M2)+ 4*@SPE *(@M2*(1-@SPE) - 1)))/(2*(@M2+POWER(1.96,2)))

SELECT @SEN, @SenL, @SenU, 1-@SPE, 1-@SPEL, 1-@SpeU

To execute the stored procedure, you want to populate an instance of the generated user-defined table data type:
DECLARE @R_MODS R_MODS_TBL

INSERT INTO @R_MODS VALUES ('11-0001','TP');
INSERT INTO @R_MODS VALUES ('11-0002','TP');
INSERT INTO @R_MODS VALUES ('11-0003','TP');
INSERT INTO @R_MODS VALUES ('11-0004','TP');
INSERT INTO @R_MODS VALUES ('11-0005','TP');
INSERT INTO @R_MODS VALUES ('11-0006','I');
INSERT INTO @R_MODS VALUES ('11-0007','TP');
INSERT INTO @R_MODS VALUES ('11-0008','TP');
INSERT INTO @R_MODS VALUES ('11-0009','I');
INSERT INTO @R_MODS VALUES ('11-0010','TP');
INSERT INTO @R_MODS VALUES ('11-0011','TP');
INSERT INTO @R_MODS VALUES ('11-0012','TN');
INSERT INTO @R_MODS VALUES ('11-0013','TP');
INSERT INTO @R_MODS VALUES ('11-0014','I');
INSERT INTO @R_MODS VALUES ('11-0015','TP');
INSERT INTO @R_MODS VALUES ('11-0016','TP');
INSERT INTO @R_MODS VALUES ('11-0017','TN');
INSERT INTO @R_MODS VALUES ('11-0018','TP');
INSERT INTO @R_MODS VALUES ('11-0019','FP');
INSERT INTO @R_MODS VALUES ('11-0020','FP');

EXEC dbo.YourStoredProcedure @R_MODS

SQL Fiddle

Note:
When using table valued as an input parameter in a stored procedure, it is required to declare the parameter as READONLY. Read this answer by Mikael Eriksson for more information.


text:
Q: Yii2 - "Unable to verify your data submission" on Ajax calls I'm currently to send some Ajax request in my Yii2 application, but I keep getting 'Bad request 500 (Internal server error)' errors in my console.
I'm trying to do something simple and I'm new to AJAX, so just passing data from a text input when I click on a button to my controller and see how it's formatted (through var_dump).
I tried disabling crsf token in beforeAction and it works, but I don't want to disable it.
Here is my Ajax request :
<script>

    // Bind to the submit event of our form
    $(document).on('click', '#sendButton', function() {

        var newMessage = $('#newMessage').val();

        var myUrl = "<?php echo Url::to(['chat/send']); ?>"

        $.ajax({
            url: myUrl,
            type: "POST",
            data: {newMessage: newMessage, _csrf: '<?=\Yii::$app->request->csrfToken?>'},
            success: function(response) {
                console.log("Hooray");
            }
        });

    });

</script>

And here is my Yii2 action :
   public function actionSend() {
        $data = Yii::$app->request->post();

        var_dump($data);

        return $this->render('dump');
    }


text:
Q: How to show warning before installing android app? Is it possible to show warning or licence agreement before android app installing(like showing permissions)? And how does it make?

A: No, you can't interrupt Play Market install process.
What you can do:

*

*Add warning, license agreement etc. at your app market
descriprtion. Your have a special field in your apps market profile for license agreement.

*Use special screen with warnings/agreement on the
    first run of your app. If user disagrees, just close it.


text:
Q: `sudo echo "bla" >> /etc/sysctl.conf` permission denied Disclaimer: I'm pretty novice at sysadmin stuff.
I'm trying to set up port forwarding in an AWS EC2 instance, this has to be done in the command-line because I don't want to go in and edit anything, it has to be automatic (it's part of a build process).
sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

Permission denied

The weird thing is I've been (successfully) using sudo for pretty much every command that required su privileges. If I do sudo su before the command (trying it out by hand in an ssh session), then it works.
Reasons behind this? Possible solutions that don't involve sudo su or manual edits?

A: You can't use sudo to affect output redirection; > and >> (and, for completeness, <) are effected with the privilege of the calling user, because redirection is done by the calling shell, not the called subprocess.
Either do
cp /etc/sysctl.conf /tmp/
echo "net.ipv4.ip_forward = 1" >> /tmp/sysctl.conf
sudo cp /tmp/sysctl.conf /etc/

or
sudo /bin/su -c "echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf"

A: The command sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf is interpreted as that you (nonroot) write the result of sudo echo "net.ipv4.ip_forward = 1" into /etc/sysctl.conf.
Run
sudo -s 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

or
sudo su -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

to run echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf as root.

A: You might find it simpler to use this command:
echo net.ipv4.ip_forward = 1 | sudo tee -a /etc/sysctl.conf

A: sudo sed -i "$ a <text>" <file>

*

*-i  : edit file in place.

*$ a: append text to the last line

Using sed command avoids you the hassle of redirections and pipelines.
In your case: sudo sed -i "$ a net.ipv4.ip_forward = 1" /etc/sysctl.conf

A: sudo runs only your command, not the redirect, as root.  You'll need to wrap it all in a command where the whole thing runs as root:
sudo sh -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'


text:
Q: how to add a 4 spaces in pyhon 3 idle or shell (space between lines) a = 1
if a > 1: #hit enter
    print ("L") #hit enter
        print ("K") #add 4 spaces or press tab
#hit enter

SyntaxError: unexpected indent

A: The indent in the second print statement is unwanted. Don't add the extra 4 spaces on print ("K"). Its indentation level already matches the if block.

A: a = 1
if a > 1: #hit enter
    print ("L"+"\n" ) #hit enter
    print ("K"+"\n") #add 4 spaces or press tab
#hit enter

The \n adds a line break after the string. Like hitting enter in some text editor, or like <br> in HTML


text:
Q: MySQL create view across all prefixed databases' table I have databases named company_abc, company_xyz, etc. Those company_* databases have all the same structure and they contain users table.
What I need to do is to aggregate all users data from just company_* databases and replicate this view to another server. The view would just be something like
COMPANY NAME | USERNAME
abc          | user@email.com
abc          | user1@email.com
xyz          | user2@email.com
company3     | user3@email.com

Is something like that possible in MySQL?
The databases are created dynamically, as well as the users so I can't create a view with just a static set of databases.

A: As you say you want to create view with dynamic database names - so the result you want to achieve is not possible in current versions of mysql.
So you have example following options:
Option 1
If you want to get result of all databases users tables you could define a stored procedure that uses prepared statement. This procedure needs parameter db_prefix what in your case is company_%. Basicly this procedure selects all tables named as users from information_schema when database name is like db_prefix parameter value. After that it loops through results and creates query string as union all users tables and executes this query. When creating a query string i also add field called source, so i can identify from what database this result is coming. In my example my databases are all in default collation utf8_unicode_ci.
In this case you can define procedure example "getAllUsers"
-- Dumping structure for procedure company_abc1.getAllUsers
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `getAllUsers`(IN `db_prefix` TEXT)
    DETERMINISTIC
    COMMENT 'test'
BEGIN
    DECLARE qStr TEXT DEFAULT '';
    DECLARE cursor_VAL VARCHAR(255) DEFAULT '';
    DECLARE done INTEGER DEFAULT 0;
    DECLARE cursor_i CURSOR FOR SELECT DISTINCT (table_schema) FROM information_schema.tables WHERE table_name = 'users' AND table_schema LIKE db_prefix COLLATE utf8_unicode_ci;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN cursor_i;
    read_loop: LOOP
        FETCH cursor_i INTO cursor_VAL;
        IF done = 1 THEN
        LEAVE read_loop;
        END IF;
        IF qStr != '' THEN
            SET qStr = CONCAT(qStr, ' UNION ALL ');
        END IF;
        SET qStr = CONCAT(qStr, ' SELECT *, \'', cursor_VAL ,'\' as source FROM ', cursor_VAL, '.users');
    END LOOP;
    CLOSE cursor_i;

    SET @qStr = qStr;

    PREPARE stmt FROM @qStr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET @qStr = NULL;
END//
DELIMITER ;

Now you can get your all users result as:
CALL getAllUsers('company_%');

In my example database it results as:
id  name    source
1   User 1  company_abc1
2   User 2  company_abc1
3   User 3  company_abc1
1   User 1  company_abc2
2   User 2  company_abc2
3   User 3  company_abc2
1   User 1  company_abc3
2   User 2  company_abc3
3   User 3  company_abc3
1   User 1  company_abc4
2   User 2  company_abc4
3   User 3  company_abc4
1   User 1  company_abc5
2   User 2  company_abc5
3   User 3  company_abc5

Option 2
If you really, really need view then you can modify first procedure and instead of executeing select you can create view. Example like this:
-- Dumping structure for procedure company_abc1.createAllUsersView
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `createAllUsersView`(IN `db_prefix` TEXT)
    DETERMINISTIC
    COMMENT 'test'
BEGIN
    DECLARE qStr TEXT DEFAULT '';
    DECLARE cursor_VAL VARCHAR(255) DEFAULT '';
    DECLARE done INTEGER DEFAULT 0;
    DECLARE cursor_i CURSOR FOR SELECT DISTINCT (table_schema) FROM information_schema.tables WHERE table_name = 'users' AND table_schema LIKE db_prefix COLLATE utf8_unicode_ci;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN cursor_i;
    read_loop: LOOP
        FETCH cursor_i INTO cursor_VAL;
        IF done = 1 THEN
        LEAVE read_loop;
        END IF;
        IF qStr != '' THEN
            SET qStr = CONCAT(qStr, ' UNION ALL ');
        END IF;
        SET qStr = CONCAT(qStr, ' SELECT *, \'', cursor_VAL ,'\' as source FROM ', cursor_VAL, '.users');
    END LOOP;
    CLOSE cursor_i;

    SET @qStr = CONCAT('CREATE OR REPLACE VIEW allUsersView AS ', qStr);
    PREPARE stmt FROM @qStr;
   EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET @qStr = NULL;
END//
DELIMITER ;

In this stored procedure we create/replace view called allUsersView, so basicly every time you will execute this procedure it will updates view.
In my test case it creates view like this:
CREATE OR REPLACE VIEW `allusersview` AS
    SELECT *, 'company_abc1' as source FROM company_abc1.users
    UNION ALL  SELECT *, 'company_abc2' as source FROM company_abc2.users
    UNION ALL  SELECT *, 'company_abc3' as source FROM company_abc3.users
    UNION ALL  SELECT *, 'company_abc4' as source FROM company_abc4.users
    UNION ALL  SELECT *, 'company_abc5' as source FROM company_abc5.users ;

And now you can use view.
SELECT * FROM allusersview

And result is same as in first option.
All tested on:
Mysql 5.6.16

A: To find the list of database names:
SELECT SCHEMA_NAME
    FROM information_schema.`SCHEMATA`
    WHERE SCHEMA_NAME LIKE 'company%';

If you can code in something like PHP, the rest is pretty easy -- build a UNION of SELECTs from each database.  But, if you must do it just in SQL...
To build the UNION, write a Stored Procedure.  It will do the above query in a CURSOR.  Inside the loop that walks through the cursor, CONCAT() a constructed SELECT onto a UNION you are building.
When the loop is finished, PREPARE and EXECUTE the constructed UNION.  That will deliver something like the output example you had.
But, if you now need to INSERT the results of that into another server, you should leave the confines of the Stored Procedure and use some other language.
OK, OK, if you must stay in SQL, then you need some setup:  Create a "Federated" table that connects to the other server.  Now, in your SP, concatenate INSERT INTO fed_tbl in front of the UNION.  Then the execute should do the entire task.
If you have trouble with the FEDERATED Engine, you may need to switch to FederatedX in MariaDB.
"The details are left as an exercise to the reader."

A: I already marked this as duplicate of Mysql union from multiple database tables
(SELECT *, 'abc' as COMPANY_NAME from company_abc.users)
union
(SELECT *, 'xyz' as COMPANY_NAME from company_xyz.users)
union
(SELECT *, 'company3' as COMPANY_NAME from company_company3.users)
...

A: I think that the only method to make this is to write a stored procedure that read all database and table name from information_schema.table, build a string with union select * from company_abc.users union all select * from company_xyz and then execute the command with prepared statement: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html


text:
Q: MassTransit MessageData Management I have been starting to make greater use of the message data feature of masstransit and am getting to the point needing to manage the message data in the store - i.e. remove old data.
The obvious choice is to have some outside process tidy up data, but clearly a scheduled (or not) clean up could remove data still in use or referenced by error or dead letter queues.
Ideally I would like to limit stored message data retention to messages only in error or dead letter queues, and automatically remove data for messages that have been successfully processed.
What would be the best approach to achieve this with MassTransit? Perhaps with a MiddleWare approach or similar, and if that is the case what is the correct approach?

A: Manual cleanup is recommended, using whatever makes sense for the repository in use. Because messages may still be in queues, or in error/dead-letter queues as you pointed out, it is really up to development/operations team to know when the right time is to remove older message data.
I'd suggest monitoring and managing the error/dead-letter queues more aggressively, keeping them empty. And then, just figure a good timeframe to delete old message data - one week, ten days, whatever - and deal with it that way.

I have had a backlog item to come up with a way to automatically manage message data, but since message data can be forwarded (using the same stored data) either via publish or send, there is no good way to track references.


text:
Q: jQuery.bind() doesn´t respond to event I have a block of jQuery like this :
jqObj.bind('change', function () {
      debugger;
    });

jqObj matches two elements (dropDownList), but only the first of them respond to the 'change' event, the second element that on position [1] do nothing on change.
Any suggestions?


text:
Q: ESP32 stops everything when interacting with MIT App inventor 2 Making an app right now that interacts with an ESP32 through bluetooth classic. I'm reading the hall sensor and sending a 0 when its value is above 0, and a 1 when below. Now, when I register that 1 in ai2 and some things happen in the app because of it, the ESP32 malfunctions or something. I stop getting readings from the sensor in the serial monitor, and the bluetooth connection stops. It just seems like the whole esp just stops dead in its tracks. I'm also not sending any data to the ESP32, just receiving from it. The esp code is super small, but the app code not so much.
Only way to fix this issue is resetting the esp, which isn't really doable in my usecase. Any way to fix this?
    #include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("Sport Spel"); //Bluetooth device name
}

void loop() {
  Serial.println(hallRead());
  if (SerialBT.available)
  {
    if (hallRead() < 0)
    {
      SerialBT.write('1');
    }
    else
    {
      SerialBT.write('0');
    }
    delay(20);
  }

}

Image 1 of app code
Image 2
3
4
5
6

A: The line
  if (SerialBT.available)

should be
  if (SerialBT.available())

As it's written in your question, you're testing whether the address of the method named available on the SerialBT object is true, which it always will be. You want to actually call that method, so you need to include the parentheses in order to invoke it.


text:
Q: How to run a DalvikVM application with more than 1 DEX files? I just compiled a customized Minecraft server (PC-server running in console) into a .zip file, named test.zip, containing classes.dex and classes2.dex, with sdk-dx tool.
I want to run the application with the "dalvikvm" shell command, but it keeps throwing java.lang.NoClassDefFoundError: test.server.Start
The path of the .zip file is /sdcard/Test/test.zip, and the original main class is test.server.Start in classes.dex. (I don't think it's modified since I tried dex2jar and the class names remain the same.)
These are the commands I've tried. Non of them works.
dalvikvm -cp /sdcard/Test/test.zip test.server.Start
dalvikvm -cp /sdcard/Test/test.zip/classes.dex;/sdcard/Test/test.zip/classes2.dex test.server.Start
dalvikvm -cp "/sdcard/Test/test.zip/classes.dex /sdcard/Test/test.zip/classes2.dex" test.server.Start
Does anyone know what's wrong here?

A: Setting aside bigger questions, the Dalvik classpath is a colon-separated list of filenames (e.g. /sdcard/foo1.jar:/sdcard/foo2.jar). Each jar/apk contains a single classes.dex.  For an APK you'd work around this with multidex, but for command-line invocation you just need to put each classes.dex into its own jarfile.


text:
Q: ASP: Reading Scripting.Dictionary with ADODB.Command Result I'm trying to query the userAccountControl from Active Directory and match it against a dictionary that I've set up in my script.
First of all I set up my dictionary object and fill it:
dim uac
Set uac=Server.CreateObject("Scripting.Dictionary")
uac.add "512", "Enabled Account"
uac.add "514", "Disabled Account"
uac.add "544", "Enabled, Password Not Required"
uac.add "546", "Disabled, Password Not Required"
uac.add "66048", "Enabled, Password Doesn't Expire"
uac.add "66050", "Disabled, Password Doesn't Expire"
uac.add "66080", "Enabled, Password Doesn't Expire & Not Required"
uac.add "66082", "Disabled, Password Doesn't Expire & Not Required"
uac.add "262656", "Enabled, Smartcard Required"
uac.add "262658", "Disabled, Smartcard Required"
uac.add "262688", "Enabled, Smartcard Required, Password Not Required"
uac.add "262690", "Disabled, Smartcard Required, Password Not Required"
uac.add "328192", "Enabled, Smartcard Required, Password Doesn't Expire"
uac.add "328194", "Disabled, Smartcard Required, Password Doesn't Expire"
uac.add "328224", "Enabled, Smartcard Required, Password Doesn't Expire & Not Required"
uac.add "328226", "Disabled, Smartcard Required, Password Doesn't Expire & Not Required"

Then I connect to my Active Directory to query it:
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.provider ="ADsDSOObject"
objConn.Properties("User ID") = "domain\administrator"
objConn.Properties("Password") = "password"
objConn.Properties("Encrypt Password") = True
objConn.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objConn
objCom.CommandText ="select name,userAccountControl FROM 'GC://"+objADsPath+"' where sAMAccountname='*' and objectCategory='user' and objectCategory='person' ORDER by sAMAccountname"

Then I loop through the results like so:
Set objRS = objCom.Execute
Do While Not objRS.EOF Or objRS.BOF
Response.Write objRS("name")
set uacResult = objRS("userAccountControl")
objRS.MoveNext
Response.Flush
Loop
objRS.Close
objConn.Close
Set objRS = Nothing
Set objConn = Nothing
Set objCom = Nothing
Set objADsPath = Nothing
Set objDomain = Nothing

This all works absolutely fine. What I want to do now is to query the uac dictionary that I created using the result from objRS("userAccountControl"). When I try to do that, it returns a blank value?
set uacResult = objRS("userAccountControl")
Response.Write uac.Item(uacResult)
Response.Write " (" & uacResult & ")"

I'm stumped - is the objRS value returned as a string?? It works if I do Response.Write uac.Item("512") but not if I do Response.Write uac.Item(uacResult)
Any ideas?

A: Found it!!
I needed to convert the objRS("userAccountControl") to a string using CStr().
This works:
set uacResult = objRS("userAccountControl")
Response.Write uac.Item(CStr(uacResult))
Response.Write " (" & uacResult & ")"

A: You've already found a valid solution, but I want to explain what's going on here.
The keys of a Dictionary object can be of any type except arrays (see the docs). Since you used the Set statement, the variable uacResult is an object reference (more on that later). When you call the Item method on the Dictionary, it is actually looking for key that matches the object reference, instead of searching for the string as you expected. CStr() corrects that by explicitly converting the object reference to a string.
Since you used the Set keyword in its assignment, uacResult ends up containing a reference to a Field object, since the default property of the Recordset object is the Fields collection. When you call CStr(uacResult), this is converting the object to a string by calling the default property of the Field object, which is the Value property. You could achieve the same effect in a few different ways:
' method 1 - from accepted answer (https://stackoverflow.com/a/17786308/249624)
set uacResult = objRS("userAccountControl")
Response.Write uac.Item(CStr(uacResult))

' method 2 - explicitly using the Value property
set uacResult = objRS("userAccountControl")
Response.Write uac.Item(uacResult.Value)

' method 3 - make uacResult a string instead of a Field object
uacResult = objRS("userAccountControl")
Response.Write uac.Item(uacResult)

' method 4 - same as method 3, but explicitly use the Value property
uacResult = objRS("userAccountControl").Value
Response.Write uac.Item(uacResult)


text:
Q: The PDE $u_t=u_{xx}-u_{yy}$: The simplest linear second-order PDE that isn't elliptic, parabolic, or hyperbolic. I know that there have been several questions on here and stackexchange about linear PDE's which don't fall into the standard classification, but I had a more focused question which I haven't seen answered. The PDE $u_t=u_{xx}-u_{yy}$ (or, equivalently, $u_t=u_{xy}$), is the simplest linear second-order PDE that is not elliptic, parabolic, or hyperbolic. Its time-invariant solutions are solutions to the one-dimensional wave equation.
My question is,
How does this PDE compare to the standard parabolic and hyperbolic PDE's in the following categories:

*

*Fundamental solution: is there an integral solution which is a convolution with a fundamental solution?

*Smoothness: are solutions infinitely smooth or does the smoothness depend on boundary conditions?

*Propagation speed: infinite or finite?
I only recently read Evan's PDE book, and the only question I really took a crack at was the first. I looked for a solution involving exponentials in t, but I couldn't find one. I am interested in this question purely from a classification standpoint. Thanks!
Edit: As the comments below indicate, there can be no general solution with arbitrary initial conditions analogous to that for parabolic or hyperbolic equations. Also, solutions need not be infinitely smooth. Since this answer was pieced together from the comments, I'm making this community wiki, in case anyone would like to add to it later.

A: Exponential solutions are easy to find. Just plug $\exp(ax+by+ct)$, and you will see that every
$(a,b,c)$ that satisfies $c=a^2-b^2$ gives you a solution. This polynomial is called the symbol
of the differential operator. For the general theory of linear PDE with constant coefficients,
the best source is the first two volumes of Hormander, Analysis of Linear Differential Operators.


text:
Q: Can't fetch data through the key (Firestore) I can't fetch the data through Firestore key.

TypeError: relativePath.split is not a function

export const itemsFetch = () => {
  return (dispatch) => {
  firebase.firestore().collection('users').doc(19910929).get()
      .then((snapshot) => {
        console.log('snapshot:', snapshot);
      })
  };
};

A: I have updated data to that with string.
19910929 to '19910929'
That would work!


text:
Q: Write a maximum as integral of indicator function (clarification) It is known that a random variable $X$ can be written in terms of positive and negative parts $X=X^+-X^-$.
Also, $X^+=\max(0,X)=\int_0^\infty I(X>x)dx$. I don't know how to show it.
Say that $a\in\mathbb{R}$. I can see that $\max(0,a)=aI(a>0)$, and that $a=\int_0^adx$. It indicates me that $\max(0,a)=\int_0^{aI(a>0)}dx$, but I can't relate this with $\max(0,a)=\int_0^\infty I(a>x)dx$.
Can you help me with it?

A: As you noticed, a real number $x\ge 0$ can be written as $\int_0^x 1\,dz$. Thus,
$$
X\vee 0=\int_0^{\infty} 1\{X\vee 0>z\}\,dz=\int_0^{\infty} 1\{X>z\}\,dz.
$$


text:
Q: Full background image not displaying on mobile device The full background image isn't displaying properly on mobile. How can I have the full background image display?
body {
background-color: #000;
background-image: url(http://godwellontheloose.com/IMG_0463bwssww.jpg);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

a {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}

A: Define the HTML and body to be 100% height and width first.
html,body{width:100%; height:100%;}

Once this is added any element set to 100% height will show it at 100% height. A working example is below, run the code and click on full screen.

html,body{width:100%; height:100%;}
body{margin:0px; padding:0px;}
.background{background-image:url('https://media-cdn.tripadvisor.com/media/photo-s/0e/85/48/e6/seven-mile-beach-grand.jpg');width:100%; height:100%;
background-color: #000;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}


text:
Q: Solve a modular linear system I need to know the encryption matrix of the Hill cipher given the plain-text "HILLCIPHER" and cipher-text "WLHDMWLHZU"
Let the encryption matrix $$A=\begin{pmatrix}x
 & y\\z
 & w
\end{pmatrix}$$
We will split the plain-text $$"HI-LL-CI-PH-ER"=(7 \ 8)-(11  \ 11)-(2  \ 8)-(15  \ 7)-(4  \ 17)$$
And the same for the cipher-text : $$"WL-HD-MW-LH-ZU"=(22 \  11)-(7 \  3)-(12 \  22)-(11 \  7)-(25 \  20)$$
Using the fact that $"WL" =( "HI" \cdot  \ A) \ mod \ 26$ and that it's the same for all the other encrypted letters,
this leads to the system (just using the 2 first pairs):
$$\begin{pmatrix}
 (7x+8z) \ mod \ 26 = 22
 & \\ (11x+11z) \ mod \ 26 = 7
\end{pmatrix}$$
But I just can't resolve this.. Any help would be great !


text:
Q: Apply a function to all rows using 2 columns and creating a new column I have a Dataframe with two columns (date as index)
date       col_a   col_b
1.1.2020    23     34

and I want to apply a function using the 2 columns and creating a third one (error)
date      col_a  col_b   col_error
1.1.2020   23     34     0.4

here is my Dataframe
and below the code with the TypeError (sorry I can't provide the data :( )
def mean_absolute_percentage_error(y_true, y_pred):
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

# Apply a lambda function to each row by calculating the error
result['mape'] = result.apply(mean_absolute_percentage_error(test_df, pred_df))
result

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-125-681609c31734> in <module>
      4
      5 # Apply a lambda function to each row by calculating the error
----> 6 result['mape'] = result.apply(mean_absolute_percentage_error(test_df, pred_df))
      7 result

~/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
   6911             kwds=kwds,
   6912         )
-> 6913         return op.get_result()
   6914
   6915     def applymap(self, func):

~/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py in get_result(self)
    184             return self.apply_raw()
    185
--> 186         return self.apply_standard()
    187
    188     def apply_empty_result(self):

~/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py in apply_standard(self)
    290
    291         # compute the result using the series generator
--> 292         self.apply_series_generator()
    293
    294         # wrap results

~/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py in apply_series_generator(self)
    319             try:
    320                 for i, v in enumerate(series_gen):
--> 321                     results[i] = self.f(v)
    322                     keys.append(v.name)
    323             except Exception as e:

TypeError: ("'numpy.float64' object is not callable", 'occurred at index Night_Cons(+)')

A: The simplest way to manipulate the columns and add a new one would be something like this:
import pandas as pd

df = pd.DataFrame({'col_a': [23], 'col_b': [34]},
    index=[pd.to_datetime('2020-01-01')])
print(df)

            col_a  col_b
2020-01-01     23     34

df['col_error'] = abs((df['col_a'] - df['col_b'])/df['col_b'])
print(df)

            col_a  col_b  col_error
2020-01-01     23     34   0.323529

A: To create a new column from the existing one you can simply use a lambda function. For instance, if you your new column to be the difference from the previous ones:
df['new_col'] = df.apply(lambda row: row.col_1 - row.col_2, axis=1)

Hope this helps!


text:
Q: Factoring a polynomial with big integer coefficients and some known factors. I have the following polynomial that I want to factor
$$
\begin{align*}
p(x)=
&- 236364091 x^{13}- 28363690920 x^{12}- 1487737229594 x^{11}\\
&- 44880832661940 x^{10} - 860924276925225 x^9- 10941278514219396 x^8 \\
&- 92883153994532540 x^7 - 516122234647942344 x^6 - 1766587850009264989 x^5 \\
&- 3172232270188300464 x^4 - 1263789594225408906 x^3 + 3700632893619477564 x^2 \\
&+ 3120329011246701345 x+5179915266025500 \\
\end{align*}
$$
I suspect that $(x+24)$ and $(x+25)$ are factors. I'm interested in the remaining polynomial $q(x)$ such that $p(x)=(x+24)(x+25)q(x)$. I've tryed Mathematica with no success. Can anyone help?
I'm also interested in other software packages more suited to the factorization of this kind of polynomials.
Thanks.

I'm back!!!
Unfortunately there was an error in the above polynomial, so it didnt factor as expected. The correct one follows
$$
\begin{align*}
p(x)=
&-2363640910 x^{13}- 283636909200 x^{12}- 14830715886140 x^{11} \\
&-445215783064800 x^{10}- 8492530754498370 x^9- 107310315789497520 x^8 \\
&- 905953817318009480 x^7-  5008244551318927680 x^6- 17061651312407299570 x^5\\
&-  30494240185050800880 x^4- 12007914756669549180 x^3 + 35636084573032450080 x^2\\
&+ 29908147265568403650 x +103598305320510000
\end{align*}
$$
and factors as expected to:
$$
\begin{align*}
p(x)=-10 (24 + x) (25 + x) q(x)
\end{align*}
$$
where
$$
\begin{align*}
q(x)=&236364091 x^{11}+ 16781850461 x^{10}+518942461425 x^9\\
&+ 9024287420055 x^8 + 95697515012142 x^7+ 627280891321794 x^6\\
&+ 2440109049747842 x^5+ 4890576901172110 x^4+ 2461433234591367 x^3\\
&- 5532350693162895 x^2- 4983281122883427 x-17266384220085
\end{align*}
$$
Thanks, next time I'll think twice...

A: This function has no factorization in $\mathbb{Q}$. I did a manual check with Mathematica.


text:
Q: Fitting nls to grouped data R I'm trying to fit a non-linear model to a series of measurements collected on several plots throughout the season. Below is a subsample from the larger dataset.
data:

dput(nee.example)
  structure(list(julian = c(159L, 159L, 159L, 159L, 159L, 159L,
  159L, 159L, 159L, 159L, 159L, 159L, 159L, 159L, 169L, 169L, 169L,
  169L, 169L, 169L, 169L, 169L, 169L, 169L, 169L, 169L, 169L, 169L,
  169L), blk = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
  1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
  2L, 2L, 2L, 2L), .Label = c("e", "w"), class = "factor"), type = structure(c(1L,
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
  2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("b",
  "g"), class = "factor"), plot = c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
  2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
  3L, 3L, 3L, 3L, 3L, 3L), trt = structure(c(1L, 1L, 1L, 1L, 1L,
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "a", class = "factor"),
      cloth = c(25L, 50L, 75L, 100L, 0L, 25L, 50L, 75L, 100L, 0L,
      25L, 50L, 75L, 100L, 0L, 25L, 50L, 100L, 0L, 25L, 50L, 75L,
      100L, 0L, 25L, 50L, 75L, 75L, 100L), plotID = c(1L, 1L, 1L,
      1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 13L, 13L, 13L,
      13L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L
      ), flux = c(0.76, 0.6, 0.67, 0.7, 1.72, 1.63, -7.8, 0.89,
      0.51, 0.76, 0.48, 0.62, 0.18, 0.21, 3.87, 2.44, 1.26, -1.39,
      2.18, 1.9, 0.81, -0.04, -0.83, 1.99, 1.55, 0.57, -0.02, -0.16,
      -2.12), ChT = c(18.6, 19.1, 19.6, 19.1, 16.5, 17.3, 18.3,
      19, 18.6, 17.2, 18.4, 19, 19.2, 20.6, 22, 21.9, 22.4, 23.8,
      20.7, 21.5, 22.5, 23.3, 23.8, 20.1, 20.8, 21.2, 21.8, 21.8,
      21.4), par = c(129.9, 210.2, 305.4, 796.6, 1.3, 62.7, 149.9,
      171.2, 453.3, 1.3, 129.7, 409.3, 610, 1148.6, 1.3, 115.2,
      237, 814.6, 1.3, 105.4, 293.4, 472.1, 955.9, 1.3, 100.5,
      290, 467, 413.6, 934.2)), .Names = c("julian", "blk", "type",
  "plot", "trt", "cloth", "plotID", "flux", "ChT", "par"), class = "data.frame", row.names = c(NA,
  -29L))

I need to fit the following model (rec.hyp, below) to each plot on each date and retrieve the parameter estimates for each julian-plotID combination. After some poking around, it sounded like nlsList would be an ideal function because of the grouping aspect:
library(nlme)
rec.hyp <- nlsList(flux ~ Re - ((Amax*par)/(k+par)) | julian/plotID,
             data=nee.example,
             start=c(Re=3, k=300, Amax=5),
             na.action=na.omit)
coef(rec.hyp)

However I keep getting the same error message:
Error in nls(formula = formula, data = data, start = start, control = control) :
step factor 0.000488281 reduced below 'minFactor' of 0.000976562

I've tried tweaking the controls in nls.control to increase the maxIter and tol, but the same error message is displayed. And I've altered the initial starting values to no avail.
It should be noted that I need to fit the model using least squares in order to be consistent with prior work.
Questions:

*

*Is my grouping structure allowed in nlsList. In other words, can I nest plotID within julian? Could this be the source of my error.

*I've read that inappropriate starting parameter estimates cause the error message, yet I get the same message after changing them.
I feel like I'm missing something simple here, but my brain is fried.
Thanks in advance.

A: Answer to Q1: your grouping structure is correct. You can validate it by running nls on a subset of your data:
rec.hyp.test <- nls(flux ~ Re - ((Amax*par)/(k+par)),
                   data=subset(nee.example,julian==159 & plotID==3),
                   start=c(Re=3, k=300, Amax=5),
                   na.action=na.omit)
coef(rec.hyp.test)
#        Re           k        Amax
# 0.7208943 792.4412287   0.8972519

coef(rec.hyp)[3,]
#              Re        k      Amax
# 159/3 0.7208943 792.4412 0.8972519

Answer to Q2: Some data sets just cannot be properly fitted by a given model. From the flux ~ Re - ((Amax*par)/(k+par)) formula, one might expect that flux monotonically decreases with par (or increases, if Amax < 0). Just for curiosity, I plotted one of the data sets that cause nls to fail:
plot(flux~par,subset(nee.example,julian==159 & plotID==1))

and found that it was not monotonic, and I'd even say that it had no any trend at all! I guess that even if you force nls to get some solution for this case, it could be well possible a spurious one, so you might just want to leave it unfitted (viz. NA).

I would also suggest to perform a visual inspection of the input data and fitting model quality. With R and packages like reshape2 and ggplot2, you can easily plot hundreds of them, and even taking a quick look at them will help you to stay out of trouble.


text:
Q: If x is in the closure of the closure of A, then it is in the closure of A I am trying to prove the following statement: if $x$ is in the closure of the closure of $A$, then it is in the closure of $A$ ($\bar{A}$).
Suppose $x$ is in the closure of the closure of $A$. Then it is the case that, $\forall \epsilon>0$, $B(x, \epsilon) \cap \bar{A} \neq \emptyset$. Suppose $y$ is in this intersection. Since $y$ is in $\bar{A}$, and $y$ is in the open set $B(x, \epsilon)$, $B(x, \epsilon)$ must contain at least one point from $A$ (by the definition of the closure). So the $B(x, \epsilon)\cap A\neq \emptyset$.
Is this correct? Thank you.

A: Looks more or less good, yes! By more or less I mean if I was a TA and this was an answer on a test, I'd give it all points.

That said, I have some very minor and nitpicky comments strictly on how the proof is written.
Comment 1:
In particular, when you say

suppose $y$ is in this intersection.

It is clear from context what you mean by this intesection, but technically, you only wrote a statement true for all $\epsilon$. To make it more clear, I would add the sentence

"Let $\epsilon > 0$

before "suppose $y$ is in this intersection". So the beginning of the proof would be:

Suppose $x$ be an element of the closure of the closure of $A$. Further, let $\epsilon > 0$. Then, we know that $B(x,\epsilon)\cap \overline A\neq\emptyset$. Therefore, there exists some $y\in B(x,\epsilon)\cap \overline A$

Comment 2:
When you say "By the definition of closure", this is a little unclear because there are several equivalent definitions of closure. I assume you mean the one saying:

$B$ is the closure of $A$ if, for every $x\in B$ and every open set $O$ containing $x$, the intersection $O\cap A$ is nonempty.

If you mean that definition, then I would rewrite the end of the proof ever so slightly into:

Since $y$ is in $\bar{A}$, and $y$ is in the open set $B(x, \epsilon)$, we know that $B(x, \epsilon)\cap A$ is nonempty, which concludes the argument.


text:
Q: jQuery Validation not showing custom messages I am using the jQuery Validation Plugin. My validations are clearly working. However, my custom error messages are not displaying correctly?

*

*I am using Unobtrusive along with Validation

Thanks for the help...
JAVASCRIPT:
dictionary.elements.form.validate({
    rules: {
        txtBSAPLocalAddress: {
            required: true
        },
        txtBSAPGlobalAddress: {
            required: true
        },
        txtBSAPDeviceLevel: {
            required: true
        }
    },
    messages: {
        txtBSAPLocalAddress: "Local Address is required.",
        txtBSAPGlobalAddress: "Global Address is required.",
        txtBSAPDeviceLevel: "Device is required."
    }

HTML:
<form>

                    Local Address

                    <input type="text" class="form-control input-sm" id="txtBSAPLocalAddress" name="txtBSAPLocalAddress" placeholder="0 to 254..." required />

                    Global Address

                    <input type="text" class="form-control input-sm" id="txtBSAPGlobalAddress" name="txtBSAPGlobalAddress" placeholder="0 to 254..." required />

                    Device Level

                    <input type="text" class="form-control input-sm" id="txtBSAPDeviceLevel" name="txtBSAPDeviceLevel" placeholder="0 to 6..." required />

</form>


text:
Q: Insert data using Mongodb Rest Interface i am using mongodb rest interface to get data from server.
but anyone have idea how to insert data to particular collection using Rest interface.

A: If you are using the built-in REST-interface then there is no support for inserting new documents. It's stated in their documentation.

The mongod process includes a simple REST interface, with no support for insert/update/remove operations, as a convenience – it is generally used for monitoring/alerting scripts or administrative tasks.


text:
Q: How to achieve animated search app bar in flutter? I want to achieve the animated search app bar: https://drive.google.com/file/d/1BnykuOZExHusxIRgareKmdaPM6RlswYe/view?usp=sharing
I tried to use a stack and an animated container, to achieve it. however, it was giving renderflex error.
I would like to know if anyone has other suggestions to achieve it.
Following is the code for the custom appbar and search widget:
AppBar:
class CustomHomeAppBar extends ConsumerStatefulWidget with PreferredSizeWidget {
  @override
  final Size preferredSize;
  CustomHomeAppBar({Key? key, required this.title})
      : preferredSize = const Size.fromHeight(60.0),
        super(key: key);

  final String title;

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _CustomHomeAppBarState();
}

class _CustomHomeAppBarState extends ConsumerState<CustomHomeAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        title: Stack(children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {},
                child: const CircleAvatar(
                  radius: 18,
                  backgroundColor: Colors.teal,
                  child: CircleAvatar(
                    backgroundImage: NetworkImage(
                        "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"),
                    radius: 28,
                  ),
                ),
              ),
              const SizedBox(
                width: 10,
              ),
              Text(
                widget.title,
                style:
                    const TextStyle(fontWeight: FontWeight.w400, fontSize: 22),
              ),
            ],
          ),
          Positioned(right: 0, child: AnimatedSearchBar())
        ]));
  }
}

search widget:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';

class AnimatedSearchBar extends StatefulWidget {
  const AnimatedSearchBar({Key? key}) : super(key: key);

  @override
  State<AnimatedSearchBar> createState() => _AnimatedSearchBarState();
}

class _AnimatedSearchBarState extends State<AnimatedSearchBar> {
  bool _folded = true;

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 400),
      width: _folded ? 24 : MediaQuery.of(context).size.width - 16,
      // height: 56,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(32),
        color: Colors.white,
      ),
      child: Row(children: [
        Expanded(
          child: Container(
            // padding: const EdgeInsets.only(left: 16),
            decoration:
                BoxDecoration(color: Color.fromARGB(255, 212, 207, 207)),
            child: !_folded
                ? const TextField(
                    decoration: InputDecoration(
                        hintText: 'Search',
                        hintStyle: TextStyle(color: Colors.blue),
                        border: InputBorder.none))
                : null,
          ),
        ),
        AnimatedContainer(
          duration: const Duration(milliseconds: 400),
          child: InkWell(
            onTap: () {
              print("clicks");
              setState(() {
                _folded = !_folded;
              });
            },
            // child: Padding(
            // padding: const EdgeInsets.all(16.0),
            child: Icon(
              _folded ? Icons.search : Icons.close,
              color: Colors.blue[900],
            ),
          ),
        ),
        // )
      ]),
    );
  }
}

It results in the following appbar:
search with stack


text:
Q: CKError code: 12, No operations present in request I keep seeing this error when performing a query in CloudKit. Here is the code that usually sets it off:
if (self.userID) {

    CKReference *referenceToUser = [[CKReference alloc]initWithRecordID:self.userID action:CKReferenceActionDeleteSelf];
    NSPredicate *userSearch = [NSPredicate predicateWithFormat:@"%K == %@", @"User", referenceToUser];
    CKQuery *findHoneymoon = [[CKQuery alloc]initWithRecordType:@"Honeymoon" predicate:userSearch];
    CKQueryOperation *findHMOp = [[CKQueryOperation alloc]initWithQuery:findHoneymoon];
    findHMOp.resultsLimit = 1;

    __block CKRecord *userHoneyMoon;
    findHMOp.recordFetchedBlock = ^(CKRecord *record){
        userHoneyMoon = record;
        self.userHoneymoon.honeymoonID = record.recordID;
    };

    __block BOOL errorOccured = NO;
    findHMOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *operationError){

        if (operationError)
        {
            NSLog(@"Error searching for user honeymoon, description: %@, and code: %lu, and heck, heres the domain: %@", operationError.localizedDescription, operationError.code, operationError.domain);

            [[NSNotificationCenter defaultCenter]postNotificationName:@"HoneymoonError" object:nil];

            errorOccured = YES;
        }

        if (!userHoneyMoon && !errorOccured)
        {
            [self createBlankHoneymoon];
        }
        else
        {
            [self.userHoneymoon populateHoneymoonImages];
        }
    };

    [[[CKContainer defaultContainer] publicCloudDatabase] addOperation:findHMOp];
}

What's really vexing is that this error only occurs about 1 in 5 times I try to run the program.
Here is what gets logged when the error occurs:

Error searching for user honeymoon, description: No operations present in request, and code: 12, and heck, heres the domain: CKErrorDomain

As you can see from the code there ARE operations in the request, does anyone know any other reason this error might occur and how to handle it?


text:
Q: PyQt Automatic Repeating Forms I'm currently attempting to migrate a legacy VBA/Microsoft Access application to Python and PyQt. I've had no problems migrating any of the logic, and most of the forms have been a snap, as well. However, I've hit a problem on the most important part of the application--the main data-entry form.
The form is basically a row of text boxes corresponding to fields in the database. The user simply enters data in to a fields, tabs to the next and repeats. When he comes to the end of the record/row, he tabs again, and the form automatically creates a new blank row for him to start entering data in again. (In actuality, it displays a "blank" row below the current new record, which the user can actually click in to to start a new records as well.) It also allows the user to scroll up and down to see all the current subset of records he's working on.
Is there a way to replicate this functionality in PyQt? I haven't managed to find a way to get Qt to do this easily. Access takes care of it automatically; no code outside the form is required. Is it that easy in PyQt (or even close), or is this something that's going to need to be programmed from scratch?

A: You should look into QSqlTableModel, and the QTableView Objects. QSqlTableModel offers an abstraction of a relational table that can be used inside on of the Qt view classes. A QTableView for example. The functionality you describe can be implemented with moderate effort just by using these two classes.
The QSqlTableModel also supports editing on database fields.
My guess the only functionality that you will have to manually implement is the "TAB" at the end of the table to create a new row if you want to keep that.
I don't know much about Access, but using the ODBC-SQL driver you should be able use the actual access database for your development or testing there is some older information here, you might want to consider moving to Sqlite, Mysql or another actual SQL database.


text:
Q: jQuery's .serialize() doesn't do anything I've got a fairly simple form with some checkboxes, radiobuttons and selectboxes. I want to post all the selected form-data using jQuery's $.ajax. But for some reason the form just doesn't get serialized. I'm not sure what's causing this... (Sidenote: $('#FormID').submit(..) doesn't work either with me). So I've created a button with the following code:
$(document).ready(function() {
    $('#DoSearchRequest').click(function(event) {
        //event.preventDefault(); // read about this somewhere, doesn't help
        $('#res').html($('#FormSearch').serialize()); // just some <p> to output the result to
        $.ajax({
            url:        'http://www.domain.nl/ajax/GetResultsBySearchRequest.php',
            data:       $('#FormSearch').serialize(),
            type:       'POST',
            success:    function(result) {
                            console.log(result);
                        },
            error: function(a, b, c) { console.log(a); }

        });

        return false;
    });
});

My button is outside the form (it doesn't matter if it's in the form either).
My form:
<form name="FormSearch" id="FormSearch" method="post">
... form elements
</form>

I'm using jQuery 1.7.1 and jQueryUI 1.8.18

A: After looking at your preview webpage I'd say the problem might be that you have nested form element "form543" inside another form element "searchbar".
Testing in Firefox, I found that $("#form543").length was 0 so jQuery obviously can't find the form at all. When I tried $("#searchbar").serialize() it returned actual field values for the select elements and the checkboxes that I'd checked and so forth.
I'd suggest removing the outer form element "searchbar" (or otherwise change the markup so you don't have nested forms) and see if your JS code works then.

A: Silly but for me it was that I didn't name the fields in my form so .serialize gave me an empty string, also .serializeArray didn't work.
Do name your form fields or you won't get any values.
<input name='importantField'/>

is not the same as
<input id='importantField'/>

.serialize or .serializeArray or even default form submit won't work if you haven't defined any names on your form fields.

A: You have to make something like that :
$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

A: use name attribute for all your inputs in the form (including button)
E.g. <input type="text" id="fname" name="fname"/>
Then you can test if the serial() function works:
$('#contact-form').submit(function() {
  alert($(this).serialize());
});

Then in Ajax:
  $.ajax({
    type: 'POST',
    url: 'SendAd.php',
    dataType: 'json',
    data: $('#contact_form').serialize(),
})


text:
Q: Iframe Link Question I have an iframe on a page and there's a link inside the iframe. When user clicks on the link I want it to open in the current page (but not in the iframe), I want the current page to reload with the target of the link in the iframe.
How can I do that? I hope there is some javascript or jquery solution because I need to achieve this in my current project.
EDIT:
Or let's say there's a form in the iframe and when submitted I don't want the page to load in the iframe but to reload the whole page.

A: Make the target attribute of the anchor "_top".
Therefore:
Test

this works in FF
Edit Concerning the new scenario of the form, I truly wouldn't know but for the anchor the above works.

A: For the anchor problem: To comply with XHTML Strict Doctype, you need to use JavaScript to accomplish this.
$('.your_link').click(function(evt) {
    evt.preventDefault();
    window.top.location.href = $(evt.target).attr('href');
});

But if Strict Doctypes don't matter, you can just use the target attribute
...

For the form problem: If you don't care about the Strict Doctype, then you can use the target attribute on the form element like so
<form target="_top" action="...">...</form>

But if you do care, then you'll have to get tricky. You will need to submit the form with AJAX. On a success, replace the html of top with the response.


text:
Q: How to get the value of the selected item in drop down and pass it without using $_POST I need to get the value of the selected items on the first dropdown because on the second drop down the list that will be shown will depend on the value from the first drop down. Here's my coding. By the way I am using PHP.
In here I am displaying the list of region, then when region is already selected the province that are only under that region should be displayed in the second drop down.
First drop down:

Region:
<select class="w3-select" name="region" id="region_value"
onChange="myFunction()" required>
<option value="">--- Select Region ---</option>
<?php
    $Region = $FormModel->RegionList();
    foreach($Region as $RegionList) {
?>
<option id="option" value="<?php echo $RegionList['region_code']?>"><?php
echo $RegionList['region_name'] ?> </option>

<?php } ?>
</select>

Second drop down:

Province:
<select class="w3-select" name="province" id="demo"  required>
<option value="">--- Select Province ---</option>
<?php
    $Province = $FormModel->ProvinceList();
    foreach($Province as $ProvinceList) {
?>
<option value="<?php echo $ProvinceList['prov_code']?>"> <?php echo
$ProvinceList['prov_name'] ?> </option>

<?php } ?>
</select>

I have a java script here getting the value of the selected items but I don't know how to pass it as an attribute to set the value as the region code.
I have a setter and getter in which I will set first the region code and in my query I am getting the value of the region code. But it's not working.

Here's my query where I get the list of province.
public function ProvinceList(){

    $region = $this->getRegion();
    $sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces WHERE
    region_code='$region' ORDER BY prov_name";

    $this->openDB();
    $this->prepareQuery($sql);
    $result = $this->executeQuery();
    $recordlist = array();
    $trash = array_pop($recordlist);

    foreach($result as $i=>$row){

                $row_data = array(
                    "prov_code"=>$row["prov_code"],
                    "psgc_prv"=>$row["psgc_prv"],
                    "prov_name"=>$row["prov_name"]
                );
            $recordlist[$i] = $row_data;
    }
    $this->closeDB();
    return $recordlist;

}

I would be a great help if someone can answer me in this work around.Thanks!

A: If fetching all the provinces at once is an option you should do this via javascript.
You need to have all the items in a javascript variable and fill you select with these values.
OnChange you should filter the values using only the ones that applies

The second drop down would be just
<select class="w3-select" name="province" id="demo"  required>
</select>

This implies stop filtering in the php query to the database
 $sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces ORDER BY prov_name";

See this feedle with a working example (without the php)
https://fiddle.jshell.net/7k18euhw/3/

Edit since there is a new request of having another select level
If you have a lot o municipalities the approach of getting all of them in the same way as in Provinces is not a good idea. In that case you will need use ajax to fetch them.
This is what you need to do:

*

*Having an accesible url that receives a province id as param and returns a json with the list of municipaties

Depending on how are you using php are many ways to do this for example if you have a framework you should have a controller is is just vainilla php should be something like this.
mun-list.php
echo json_encode($FormModel->ProvinceList($_GET['prov_id']));

*

*get the onChange event for provinces (in the same way that you are doing with regions) and make a ajax call to the service that you jus created.

As already Kaja suggested you should use jquery to do this (http://jquery.com/)
function onProvChange() {
        var prov_id = $("#prov_select").val();
        $.ajax({
            url: 'mun-list.php?prov_id='+prov_id,
            type: 'GET',
            success: function(data) {
                //without a lot of detail this should populate in the way you did before
                refreshMunicipalities(data);
            }
        });

}

You can do it without it but is harder, take a look at this post.How to make an AJAX call without jQuery?

A: By using Ajax you can fix. I have used jquery and php
For an example

$("#region_value").change(function() {
    region_value= $("#region_value").val();
        $.ajax({
            url: 'ProvinceList URL',
            data:  { region_value: region_value },
            type: 'POST',
            success: function(data) {
                var json = JSON.parse(data); \\ I have used JSON to parse data
                $('#demo').empty(); // clear the current elements in select box
                $('#demo').append('<option value=>Select province</option>');
                for (row in json) {
                    $('#demo').append('<option value='+json[row].prov_code+'>'+json[row].prov_name+'</option>');
                }
            }
        });
    });


text:
Q: MySQL Trigger Validate Before Insert I am new to MySQL TRIGGER. I want to know is it possible to check before insert using last record found?
Table AccountChecking
 ====================================================
 || ID ||  ACID  || Debit  ||    Credit   ||  Saldo ||
 ====================================================
 || 1  ||   10    || 0      ||      0     ||  100   ||
 || 2  ||   20    || 20     ||      0     ||  120   ||
 || 3  ||   30    || 0      ||      20    ||  100   ||
 ====================================================

So, what I want trying to do in Mysql is : check the inserted last Saldo with ( Debit or Credit and Saldo ) addition to Table AccountChecking , if not match the MySQL itself reject the inserted Query.
This is my Query :
DELIMITER $$

CREATE
    TRIGGER `DB`.`balanceCheck` BEFORE INSERT
    ON `DB`.`AccountChecking`
    FOR EACH ROW BEGIN
        IF(NEW.Saldo != (SELECT (SALDO+NEW.Debit-NEW.Credit) FROM AccountChecking WHERE ACID='10' ORDER BY ID DESC))
        THEN
            signal SQLSTATE '00000' SET message_text = "no no no DONT INSERT !";
        END IF;
    END$$

DELIMITER ;

A: I think you are on the right track. One thing though is that you need to handle the case when there is no match. Assuming someone adds a row like:
(4, 40, 0, 0, 1000000000)

Your IF statement will evaluate to:
IF ( 1000000000 != null ) THEN ...
IF ( null ) THEN ...

i.e. this will be allowed.
If you add a create table statement and some insert statements, together with info on whether they should be allowed or not I'm pretty sure someone can come up with a suggestion.


text:
Q: youtube_dl outtmpl format for linux  queue_path = os.path.abspath(os.path.realpath("Queue") + f"\song{q_num}.%(ext)s")

                ydl_opts = {
                    'format': 'bestaudio/best',
                    'quiet': True,
                    'outtmpl': queue_path,
                    'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }],
            }

                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    print("Downloading audio now\n")
                    ydl.download([carmelSongs[query]])

This code works as expected on a windows machine, but the file doesn't go to the queue folder in the working directory in a linux machine(cloud hosting with heroku). This is a discord.py bot, and a lot of this code is from a youtube video that I watched where I adapted the code to fit to my needs. This is one of the parts of his code that I don't fully understand, so any help would be much appreciated!
I had a testing mechanism which didn't return anything:
@client.command()
async def troubleshoot(ctx):
    for item in os.listdir("Queue"):
        print(item)

Again, any help would be very much appreciated.
I'm very much sure that this is the main issue, as all other aspects work perfectly.

A: Thanks to @peeol I was able to change all of the backslashes in my script to forwards slashes as per linux standard.


text:
Q: Align contents of two table columns together Working on an email template trying to make it a 2 column email with a Date and Message column. I was able to get the columns working using a table but now it doesnt quite line up correctly.

This is the code that builds the html

Date

<?= $title; ?>

Message

<?= $title1; ?>

Is there a way to change the HTML so that each entry lines up correctly?

A: Not quite sure what you're trying to doing with tables within tables.  Tables by default will line up rows, that's what it does. Looks like you have 1 row and put all your data for each column into a single cell.
One row to define your table headers; Date and Message
The a new row for each line of data.

            Date
            Message

                <?= $title; ?>

                <?= $title1; ?>

Do your two variables contain all that column data in each one? Like, does $title contain that entire list of dates? If so, we'll need to parse that data out using some javascript


text:
Q: ImageCommandColumn Click event not fired when i palced it in Asp.net master page
Hi,  I am working with Ext.net gridPanel, which has ImageCommandColumn
  as one column, when i click on particular image button, that is fired
  and call one Directmethod in common .aspx page. But when i place the
  Same code in contenPage which is loaded in asp.net master page the
  Click Event for the ImageCommandColumn is not firing in Gridpanel.
what should i have to do, to work with masterpage and content page
  scenario with gridpanel.
Thank you.


text:
Q: Can I add all user data in one object in mongodb? Is it possible to add all data in one object in the collection,
for example :

 {
  id:134....,
  fullname : "jack...",
  email : "amsdk@gm....",
  messages :[
   all messages here
   Perhaps up to fifty thousand items
 ],
  orders : [
   all orders here
 ],.........
 }

Does this cause any overload on the server?

A: The Mongo docs have helpful guidance for selecting a data model. The nested model you describe above is known as the Embedded Data Model:

In general, embedding provides better performance for read operations,
  as well as the ability to request and retrieve related data in a
  single database operation. Embedded data models make it possible to
  update related data in a single atomic write operation.

Embedding documents simplifies getting data out of the database. The flip-side is that it can be challenging to add and update documents with a complex document hierarchy.
Mongo calls a traditional PK/FK structure the Normalized Data Model

In general, use normalized data models:

*

*when embedding would result in duplication of data but would not provide sufficient read performance advantages to outweigh the implications of the duplication.

*to represent more complex many-to-many relationships.

*to model large hierarchical data sets.

The Aggregation Pipeline can be scary, which may make an Embedded Data Model tempting. If you feel that way, check out this free course on the MongoDB Aggregation Pipeline. A Normalized Data Model may be more appealing if you can confidently retrieve related data across collections.
Test read/write queries with a small data set for each model. You'll gain clarity about the benefits and challenges of each approach. For my current project, I found a Normalized Data Model simplified the many write operations required. Ultimately, separating concerns like orders and users into distinct collections proved simpler, especially once I understood how to use $lookup to merge data from related collections.


text:
Q: Increase Count for Conditional Values in Row I have a dataset that I am using Python 3.7 and Pandas on and I am strugging with counting rows. Based on the simplified version below, I have a dataframe with multiple columns and I need to interate over to get a count.
A          B
WalMart  "Yes"
Target
WalMart  "Yes"
BestBuy
Target   "Yes"

What I am trying to make work is below:
A          B     C
Gap              0
WalMart  "Yes"   1
Target           1
WalMart  "Yes"   2
BestBuy          2
Target   "Yes"   3

Code Attempt:
initial_count = 0
if (df["B"]=="Yes"):
   df["C"]= initial_count+1

I have a count that starts at zero, and every time column B contains a "Yes", add to this count. Any thoughts on how I can do this? I appreciate the help!

A: Compare value and use cumulative sum by Series.cumsum:
df['new'] = (df["B"]=="Yes").cumsum()
print (df)
         A    B  new
0  WalMart  Yes    1
1   Target  NaN    1
2  WalMart  Yes    2
3  BestBuy  NaN    2
4   Target  Yes    3

With some rows before first Yes:
df['new'] = (df["B"]=="Yes").cumsum()
print (df)
         A    B  new
0      gap  NaN    0
1  WalMart  Yes    1
2   Target  NaN    1
3  WalMart  Yes    2
4  BestBuy  NaN    2
5   Target  Yes    3


text:
Q: python - export or write to excel ms SQL server QUERY I have a database in sql server called zd and a table called user_tab_columns. I want to export in bulk or write to excel the result of the query statement. The code that I tried to mimic from different sources ended up giving me error messages.
In the database zd and table user_tab_columns, the field are as below:

Here is an example of my code below:
ValueError with Pandas - shaped of passed values

error message SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

import pyodbc
import pandas as pd
import os

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                              "Server=DPC;"
                               "Database=zD;"
                               "trusted_connection=yes;")

cursor = cnxn.cursor()
script = """
SELECT *
FROM user_tab_columns
WHERE table_name = "A"
"""

cursor.execute(script)

columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(list(data), columns=columns)

writer = pd.ExcelWriter('C:\Users\PROGRAMs\TEST\export.xlsx')
df.to_excel(writer, sheet_name ='bar')
writer.save()

A: I would use pandas' built-in .read_sql(). Also, in order to put " in a string in python, you need to use ' as your quotation as opposed to ".
import pyodbc
import pandas as pd
import os

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                              "Server=DPC;"
                               "Database=zD;"
                               "trusted_connection=yes;")

cursor = cnxn.cursor()
script = """
SELECT *
FROM user_tab_columns
WHERE table_name = 'A'
"""

df = pd.read_sql(script, cnxn)

writer = pd.ExcelWriter('C:\Users\PROGRAMs\TEST\export.xlsx')
df.to_excel(writer, sheet_name ='bar')
writer.save()

A: use forward slashes (/) instead of backslashes


text:
Q: React, estado tarda en actualizarse Necesito guardar algo en mi base de datos por lo que tengo que mandar un objeto, este objeto lo tengo en un estado debido a que uso algunas propiedades para el formulario y otras las asigno antes de enviar la petición al servidor
Mi problema es que el estado se actualiza después que hago la petición al servidor y no debería ser así
Este es mi código cuando inicia el componente
const [seguimientoActividad, setSeguimientoActividad] = useState<ISeguimientoActividades>({
    idActividad:0,
    descripcion:'',
    fecha: moment().format('YYYY-MM-DD'),
    idEmpleado: user.idUsuario,
    idEstatus: 0,
});

Este es mi código donde envió la petición al servidor asignando nuevos valores al estado
const guardarSeguimiento = async (idAct: number) => {

    const id = finalizada ? estatus.filter(estatus => estatus.nombre === 'Finalizada')[0].idEstatus : estatus.filter(estatus => estatus.nombre === 'Abierta')[0].idEstatus;
  //Agregando valores al estado
    setSeguimientoActividad({
        ...seguimientoActividad,
        idActividad: idAct,
        idEstatus: id
    });
    console.log(seguimientoActividad) //Me muestra el estado sin los nuevos valores

    const respuesta = await saveSeguimientoActividad(seguimientoActividad);
    if (respuesta) return true;
    return false;
}

El problema es que cuando hago el console.log, el estado aun no se ha actualizado

A: Voy a dar una breve explicación de por qué sucede esto y al mismo tiempo darte una posible solución a lo que quieres hacer.
¿Por qué no veo mi estado actualizado?
Cuando estás utilizando el hook useState, este te devuelve un valor con estado y una función para actualizarlo.

Durante el renderizado inicial, el estado devuelto (state) es el mismo que el valor pasado como primer argumento (initialState).

Cuando llamas la función setState , esta recibe un nuevo valor para actualizar el estado del componente, sitúa en la cola una nueva renderización del componente.
¿Esto qué significa?
Cuando colocas el console.log(state) inmediatamente después de haber llamado el setState, estas apuntando al valor pasado (que en tu caso es el objeto inicial que le pasas) tal que no verás ninguna actualización hasta que el componente vuelva actualizarse.
En pocas palabras
setState no cambia tu estado inmediatamente, lo agrega a una lista de "voy a cambiarlo".
Es como decirle a tu componente "Ok componente, llegamos a un acuerdo, y es que en el proximo re-render vas a tener este valor".
¿Qué puedo hacer para solucionarlo?
Aquí es donde viene el hook useEffect.

Por defecto, los efectos se ejecutan después de cada renderizado completado, pero puede elegir ejecutarlo solo cuando ciertos valores han cambiado.

Teniendo en cuenta esto, lo que quieres hacer es correr el efecto justo cuando el estado seguimientoActividad cambie.

...

useEffect(() => {

   async function saveNuevaActividad(actividad) {
    /**
      idActividad es un falsy value. Inicialmente esto me dará falso por lo cual
      el efecto no va a correr. Cuando lo setees va tener un valor diferente de
      cero y va entrar
    */
    if (seguimientoActividad.idActividad) {
      try {
        const respuesta = await saveSeguimientoActividad(seguimientoActividad);
        if (respuesta) {
          // Aquí console.log(respuesta) te dará el valor que quieres.
        }
      } catch (error) {
        // Maneja los errores en tu petición.
      }
    }
  }

  saveNuevaActividad(); // Llamas la función

}, [seguimientoActividad])// Le pasas la dependencia que quieres que dispare este efecto

...

Dame algo para copiar y pegar (?)
Así se vería tu código completo.

const [seguimientoActividad, setSeguimientoActividad] = useState<ISeguimientoActividades>({
    idActividad:0,
    descripcion:'',
    fecha: moment().format('YYYY-MM-DD'),
    idEmpleado: user.idUsuario,
    idEstatus: 0,
}); // Te recomiendo separar este objeto en varios useState

useEffect(() => {
   async function saveNuevaActividad(actividad) {
    if (seguimientoActividad.idActividad) {
      try {
        const respuesta = await saveSeguimientoActividad(seguimientoActividad);
        if (respuesta) {
         // TODO:
        }
      } catch (error) {
        // TODO:
      }
    }
  }
  saveNuevaActividad(); // Llamas la función

}, [seguimientoActividad])

const guardarSeguimiento = async (idAct: number) => {
const id = finalizada ? estatus.filter(estatus => estatus.nombre === "Finalizada")[0].idEstatus : estatus.filter(estatus => estatus.nombre === "Abierta")[0].idEstatus;
    const nuevoState = {
        ...seguimientoActividad,
        idActividad: idAct,
        idEstatus: id
    };
    setSeguimientoActividad(nuevoState);
}

En general puedes usar esta plantilla para ejectuar cualquier caso similar. No hay limitaciones en cuanto a la cantidad de useEffect que puedes crear, así que no te preocupes por eso.
Nota: Estoy considerando que saveSeguimientoActividad es algun tipo de función que ya tienes definida y la cual es asíncrona.

A: Creo que lo que debes hacer es asignar un estado para cada una de las propiedades que estan dentro de ese objeto. De esa manera si ese estado especifico no se modifica, envias el estado que asignaste cuando el componente carga:
En vez de esto const [seguimientoActividad, setSeguimientoActividad]
Haz esto:
const [idActividad, setIdActividad] = useState(0);
const [descripcion, setDescripcion] = useState('');
const [fecha, setFecha] = useState(moment().format('YYYY-MM-DD');
const [idEmpleado, setIdEmpleado] = useState(user.idUsuario);
const [idEstatus, setIdEstatus] = useState(0);

Asi estaras controlando cada estado por separado. No olvides asignar el onChange property en el input del formulario


text:
Q: Как достать переменные из URL? Добрый день. Пишу интернет магазин, по одному курсу, который нашел на просторах интернета. В одном моменте у меня выявилась загвоздка. Товары из БД выводятся полностью по всем категориям. Не захватывает в url переменные cat и type (например: ../viewCat.php?cat=canon&type=laserCartridge):

$cat = $_GET['cat'];
        $cat = strip_tags($cat);
        $cat = mysql_real_escape_string($cat);
        $cat = trim($cat);
    $type = $_GET['type'];
        $type = strip_tags($type);
        $type = mysql_real_escape_string($type);
        $type = trim($type);
    if (!empty($cat) && !empty($type)){
        $querycat = "AND brand='$cat' AND type_product='$type'";
    }else{
        if(!empty($type)){
            $querycat = "AND type_product='$type'";
        }else{
            $querycat = "";
        }
    }
    $result = mysql_query("SELECT * FROM products WHERE visible='1' $querycat ORDER BY $sorting",$link);

A: Это должно помочь вам выяснить что "захватывается", а что нет:
$cat = $_GET['cat'];
        $cat = strip_tags($cat);
        $cat = mysql_real_escape_string($cat);
        $cat = trim($cat);
    $type = $_GET['type'];
        $type = strip_tags($type);
        $type = mysql_real_escape_string($type);
        $type = trim($type);
    if (!empty($cat) && !empty($type)){
        $querycat = "AND brand='$cat' AND type_product='$type'";
    }else{
        if(!empty($type)){
            $querycat = "AND type_product='$type'";
        }else{
            $querycat = "";
        }
    }

    echo "
";
    var_dump($_GET['cat']);
    echo "
";
    echo "
";
    var_dump($_GET['type']);
    echo "
";
    echo "
";
    var_dump($querycat);
    echo "
";
    die();

    $result = mysql_query("SELECT * FROM products WHERE visible='1' $querycat ORDER BY $sorting",$link);


text:
Q: Java vs. firewall: how to let Java applications have their own set of rules Let's say I have coded a Java application that requires Internet access. Usually the firewall pops up and asks whether or not this is OK. Now I have the options to generally allow Internet access or use specific rules. Since I only check a web service I'd set a rule that restricts access to exactly that server at some port.
Now I have Java application #2 that also requires Internet access. If I decided to give application #1 full access then #2 also has full access. For the solution with the rule set above I'd need to add another rule or just give up and grant full access and, therefore, also give application #1 full access.
I guess you can see what my problem is. A while ago I ran into the same situation and I tried one or two wrappers that convert a JAR into an executable. I noticed that in the end they simply launched the JVM causing the usual Java binary to open the Internet connection.
So my question is: which options do I have to allow a user to specify different firewall rules for each Java application?
EDIT: after reading the first comment I'd like to make clear that I'm not thinking about how to configure the firewall, but rather have some way that Java applications themselves have a more or less unique way of identifying themselves or have another way of handling network access.

A: When you require is more fine grained access. Why not author a policy file and allow the security manager to govern the SocketPermissions that are allotted to your program?
http://download.oracle.com/javase/7/docs/technotes/guides/security/permissions.html.
Example below.
grant signedBy "paul" {
    permission java.net.SocketPermission "localhost:1024-", "accept, connect, listen";
};

A: A firewall is like a semi-permeable membrane, allowing outbound but not inbound connections:
                      |
 Outside world <===== | ====== Your computer
                      |
                   Firewall [OK]

                      |
 Outside world ====== X =====> Your computer
                      |
                   Firewall [Disallowed]

One thing that you can do to get around this is to setup a proxy that is outside of the firewall that accepts inbound connections from the outside world, as well as inbound connections from your "real" server. The proxy can route the external requests to one of the inbound sockets from one of the servers:
                                   |
 Outside world ===> [Proxy] <===== | ====== Your computer
                                   |
                              Firewall [OK]

That said, without knowing your exact situation, this might not be the best design choice. For example, you might be doing something that does not really require running a server, or maybe you really do want to be running a server, but maybe should be running one on cloud computing infrastructure. It is hard to recommend an actual design without additional details as to what you wish to accomplish.

A: Simple silly way around this. Copy and rename java.exe to different names.
If you have two apps rename java[w].exe to:
MyApp.exe
MyApp2.exe
then you can put specific rules in your firewall based on executable.

A: Ship your jvm with your product and write a script to launch it and set the necessary variables for it to function independent of any other jvm on the system.
I.e
Classpath
/app/launch/java -jar jar.file
This way only your version of java is launched.