text:
Q: Resubmit Search Results From Array Back To MySQL DB with hidden fields my first post on here, even though I am a regular visitor to this very helpful site
I wonder if someone can please help me with the following:
I am writing a simple stock check solution for my company in PHP with MySQL, im still a novice but learning.
We have the following search form that shows results from a database when the barcode of the product is entered, what I am looking to do is have a button at the bottom of the results that says "Checked OK", which resubmits the info back to the database, updates the timestamp, and has a hidden field to change the "status" to checked.
The database name is "stock"
The table name is "main_stock"
The fields are:
id
curr_timestamp
mastercategory
category
product_desc
barcode
serial
status
Each search only gives one result as the barcodes are unique
The bit i am stuck on is how to get the result into a form to be able to resubmit them back into the database
This is only for internal use within a protected network, any help is greatly appreciated
Thanks
Jon
    <?php

    $dbHost = 'localhost'; // localhost will be used in most cases

    // set these to your mysql database username and password.

    $dbUser = 'xxxxxxxx';
    $dbPass = 'xxxxxxx';
    $dbDatabase = 'stock'; // the database you put the table into.

    $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL         Server. Error: " . mysql_error());
    mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}.         Error: " . mysql_error());

    // Set up our error check and result check array

    $error = array();
    $results = array();

    // First check if a form was submitted.
    // Since this is a search we will use $_GET

    if (isset($_GET['search'])) {
    $searchTerms = trim($_GET['search']);
    $searchTerms = strip_tags($searchTerms); // remove any html/javascript.

    if (strlen($searchTerms) < 2) {
    $error[] = "Search terms must be longer than 2 characters.";
    }else {
    $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
    }

    // If there are no errors, lets get the search going.

    if (count($error) < 1) {
    $searchSQL = "SELECT mastercategory, category, product_desc, barcode, serial FROM main_stock         WHERE ";

    // grab the search types.
    $types = array();
    $types[] = isset($_GET['barcode'])?"`barcode` LIKE '%{$searchTermDB}%'":'';
    $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not         checked)

    if (count($types) < 1)
    $types[] = "`barcode` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked

    $andOr = isset($_GET['matchall'])?'AND':'OR';
    $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `barcode`"; // order by title.
    $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.
" .         mysql_error() . "
SQL Was: {$searchSQL}");

    if (mysql_num_rows($searchResult) < 1) {
    $error[] = "The scanned barcode {$searchTerms} is not in the database.";
    }else {
    $results = array(); // the result array
    $i = 1;
    while ($row = mysql_fetch_assoc($searchResult)) {
    $results[] = "{$i}:Product Name :
  {$row['product_desc']}
Master Category :
  {$row['mastercategory']}
Sub         Category :
  {$row['category']}
Barcode : {$row['barcode']}
Serial No. : {$row['serial']}";
    $i++;
    }
    }
    }
    }
    function removeEmpty($var) {
    return (!empty($var));
    }?>

    <title>Search Form</title>

    <form action="index.php">

      <input type=submit value="Home" />

</form>
    <?php echo (count($error) > 0)?"The following had errors:
" . implode("
", $error) . "

":""; ?>

    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="GET" name="searchForm" class="cent">
    <onLoad="document.searchForm.search()">

        Search For:

          <input name="search" type="text" onFocus="this.value='';" value="<?php echo isset        ($searchTerms)?htmlspecialchars($searchTerms):''; ?>" size="28" maxlength="15" />

    </form>

        <form action="addproduct.php">

              <input type=submit value="Add New Product" />

        </form>

    <?php
    echo (count($results) > 0)?"SUCCESS: {$searchTerms} :

" . implode("", $results):"";
    ?>

A: Welcome to StackOverflow!
The idea here is to grab the data from the database, and re-populate the form. When I build pages like this, I usually have a parameter in the URL contains the primary key of the MySQL row, I want to grab, like this mypage.php?id=37.
If $_GET['id'] is set and is numeric, then I run a query like this:
$id = mysqli::real_escape_string($_GET['id']);
$data = mysqli::query("SELECT * FROM table WHERE id = '{$id}'");

//Check to see if we got any data back :)

Then, we can populate the form again:
<input name="value1" type="hidden" value="<?php echo stripslashes($data['value1'])" />

Once the data is submitted from the user again, then run a query like this:
$id = mysqli::real_escape_string($_GET['id']);
$value1 = mysqli::real_escape_string($_POST['value1']);
$value2 = mysqli::real_escape_string($_POST['value2']);
mysqli::query("UPDATE table SET value1='{$value1}', value2='{$value2}' ... WHERE id = '{$id}' LIMIT 1");

Edit:
From what I gather, your button on the detail page will submit (I'm guessing the product name  of) one of the returned products back into the database, along with the time it was searched, and a status, of some sort.
As you loop through the array of fetched results to display them to the user, I would gather the name of the product and push it on an array like this:
$fetchedProducts = array();

while (/*Loop condition to loop through fetched results*/) {
  array_push($loopVariable['productName'], $fetchedProducts);

  //Build HTML to display results
}

//Insert into database
$products = mysqli::real_escape_string(json_encode($fetchedProducts));
$timestamp = strtotime("now");
$status = "some status";

mysqli::query("INSERT INTO searchRecords (
                  `id`, `products`, `timestamp`, `status`
               ) VALUES (
                  NULL, '{$products}', '{$timestamp}', '{$status}'
               )");

Hope that helps.


text:
Q: PHP print- TD class is not working I have the following problem:
I want to print a  in PHP, which will have the class "myclass" which gives blue background to the  that cointains variables less than 5 ,and an orange background to the  that contains variables greater than 5 .
Problem is that when ever i try to do that, the  background stays default.
Anyone knows why?

<?php
for($x=0;$x<10;$x++){
$myVar=rand(0,10);
  if($myVar<5){
    print "
";
    print "$myVar	";
    print "
";
    print "
";
  }
   else{
    print "
";
    print "$myVar	";
    print "
";
    print "
";

}

}

?>

A: Because you closed your
 tag to early:

This should be in this format:

Example with your code:

<?php
for($x=0;$x<10;$x++){
$myVar=rand(0,10);
  if($myVar<5){
    print "
";
    print "$myVar	";
    print "
";
    print "
";
  }
   else{
    print "
";
    print "$myVar	";
    print "
";
    print "
";
}
}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to 'make prod' Akeneo PIM on macOS Catalina using Docker I am trying to install Akeneo PIM Community Edition on my macOS Catalina following these instructions: https://docs.akeneo.com/4.0/install_pim/docker/installation_docker.html
Steps using Docker are successful until I want to launch PIM in prod mode using the command
$ make prod
when I get the error message: make: *** No rule to make target `prod'.  Stop.
I execute this command inside the 'pim' directory in my home directory (~iwan/pim).
Instructions say the make command needs to be executed within directory /srv/pim but I do not find this directory on my Mac.
Where do I find /srv/pim or what went wrong?
Thanks for any help,
Iwan
in directory ~iwan/pim (pim is a subdirectory in my home directory (iwan))

A: The /srv/pim directory exists inside the pim_fpm_1 container and is mapped via a volume to your ~/iwan/pim directory.
There should be a Makefile in this directory with lines like these:
.PHONY: prod
prod:
  $(MAKE) dependencies
  $(MAKE) pim-prod

(The Makefile was created when you ran the commands under https://docs.akeneo.com/latest/install_pim/docker/installation_docker.html#creating-the-pim-project)


text:
Q: How to check apk files for common security issues before the deployment? I would like to check apk files for common security issues before the deployment.
Is there any tool which can scan my file?
For example: I am deploying an apk but Google Play notify me that the apk contains a webview vulnerability. -> I would like to avoid from these situations.

A: This github repository provides various list of tools like app vulnerability scanners,static and dynamic analysis and so on.It is continuously updated and should be helpful.
github link


text:
Q: Read data of known format in c++ I had a txt file that contains float numbers separated by space like this:

3.141600 7.54654
4.021560 7.54654
7.54654 4.021560
9.549844 3.141600

and I used the following code to read the data..
int main ()
{

    ifstream file("myFile.txt");

    float x;
    float y;

    while(file >> x >> y)
    std::cout << x << ' ' << y << std::endl;

    system ("pause");
}

That works just fine.....
Now I am given a very strange text file which has some stuff like this:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0
  Arial;}}
{*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20
  0.017453293\tab
2.01623406\par
0.087266463\tab 2.056771249\par
0.191986218\tab 2.045176705\par
0.27925268\tab 1.971733548\par
0.366519143\tab 1.844657601\par
0.453785606\tab 1.669694097\par
0.541052068\tab 1.4539812\par
0.628318531\tab 1.205819241\par
0.715584993\tab 0.934405231\par
0.802851456\tab 0.649540807\par

...... and so on...
I want to read this file and get the x (that appears before \tab) and y (appears before \par) values how can I do that? Notice that there is no space. It is know that \tab and \par appears in all lines of data.

A: Your "strange text file" is in RTF format. You can try to write a parser yourself, but you may well be better off by using a library like http://sourceforge.net/projects/librtf/ .
Even better, ask whoever gave you the data to send it in a proper format. Data for processing in an RTF file is somewhat ridiculous in my humble opinion.

A: You can always use regular expressions, something like:
    std::string pattern("(\\d+.\\d+)\\\\tab[^\\d]+(\\d+.\\d+)\\\\par");
    std::regex r(pattern);

    std::ifstream ifs("input_data.txt");

    std::string data;
    while(getline(ifs, data))
    {
        for (std::sregex_iterator it(data.begin(), data.end(), r), end_it; it != end_it; ++it)
        {
            std::cout << it->str(1) << " " << it->str(2) << std::endl;
        }
    }

(!) If there are line breaks between X and Y values, you might need to read the contents of the file in a string.
EDIT:
A pattern using raw string literals:
std::string pattern(R"((\d+.\d+)\\tab[^\d]+(\d+.\d+)\\par)");


text:
Q: ng build dist folder not rendering site I'm having issues making my angular2 app work on an ftp server. This is my first time adding angular2 site to ftp server. I ran ng build in the project folder and put the dist folder on the ftp server, but all I get is the message Loading... from index.html Loading... Is there another step after running ng build that I'm missing. I'm also getting the following errors in console
The files it says are missing are in the dist folder so I'm not sure why I'm getting that error. I've been stuck on this for a couple days now so any help is greatly appreciated.

A: I fixed these issues with the command
ng build --base-href="./"

and in the angular.json file, must set the property outputPath with only dist.
Here an example: https://javadesde0.com/deploy-subida-de-una-aplicacion-de-angular-a-github-pages-de-forma-totalmente-gratuita/  by David Bernal

A: You have to configure the server to serve from the index file.

So you would like to deploy your production build to an Apache2
  server? You will notice then that
reloading pages, besides root, and deep linking will cause 404 errors
  (unless you are using the HashLocation strategy). The reason is that
  all Angular2 routes should be served via the index.html file.
This can be achieved by adding a .htaccess file (in the same directory
  where the index.html resides) with the following contents.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Check this for more information.


text:
Q: SQL or PL/pgSQL for the following query to have a better performance I am migrating from SQL Server to PostgreSQL and I have the following stored procedure and function in SQL Server.
ALTER FUNCTION [dbo].[GetContainsSafeText] (@text nvarchar(250))
RETURNS nvarchar(250)
AS
BEGIN
    SET @text = ISNULL(NULLIF(ISNULL(@text, ''), ''), '""');
    SET @text = TRIM(@text);

    WHILE (CHARINDEX('  ', @text) > 0)
        SET @text = REPLACE(@text, '  ', ' ');

    SET @text = REPLACE(@text, ' ', ' AND ');

    RETURN @text;
END

ALTER PROCEDURE [dbo].[SearchGroupQuery]
    @skip int,
    @count int,
    @text nvarchar(250),
    @from datetime2,
    @location uniqueidentifier,
    @category uniqueidentifier,
    @geoLocation geography
AS
BEGIN
    SET NOCOUNT ON;

    SET @text = dbo.GetContainsSafeText(@text);

    WITH LocationTree AS
    (
        SELECT Id, ParentId
        FROM Locations
        WHERE Id = @location
        UNION ALL
        SELECT Locations.Id, Locations.ParentId
        FROM LocationTree
        JOIN Locations ON LocationTree.Id = Locations.ParentId
    )
    SELECT *
    FROM [groups] g
    WHERE (@text = '""' OR
           CONTAINS([Description], @text) OR
           CONTAINS([Title], @text) OR
           Id IN (SELECT GroupId
                  FROM [Events]
                  WHERE [Time] >= @from
                     AND (CONTAINS([Description], @text) OR
                          CONTAINS([Title], @text))
                 ))
      AND (@location IS NULL OR LocationId IN (SELECT Id FROM LocationTree))
      AND (@category IS NULL OR Id IN (SELECT GroupId  FROM [GroupCategories] cg
                                       WHERE cg.CategoryId = @category))
    ORDER BY
        Title
        OFFSET @skip ROWS FETCH NEXT @count ROWS ONLY;
END

I have migrated them to the following but I faced with the control reached end of function without RETURN. I found this question but the accepted answer was not helpful for me. It just made me wondered which one is better SQL or PL/pgSQL. I found the accepted answer here interesting. If I understand it correctly, I cannot use SQL but the question is how can I make the following better? Also, adding return query did not solve my issue.
CREATE OR REPLACE FUNCTION GetContainsSafeText(p_text char varying(250))
RETURNS char varying(250)
AS $$
    BEGIN
        p_text := coalesce(nullif(coalesce(p_text, ''), ''), '""');

        p_text := trim(p_text);

        while(POSITION('  ' IN  p_text) > 0) loop
            p_text := replace(p_text, '  ', ' ');
        END Loop;

        p_text := replace(p_text, ' ', ' & ');

        RETURN p_text;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION SearchGroupQuery (
    p_skip int,
    p_count int,
    p_text char varying(250),
    p_from timestamp(6),
    p_location char varying(36),
    p_category char varying(36),
    p_geoLocation geography)
RETURNS setof "Groups" AS $$
BEGIN

    p_text := GetContainsSafeText(p_text);

    return query --<< this was missing the first time

    with recursive LocationTree
    as
    (
        select "Id", "ParentId" from "Locations" where "Id" = p_location
        union all
        select "Locations"."Id", "Locations"."ParentId" from LocationTree t join "Locations" on t."Id" = "Locations"."ParentId"
    )
    select
        *
    from "Groups" g
    where
        (
            p_text = '""""' or
            to_tsvector('simple', "Title" || ' ' || "Description") @@ to_tsquery(p_text) or
            Id in (
                select "GroupId"
                from "Events"
                where "Time" >= p_from and
                    to_tsvector('simple', "Title" || ' ' || "Description") @@ to_tsquery(p_text)
            )
        ) and
        (
            p_location is null or
            "LocationId" in (select "Id" from "LocationTree")
        ) and
        (
            p_category is null or
            "Id" in (
                select "GroupId"
                from "GroupCategories" cg
                where cg."CategoryId" = p_category
            )
        )
    order by "Title"
    LIMIT  v_count offset p_skip ;

END;
$$ LANGUAGE plpgsql;

A: I ended up with the following functions:
I made GetContainsSafeText a SQL because it does not need an execution plan to be ready.
CREATE OR REPLACE FUNCTION GetContainsSafeText(p_text char varying(250))
RETURNS char varying(250)
AS $$
     select trim(regexp_replace(coalesce(nullif(coalesce(p_text, ''), ''), '""'), '\s+', ' ', 'g'));
$$ LANGUAGE SQL;

And SearchGroupQuery a PL/pgSQL because the execution plan seems complex (At least to me). So it is nice to have it ready the first time and use it so on.
CREATE OR REPLACE FUNCTION SearchGroupQuery (
    p_skip int,
    p_count int,
    p_text char varying(250),
    p_from timestamp(6),
    p_location uuid,
    p_category uuid,
    p_geoLocation geography)
RETURNS setof "Groups" AS $$
BEGIN

    p_text := GetContainsSafeText(p_text);
 return query --<< this was missing
    with recursive LocationTree
    as
    (
        select "Id", "ParentId" from "Locations" where p_location is not null and "Id" = p_location
        union all
        select "Locations"."Id", "Locations"."ParentId" from LocationTree t join "Locations" on t."Id" = "Locations"."ParentId"
    )
    select
        *
    from "Groups" g
    where
        (
            p_text = '""""' or
            to_tsvector('simple', "Title" || ' ' || "Description") @@ to_tsquery(p_text) or
            "Id" in (
                select "GroupId"
                from "Events"
                where "Time" >= p_from and
                    to_tsvector('simple', "Title" || ' ' || "Description") @@ to_tsquery(p_text)
            )
        ) and
        (
            p_location is null or
            "LocationId" in (select "Id" from LocationTree)
        ) and
        (
            p_category is null or
            "Id" in (
                select "GroupId"
                from "GroupCategories" cg
                where cg."CategoryId" = p_category
            )
        )
    order by "Title"
    LIMIT  p_count offset p_skip ;

    return;
END;
$$ LANGUAGE plpgsql;

Also, please inform me if I did it wrong or did it with the wrong resean.


text:
Q: Upload file not work with ajax I tired to solve this.
my form cant upload file using ajax, but it's work without ajax.
this's my code
insertpage.php

<?php

$tanggal    = date("Y-m-d");

echo"

<form id='form1' enctype='multipart/form-data' action='simpanpage.php' method='post'>

             Foto 	  : 	  <input type=file name=fotoh id=fotoh>

             Judul 	  : 	  <input type=text name=judul id=judul maxlength='50' size='50' required placeholder='Masukan Judul'>

             Deskripsi 	  : 	  <textarea required id=deskripsi  name='deskripsi' > </textarea>

             Isi 	  : 	  <textarea required id=isi name='isi'> </textarea>

             Label 	  : 	  <input type=text id=label name=label  placeholder='Masukan Label'><input type=hidden name=tgl_dibuat id=tgl_dibuat value=".$tanggal.">

    <button id='btn'>Save</button>

</form>

";

?>

koneks.php
<?php

class database{

private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "oop_blog";

    function connectMySQL(){
    mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
    mysql_select_db($this->dbName) or die("Database tidak ada!");
    }

    function manageinsertPage($judul, $isi, $tgl_dibuat, $deskripsi, $label){
        $lokasi     = $_FILES["fotoh"]["tmp_name"];
        $namafoto   = $_FILES["fotoh"]["name"];
        $direktori  = "gambar/$namafoto";

        if (move_uploaded_file($lokasi, $direktori))
        {
            $qry    = mysql_query("INSERT INTO pages(judul,isi,foto,tgl_dibuat,deskripsi,label) VALUES('$judul','$isi','$namafoto','$tgl_dibuat','$deskripsi','$label')");

            echo"berhasil Insert Bersama Foto";
        }

        else{
            $qry1    = mysql_query("INSERT INTO pages(judul,isi,tgl_dibuat,deskripsi,label) VALUES('$judul','$isi','$tgl_dibuat','$deskripsi','$label')");
            echo"Berhasil";
        }
    }

?>

simpanpage.php
<?php

include "koneks.php";

$dbi = new database;

$dbi->connectMYSQL();

$dbi->manageinsertPage($_POST["judul"],$_POST["isi"],$_POST["tgl_dibuat"],$_POST["deskripsi"],$_POST["label"]);

?>

im just confused because, my form cant read $_FILES['fotoh']['name']; with ajax, that's made me fail when uploading..
the answer allways null in database.
i need help here, thank you so much

A: check here, tested
$('document').ready(function(){

    $('#btn').click(function(event){
        event.preventDefault();
        $.ajax({
            url : $('#form1').attr('action'),
            type: "POST",
            data : new FormData($('#form1')[0]),
            processData: false,
            contentType: false,
            success:function(data){

            }
        });
    })

})

A: If you are using a compatible browser, you can use the $.ajax function and FormData to do the file upload with something like this:
$('document').ready(function(){
  $('#btn').click(function(event){
    event.preventDefault();
    $.ajax({
      url: $('#form1').attr('action'), // simpanpage.php
      type: 'POST',
      contentType: 'multipart/form-data', // Same as your form enctype.
      data: new FormData($('#form1')), // Your form with the file inputs.
      processData: false               // No need to process data.
    }).done(function(){
      console.log("Success: File uploaded!");
    }).fail(function(){
      console.log("Error: Failed to upload file!");
    });
  });
});

For more examples, please refer the doc.


text:
Q: Slice values are getting wiped out after refreshing Pie chart I am using below code to populate slice values in a pie chart using JS and it's correctly working but
I am observing another problem as these values are getting populated only once and when I reload the charts it's getting disappeared. Now let's say if I close the browser and open again or change the browser it will show values again. But after doing multiple force refresh Ctrl+F5 then also it's not showing the values. Could you please help?
Please note I am having more than 3 pie charts on the same page with a different id.
var canvas = document.getElementById('myChart');
new Chart(canvas, {

    type: 'pie',
    data: {
      labels: ['January', 'February', 'March'],
      datasets: [{
        data: [50445, 33655, 15900],
        backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: true,
      plugins: {
        labels: {
          render: 'percentage',
          fontColor: ['green', 'white', 'red'],
          precision: 2
        }
      },
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>


text:
Q: I want to take user input in Spark dataframe but giving error ['list' object is not callable] I can not take any inputI have a schema.
schm = StructType([
    StructField("ID", IntegerType(), True),
    StructField("fixed_credit_limit", IntegerType(), True),
    StructField("credit_limit", IntegerType(), True),
    StructField("due_amount", IntegerType(), True),
    StructField("created_date", StringType(), True),
    StructField("updated_date", StringType(), True),
    StructField("agent_name_id",IntegerType(), True),
    StructField("rfid_id", StringType(), True),
])

input=[(13158,100,100,0,'05/29/2021 11:01:31','05/29/2021 11:01:31',5,'862b4497-577f-47f9-8725-dd6c397ce408')]
df1 = spark.createDataFrame(input, schema)

I want to take the user input of agent_name_id but it gives the error ['list' object is not callable]
how can I take the user input of agent_name_id.


text:
Q: Excel Number to Word shows Four Hundred and Fifty Fifteen and Not Four Hundred and Fifty Five I have a UDF that spells numbers into words. The issue I'm having is that when I type in a number between 11-19 I run into the issue of it being spelt as "OneTwo" for 12 etc
This is my code:
Function NumInHundredsThousandsMillions(IPNum As Long)
If IPNum > 999999999 Then NumInHundredsThousandsMillions = "ERROR": Exit Function

Dim TempNum As Long
Dim Num(1 To 3)
Dim Dig1, Dig2, Pos
Dim IpnumTxt As String, StrHun As String, Str2digit As String, TempStr As String
Dim T As Long
Dig1 = Array("", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", _
        "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen ")

Dig2 = Array("", "", "Twenty ", "Thirty ", "Fourty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety ")

Pos = Array("", "Million ", "Thousand ", "")

Num(1) = Int(IPNum / 1000000)
Num(2) = Int((IPNum - Num(1) * 1000000) / 1000)
Num(3) = IPNum Mod 1000

For T = 1 To 3
 If Num(T) > 0 Then
 If Len(Num(T)) = 3 Then StrHun = Dig1(Int(Num(T) / 100)) & "Hundred "
 Num(T) = Right(Num(T), 2) + 0
 Str2digit = Dig2(Int(Num(T) / 10)) & Dig1(Num(T) Mod 10)
    If T = 3 And StrHun <> "" And Str2digit <> "" Then StrHun = StrHun & "and "
    TempStr = TempStr & StrHun & Str2digit & Pos(T)
 End If
Next T
NumInHundredsThousandsMillions = TempStr
End Function

Everything functions as it should but If a number is from 11-19 it will say "OneTwo" for 12, etc.
The other thing I'd like to achieve for a number like 555,555 I would like it to say "Five Hundred and Fifty Five Thousand Five Hundred and Fifty Five" and not Five Hundred Fifty Five Thousand Five Hundred and Fifty Five - I can't seem to work out how to add this in without other numbers being affected with my code


text:
Q: Scan html files in poedit Hello I want scan html files in Poedit to translate the text there.
I have code in html file like this:
_("translate me")

and I want the Poedit scan the word translate me like he scan PHP file without using PHP codes only
pure html.
Please give me helpful answer. I really stuck I can't translate my template.
I tried to add .html, .htm in Poedit preferences and actually it does not read my words,
I asked Poedit service center in email and they give me a "shift for oneself" answer.

A: This is a complicated problem. The basic answer is "Poedit will not parse strings inside of PHP functions such as _() unless they are within <?php ?> wrappers". You did the right thing by adding *.html to the extensions list, but it still will not parse strings that are not contained within <?php ?> tags.
My solution to this is to place <?php ?> wrappers in the file, even if they will not be parsed by the server or render correctly, and then use some javascript to strip the PHP tags at load. This allows Poedit to parse the strings within the _() function calls, while quickly stripping away the ugly php tags before the user can see them.
Below is the js code I put together to solve this problem today (requires jQuery). Please be aware that it is not fully tested, and almost assuredly needs additional work. It only supports a small handful of element types currently, and only supports stripping of _() and __() functions. You must give elements that you want it to strip a class of i18n in order for this to work (complete example below):

function _get_elem_translatable_string(elem) {
    // Get attr_name
    attr_name = _get_attr_name(elem);

    // Get current translatable value
    if (attr_name == 'html') {
        str = $(elem).html();
    }else{
        str = $(elem).attr(attr_name);
    }

    // Return
    return str;
}
function _set_elem_string(elem, str) {
    // Get attr_name
    attr_name = _get_attr_name(elem);

    // Update the element
    if (attr_name == 'html') {
        // Set html for 'normal' elements
        $(elem).html(str);
    }else if (attr_name == 'value') {
        // Set value for 'value' elements (typically a submit input)
        $(elem).val(str);
    }else{
        // Set attr value for other elements
        $(elem).attr(attr_name, str);
    }
}
function _get_attr_name(elem) {
    // Determine attr that will be affected based on tag type of elem
    if ($(elem).is('input') && ($(elem).attr('type') == 'text' || $(elem).attr('type') == 'password')) {
        attr_name = 'placeholder';
    }else if ($(elem).is('input') && $(elem).attr('type') == 'submit') {
        attr_name = 'value';
    }else{
        attr_name = 'html';
    }

    // Return
    return attr_name;
}
function _contains_php_gettext(str) {
    // bool: Is the string is a php tag containing a call to 'echo _()'?
    regexp = _php_regexp();
    if (str.match(regexp))
        return true;
}
function _strip_php_gettext(str) {
    // If the string is a php tag containing a call to 'echo _()', strip to PHP tag
    regexp = _php_regexp();
    if (str.match(regexp)) {
        // Detect if delimieter is apostrophe or quotation mark
        delim = (str.match(/echo[ \t]*_\('/) ? "'" : (str.match(/echo[ \t]*_\("/) ? '"' : ''));

        // Strip tag
        str = str.replace(regexp, "$2");

        // Strip escape chars
        if (delim == "'")
            str = str.replace(/\\'/, "'");
        if (delim == '"')
            str = str.replace(/\\"/, '"');
    }

    // Return
    return str;
}
function _php_regexp() {
    return /^<(!--)*\?php[ \t]*echo[ \t]*_\(['"](.*)['"]\)[ \t;]*\?[-]*>/i;
}

// Start when document ready
$(document).ready(function() {
    // Convert non-parsed PHP tags (for instance if this page is running on a server that does not run PHP)
    $('.i18n').each(function(i, elem) {
        // Get translatable string from elem
        str = _get_elem_translatable_string(elem);

        // Strip PHP, ITIS
        if (_contains_php_gettext(str)) {
            // Set
            _set_elem_string(elem, _strip_php_gettext(str), true, true);
        }
    });
});

This will allow you to place the following into your .html/.php file:

<?php echo _("translate me"); ?>

But after the js runs the user will only see:

translate me


text:
Q: How do masses on a spring accelerate when the connection between them is cut?
I'm learning about springs in Physics and have come across something I do not fully understand.
As in the picture, there are three masses (A, B and C), with mass ma, mb and mc, respectively. In the configuration above, masses A and B are connected by a light inelastic string. The masses of the string and the two springs are negligible and the whole system is stationary (in equilibrium).
What I want to work out is the acceleration of the three masses when the string between A and B is suddenly cut.
I currently understand from slinkies that C would stay stationary while S2 contracts. So B is accelerating downwards. Therefore, C would have no acceleration.
Also, S1 is carrying all three masses but after the string is cut, it only carries ma, so it would contract upwards with a force equivalent to g(mb+mc), because they are the forces taken away from the spring. But when I calculate the acceleration of A using F=ma, I end up with a=g and I am not sure if that is correct, because I also get a=g for the acceleration of B.
I am trying to express each acceleration in terms of ma, mb, mc and g.
I am not looking for answers, as I know this is not a homework site. All I ask is for pointers in the right direction and perhaps correct me if my understanding of the spring system is flawed.
Thank you.

A: When the connection between A & B is cut, mass of B & C is removed from the spring. When the masses B & C were attached, they exerted some force on the spring causing extension. They are removed so the spring will relax and extension in it will be reduced. Mass A will be accelerated upwards and will start performing simple harmonic motion. As for the masses B & C, gravitational force will pull them down. They will be in free- fall and therefore mass C will not pull the spring downward as it was doing in initial conditions. So, the spring will relax and come back to it's natural length. Coming back to it's natural length, it will exert an upward force on C and downward force on B.


text:
Q: Connect Multiple Journey to a Single Automation in a batch process I'd like to know if it is possible to connect more than one journey within a single automation. The Automation studio receives a large amount of data on a regular basis and sends it to different journeys. What is the correct way of doing this.
My attempt:
Within the automation studio, I have created a scheduler which inserts records to a SQL table (Data Extension). Have created a server side script to read data from the tables and then fire multiple journeys. However, such a solution is slow as the java script becomes a bottleneck as the SQL operations are relatively faster.
PS: Looking for something that is faster and can be scaled to handle data in batches.
Thank you for helping out.

A: You can have a Data extension as an entry source for your journeys. From automation studio, you are pushing records to multiple data extensions. You can use these data extension as an entry source for your respective journey. So when ever the records is getting pushed to data extension your journey will get triggered.


text:
Q: What do the numbers in a version typically represent (i.e. v1.9.0.1)? I've always assumed each number delineated by a period represented a single component of the software. If that's true, do they ever represent something different?
How should a version number be structured to start assigning versions to the different builds of my software? As an aside, my software has five distinct components.

A: Numbers can be useful as described by other answers, but consider how they can also be rather meaningless... Sun, you know SUN, java: 1.2, 1.3, 1.4 1.5 or 5 then 6.
In the good old Apple II version numbers Meant Something. Nowadays, people are giving up on version numbers and going with silly names like "Feisty fig" (or something like that) and "hardy heron" and "europa" and "ganymede". Of course this is far less useful because, you're going to run out of moons of jupiter before you stop changing the program, and since there's no obvious ordering you can't tell which is newer.

A: The more points, the more minor the release.  There's no real solid standard beyond that - can mean different things based on what the project maintainers decide on.
WordPress, for example, goes along these lines:
1.6 -> 2.0 -> 2.0.1 -> 2.0.2 -> 2.1 -> 2.1.1 -> 2.2 ...
1.6 to 2.0 would be a big release - features, interface changes, major changes to the APIs, breakage of some 1.6 templates and plugins, etc.
2.0 to 2.0.1 would be a minor release - perhaps fixing a security bug.
2.0.2 to 2.1 would be a significant release - new features, generally.

A: There is the Semantic Versioning specification
This is the summary of version 2.0.0:

Given a version number MAJOR.MINOR.PATCH, increment the:

*

*MAJOR version when you make incompatible API changes,

*MINOR version when you add functionality in a backwards-compatible manner, and

*PATCH version when you make backwards-compatible bug fixes.

  Additional labels for pre-release and build metadata are available as
  extensions to the MAJOR.MINOR.PATCH format.

A: In version v1.9.0.1:
This is the explicit versioning scheme used when you don't want to use name for the pre-releases or build like -alpha,-beta.
1:Major version which might break the backward compatibility
9:Adding of new features to support you app along with backwards compatibility with previous version.
0:Some minor bug-fixes
1:Build number(Pre-release number)
but nowadays,you won't find such versioning scheme.Do refer Semantic Versioning [semver2.0]
https://semver.org/

A: release.major.minor.revision would be my guess.
But it can vary greatly between products.

A: Usually its:
MajorVersion.MinorVersion.Revision.Build

A: Version numbers don't usually represent separate components.  For some people/software the numbers are fairly arbitrary.  For others, different parts of the version number string do represent different things. For example, some systems increase parts of the version number when a file format changes. So V 1.2.1 is file format compatible with all other V 1.2 versions (1.2.2, 1.2.3, etc.) but not with V 1.3.  Ultimately it's up to you what scheme you want to use.

A: In version 1.9.0.1:

*

*1: Major revision (new UI, lots of new features, conceptual change, etc.)

*9: Minor revision (maybe a change to a search box, 1 feature added, collection of bug fixes)

*0: Bug fix release

*1: Build number (if used)—that's why you see the .NET framework using something like 2.0.4.2709
You won't find a lot of apps going down to four levels, 3 is usually sufficient.

A: It depends, but the typical representation is that of major.minor.release.build.
Where:

*

*major is the major release version of your software, think .NET 3.x

*minor is the minor release version of your software, think .NET x.5

*release is the release of that version, typically bugfixes will increment this

*build is a number that denotes the number of builds you have performed.

So for instance, 1.9.0.1, means that it's version 1.9 of your software, following 1.8 and 1.7, etc. where 1.7, 1.8 and 1.9 all in some way typically add small amounts of new features alongside bugfixes. Since it's x.x.0.x, it's the initial release of 1.9, and it's the first build of that version.
You can also find good information on the Wikipedia article on the subject.

A: Major.Minor.Bugs
(Or some variation on that)
Bugs is usually bug fixes with no new functionality.
Minor is some change that adds new functionality but doesn't change the program in any major way.
Major is a change in the program that either breaks old functionality or is so big that it somehow changes how users should use the program.

A: Everyone chooses what they want to do with these numbers.  I've been tempted to call releases a.b.c since it's rather silly anyway.  That being said, what I've seen over the last 25+ years of development tends to work this way.  Let's say your version number is 1.2.3.
The "1" indicates a "major" revision.  Usually this is an initial release, a large feature set change or a rewrite of significant portions of the code.  Once the feature set is determined and at least partially implemented you go to the next number.
The "2" indicates a release within a series.  Often we use this position to get caught up on features that didn't make it in the last major release.  This position (2) almost always indicates a feature add, usually with bug fixes.
The "3" in most shops indicates a patch release/bug fix.  Almost never, at least on the commercial side, does this indicate a significant feature add.  If features show up in position 3 then it's probably because someone checked something in before we knew we had to do a bug fix release.
Beyond the "3" position?  I have no clue why people do that sort of thing, it just gets more confusing.
Notably some of the OSS out there throws all this out of wack.  For example, Trac version 10 is actually 0.10.X.X.  I think a lot of folks in the OSS world either lack confidence or just don't want to announce that they have a major release done.

A: It can be very arbitrary, and differs from product to product. For example, with the Ubuntu distribution, 8.04 refers to 2008.April
Typically the left most (major) numbers indicate a major release, and the further you go to the right, the smaller the change involved.

A: major.minor[.maintenance[.build]]
http://en.wikipedia.org/wiki/Software_versioning#Numeric

A: Major.minor.point.build usually.  Major and minor are self-explanatory, point is a release for a few minor bugfixes, and build is just a build identifier.

A: Yup. Major releases add big, new features, may break compatibility or have significantly different dependencies, etc.
Minor releases also add features, but they're smaller, sometimes stripped-down ported versions from beta major release.
If there is a third version number component, it's usually for important bugfixes, and security fixes. If there are more, it really depends so much on product that it's difficult to give general answer.

A: Generally then number are in the format of version.major.minor.hotfix, not individual internal components. So v1.9.0.1 would be version 1, major release 9 (of v1), minor release (of v1.9) 0, hot fix 1 of (v1.9.0).

A: From the C# AssemblyInfo.cs file you can see the following:
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
/ You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

A: The paradigm of major release.minor release.bug fix is pretty common, I think.
In some enterprise support contracts there is $$$ (or breach of contract liability) associated with how a particular release is designated.  A contract, for example, might entitle a customer to some number of major releases in a period of time, or promise that there will be fewer than x number of minor releases in a period, or that support will continue to be available for so many releases.  Of course no matter how many words are put in to the contract to explain what a major release is versus a minor release, it is always subjective and there will always be gray areas – leading to the possibility that the software vendor can game the system to beat such contractual provisions.

A: People don't always recognize the subtle difference between version numbers like 2.1, 2.0.1, or 2.10 - ask a technical support person how many times they've had trouble with this.  Developers are detail oriented and familiar with hierarchical structures, so this is a blind spot for us.
If at all possible, expose a simpler version number to your customers.

A: In the case of a library, the version number tells you about the level of compatibility between two releases, and thus how difficult an upgrade will be.
A bug fix release needs to preserve binary, source, and serialization compatibility.
Minor releases mean different things to different projects, but usually they don't need to preserve source compatibility.
Major version numbers can break all three forms.
I wrote more about the rationale here.

A: version:  v1.9.0.1
where-
. v is abbreviation of version. It varies with company to company depend on nomenclature adopted in his organisation. It may silent in some organisation like 1.9.0.1
. 1 indicates major version, will be updated on Architectural modification in application stacks, infrastructure (platform) or exposed networks interface
. 9 incates minor, will be updated on activity like adding new components like ui, api, database etc; under a specific architecture
. 0 indicates feature, will be updated on any enhancements on existing components (ui, api, database etc)
. 1 indicates build counter across all phase major, minor and feature. It also include hotfixes post production release.

A: A combination of major, minor, patch, build, security patch, etc.
The first two are major & minor-- the rest will depend on the project, company and sometimes community. In OS's like FreeBSD, you will have 1.9.0.1_number to represent a security patch.

A: Depends a bit on the language, Delphi and C# for example have different meanings.
Usually, the first two numbers respresent a major and a minor version, i.e. 1.0 for the first real release, 1.1 for some important bugfixes and minor new features, 2.0 for a big new feature release.
The third number can refer to a "really minor" version, or revision. 1.0.1 is just a very small bugfix to 1.0.0 for example. But it can also carry the Revision number from your Source Control System, or an ever-incrementing number that increments with every build. Or a Datestamp.
A little bit more detail here. "officially", in .net, the 4 numbers are "Major.Minor.Build.Revision", whereas in Delphi there are "Major.Minor.Release.Build". I use "Major.Minor.ReallyMinor.SubversionRev" for my versioning.

A: The first number is typically referred to as the major version number. It's basically used to denote significant changes between builds (i.e. when you add many new features, you increment the major version). Components with differing major versions from the same product probably aren't compatible.
The next number is the minor version number. It can represent some new features, or a number of bug fixes or small architecture changes. Components from the same product which differ by the minor version number may or may not work together and probably shouldn't.
The next is usually called the build number. This may be incremented daily, or with each "released" build, or with each build at all. There may be only small differences between two components who differ by only the build number and typically can work well together.
The final number is usually the revision number. Often times this is used by an automatic build process, or when you're making "one-off" throw-away builds for testing.
When you increment your version numbers is up to you, but they should always increment or stay the same. You can have all components share the same version number, or only increment the version number on changed components.

A: The version number of a complex piece of software represents the whole package and is independent of the version numbers of the parts. The Gizmo version 3.2.5 might contain Foo version 1.2.0 and Bar version 9.5.4.
When creating version numbers, use them as follows:

*

*First number is main release. If you make significant changes to the user interface or need to break existing interfaces (so that your users will have to change their interface code), you should go to new main version.

*Second number should indicate that new features have been added or something works differently internally. (For example the Oracle database might decide to use a different strategy for retrieving data, making most things faster and some things slower.) Existing interfaces should continue working and the user interface should be recognizable.

*Version numbering further is up to the person writing the software - Oracle uses five (!) groups, ie. an Oracle version is something like 10.1.3.0.5. From third group down, you should only introduce bugfixes or minor changes in functionality.

A: the ones that vary less would be the first two, for major.minor, after that it can be anything from build, revision, release, to any custom algorithms (like in some MS products)

A: Every organization/group has it's own standard. The important thing is that you stick to whatever notation you choose otherwise your customers will be confused. Having said that I've used normally 3 numbers:
x.yz.bbbbb. Where:
x: is the major version (major new features)
y: is the minor version number (small new features, small improvements without UI changes)
z: is the service pack (basically the same as x.y but with some bug fixes
bbbb: is the build number and only really visible from the "about box" with other details for customer support. bbbb is free format and every product can use it's own.

A: Here is what we use:

*

*First number = Overall system era. Changes every couple of years and typically represents a fundamental change in technology, or client features or both.

*Second number = database schema revision. An increment in this number requires a database migration and so is a significant change (or systems replicate and so changing the database structure requires a careful upgrade process). Resets to 0 if the first number changes.

*Third number = software only change. This can usually be implemented on a client by client basis as the database schema is unchanged. Resets to zero if the second number changes.

*Subversion version number. We populate this automatically on build using the TortoiseSVN tool. This number never resets but continually increments. Using this we can always recreate any version.

This system is serving us well because every number has a clear and important function. I have seen other teams grappling with the major number/minor number question (how big a change is major) and I dont see the benefit to that. If you dont need to track database revisions just go to a 3 or 2 digit version number, and make life easier!

A: Despite the fact that most of the previous answers give perfectly good explanations for how version numbering could and should be used, there is also another scheme, which I would call the marketing versioning scheme. I'll add this as an answer, because it exists, not because I think it's worth following.
In the marketing versioning scheme, all those technical thoughts and meanings are replaced by bigger is better. The version number of a product is derived from two rules:

*

*bigger (higher) numbers are better than smaller (lower) numbers

*our version number should be bigger (higher) than any of the competitors' version numbers

That takes version numbering out of the hands of the technical staff and puts where it belongs (sales and marketing).
However, since technical version still makes sense in a way, the marketing versions are often accompanied under the hood by technical version numbers. They are usually somehow hidden, but can be revealed by some info or about dialog.


text:
Q: $_SESSION not setting? I'm working on a simple app for internal use for a small company.  I am having difficulties getting the account logins working correctly, and I believe it has something to do with $_SESSION not being set like I expected it to.  Now I am fairly new to PHP, and have been learning as I go.
index.php contains this:
<?php
session_start();

require_once('includes/config.inc.php');
require_once('includes/functions.inc.php');

// Check login status -- if not logged in, redirect to login screen
if (check_login_status() == false) {
redirect('login.php');
}

So when I load the app, I'm redirected to login.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-    strict.dtd">

<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="css/login.css" />

<form id="login-form" method="post" action="includes/login.inc.php">
<fieldset>
  <legend>Login to Inventory System</legend>

Please enter your username and password to access the Inventory system

    <input type="text" name="username" id="username" />Username:

    <input type="password" name="password" id="password" />Password:

    <input type="submit" name="submit" id="submit" value="Login" />

  </fieldset>
  </form>

When I hit submit on the login page, includes/login.inc.php is called:
<?php
session_start();

require_once('config.inc.php');
require_once('functions.inc.php');

// Escape any unsafe characters before querying database
$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);

// Construct SQL statement for query & execute
$query = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . MD5 ($password) . "'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
$_SESSION['logged_in'] = true;
 redirect('../index.php');
} else {
 redirect('../login.php');
}
?>

Now I've been able to determine that the login is being processed successfully, because if I disable the check_login_status function in index.php, I'm redirected to index.php if I login with a valid account.  Under the same conditions, an incorrect password will reload login.php.  With the function disabled, I've also tried adding "print_r($_SESSION)" at the top of index.php, but nothing ever loads, which makes me think something is wrong with my function.
functions.inc.php:
<?php
function redirect($page) {
  header('Location: ' . $page);
  exit();
}

function check_login_status() {
  // IF $_SESSION['logged_in'] is set, return the status
  if (isset($_SESSION['logged_in'])) {
    return $_SESSION['logged_in'];
  }
  return false;
}
?>
config.inc.php:

<?php
$con=mysqli_connect("server_name","user","pass","db_name");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  ?>

I'm really at a loss, and I don't know where the problem is.  I've checked for syntax errors with "php -l file.php" and found no syntax errors.  I'm not sure how to do any other debugging with this, or what I'm missing.  Help is truly appreciated!
Code blocks might be off a little. Yes, I know MD5 passwords are not recommended, and that will be changed to use salt once I can get functionality in my app.  I will also be escaping/preparing all MySQL queries once I get the login piece working.

A: this won't fix your problem, but simplifies your check_login_status function.
function check_login_status() {
    return (isset($_SESSION['logged_in']) && $_SESSION['logged_in']===true);
}

also your session variable is not being set because the cookie is not being stored by the browser. your header() function overrides the other headers that would've been set.
Many people use session_write_close(); as the fix. Add that BEFORE the redirect.
See: https://bugs.php.net/bug.php?id=14636
<?php
session_start();

require_once('config.inc.php');
require_once('functions.inc.php');

// Escape any unsafe characters before querying database
$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);

// Construct SQL statement for query & execute
$query = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . MD5 ($password) . "'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
$_SESSION['logged_in'] = true;
session_write_close();
 redirect('../index.php');
} else {
 redirect('../login.php');
}
?>

A: It seems to me like in your function you've put return false; which is meaning your function always returns false. That might be why you can't see anything when you print $_SESSION. I would encase that "return false" in an else, like this:
function check_login_status() {
  // IF $_SESSION['logged_in'] is set, return the status
  if (isset($_SESSION['logged_in'])) {
    return $_SESSION['logged_in'];
  }
  else {
  return false;
  }
}

Also, I would consider setting the user ID in the $_SESSION variable instead of just setting it as a boolean. Means you can create user-related content more easily by just setting $i = $_SESSION['id']; in your include at the beginning.


text:
Q: Test pipe with dependencies on services I have a pipe that sanatises HTML as below:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
    name: 'sanitiseHtml'
})

export class SanitiseHtmlPipe implements PipeTransform {

constructor(private _sanitizer: DomSanitizer) {}

    transform(value: any): any {
      return this._sanitizer.bypassSecurityTrustHtml(value);
    }

}

I want to test it as below:
describe('Pipe: Sanatiser', () => {
    let pipe: SanitiseHtmlPipe;

    beforeEach(() => {
        pipe = new SanitiseHtmlPipe(new DomSanitizer());
    });

    it('create an instance', () => {
        expect(pipe).toBeTruthy();
    });
});

The DomSanatizer is an abstract class which is autowired by typescript by passing it into a constructor:
constructor(private _sanitizer: DomSanitizer) {}

Currently I get the typescript errror:

Cannot create an instance of the abstract class 'DomSanitizer'.

Does anyone know what typescript does when instantiating dependencies passed into a constructor in Angular? Or what the way to test something like this is?

A: Because of the DI in your pipe, you need to configure a test environment (test bed) to resolve the dependency:
import { BrowserModule, DomSanitizer } from '@angular/platform-browser';
import { inject, TestBed } from '@angular/core/testing';

describe('SanitiseHtmlPipe', () => {
  beforeEach(() => {
    TestBed
      .configureTestingModule({
        imports: [
          BrowserModule
        ]
      });
  });

  it('create an instance', inject([DomSanitizer], (domSanitizer: DomSanitizer) => {
    let pipe = new SanitiseHtmlPipe(domSanitizer);
    expect(pipe).toBeTruthy();
  }));
});

A: In case you want to mock the whole providers and don't wanna use the constructor, this is how I do it (with Jest but replace the spy with your regular jasmine.createSpyObj)
spec
describe("MyPipe", () => {
  let pipe: MyPipe;
  const myServiceSpy = { myFunction: jest.fn() };

  beforeEach(() => {
    jest.clearAllMocks();
    TestBed.configureTestingModule({
      providers: [
        MyPipe,
        {
          provide: MyService,
          useValue: myServiceSpy
        }
      ]
    });

    pipe = TestBed.inject(myPipe);
  });

  it("create an instance", () => {
    expect(pipe).toBeTruthy();
  });
});

pipe
@Pipe({
  name: "myPipe"
})
export class MyPipe implements PipeTransform {
  constructor(private readonly myService: MyService) {}

  transform(value: Item): boolean {
    // stuff with your service
    return true;
  }
}

A: just in case anyone would like to reuse the constructor of the Pipe, you can use the TestBed to acheive the same result :
  let pipe: SafeHtmlPipe;
  let sanitized: DomSanitizer

  beforeEach(async() => {
    TestBed.configureTestingModule({
      providers: [DomSanitizer]
    });
    sanitized = TestBed.get(DomSanitizer);
    pipe = new SafeHtmlPipe(sanitized);
  });

  it('create an instance', () => {
    expect(pipe).toBeTruthy();
  });


text:
Q: Jquery trigger animation on each click (issue) I need to trigger the animation on each button click not toggling the button class as I have on my snippet bellow:
I tried with addClass() and removeClass() similar methods, but it doesnt work as expected, here is the code:

$(document).ready(function () {
    $("button[class*='navbar-toggler']").click(function () {
        $(this).toggleClass("my-animation")
    });
})
@keyframes my-animation {
 16.65% {
  transform: translateY(8px);
 }

 33.3% {
  transform: translateY(-6px);
 }

 49.95% {
  transform: translateY(4px);
 }

 66.6% {
  transform: translateY(-2px);
 }

 83.25% {
  transform: translateY(1px);
 }

 100% {
  transform: translateY(0);
 }
}

.my-animation {
  animation-name: my-animation;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: 1;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navToggler" aria-controls="navToggler" aria-expanded="false" aria-label="Toggle navigation">

                        </button>

A: Use setTimeout funtion for remove my-animation class and use
.navbar-toggler{
outline:0!important;
}

$(document).ready(function () {
    if(!$("button[class*='navbar-toggler']").hasClass('my-animation')){
    $("button[class*='navbar-toggler']").click(function () {
        $(this).addClass("my-animation");
        setTimeout(function(){  $("button[class*='navbar-toggler']").removeClass("my-animation"); }, 1000);
    });
    }
})
@keyframes my-animation {
 16.65% {
  transform: translateY(8px);
 }

 33.3% {
  transform: translateY(-6px);
 }

 49.95% {
  transform: translateY(4px);
 }

 66.6% {
  transform: translateY(-2px);
 }

 83.25% {
  transform: translateY(1px);
 }

 100% {
  transform: translateY(0);
 }
}

.my-animation {
  animation-name: my-animation;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: 1;
}

.navbar-toggler{
outline:0!important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navToggler" aria-controls="navToggler" aria-expanded="false" aria-label="Toggle navigation">

                        </button>

A: this may help you
using

$(document).ready(function () {
    $("button[class*='navbar-toggler']").click(function () {
        $(this).addClass("my-animation");
            setTimeout(function () {
                $('#YourId').removeClass('my-animation');
            }, 200);
    });
})


text:
Q: Is the set of continuous function with Lebesgue zero set a Borel set in continuous space? Let $D$ be a domain in $\mathbb{R^d}$ and denote the continuous function space on $D$ as $X := C(\overline{D})$ where we can define the $\sigma$-algebra $\mathscr{B}(X)$ of $X$, that is sets in $X$ containing all open sets of $X$ and closed under countable unions and taking complements. We define the zero set of $u$ as $Z_u = \{x\in \overline{D}: u(x) = 0\}$ and denote $m(A)$ as the Lebesgue measure of $A\subset \overline{D}$. If $F: = \{u\in C(\overline{D}): m(Z_u) = 0\}$, can we prove that $F\in \mathscr{B}(X)$?
It is easy to see that $F$ is not a closed set in $X$. But can we write $F$ as countable union of closed set or other form of Borel set? Otherwise, is there any counterexample to make that false?

A: Your set $F$ is a $G_\delta$ set (countable intersection of open sets).
I assume that your domain $D$ is bounded, so that $K:=\overline D$ is compact;  and that the topology of $X=\mathcal C(K)$ is accordingly given by the sup norm.
Observe first that a set $A\subset K$ has Lebesgue measure $0$ if and only if, for any $\varepsilon >0$, one can find an open set $O$ containing $A$ such that $m(O)<\varepsilon$. Denoting (for each $\varepsilon >0$)by $\mathcal O_\varepsilon$ the family of all open sets $O\subset \mathbb R^d$, it follows that $$F=\bigcap_{k\in\mathbb N} \bigcup_{O\in\mathcal O_{1/k}}\mathbf U_{O}\, , $$
where
$$\mathbf U_{O}=\{ u\in X;\; Z_u\subset O\}\, . $$
So, the only thing to check is that for any fixed ope set $O$, the set $\mathbf U_O$ is open in $X=\mathcal C(K)$.
Let us fix an open set $O$, and let $u\in\mathbf U_O$. Then $u(x)\neq 0$ for all $x\in K\setminus O$. Since $u$ is continuous and $K\setminus O$ is compact, it follows that one can find $\alpha >0$ such that $u(x)\geq\alpha$ for all $x\in K\setminus O$. Then, any function $v\in X$ such that $\Vert v-u\Vert_\infty<\alpha/2$ will satisfy $v(x)>\alpha/2$ on $K\setminus O$, so that in particular $Z_v\subset O$. In other words, the open ball $B(u,\alpha/2)$ in $X$ is contained in $\mathbf U_O$. This shows that $\mathbf U_O$ is open in $X$, as required.


text:
Q: Trouble running converted custom trained model on RPI4 using TFLite I am trying to run a mask detecting model on my RPI4.
I followed this Roboflow tutorial:
https://www.youtube.com/watch?v=pXLLNa4IrmM&list=LL&index=1&t=1169s.
However, after converting the darknet model to a TFLite model, I am getting this error:

2021-01-30 21:42:03.351149: E
tensorflow/core/platform/hadoop/hadoop_file_system.cc:132]
HadoopFileSystem load error: libhdfs.so: cannot open shared object
file: No such file or directory Traceback (most recent call last):
File "TFLite_detection_webcam.py", line 138, in
interpreter = Interpreter(model_path=PATH_TO_CKPT)   File
"/home/pi/.local/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter.py",
line 207, in init    model_path, self._custom_op_registerers))
ValueError: Didn't find op for builtin opcode 'RESIZE_BILINEAR'
version '3' Registration    failed.

I know I am probably missing information that could help solve this problem, but I am not sure what else I should be including.
I was able to run premade object models, however the custom model I made using the YouTube guide did not work.
How do I solve this issue? Or, is there another way to train a custom model to work on the RPI4?

A: I think you are using a too old version of Tensorflow. Can you try the latest version of nightly?


text:
Q: Rails & Capistrano 3 - staging server trying to user production database I've setup a server for my staging environment using NGINX & Passenger.  I've also setup a staging.rb file which is a duplicate of my production.rb file under environments.  In my database.yml file I've put in a staging configuration:
  staging:
  adapter: mysql2
  database: myapp_staging
  username: root
  password: xxxxxxxxxxxxx
  port: 3306
  pool: 15
  timeout: 5000

Environments/staging.rb:
role :app, %w{deploy@111.111.111.111}
role :web, %w{deploy@111.111.111.111}
role :db,  %w{deploy@111.111.111.111}

# Extended Server Syntax
# ======================
# This can be used to drop a more detailed server definition into the
# server list. The second argument is a, or duck-types, Hash and is
# used to set extended properties on the server.

server '111.111.111.111', user: 'deploy', roles: %w{web app db}, port: 0001

I deploy with cap staging deploy however the app won't start and in the logs it says: Unknown database 'myapp_production'
How can I force it to use the staging database?
EDIT
Deploy.rb:
set :application, 'dispatch'
set :repo_url, 'myapp'

set :deploy_to, '/home/deploy/myapp'

set :scm, :git
set :branch, 'master'
set :keep_releases, 5
set :format, :pretty
set :log_level, :debug
set :pty, true
set :passenger_restart_with_sudo, true

set :stages, ["staging", "production"]
set :default_stage, "staging"

set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}
set :rvm_map_bins, fetch(:rvm_map_bins, []).push('rvmsudo')

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  after :publishing, 'deploy:restart'
  after :finishing, 'deploy:cleanup'
end

A: With my cap 3 setup, i have a config/deploy/production.rb file where the environment gets set. Are you doing the same for both staging & production?
set :stage, :staging
server 'example.com', user: 'aaron', roles: %w{web app db}
set :rails_env, :staging

Need to be sure it sets the proper environment, so the db tasks will know what database to connect to.

A: You should set environment in staging.rb
set :stage, :staging
set :rails_env, :staging

Then you should also set environment using "PassengerAppEnv" variable in apache virtual host file
  <VirtualHost *:80>
    ServerName myserver.com
    # Tell Apache and Passenger where your app's 'public' directory is
    DocumentRoot /var/www/your_app/current/public

    PassengerAppEnv staging
    <Directory /var/www/your_app/current/public>
      Allow from all
      Options -MultiViews
      Require all granted
    </Directory>
</VirtualHost>

This fixed the same problem for me. I hope it helps everyone face it too.

A: OK this was a pretty stupid to miss, but I did not set my NGINX config file to "Staging"
     server_name localhost;
     passenger_enabled on;
     rails_env    staging;
     root         /home/myapp;

A: I have met with a similar problem. In my case issue was related with ENV variables into .bashrc file in staging server. In this file was set variable:
RAILS_ENV=production

I changed to:
RAILS_ENV=staging

After you need reload variables:
source ~/.bashrc


text:
Q: Total all counts foreach count in php array The code selects department, which then lists courses in that department, i then want the total amount of resources for linked courses (parent and child courses) to also be echoed.
I am trying to get a Total sum from foreach count in php array.
Can anbody help me with this please?
Here is my code:
$categoryid = $_POST['dept'];

//get course codes from department
$get_dept_codes = mysql_query("SELECT id, name FROM course_categories WHERE parent = 0 order by name asc");

    echo "<form method='POST' action='gsb_by_department.php'>
";
    echo "<select size='1' name='dept'>";
    //loop through and list department names in drop down box
    while($row = mysql_fetch_array($get_dept_codes))
        {
        $catid = $row['id'];
        $catname = $row['name'];
        echo "<option name='category' value=$catid>$catname</option>";

        //echo $catid;
        //echo $catname;
        echo "
";
        }

echo "</select><input type='submit' value='Submit' name='submit'>
</form>";

//get course codes from department

$get_dept_codes = mysql_query("SELECT course.id, course.shortname, course.fullname, gsb_content.gsb
FROM _course INNER JOIN gsb_content ON course.id = gsb_content.courseid
WHERE (((course.category)=$categoryid)) AND course.metacourse = 0
ORDER BY course.id;");

//loop through and process for courses

while($row = mysql_fetch_array($get_dept_codes))
    {

$childcourse = $row['id'];

//Get the $parentcourses

    $parentcourses= mysql_query("SELECT parent_course FROM course_meta where child_course = $childcourse");

//for each of the $parentcourses count FROM resource where course=$theparentcourse

    foreach($parentcourses as $parentcourse)) {
    $thenewid = $parentcourse['parent_course'];
    $thecount = mysql_query("SELECT count(*) FROM resource where course=$thenewid");
    }

//I want to be able to add up all the counts from the above and store in variable

    $allcountstandardslinknum = array_sum($countstandardslinknum);
}

Does anybody have any ideas/guidance.
Would be greatly appreciated.

A: I think this is what you need:
$sql = "SELECT
    course_meta.parent_course,
    COUNT(DISTINCT resource.id) AS count
FROM
    course_meta
INNER JOIN resource ON course_meta.parent_course = resource.course
WHERE
    course_meta.child_course = $childcourse
GROUP BY course_meta.parent_course";

$query = mysql_query($sql);

while ($result = mysql_fetch_assoc($query))
{
  echo 'Course "' . $result['parent_course'] . '" has " . $result['count'] . " resources.
';
}

Word of warning, if $childcourse is a string you'll need to enclose it in single-quotes here.
Also, are you sure the naming here is right? Surely a child course only has one parent course (and a parent course potentially having many child courses?).

A: I'm not sure if the above was meant as pseudo code but the mysql_query method returns a result object so you need to do something like mysql_fetch_array.
As for getting the total you can just sum in your loop like so:
$total = 0;
foreach($parentcourse as $parentcourses)) {
    $thenewid = $parentcourse['parent_course'];
    $thecountrow = mysql_fetch_array(mysql_query("SELECT count(*) FROM resource where course=$thenewid"));
    $thecount = $thecountrow[0];
    $total += $thecount;
}
echo "Total is $total";

You may also want to add sanity checking and the like too.
Edit:
Also just noticed your foreach loop has the variables the wrong way, it should be:
foreach($parentcourses as $parentcourse){

I always remember this as a sentence: "for each of the items in $parentcourses name $parentcourse"
Edit2:
Your $parentcourses variable isn't actually an array you need to grab each row in a similar way to your outer while loop something like:
$parentcoursesres= mysql_query("SELECT parent_course FROM course_meta where child_course = $childcourse");
$total = 0;
while($parentrow = mysql_fetch_assoc($parentcoursesres)){
    $thenewid = $parentrow['parent_course'];
    $thecountrow = mysql_fetch_array(mysql_query("SELECT count(*) FROM resource where course=$thenewid"));
    $thecount = $thecountrow[0];
    $total += $thecount;
}
echo "Total is $total";

A: Try this :
$result= mysql_query("SELECT parent_course FROM course_meta where child_course = $childcourse");

$parentcourses = mysql_fetch_array($result);


text:
Q: KDE Template Header not displaying The KDE template won't display the .png image file.  I haven't changed anything from the stock settings.  I wanted to give the template a whirl, but all I see is a label called oxygen-header for a space where the image file should be.  What do you guys think is the issue?

A: You have to build directly to pdf. Since it is a png file you have to compile it with pdflatex. Standard latex can't embed png files. A simple pdflatex example-talk works fine for me.
You can build it using the Makefile if your editor supports it. But someone else might be able to tell you how to do this with texify or WinEdt.


text:
Q: Export table to excel table Hi I'm trying to export a table present in a site, when I open the csv file I find myself exported only the first row and in the execution of the code it returns me

cannot set a row with mismatched columns

the code:
from curses import color_content
from email import header
from lib2to3.pgen2.token import COLONEQUAL
from wsgiref import headers
import requests
from bs4 import BeautifulSoup
import pandas as pd

#page to access
url = 'site.xxx'

#request.get

page = requests.get(url)

#beatifulSoup

soup = BeautifulSoup(page.text, 'lxml')

#extract table

table1=soup.find('table',id='table28')

#extract column

headers = []
for i in table1.find_all('th'):
   title = i.text
   headers.append(title)

#create dataframe

mydata=pd.DataFrame(columns=headers)

# Create a for loop to fill mydata
for j in table1.find_all('tr')[1:]:
    row_data = j.find_all('td')
    row = [i.text for i in row_data]
    length = len(mydata)
    mydata.loc[length] = row

# Export to csv
mydata.to_csv('classifica_piloti2.csv', index=False)# Try to read csv
mydata2 = pd.read_csv('classifica_piloti2.csv')


text:
Q: sonarqube gradle plugin exception when using android productFlavors In my Android project I am using org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6.1.
When I added some productFlavors using android.productFlavors and android.flavorDimensions the sonarqube task fails with error:

:app:sonarqube
Invalid value for sonar.java.test.binaries

And with following trace:
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:sonarqube'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.IllegalStateException: No files nor directories matching 'build/intermediates/classes/debug'
    at org.sonar.java.AbstractJavaClasspath.getFilesFromProperty(AbstractJavaClasspath.java:93)
    at org.sonar.java.JavaTestClasspath.init(JavaTestClasspath.java:47)
    at org.sonar.java.AbstractJavaClasspath.getElements(AbstractJavaClasspath.java:281)
    at org.sonar.java.SonarComponents.getJavaTestClasspath(SonarComponents.java:145)
    at org.sonar.java.JavaSquid.<init>(JavaSquid.java:84)
    at org.sonar.plugins.java.JavaSquidSensor.execute(JavaSquidSensor.java:83)
    at org.sonar.batch.sensor.SensorWrapper.analyse(SensorWrapper.java:57)
    at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:58)
    at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:50)
    at org.sonar.batch.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:83)
    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:192)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:241)
    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:236)
    at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:226)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
    at org.sonar.batch.task.ScanTask.execute(ScanTask.java:47)
    at org.sonar.batch.task.TaskContainer.doAfterStart(TaskContainer.java:86)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
    at org.sonar.batch.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:106)
    at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:119)
    at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
    at com.sun.proxy.$Proxy323.execute(Unknown Source)
    at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
    at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
    at org.sonarqube.gradle.SonarQubeTask.run(SonarQubeTask.java:99)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:731)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 27 more

My build.gradle looks like this:
android {
  ...
  flavorDimensions "deploymentEnvironment"
  productFlavors {
        prevalidation {
            dimension "deploymentEnvironment"
        }
        ...
  }
...
sonarqube {
    androidVariant 'prevalidationDebug'
    properties {
        property "sonar.exclusions", "**/*Generated.java"
    }
}

Is this a known issue? How can I work around or fix this? TIA

A: I have found that I was overriding correct defaults for 'sonar.binaries' and 'sonar.java.test.binaries' and various other sonar properties in my gradle.properties file without realizing it. Once I removed those from my gradle.properties the problem has gone away.


text:
Q: Why does this code work without dynamicly allocating memory The Code is supposed to count the amount of times a substring accours in a longer string and detect the location of the substring in the longer string. My Code seems to work but I am wondering why it worked even without allocating memory to index. Intuitvely i thought that because its not clear how many elements index has i would have to allocate memory to it.
I appreciate your answers.
#include <stdio.h>
#include <string.h>

int *count_substr2(char *str, char *substr){

    int i;
    int counter= 0;
    int *index;

    for(i=0; i< (strlen(str)-1); i++){
        if(str[i]== substr[0] && str[i+1]==substr[1]){
            index[counter]=i;
            counter++;
        }

    }
    return index;
}

int main () {

    char *string= "abqervbqyyxöiböxxivxybaböxxrnvrixmxcxpäxyeyoymäab";
    char *substr= "ab";

    int* y =count_substr2(string, substr);
    printf("%d     %d      %d    ", y[0], y[1], y[2]);

    return 0;
}

A: The pointer index is not initialised.  It could be zero, or anything else.  The code is offsetting that pointer by [counter] and storing values somewhere.  If it happens to be pointing to somewhere you don't own, your code will crash with a segmentation violation.  But for now, it's just corrupting some area you do own - perhaps the stack, or your heap.
So at the moment, whatever value index is holding is somewhat benign. In the future it may not be.  Commonly uninitialised local pointers tend to be filled with whatever was on the stack previously.
There are terrible side-effects of these sorts of bugs.  Right here and now, you see no bug.   But then ages later (in CPU time at least), the code using a data structure corrupted by this over-write will crash.  This can be very expensive to debug.


text:
Q: Android app IndexOutOfBoundsException on PackedIntVector i am developing an Android app that communicates with Bluetooth sending and receiving raw commands on byte array.
Randomly the app crashes right after i send some of this command, with the following excepcion;
 `Process: xxx.xxx.xxx, PID: 19983
    java.lang.IndexOutOfBoundsException: 2, 1
    at android.text.PackedIntVector.getValue(PackedIntVector.java:75)
    at android.text.DynamicLayout.getLineTop(DynamicLayout.java:1010)
    at android.text.Layout.getLineBottom(Layout.java:1725)
    at android.widget.Editor.drawHardwareAcceleratedInner(Editor.java:2310)
    at android.widget.Editor.drawHardwareAccelerated(Editor.java:2251)
    at android.widget.Editor.onDraw(Editor.java:2191)
    at android.widget.TextView.onDraw(TextView.java:8852)
    at android.view.View.draw(View.java:23901)`

As i understand the problem is on the PackedIntVector.java class, but its an Android class and on the stack trace there isn`t any of my app files, all are from Android classes.
Does anybody know what could be happening? The excepcion always happen right after sending a command and not always happen, but i have not found any thtat triggers it, seems "random".
Thanks in advice!


text:
Q: Atan2 Faster Approximation I am using atan2(y, x) for finding the polar angle from the x-axis and a vector which contains the point (x,y) for converting Cartesian coordinates to polar coordinates. But, in my program which will be used for calculations to move a robot, atan2 is a very computationally expensive procedure. What are ways to approximate atan2's result with a fast calculation with error bounds of 1 degree.
Wikipedia reference for atan2: https://en.wikipedia.org/wiki/Atan2
Here is some sample output:
atan2(1, 0)     -->  pi/2
atan2(-1, 0)    -->  -pi/2
atan2(0, 1)     -->  0
atan2(0, -1)    -->  pi

A: Denote
$$
atan2(y,x) = \arctan z, \quad \mbox{where} \quad z = \dfrac{y}{x}.
$$
Note that (in degrees) if $z>1$, then
$$
\arctan z = 90^\circ - \arctan \dfrac{1}{z},
$$
and that
$$
\arctan(-z) = -\arctan ~ z.
$$
So, it is enough to write approximation for $z\in [0,1]$.
This simple approximation
$$
\arctan z \approx z\Bigl(45^\circ - 15.66^\circ(z-1)\Bigr)\tag{1}
$$
gives us error $\pm0.22^\circ$.

This source gives us not bad approximation.
I just translated it to degrees:
$$
\arctan z \approx z\Bigl(45^\circ- \bigl(z - 1\bigr)\bigl(14^\circ + 3.83^\circ z\bigr)\Bigr), \qquad 0\le z \le 1;\tag{2}
$$
error is $\pm 0.09^\circ$.
Authors of the paper said that this formula is $3\times$ faster than standard one.

A: The pseudo code below computes r = atan2 (y,x) in radians. Using IEEE-754 single precision for all variables, the maximum relative error observed for 100 million trials was $6.14(10^{-4})$, thus complying with the requirement that the relative error be $\lt \frac{1}{360} \approx 2.77(10^{-3})$.
The algorithm does not deal with special cases such as $x=0, y=0$, nor does it consider special IEEE-754 floating-point operands such as infinities and NaN.
This is based on a simple argument reduction using the identities $arctan (z) = \frac{\pi}{2} - arctan (\frac{1}{z})$ if $z \gt 0$ and $arctan (-z) = -arctan(z)$ followed by a polynomial minimax approximation on $[0,1]$, with final result mapped back to $[-\pi,\pi]$ based on the octant of the original vector. The polynomial is evaluated using the Horner scheme. The minimax approximation was computed using the Remez algorithm.
a := min (|x|, |y|) / max (|x|, |y|)
s := a * a
r := ((-0.0464964749 * s + 0.15931422) * s - 0.327622764) * s * a + a
if |y| > |x| then r := 1.57079637 - r
if x < 0 then r := 3.14159274 - r
if y < 0 then r := -r


text:
Q: IE Hover Issue with an Image Overlay I have an image and an overlay within an image wrapper. Hovering over the wrapper causes the overlay to go from transparency 0 to 0.8. It works in all browsers but IE. I believe I am using the proper IE filter for opacity. Please take a look at the code:
HTML

CSS
.img-wrap {
    margin-right: 3px;
    float: left;
    height: 100%;
    overflow: hidden;
    position: relative;
    width: 250px;
}

.img-overlay {
    text-decoration: none;
    display: none;
    height: 100%;
    background-color: #000;
    color: #fff;
    opacity: 0;
    filter: alpha(opacity = 0);
    position: absolute;
    width: 100%;
    z-index: 100;
}

.img-overlay.team {
    top: 0;
}

.img-wrap:hover .img-overlay {
    display: block;
    opacity: 0.80;
    filter: alpha(opacity = 80);
    transition: opacity 0.25s;
    -moz-transition: opacity 0.25s;
    -webkit-transition: opacity 0.25s;
}

A: -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
this filter should work for ie 7-8


text:
Q: Pycharm import unresolved It can work but...

It is all fine until I create new python3.7.7 virtualenv

and I notice that init.py is different from before.

A: Oh...my fault...
File--->Settings--->Editor--->File Types ---> find Text ---> delete init.py
I really don't when and how I modified the config.

A: There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:

*

*close the project and quick PyCharm

*delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.

*start PyCharm and recreate the project

imports relative not to project folder
Relative imports while code root folder is not the same as the project folder. Solution:

*

*Find the folder that relative imports require in the project explorer

*right click and mark it as "Source Root"

Editor not marking init.py as Python
Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all init.py files not to be python files, and thus ignores them during code analysis. To fix this:

*

*Open PyCharm settings

*Navigate to Editor -> File Types

*Find Python and add init.py to the list of python files (screenshot) or find Text and delete init.py from the list of text files


text:
Q: Solving Uncaught ReflectionException: Class log does not exist in C:\......\Container.php: I am experiencing an unexpected Reflection Exception error that class log does not exist. I am currently using Laravel 5.2. The addition of use log amongst namespaces into my controller hasn't solved this.
Fatal error: Uncaught ReflectionException: Class log does not exist in C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:741

Stack trace:

#0 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(741): ReflectionClass->__construct('log')
#1 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(631): Illuminate\Container\Container->build('log', Array)
#2 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(674): Illuminate\Container\Container->make('log', Array)
#3 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(842): Illuminate\Foundation\Application->make('log')
#4 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(805): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#5 C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(775): Illuminate\Conta in C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 741

controller.php
  <?php

namespace App\Http\Controllers;

use Log;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Database\Eloquent\ModelNotFoundException;

 class Controller extends BaseController
{
    use AuthorizesRequests,AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

routes.php
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
Route::get('/', function () {
    return view('welcome');
});

A: Check for spaces in your .env or config files as suggested here
https://laracasts.com/discuss/channels/general-discussion/class-log-does-not-exist?page=2
enclose it with double quotes if any


text:
Q: unable to get the match property of the worksheetfunction class I'm consolidating the data from different workbook into a master workbook. But after consolidating I need to the remove the duplicate..
Work sheet
Work sheet
:---------------
Task Category   Task Description/ Detail    Assigned To     Assigned Date   Expected Delivery  Date Actual Completion Date  Status
:-------------------------------------------------------------------------
Analysis    Task1   Maaya   02-01-2017  19-01-2017  19-01-2017  Completed
Analysis    Task2   Maaya   02-01-2017  19-01-2017  19-01-2017  Completed
Analysis    Task3   Maaya   20-01-2017  10-03-2017  10-03-2017  Completed
Analysis    Task4   Maaya   20-01-2017  10-03-2017  10-03-2017  Completed
Coding & Testing    Task5   Maaya   01-03-2017  10-03-2017  10-03-2017  Completed
Coding & Testing    Task5   Maaya   01-03-2017  10-03-2017      Ongoing
With the code below I'm able to remove the duplicated... But the TASK5 having 2 status like Completed and Ongoing. I need the latest updated data.
Code is here:
Public Sub duplicate_removal()
Dim Colm, lastrow As String
Dim i, Value1, Value2 As Integer
ActiveWorkbook.Worksheets("Work Management").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Work Management").Sort.SortFields.Add
Key:=Range("F3:F104857"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Work Management").Sort
        .SetRange Range("A3:X104857")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
End With
Colm = WorksheetFunction.Match("ID", Sheets("Work Management").Rows(1), 0)
lastrow = ActiveSheet.Cells(Rows.Count, Colm).End(xlUp).Row
For i = 2 To lastrow

   Value1 = Range("C" & i).Value
  Value2 = Range("C" & i + 1).Value

    If Value1 = Value2 Then
    Rows(i).Delete
    End If

MsgBox ("Duplicates removed ")

Next

Application.ScreenUpdating = True
End Sub

`

A: Inside the Code. You have a code line like this,
Colm = WorksheetFunction.Match("ID", Sheets("Work Management").Rows(1), 0)

It is looking for the Column Header - "ID" which you don't have in your data. If you change that your own column header which you need. It will work


text:
Q: How can I have iCal email me reminders I have heard of people getting email reminders from iCal, but I can't figure out how to do it. So the obvious question is:
How do I have iCal email me reminders?
As I see now that was removed. In that case is there a widget to let me email reminders to myself?

A: The email reminder function was removed some time before iCal was renamed to Calendar. Presumably it was a security risk, but I can't find a good link explaining the exploits that used that pathway to harm people.

A: It seems what you are now looking for is an Alert.
From Yosemite Calendar help:

Set event alerts and receive notifications
Be notified of an upcoming Calendar event by setting one or more
  alerts for it. An alert can place a notification on your screen, send
  an email, or open a file.
Set an alert for an event

*

*Double-click an event, then click the event's date.

*Click next to Alert and do either of the following:

*

*Choose a time or day from the pop-up menu.

*Choose Custom and then choose one of the following options:

*Message: Displays a notification on the screen.

*Message with sound: Displays a notification on the screen and makes a sound.

*Email: Sends you an email.


text:
Q: Dynamically Create Widgets in DOM I'm using jQuery mobile 1 alpha 1.
To create a text input for instance in jQuery mobile you add to your HTML

Text Input:
<input type='text' name='name' id='name' value=''  />

Supposing you assign the above HTML code to a variable $textinput and type $("#someid").append($textinput); then the problem is that the text input appears but its not themed properly. My guess is that some Javascript runs on page load that adds the correct classes for CSS purposes. This Javascript does not run when I add the HTML directly into the DOM.
What do I do so that the correct Javascript runs when I dynamically add widgets to my DOM?

A: While adding input instance runtime give id to your div so it can be catch by $. Create your dome like below

Text Input:

After adding it just run below script to convert it mobile object.

$("#field1").fieldcontain();
  $("#name").textinput();

A: Take a look at Live Query.

Live Query (formerly Behavior) utilizes the power of jQuery selectors
by binding events or firing callbacks or matched elements auto-magically,
even after the page has been loaded and the DOM updated.