text:
Q: Hide graphically some items iterating with ng-repeat I am developing a web-application using Angular Js.
I want to fill a div, into my html view, using the ng-repeat directive. The array used by ng-repeat has some duplicates, but in my view I want to display item only once (if an element has already been shown, its copies must be graphically hidden). How can I do this?

    {{item.id}}

A: Just use a unique filter like this:

    {{item.id}}

Then create the unique filter:
app.filter('unique', function() {
    return function(collection, property) {
        var output = [];
        angular.forEach(collection, function(item) {
            //check if it exists in output on the basis of property, if not then add to output
            output.push(item);
        })
        return output;
    }
})

'property' in the function is 'id' in the example whereas collection refers to the entire array.

A: I would recommend you not to hide generated Html, but to add a filter to delete duplicates :

. . .

angular.module('myApp').filter('deleteDuplicates', function(){
    return function filterCore(source)
    {
        var out = [];
        // . . .
        return(out);
    };

});

Here is the AngularJS custom filter tutorial.


text:
Q: how to know various spark application statistics Spark Job:
//DATA READ/LOAD
val df1 = spark.sql("select colList from table1")
val df2 = spark.sql("select colList from table2")

//DATA PROCESSING/TRANSFORMATION
val df1_filter = df1.filter("cond")
val df2_filter = df1.filter("cond")
val transformation1 = df1_filter.join(df2_filter,joinCondition)

//DATA SAVE/WRITE
transformation1.write.format("com.databricks.spark.csv").option("delimiter","|").option("quote", "\u0000").save(hdfs_location)

QUESTION:
-Is there a way to find out approximate time the job takes to read, process and write the data separately.
the reason for the ask is to approximately find out the time it takes for a bigger dataset by running the job on a sample dataset.

A: RUN it and look at Spark UI for SparkContext when running or via Spark History Server.

A: you can see the execution plan by running explain plan. But it won't give you any idea about the actual runtime. Its specially tricky with join which depends on lots of things on big data set. Once the job is complete or running, you can check the progress in Spark UI.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why did my SQL Server database fill up so fast, and how can I get back my space? Have a SQL Server environment in which we are using Microsoft SQL Server Management Studio to perform data analysis. The server capacity is 50GB and we loaded in about 8GB worth of '.csv' datasets using the Import Wizard. The 8GB worth of '.csv' files are no longer stored on the server environment.
However, after a few days of querying and creating three new tables, the full 50GB is taken up.
I tried to delete all interim tables, restart the server multiple times, turn off backup, and limit log autogrowth--all to no avail.
How can I get back my storage space? Or at least figure out what is using it all up?

A:
The 8GB worth of '.csv' files...
However, after a few days of querying and creating three new tables, the full 50GB is taken up.

If you're using nvarchar instead of varchar then you're using UCS-2 to store textual data, so your 8GB of data becomes 16GB right there (I wish SQL Server natively supported UTF-8...), then with 3 tables that's 48GB right there - not to mention space used by transaction logs.
When you create a table, then fill it, then delete it, then create a new table, the previously-occupied space is not necessarily reclaimed or overwritten by the new table - this is what probably what's happening. "Normal" tables are expensive in relational database servers - that's why in-memory tables and temporary-tables should be used for ephemeral data (as I believe, though I don't have a reference, that temporary-tables have different storage behavior, and their disk space is more aggressively reclaimed compared to normal tables).
Note that you should use BULK INSERT or at least INSERT INTO ... SELECT FROM instead of repeating a single INSERT INTO ... VALUES... statement because that will hit your transaction log pretty hard (though I'll concedede that BULK INSERT in SQL Server does not offer much flexibility when processing CSV files)

A: In Simple mode, the log files should cycle on themselves and cause few issues unless you have really big transactions.
In Full mode, the log will grow until you backup the database. Indeed, SQL Server wants to keep all the logs until the datas are safely stored somewhere else. So, rule of the thumb, in Full mode, you MUST backup your database.
Now, when you delete a record or a table, it is not physically deleted from the storage until you clean the database. Use the command DBCC SHRINKDATABASE to do that. You can also shrink a specific file, just lookup the various commands offered.
For more informations:
https://learn.microsoft.com/en-us/sql/relational-databases/databases/shrink-a-database
https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkdatabase-transact-sql
https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkfile-transact-sql


text:
Q: Hard-coding values in SQL (complex query) Take a look at this SQL FIDDLE: LINK
There exist a table called "clients" that contains information related to clients:

The relation is "account number" - "client name"

and i used this sentence in order to obtain the name of the client:

LEFT JOIN clients c ON ppc.customer_number = c.account_number

I do not want to join the table clients anymore, but i want to obtain the same result, do you get me?.
I mean, i need this output:

{"sku":"99342435","PRICE":"9999",PRICES_FOR_CLIENTS:[{"group":"A","PRICE":"29223"},{"group":"B","PRICE":"33223"},{"group":"SUPERMARKET","PRICE":"48343"},{"group":"WALMART","PRICE":"40340"}]};

Somehow i would need to hard-code the values related to the account_number, i.e:

If account_number = 112121 replace it by WALMART
and if the account_number = 119435 replace it by SUPERMARKET

I tried to do it but i failed.
Can you help me?

A: insert the value into the prices_per_client table directly, so you won't need this left join anymore.

or use a case statement in the select-section:
CREATE VIEW ppc_v AS
SELECT ppc.*,
  CASE CUSTOMER_NUMBER
    WHEN 112121 THEN 'WALMART'
    WHEN 119435 THEN 'SUPERMARKET'
    ELSE NULL
  END description
FROM prices_per_client ppc

, create a view and apply it to the query:
SELECT '{"sku":"'||sub.item_code||'","PRICE":"'||sub.item_price||'",PRICES_FOR_CLIENTS:['||listagg('{"group":"'||sub.identifier||'","PRICE":"'||sub.price||'"}',',') WITHIN GROUP (ORDER BY sub.identifier)||']};' AS JSON
FROM (SELECT DECODE(ppc.customer_class_code, 'E', ppc.description, ppc.customer_class_code) AS IDENTIFIER, tpp.item_code, replace(tpp.price, ',', '.') AS ITEM_PRICE, REPLACE(avg(ppc.price), ',', '.') AS PRICE,
      tpl.request_id, max(tpl.request_id) over (partition by tpp.item_code) as max_request
      FROM table_price_list tpl
      INNER JOIN table_price_product tpp ON tpp.list_header_id = tpl.list_header_id AND tpp.request_id = tpl.request_id
      INNER JOIN ppc_v ppc ON tpp.item_code = ppc.item_code

      WHERE SYSDATE BETWEEN NVL(tpp.start_date_active, SYSDATE) AND NVL(tpp.end_date_active, SYSDATE+1)
      GROUP BY DECODE(ppc.customer_class_code, 'E', ppc.description, ppc.customer_class_code), tpp.item_code, tpp.price, tpl.request_id) sub
WHERE sub.identifier IS NOT NULL
and sub.request_id = sub.max_request
GROUP BY sub.item_code, sub.item_price;


text:
Q: Valid SSL cert for laptop not connected to the internet We have a laptop which isn't connected to the internet via wifi or mobile data, it has a wifi hotspot which is used to serve a website to an android phone. We want to demonstrate a webpage which uses the appcache technology on the phone
The problem is in chrome you require a valid certificate for a appcache, but how do you get a certificate for a laptop which isn't connected to anything?

A: In case the laptop is running linux.
You could try to create your own self-signed certificate using openssl.
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365


text:
Q: If a sequence occurs then a subsequence occurs within it in System-Verilog assertions I want to say:
"if the sequence A occurs then the sequence B occurs within that sequence". How can I do this?
I would have thought I could use the assertion:
assert property (@(posedge clk) (A |-> (B within A));

but this doesn't seem to work for my example.
I've read that:

The linear sequence is said to match along a finite interval of consecutive clock ticks provided the first boolean expression evaluates to true at the first clock tick, the second boolean expression evaluates to true at the second clock tick, and so forth, up to and including the last boolean expression evaluating to true at the last clock tick.

but i suspect that the clock tick passed to the otherside of the |-> the last clock tick when I want it to be the first.
My particular example is an accumulator which I expect to overflow if I add enough positive numbers, so I want A = (input == 1)[*MAX_SIZE] and B = (output == 0), so here B is a sequence of length 1, I don't know if that causes problems.
I'm very new to system-verilog so it maybe that it's some other part of my code which is going wrong but I've not seen this example done anywhere.

A: You are correct that the consequent in the |-> operator is started once A has already matched. What you want is to look into the past: "once I've seen A, have I seen B within A?".
You could use the triggered property of a sequence to do this:
sequence b_within_a;
  @(posedge clk)
    B within A;
endsequence

assert property (@(posedge clk) A |-> b_within_a.triggered);

The b_within_a sequence will match exactly at the end of A, of course, if B also happened, which is when the triggered property will evaluate to 1.
Note that the b_within_a sequence has its clock defined specifically. This is a requirement from the LRM, otherwise you won't be allowed to call triggered on it.


text:
Q: Create 'correlation matrix' for two lists to check if the values have something in common Could someone please help me out with the following?
I have one dataframe with two columns: products and webshops (n x 2) with n products. Now I would like to obtain a binary (n x n) matrix with all products listed as the indices and all products listed as the column names. Then each cell should contain a 1 or 0 denoting whether the product in the index and column name came from the same webshop.
The following code is returning what I would like to achieve.
dist = np.empty((len(df_title), len(df_title)), int)

for i in range(0,len(df_title)):
    for j in range(0,len(df_title)):
            boolean = df_title.values[i][1] == df_title.values[j][1]
            dist[i][j] = boolean
df = pd.DataFrame(dist)

However, this code takes quite a significant time already for n = 1624. Therefore I was wondering if someone would have an idea for a faster algorithm.
Thanks!

A: It seems like you're only interested in the element at position 1 for every column anyways, so creating a temp-variable for easier lookup could help:
lookup = df_title.values[:, 1]

Also since you want to interpret the resulting matrix as bool-matrix, you should probably specify dtype=bool (1 byte per field) instead of dtype=int (8 bytes per field), which also cuts down memory consumption by 8.
dist = np.empty((len(df_title), len(df_title)), dtype=bool)

Your matrix will be symmetric along the diagonal anyways, so you only need to compute "half" of the matrix, also if i == j we know the corresponding field in the matrix should be True.
lookup = df_title.values[:, 1]
dist = np.empty((len(df_title), len(df_title)), dtype=bool)

for i in range(len(df_title)):
    for j in range(len(df_title)):
        if i == j:
            # diagonal
            dist[i, j] = True
        else:
            # symmetric along diagonal
            dist[i, j] = dist[j, i] = lookup[i] == lookup[j]

Also using numpy-broadcasting you could actually transform all of that into a single line of code, that is orders of magnitude faster than the double-for-loop solution:
lookup = df_title.values[:, 1]
dist = lookup[None, :] == lookup[:, None]


text:
Q: Camel File Consumer not stopping I have a question similar to camel-file-consumer-template-threads-remaining-alive. I have a webapp running in a Tomcat container. I am using Camel version 2.10.4. In it I have I use the File component as a polling consumer. It is set up as follows:
from("/myDir"+
     "?delete=true"+
     "&startingDirectoryMustExist=true"+
     "&scheduledExecutorService=#mySpringManagedExecutorService")

This runs fine as expected but when I attempt to stop Tomcat I get the following message:
SEVERE: The web application [/myapp] appears to have started a thread
     named [MyExecuteService-0] but has failed to stop it. This is very likely to
     create a memory leak.

After invoking the shutdown.sh script I invoke ps -ef | grep tomcat and the process is still running. If my app is not loaded or if I do not load this route in my app tomcat stops properly.

A: FYI, so the solution was posted on Nabble. This was that I needed to shutdown the executor service in Spring. I did this by adding a destory-method="shutdown" to the executor service.
FYI, I had set up the executor service this was so that I could have different thread names per route in a single context. Neither Spring nor Camel seems to provide this mechanism.
The Nabble thread is here


text:
Q: Show popup menu for row in recyclerview using databinding I am trying to show a popup menu for the items in my RecyclerView:

All the code samples on how to do this that I found online either use Java or when they in rare cases do use Kotlin, it's done without data binding.
Anyway what I'm trying to achieve is this:
<ImageButton
    android:id="@+id/options"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="14dp"
    android:layout_marginEnd="16dp"
    android:background="?attr/selectableItemBackground"
    android:contentDescription="@string/desc_options"
    android:onClickListener="@{(v) -> holder.test1.invoke()}"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/ic_more_vert" />

And in my RowHolder I have the following code:
class AgendaRowHolder(
    private val binding: AgendaRowBinding,
    val onRowClick: (AgendaModel) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
    fun bind(model: AgendaModel) {
        binding.model = model
        binding.holder = this
        binding.executePendingBindings()
    }

    fun test1() {
        // do something here
    }
}

However this will not compile at all and a workaround to solving this problem is to have a function as a property of the AgendaRowHolder class, but this approach doesn't work since I also have to pass the ImageView for the popup menu to know where to show up. So I used this alternative approach, namely adding an onClickListener in the bind() function:
fun bind(model: AgendaModel) {
    binding.model = model
    binding.holder = this
    binding.executePendingBindings()

    binding.options.setOnClickListener { showPopup(it) }
}

private fun showPopup(view : View) {
    val popup = PopupMenu(view.context, view)
    popup.setOnMenuItemClickListener { item ->
        when (item.itemId) {
            R.id.delete -> {
                AgendaRepository.delete(binding.model!!)
                true
            } else -> false
        }
    }
    val inflater: MenuInflater = popup.menuInflater
    inflater.inflate(R.menu.actions_agenda, popup.menu)
    popup.show()
}

This approach "works" in that it will show a popup menu and allow me to delete items, but I have a new problem here in that when an item/row gets delete it doesn't show up until the view is recreated, right now I'm not observing my data so that might be the reason as to why, but what I'm wondering is what would be the best approach to achieve this? Note: another thing that I tried is adding an android:onClick attribute in the xml and trying to handle this in the MainActivity, but I'm not sure which approach to take here. Can the first one be achieved? Ideally, I'd have:
android:onClickListener="@{(v) -> holder.showPopup.invoke(model, v)}" and then that showPopup function in the ViewHolder.


text:
Q: How to backup MySQL database in PHP? I don't have a basic understanding of how backup of a MySQL database through PHP would work. I have followed one tutorial but it didn't help me understand.
Can someone explain how to create a MySQL backup from PHP?

A: While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.
I'd suggest using the mysqldump utility to back up your database.  The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.
The basic usage of mysqldump is
mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like
mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like
<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.
It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.
You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

A: If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:
<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>

<?php /*defined in examplemyclass.php*/
    class MySql{
        private $dbc;
        private $user;
        private $pass;
        private $dbname;
        private $host;

        function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
            $this->user = $user;
            $this->pass = $pass;
            $this->dbname = $dbname;
            $this->host = $host;
            $opt = array(
               PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
               PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );
            try{
                $this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
            }
            catch(PDOException $e){
                 echo $e->getMessage();
                 echo "There was a problem with connection to db check credenctials";
            }
        } /*end function*/

        public function backup_tables($tables = '*'){  /* backup the db OR just a table */
            $host=$this->host;
            $user=$this->user;
            $pass=$this->pass;
            $dbname=$this->dbname;
            $data = "";
            //get all of the tables
            if($tables == '*')
            {
                $tables = array();
                $result = $this->dbc->prepare('SHOW TABLES');
                $result->execute();
                while($row = $result->fetch(PDO::FETCH_NUM))
                {
                    $tables[] = $row[0];
                }
            }
            else
            {
                $tables = is_array($tables) ? $tables : explode(',',$tables);
            }
            //cycle through
            foreach($tables as $table)
            {
                $resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
                $resultcount->execute();
                $num_fields = $resultcount->fetch(PDO::FETCH_NUM);
                $num_fields = $num_fields[0];

                $result = $this->dbc->prepare('SELECT * FROM '.$table);
                $result->execute();
                $data.= 'DROP TABLE '.$table.';';

                $result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);
                $result2->execute();
                $row2 = $result2->fetch(PDO::FETCH_NUM);
                $data.= "\n\n".$row2[1].";\n\n";

                for ($i = 0; $i < $num_fields; $i++)
                {
                    while($row = $result->fetch(PDO::FETCH_NUM))
                    {
                        $data.= 'INSERT INTO '.$table.' VALUES(';
                        for($j=0; $j<$num_fields; $j++)
                        {
                            $row[$j] = addslashes($row[$j]);
                            $row[$j] = str_replace("\n","\\n",$row[$j]);
                            if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
                            if ($j<($num_fields-1)) { $data.= ','; }
                        }
                        $data.= ");\n";
                    }
                }
                $data.="\n\n\n";
            }
            //save filename
            $filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
            $this->writeUTF8filename($filename,$data);
        /*USE EXAMPLE
           $connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
           $connection->backup_tables(); //OR backup_tables("posts");
           $connection->closeConnection();
        */
        } /*end function*/

        private function writeUTF8filename($filenamename,$content){  /* save as utf8 encoding */
            $f=fopen($filenamename,"w+");
            # Now UTF-8 - Add byte order mark
            fwrite($f, pack("CCC",0xef,0xbb,0xbf));
            fwrite($f,$content);
            fclose($f);
        /*USE EXAMPLE this is only used by public function above...
            $this->writeUTF8filename($filename,$data);
        */
        } /*end function*/

        public function recoverDB($file_to_load){
            echo "write some code to load and proccedd .sql file in here ...";
        /*USE EXAMPLE this is only used by public function above...
            recoverDB("some_buck_up_file.sql");
        */
        } /*end function*/

        public function closeConnection(){
            $this->dbc = null;
        //EXAMPLE OF USE
        /*$connection->closeConnection();*/
        }/*end function*/

    } /*END OF CLASS*/
    ?>

Now you could simply use this in your backup.php:
include ('config.php');
include ('myclass.php');
    $connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
    $connection->backup_tables(); /*Save all tables and it values in selected database*/
    $connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
    $connection->closeConnection();

Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would  recommend to write it to one file at all the time instead of creating new files with time()... as it is above.
Hope it helps and good luck ! :>

A: Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.
Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.
MySQLDump-PHP is the only library that supports:

*

*output binary blobs as hex.

*resolves view dependencies (using Stand-In tables).

*output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)

*dumps stored procedures.

*dumps events.

*does extended-insert and/or complete-insert.

*supports virtual columns from MySQL 5.7.

You can install it using composer, or just download the php file, and it is as easy as doing:
use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

A: Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect has deprecated and not supported in new php version. I've used mysqli_connect instead and increased the performance of inserting values to the database:
<?php

/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/

//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';

//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);

//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
    $link = mysqli_connect($host,$user,$pass, $dbname);

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    }

    mysqli_query($link, "SET NAMES 'utf8'");

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;

        //Over tables
        for ($i = 0; $i < $num_fields; $i++)
        {   //Over rows
            while($row = mysqli_fetch_row($result))
            {
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }

                //Over fields
                for($j=0; $j<$num_fields; $j++)
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }

                if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }
                ++$counter;
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
    $handle = fopen($fileName,'w+');
    fwrite($handle,$return);
    if(fclose($handle)){
        echo "Done, the file name is: ".$fileName;
        exit;
    }
}

A: An easy way to do this (output SQL file). To do this, we can use exec or mysqli method

code 1:

*

*example 1 : If you want to back-up a specific database

$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';

$dir_1 = dirname(__FILE__) . '/table-'. $database .'.sql';

exec("mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$dir_1} 2>&1", $output_1);

var_dump($output_1);

*

*example 2 : Backup all database

$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';

$dir_2 = dirname(__FILE__) . '/all-database.sql';

exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --result-file={$dir_2} 2>&1", $output_2);

var_dump($output_2);

*

*example 3 : Backup all database and skip lock tables

$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';

$dir_3 = dirname(__FILE__) . '/skip-lock-tables.sql';

exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --skip-lock-tables --result-file={$dir_3} 2>&1", $output_3);

var_dump($output_3);

I usually use the following code as well to display errors and warning : Not important
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Method 2 If you can not activate exec() function. By Mysqli :

<?php
$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$charset = "utf8mb4"; # utf8mb4_unicode_ci

$conn = new mysqli($host, $user, $pass, $database);
$conn->set_charset($charset);

# get all tables
$result = mysqli_query($conn, "SHOW TABLES");
$tables = array();

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

# Get tables data
$sqlScript = "";
foreach ($tables as $table) {
    $query = "SHOW CREATE TABLE $table";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);

    $sqlScript .= "\n\n" . $row[1] . ";\n\n";

    $query = "SELECT * FROM $table";
    $result = mysqli_query($conn, $query);

    $columnCount = mysqli_num_fields($result);

    for ($i = 0; $i < $columnCount; $i ++) {
        while ($row = mysqli_fetch_row($result)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $columnCount; $j ++) {
                $row[$j] = $row[$j];

                $sqlScript .= (isset($row[$j])) ? '"' . $row[$j] . '"' : '""';

                if ($j < ($columnCount - 1)) {
                    $sqlScript .= ',';
                }

            }
            $sqlScript .= ");\n";
        }
    }

    $sqlScript .= "\n";
}

//save file
$mysql_file = fopen($database . '_backup_'.time() . '.sql', 'w+');
fwrite($mysql_file ,$sqlScript );
fclose($mysql_file );

A: A solution to take the backup of your Database in "dbBackup" Folder / Directory
<?php
error_reporting(E_ALL);

/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", 'root');
define("DB_NAME", 'YOUR_DATABASE_NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder Path / Directory Name
define("TABLES", '*');

/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status;

/* The Backup_Database class */
class Backup_Database {

    private $conn;

    /* Constructor initializes database */
    function __construct( $host, $username, $passwd, $dbName, $charset = 'utf8' ) {
        $this->dbName = $dbName;
        $this->connectDatabase( $host, $username, $passwd, $charset );
    }

    protected function connectDatabase( $host, $username, $passwd, $charset ) {
        $this->conn = mysqli_connect( $host, $username, $passwd, $this->dbName);

        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

        /* change character set to $charset Ex : "utf8" */
        if (!mysqli_set_charset($this->conn, $charset)) {
            printf("Error loading character set ".$charset.": %s\n", mysqli_error($this->conn));
            exit();
        }
    }

    /* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables  */
    public function backupTables($tables = '*', $outputDir = '.') {
        try {
            /* Tables to export  */
            if ($tables == '*') {
                $tables = array();
                $result = mysqli_query( $this->conn, 'SHOW TABLES' );

                while ( $row = mysqli_fetch_row($result) ) {
                    $tables[] = $row[0];
                }
            } else {
                $tables = is_array($tables) ? $tables : explode(',', $tables);
            }

            $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
            $sql .= 'USE ' . $this->dbName . ";\n\n";

            /* Iterate tables */
            foreach ($tables as $table) {
                echo "Backing up " . $table . " table...";

                $result = mysqli_query( $this->conn, 'SELECT * FROM ' . $table );

                // Return the number of fields in result set
                $numFields = mysqli_num_fields($result);

                $sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
                $row2 = mysqli_fetch_row( mysqli_query( $this->conn, 'SHOW CREATE TABLE ' . $table ) );

                $sql.= "\n\n" . $row2[1] . ";\n\n";

                for ($i = 0; $i < $numFields; $i++) {

                    while ($row = mysqli_fetch_row($result)) {

                        $sql .= 'INSERT INTO ' . $table . ' VALUES(';

                        for ($j = 0; $j < $numFields; $j++) {
                            $row[$j] = addslashes($row[$j]);
                            // $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                            if (isset($row[$j])) {
                                $sql .= '"' . $row[$j] . '"';
                            } else {
                                $sql.= '""';
                            }
                            if ($j < ($numFields - 1)) {
                                $sql .= ',';
                            }
                        }

                        $sql.= ");\n";
                    }
                } // End :: for loop

                mysqli_free_result($result); // Free result set

                $sql.="\n\n\n";
                echo " OK <br/>" . "";
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
            return false;
        }

        return $this->saveFile($sql, $outputDir);
    }

    /* Save SQL to file @param string $sql */
    protected function saveFile(&$sql, $outputDir = '.') {
        if (!$sql)
            return false;

        try {
            $handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
            fwrite($handle, $sql);
            fclose($handle);

            mysqli_close( $this->conn );
        } catch (Exception $e) {
            var_dump($e->getMessage());
            return false;
        }
        return true;
    }

} // End :: class Backup_Database

?>

A: From the answer of @DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }

I made some changes to:

*

*preserve relationships (foreign keys)

*use Transactions

*remove the uneedy $num_fields

class DBbackup {
 public $suffix;
 public $dirs;
 protected $dbInstance;
 public function __construct() {
   try{
    $this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
    $username, $password);
  } catch(Exception $e) {
    die("Error ".$e->getMessage());
  }
   $this->suffix = date('Ymd_His');
 }

 public function backup($tables = '*'){
   $output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
   $output .= "SET NAMES utf8;".PHP_EOL;
   $output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
   $output .= "SET foreign_key_checks = 0;".PHP_EOL;
   $output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
   $output .= "START TRANSACTION;".PHP_EOL;
   //get all table names
   if($tables == '*') {
     $tables = [];
     $query = $this->dbInstance->prepare('SHOW TABLES');
     $query->execute();
     while($row = $query->fetch(PDO::FETCH_NUM)) {
       $tables[] = $row[0];
     }
     $query->closeCursor();
   }
   else {
     $tables = is_array($tables) ? $tables : explode(',',$tables);
   }

   foreach($tables as $table) {

     $query = $this->dbInstance->prepare("SELECT * FROM `$table`");
     $query->execute();
     $output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;

     $query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
     $query2->execute();
     $row2 = $query2->fetch(PDO::FETCH_NUM);
     $query2->closeCursor();
     $output .= PHP_EOL.$row2[1].";".PHP_EOL;

       while($row = $query->fetch(PDO::FETCH_NUM)) {
         $output .= "INSERT INTO `$table` VALUES(";
         for($j=0; $j<count($row); $j++) {
           $row[$j] = addslashes($row[$j]);
           $row[$j] = str_replace("\n","\\n",$row[$j]);
           if (isset($row[$j]))
             $output .= "'".$row[$j]."'";
           else $output .= "''";
           if ($j<(count($row)-1))
            $output .= ',';
         }
         $output .= ");".PHP_EOL;
       }
     }
     $output .= PHP_EOL.PHP_EOL;

   $output .= "COMMIT;";
   //save filename

   $filename = 'db_backup_'.$this->suffix.'.sql';
   $this->writeUTF8filename($filename,$output);
 }

 private function writeUTF8filename($fn,$c){  /* save as utf8 encoding */
   $f=fopen($fn,"w+");
   # Now UTF-8 - Add byte order mark
   fwrite($f, pack("CCC",0xef,0xbb,0xbf));
   fwrite($f,$c);
   fclose($f);
 }

}
And usage example:
$Backup = new DBbackup();
$Backup->backup();

This works great on MySQL 10.1.34-MariaDB , PHP :  7.2.7

A: for using Cron Job, below is the php function
public function runback() {

    $filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';

    /*
     *  db backup
     */

    $command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass yourdb_name > $filename";
    system($command);
    if ($command == '') {
        /* no output is good */
        echo 'not done';
    } else {
       /* we have something to log the output here */
        echo 'done';
    }
}

There should not be any space between -u and username also no space between -p and password.
CRON JOB command to run this script every sunday 8.30 am:
>> crontab -e

30 8 * * 7 curl -k https://www.websitename.com/takebackup

A: Try out following example of using SELECT INTO OUTFILE query for creating table backup. This will only backup a particular table.
<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $table_name = "employee";
   $backup_file  = "/tmp/employee.sql";
   $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

   mysql_select_db('test_db');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not take data backup: ' . mysql_error());
   }

   echo "Backedup  data successfully\n";

   mysql_close($conn);
?>

A: My very simple backup solution. Each table is saved as a separate file.
<?php

error_reporting(E_ALL);

// set the path to the backup
$bc_dir = dirname(__FILE__).'/back_db/';

// DB-connect settings
$db_user = '';
$db_name = '';
$db_pass = '';
$db_host = 'localhost';

$dsn = 'mysql:dbname='.$db_name.';host='.$db_host.'';

try {
    $pdo = new PDO($dsn, $db_user, $db_pass);
} catch (Exception $e) {
    var_dump($e->getMessage());
}

$query = $pdo->query('SHOW TABLES');

while ($row = $query->fetch(PDO::FETCH_NUM)) {

    exec("mysqldump --user=".$db_user." --password=".$db_pass." --host="
      .$db_host." ".$db_name." ".$row[0]." --skip-lock-tables --result-file="
      .$bc_dir.$row[0].".sql > /dev/null 2>&1");

}

A: @T.Todua's answer.
It's cool. However, it failed to backup my database correctly. Hence, I've modified it.
Please use like so: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
Thank you.
 <?php
/**========================================================+
 *                                                         +
 * Static class with functions for backing up database.    +
 *                                                         +
 * PHP Version 5.6.31                                      +
 *=========================================================+*/
class Backup_Mysql_Db
{
private function __construct() {}
/**Initializes the database backup
 * @param String $host mysql hostname
 * @param String $user mysql user
 * @param String $pass mysql password
 * @param String $name name of database
 * @param String $outputDir the path to the output directory for storing the backup file
 * @param Array $tables (optional) to backup specific tables only,like: array("mytable1","mytable2",...)
 * @param String $backup_name (optional) backup filename (otherwise, it creates random name)
 * EXAMPLE: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
*/
public static function init($host,$user,$pass,$name, $outputDir, $tables=false, $backup_name=false)
{
    set_time_limit(3000);
    $mysqli = new mysqli($host,$user,$pass,$name);
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    //change database to $name
    $mysqli->select_db($name);
    /* change character set to utf8 */
    if (!$mysqli->set_charset("utf8"))
    {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
    }
    //list all tables in the database
    $queryTables = $mysqli->query('SHOW TABLES');
    while($row = $queryTables->fetch_row())
    {
        $target_tables[] = $row[0];
    }
    //if user opted to backup specific tables only
    if($tables !== false)
    {
        $target_tables = array_intersect( $target_tables, $tables);
    }
    date_default_timezone_set('Africa/Accra');//set your timezone
    //$content is the text data to be written to the file for backup
    $content = "-- phpMyAdmin SQL Dump\r\n-- version 4.7.4". //insert your phpMyAdmin version
           "\r\n-- https://www.phpmyadmin.net/\r\n--\r\n-- Host: ".$host.
           "\r\n-- Generation Time: ".date('M d, Y \a\t h:i A',strtotime(date('Y-m-d H:i:s', time()))).
           "\r\n-- Server version: ".$mysqli->server_info.
           "\r\n-- PHP Version: ". phpversion();
    $content .= "\r\n\r\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET AUTOCOMMIT = 0;\r\nSTART TRANSACTION;\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n\r\n--\r\n-- Database: `".
                $name."`\r\n--\r\nCREATE DATABASE IF NOT EXISTS `".
                $name."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\r\nUSE `".
                $name."`;";
    //traverse through every table in the database
    foreach($target_tables as $table)
    {
        if (empty($table)){ continue; }
        $result = $mysqli->query('SELECT * FROM `'.$table.'`');
        //get the number of columns
        $fields_amount=$result->field_count;
        //get the number of affected rows in the MySQL operation
        $rows_num=$mysqli->affected_rows;
        //Retrieve the Table Definition of the existing table
        $res = $mysqli->query('SHOW CREATE TABLE '.$table);
        $TableMLine=$res->fetch_row();
        $content .= "\r\n\r\n-- --------------------------------------------------------\r\n\r\n"."--\r\n-- Table structure for table `".$table."`\r\n--\r\n\r\n";
        //if the table is not empty
        if(!self::table_is_empty($table,$mysqli))
        {   $content .= $TableMLine[1].";\n\n";//append the Table Definition
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this
            $content .= "--\r\n-- Dumping data for table `".$table."`\r\n--\r\n";
            $content .= "\nINSERT INTO `".$table."` (".self::get_columns_from_table($table, $mysqli)." ) VALUES\r\n".self::get_values_from_table($table,$mysqli);
        }
        else//otherwise if the table is empty
        {
            $content .= $TableMLine[1].";";
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this
        }
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    date_default_timezone_set('Africa/Accra');
    //format the time at this very moment and get rid of the colon ( windows doesn't allow colons in filenames)
    $date = str_replace(":", "-", date('jS M, y. h:i:s A.',strtotime(date('Y-m-d H:i:s', time()))));
    //if there's a backup name, use it , otherwise device one
    $backup_name = $backup_name ? $backup_name : $name.'___('.$date.').sql';
    //Get current buffer contents and delete current output buffer
    ob_get_clean();
    self::saveFile($content, $backup_name, $outputDir);
    exit;
}

/** Save data to file.
 * @param String $data The text data to be stored in the file
 * @param String $backup_name The name of the backup file
 * @param String $outputDir (optional) The directory to save the file to.
 * If unspecified, will save in the current directory.
 * */
private static function saveFile(&$data,$backup_name, $outputDir = '.')
{
    if (!$data)
    {
        return false;
    }
    try
    {
        $handle = fopen($outputDir . '/'. $backup_name , 'w+');
        fwrite($handle, $data);
        fclose($handle);
    } catch (Exception $e)
    {
      var_dump($e->getMessage());
      return false;
    }
    return true;
}
/**Checks if table is empty
 * @param String $table table in mysql database
 * @return Boolean true if table is empty, false otherwise
*/
private static function table_is_empty($table,$mysqli)
{
    $sql = "SELECT * FROM $table";
    $result = mysqli_query($mysqli, $sql);
    if($result)
    {
        if(mysqli_num_rows($result) > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    return false;
}
/**Retrieves the columns in the table
 * @param String $table table in mysql database
 * @return String a list of all the columns in the right format
*/
private static function get_columns_from_table($table, $mysqli)
{
    $column_header = "";
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
    while($row = $result->fetch_row())
    {
        $column_header .= "`".$row[0]."`, ";
    }
    //remove leading and trailing whitespace, and remove the last comma in the string
    return rtrim(trim($column_header),',');
}

/**Retrieves the values in the table row by row in the table
 * @param String $table table in mysql database
 * @return String a list of all the values in the table in the right format
*/
private static function get_values_from_table($table, $mysqli)
{
    $values = "";
    $columns = [];
    //get all the columns in the table
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
    while($row = $result->fetch_row())
    {
        array_push($columns,$row[0] );
    }

    $result1 = mysqli_query($mysqli, "SELECT * FROM $table");
    //while traversing every row in the table(row by row)
    while($row = mysqli_fetch_array($result1))
    {   $values .= "(";
        //get the values in each column
        foreach($columns as $col)
        {               //if the value is an Integer
            $values .=  (self::column_is_of_int_type($table, $col,$mysqli)?
                    $row["$col"].", "://do not surround it with single quotes
                    "'".$row["$col"]."', "); //otherwise, surround it with single quotes
        }
        $values = rtrim(trim($values),','). "),\r\n";
    }
    return rtrim(trim($values),',').";";
}

/**Checks if the data type in the column is an integer
 * @param String $table table in mysql database
 * @return Boolean true if it is an integer, false otherwise.
*/
private static function column_is_of_int_type($table, $column,$mysqli)
{
    $q = mysqli_query($mysqli,"DESCRIBE $table");
    while($row = mysqli_fetch_array($q))
    {
        if ($column === "{$row['Field']}")
        {
            if (strpos("{$row['Type']}", 'int') !== false)
            {
                return true;
            }
        }
    }
    return false;
}

}


text:
Q: Android spinner is getting null after rotating the screen I am using the spinner for showing the value as dropdown, I am changing the spinner text value by using below code
<Spinner
        android:id="@+id/showUnit"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:entries="@array/unitName"
        android:background="@drawable/gradient_spinner_map_miles_button" />

    showUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                String item = arg0.getItemAtPosition(arg2).toString();
                if (arg1 != null && arg1 instanceof TextView) {
                     ((TextView)arg1).setTextColor(Color.WHITE);
                    ((TextView) arg1).setTextSize(13);
                    ((TextView) arg1).setGravity(Gravity.CENTER);
                 }

}
showUnit = (Spinner) findViewById(R.id.showUnit);

But when I try to rotate the screen, ((TextView)arg0.getChildAt(0)) returns null.
I know that when I rotate the screen in landsacpe or portrait mode activity cycle is restart then why spinner is getting null.
Please give me appropriate solution.
Thanks

A: Why are you using getChildAt when you have the appropriate view in View arg1 ?
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
     if (arg1 != null && arg1 instanceof TextView) {
         ((TextView)arg1).setTextColor(Color.WHITE);
     }
}

To change the color of a selected text in a spinner it's in the best practice to use a selector.
spinner_state.xml (in drawable folder)
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@color/black" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@color/red" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@color/red" />
    <item
        android:state_enabled="true"
        android:drawable="@color/gray" />
</selector>

in your spinner, apply the selector :
    android:dropDownSelector="@drawable/spinner_state"

Spinner source from : Spinner does not apply dropDownSelector attribute
It's doesn't explain why your values are null in onItemSelected but without your full code I can't see what's wrong.

A: I had the same problem, so I moved the setTextColor on getView :
ArrayAdapter<CharSequence> adapter =
    new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, getResources().getTextArray(R.array.myarray)){
        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent){
            View v = null;
            System.out.println("getDropDownView");
            v = super.getDropDownView(position, null, parent);
            // If this is the selected item position
            if (position == PosItemSelected) {
                v.setBackgroundColor(getResources().getColor(R.color.orange_energicod));
            }
            else {
                // for other views
                v.setBackgroundColor(Color.WHITE);
            }
            return v;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            ((TextView) v).setTextColor(getResources().getColor(R.color.white));
            return v;
        }
    };

// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content
spinner.setOnItemSelectedListener(this); // set the listener, to perform actions based on item selection

And now:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // An item was selected. You can retrieve the selected item using parent.getItemAtPosition(pos)
}

Hope it's work for you too.


text:
Q: Mockito verify(...) fails - "Actually, there were zero interactions with this mock." in more than one test run sequentially I have a Wrapper class that causes that instead of equals method, the method equalsWithoutId is called on wrapped object. Implementation here:
import org.apache.commons.lang3.Validate;

public class IdAgnosticWrapper {

    private final IdAgnostic wrapped;

    public IdAgnosticWrapper(IdAgnostic wrapped) {
        Validate.notNull(wrapped, "wrapped must not be null");
        this.wrapped = wrapped;
    }

    @Override
    public int hashCode() {
        return wrapped.hashCodeWithoutId();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof IdAgnosticWrapper)) {
            return false;
        }
        return wrapped.equalsWithoutId(((IdAgnosticWrapper) obj).getWrapped());
    }

    public IdAgnostic getWrapped() {
        return wrapped;
    }
}

IdAgnostic is a simple interface, that ensures that required methods are present
public interface IdAgnostic {
    int hashCodeWithoutId();
    boolean equalsWithoutId(Object o);
}

Then I have some Unit tests that should test, if equals() delegates to wrapped#equalsWithoutId() method and hashCode() delegates to wrapped#hashCodeWithoutId.
Now I try to test it by these tests
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.Mockito.verify;

public class IdAgnosticWrapperTest {

    @Mock
    private IdAgnostic wrappedMock;

    @InjectMocks
    private IdAgnosticWrapper tested;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testEquals_EqualsWithoutIdIsCalledOnWrapped() throws Exception {
        tested.equals(tested);
        verify(wrappedMock).equalsWithoutId(tested.getWrapped());
    }

    @Test
    public void testHashCode_HashCodeWithoutIdIsCalledOnWrapped() throws Exception {
        tested.hashCode();
        verify(wrappedMock).hashCodeWithoutId(); //line 34
    }
}

As you can see, I just create wrapped mock and I test, whether equals and hashcode delegate the functionality.
If I run tests separately, everything works fine, but if I run both tests sequentially, the second one fails with this message
Wanted but not invoked:
wrappedMock.hashCodeWithoutId();
-> at com.my.app.utils.IdAgnosticWrapperTest.testHashCode_HashCodeWithoutIdIsCalledOnWrapped(IdAgnosticWrapperTest.java:34)
Actually, there were zero interactions with this mock.

Why does this happen?

A: Effectively, what's happening here is that the @InjectMocks isn't able to correctly inject the constructor parameter wrapped. According to the Javadoc for @InjectMocks, this is the current behavior. So unless you want to use setter injection, you will need to remove the @InjectMocks annotation. See the revised code:
public class IdAgnosticWrapperTest {

  @Mock
  private IdAgnostic wrappedMock;

  private IdAgnosticWrapper tested;

  @BeforeMethod
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    this.tested = new IdAgnosticWrapper(this.wrappedMock);
  }

  @Test
  public void testEquals_EqualsWithoutIdIsCalledOnWrapped()
      throws Exception {
    tested.equals(tested);
    verify(wrappedMock).equalsWithoutId(tested.getWrapped());
  }

  @Test
  public void testHashCode_HashCodeWithoutIdIsCalledOnWrapped()
      throws Exception {
    tested.hashCode();
    verify(wrappedMock).hashCodeWithoutId(); //line 34
  }
}

When I ran the above code, both tests ran together sequentially and passed.


text:
Q: Effects of declaring a function as pure or const to GCC, when it isn't GCC can suggest functions for attribute pure and attribute const with the flags -Wsuggest-attribute=pure and -Wsuggest-attribute=const.
The GCC documentation says:

Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure.

But what can happen if you attach __attribute__((__pure__)) to a function that doesn't match the above description, and does have side effects?  Is it simply the possibility that the function will be called fewer times than you would want it to be, or is it possible to create undefined behaviour or other kinds of serious problems?
Similarly for __attribute__((__const__)) which is stricter again - the documentation states:

Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.

But what can actually happen if you attach __attribute__((__const__)) to a function that does access global memory?
I would prefer technical answers with explanations of actual possible scenarios within the scope of GCC / G++, rather than the usual "nasal demons" handwaving that appears whenever undefined behaviour gets mentioned.

A:
But what can happen if you attach __attribute__((__pure__))
  to a function that doesn't match the above description,
  and does have side effects?

Exactly. Here's a short example:
extern __attribute__((pure)) int mypure(const char *p);

int call_pure() {
  int x = mypure("Hello");
  int y = mypure("Hello");
  return x + y;
}

My version of GCC (4.8.4) is clever enough to remove second call to mypure (result is 2*mypure()). Now imagine if mypure were printf - the side effect of printing string "Hello" would be lost.
Note that if I replace call_pure with
char s[];

int call_pure() {
  int x = mypure("Hello");
  s[0] = 1;
  int y = mypure("Hello");
  return x + y;
}

both calls will be emitted (because assignment to s[0] may change output value of mypure).

Is it simply the possibility that the function will be called fewer times
  than you would want it to be, or is it possible to create
  undefined behaviour or other kinds of serious problems?

Well, it can cause UB indirectly. E.g. here
extern __attribute__((pure)) int get_index();

char a[];
int i;
void foo() {
  i = get_index();  // Returns -1
  a[get_index()];  // Returns 0
}

Compiler will most likely drop second call to get_index() and use the first returned value -1 which will result in buffer overflow (well, technically underflow).

But what can actually happen if you attach __attribute__((__const__))
  to a function that does access global memory?

Let's again take the above example with
int call_pure() {
  int x = mypure("Hello");
  s[0] = 1;
  int y = mypure("Hello");
  return x + y;
}

If mypure were annotated with __attribute__((const)), compiler would again drop the second call and optimize return to 2*mypure(...). If mypure actually reads s, this will result in wrong result being produced.
EDIT
I know you asked to avoid hand-waving but here's some generic explanation. By default function call blocks a lot of optimizations inside compiler as it has to be treated as a black box which may have arbitrary side effects (modify any global variable, etc.). Annotating function with const or pure instead allows compiler to treat it more like expression which allows for more aggressive optimization.
Examples are really too numerous to give. The one which I gave above is common subexpression elimination but we could as well easily demonstrate benefits for loop invariants, dead code elimination, alias analysis, etc.


text:
Q: Show whether a relation R is transitive for xRy iff 3|(2x+y) Define a relation
$$R : Z^+ \rightarrow Z^+$$
by xRy iff (2x+y)mod3=0.
R is reflexive:
Let x=y. So (x,x) is in R. Then we have 2x+x=3x, and since x is an integer, it must clearly be divisible by 3.
R is not antisymmetric, by counterexample:
$$[(2,5) \land (5,2) \in R] \land 5 \neq 2$$
R is symmetric, since 2x+y = 3i, 2x+x = 3x & 2y+y = 3y; to show symmetry, 2y+x must also be divisible by 3;
so 2x+y + 2y+x = 3x + 3y, with 2x+y = 3i,
2y+x = 3x+3y - 2x+y = 3x+3y - 3i = 3(x+y+i)
Now how to show that it is transitive? I need to show that for any xRy and yRz, xRz. So 2x+y = 3m and 2y+z = 3n where m,n are integers. Solving for y in the second equation, y = (3n-z)/2. Plugging that into the first, we have 2x + (3n-z)/2 = 3m, so 2x - z/2 = 3m - (3n)/2; *2: 4x - z = 6m - 3n. Which is ok, except I need 2x + z, not 4x - z =\

A: If $3 \mod c = 0$ for some $c$, then $c$ must be a factor of 3. So, if $x$R$y$, then either $2x + y = 1$ or $2x + y = 3$. The only two cases are $x = y = 1$ and $x = 0, y = 1$. So if $x$R$y$ and $y$R$z$, then $x$R$z$, because it must be that $z = 1$ and we know $x = 0$ or $x = 1$.

A: Suppose $3\mid 2x+y$ and $3\mid 2y+z$; then
$$
3\mid (2x+y)+(2y+z)
$$
or
$$
3\mid (2x+z)+3y.
$$
Since $3\mid 3y$, you conclude that $3\mid 2x+z$.
Note that this is congruence modulo $3$ in disguise: saying $3\mid 2x+y$ is equivalent to saying that $3\mid 2x+y-3x$, that is, $3\mid y-x$.


text:
Q: Why does shell ignore quoting characters in arguments passed to it through variables? These work as advertised:
grep -ir 'hello world' .
grep -ir hello\ world .

These don't:
argumentString1="-ir 'hello world'"
argumentString2="-ir hello\\ world"
grep $argumentString1 .
grep $argumentString2 .

Despite 'hello world' being enclosed by quotes in the second example, grep interprets 'hello (and hello\) as one argument and world' (and world) as another, which means that, in this case, 'hello will be the search pattern and world' will be the search path.
Again, this only happens when the arguments are expanded from the argumentString variables. grep properly interprets 'hello world' (and hello\ world) as a single argument in the first example.
Can anyone explain why this is? Is there a proper way to expand a string variable that will preserve the syntax of each character such that it is correctly interpreted by shell commands?

A: When you put quote characters into variables, they just become plain literals (see http://mywiki.wooledge.org/BashFAQ/050; thanks @tripleee for pointing out this link)
Instead, try using an array to pass your arguments:
argumentString=(-ir 'hello world')
grep "${argumentString[@]}" .

A: In looking at this and related questions, I'm surprised that no one brought up using an explicit subshell. For bash, and other modern shells, you can execute a command line explicitly. In bash, it requires the -c option.
argumentString="-ir 'hello world'"
bash -c "grep $argumentString ."

Works exactly as original questioner desired. There are two restrictions to this technique:

*

*You can only use single quotes within the command or argument strings.

*Only exported environment variables will be available to the command

Also, this technique handles redirection and piping, and other shellisms work as well. You also can use bash internal commands as well as any other command that works at the command line, because you are essentially asking a subshell bash to interpret it directly as a command line. Here's a more complex example, a somewhat gratuitously complex ls -l variant.
cmd="prefix=`pwd` && ls | xargs -n 1 echo \'In $prefix:\'"
bash -c "$cmd"

I have built command processors both this way and with parameter arrays. Generally, this way is much easier to write and debug, and it's trivial to echo the command you are executing. OTOH, param arrays work nicely when you really do have abstract arrays of parameters, as opposed to just wanting a simple command variant.

A: Why
When the string is expanded, it is split into words, but it is not re-evaluated to find special characters such as quotes or dollar signs or ...  This is the way the shell has 'always' behaved, since the Bourne shell back in 1978 or thereabouts.
Fix
In bash, use an array to hold the arguments:
argumentArray=(-ir 'hello world')
grep "${argumentArray[@]}" .

Or, if brave/foolhardy, use eval:
argumentString="-ir 'hello world'"
eval "grep $argumentString ."

On the other hand, discretion is often the better part of valour, and working with eval is a place where discretion is better than bravery.  If you are not completely in control of the string that is eval'd (if there's any user input in the command string that has not been rigorously validated), then you are opening yourself to potentially serious problems.
Note that the sequence of expansions for Bash is described in Shell Expansions in the GNU Bash manual.  Note in particular sections 3.5.3 Shell Parameter Expansion, 3.5.7 Word Splitting, and 3.5.9 Quote Removal.


text:
Q: SQL query to copy the column value to another column after checking two conditions I have a table customers, in which i have 6 attributes
CustomerID  CustomerName CustomerCity CustomerState DuplicateCustIND
1           Richard      Los Angeles  New York
2           Jerome       Houston      Texas
3           Paul         Los Angeles  New York

In the above table, there are two duplicate column values CustomerCity and CustomerState are same for Richard and Paul. I would like to update the column DuplicateCustIND for paul with the customer id of Richard after checking the two similar column condition.
Till now I was  using correlation query as
Update Customer C1 set C1.DuplicateCustIND = (select CustomerID  from customers
                                             where C3.CustomerCity =
                                             C1.CustomerCity and
                                             C3.CustomerState =
                                             C1.CustomerState)
where exists(
Select 1 from Customers C2 where
C2.CustomerCity = C1.CustomerCity and
C2.CustomerState = C1.CustomerState and
C2.RowID<C1.RowID);

The above query didn't help me.

A: The below query could work.
merge INTO customers tgt USING
(SELECT   a.id,
    a.cname,
    a.ccity,
    a.cstate
  FROM customers a,
    (SELECT   ccity,
        cstate,
        COUNT(*)
      FROM customers b
      GROUP BY ccity,
        cstate
      HAVING COUNT(*) > 1
    ) b
  WHERE a.ccity  = b.ccity
    AND a.cstate = b.cstate
) src ON (tgt.id = src.id)
WHEN matched THEN
  UPDATE SET tgt.dcustid = src.id;

A: You may probably rely on customerid and use a MERGE statement to update all records greater than that customerid with same city and state.
MERGE INTO customers t USING
  ( SELECT MIN(c1.CUSTOMERID) prim_id,
           c2.CUSTOMERID sec_id
   FROM Customers c1
   JOIN customers c2 ON C2.CustomerCity = C1.CustomerCity
   AND C2.CustomerState = C1.CustomerState
   AND C2.CustomerID > C1.CustomerID
   GROUP BY C1.CustomerCity,
            C1.CustomerState,
            c2.CUSTOMERID ) s ON (s.sec_id = t.CustomerID )
WHEN MATCHED THEN
UPDATE
SET t.DuplicateCustIND = s.prim_id;

SQLFiddle


text:
Q: Can't get a prepared statement to print in php I'm trying to get to grips with mysqli but finding it a struggle compared to the now depreciated mysql.  So far with the old methods I've been able to get information back about my tables in an associative array.  I'm trying to form a prepared statement and echo the id number back.  I would also like to be able to print the whole sql statement that has been binded, but seen as I can't even echo the id number from a single SELECT statement, it is out of the question at the moment.
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');

$sql = "SELECT user_id, name FROM users WHERE name=?"

$statement = $db -> prepare($sql);

$statement -> bind_param("s", "Emma");

$statement -> execute();

$statement -> bind_result($id, $name);

$output = $statement -> fetch();

echo $output -> $id . " " . $name;

I seem to be getting lost at the line bind_result.  I figured if statement is an object, then I should be able to echo them in the form I have devised?  When I refresh my page I just get nothing. I have 2 entries in my table and 1 of them does have the name string that is used above.

A: You think too complex. Just try this:
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?";
$statement = $db->prepare($sql);
$statement->bind_param("s", "Emma");
$statement->execute();
$statement->bind_result($id, $name);
while ($statement->fetch()) {
  echo $id . " " . $name;
}

The bind_result() methods takes care that for each $statement->fetch() you execute you get fresh values in the variables $id and $name.
You should take a look at the good documentation of those methods.


text:
Q: Using filters from other classes within rules method in Yii 2? Consider this code inside a model:
public function rules() {
    return [
        [['company_name', 'first_name', 'last_name'], 'sanitize'],
        //........
    ];
}

sanitize is a custom method inside the current class, which is:
public function sanitize($attribute) {
    $this->{$attribute} = general::stripTagsConvert($this->{$attribute}, null, true);
}

Now this method obviously will come in handy in many models so I don't want to keep repeating the same code in every model. Is there a way I can reference another class in the rules in place of the current sanitize method name which is binded to the current class?

A: Yes, it's definitely possible.
Create separate validator. Let assume it's called SanitizeValidator and placed in common/components folder.
Your custom validator must extend from framework base validator and override validateAttribute() method. Put your logic inside this method:
use yii\validators\Validator;

class SanitizeValidator extends Validator
{
    /**
     * @inheritdoc
     */
    public function validateAttribute($model, $attribute)
    {
        $model->$attribute = general::stripTagsConvert($model->$attribute, null, true);
    }
}

Then in model you can attach this validator like this:
use common/components/SanitizeValidator;

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['company_name', 'first_name', 'last_name'], SanitizeValidator::className()],
    ];
}

Check the official documentation about custom validators here and there.


text:
Q: Program structure in long running data processing python script For my current job I am writing some long-running (think hours to days) scripts that do CPU intensive data-processing.  The program flow is very simple - it proceeds into the main loop, completes the main loop, saves output and terminates:  The basic structure of my programs tends to be like so:
<import statements>
<constant declarations>

<misc function declarations>

def main():
   for blah in blahs():
      <lots of local variables>
      <lots of tightly coupled computation>

      for something in somethings():
          <lots more local variables>
          <lots more computation>

   <etc., etc.>

   <save results>

if __name__ == "__main__":
    main()

This gets unmanageable quickly, so I want to refactor it into something more manageable.  I want to make this more maintainable, without sacrificing execution speed.
Each chuck of code relies on a large number of variables however, so refactoring parts of the computation out to functions would make parameters list grow out of hand very quickly. Should I put this sort of code into a python class, and change the local variables into class variables?  It doesn't make a great deal of sense tp me conceptually to turn the program into a class, as the class would never be reused, and only one instance would ever be created per instance.
What is the best practice structure for this kind of program? I am using python but the question is relatively language-agnostic, assuming a modern object-oriented language features.

A: First off, if your program is going to be running for hours/days then the overhead of switching to using classes/methods instead of putting everything in a giant main is pretty much non-existent.
Additionally, refactoring (even if it does involve passing a lot of variables) should help you improve speed in the long run. Profiling an application which is designed well is much easier because you can pin-point the slow parts and optimize there. Maybe a new library comes along that's highly optimized for your calculations... a well designed program will let you plug it in and test right away. Or perhaps you decide to write a C Module extension to improve the speed of a subset of your calculations, a well designed application will make that easy too.
It's hard to give concrete advice without seeing <lots of tightly coupled computation> and <lots more computation>. But, I would start with making every for block it's own method and go from there.

A: Not too clean, but works well in little projects...
You can start using modules as if they were singleton instances, and create real classes only when you feel the complexity of the module or the computation justifies them.
If you do that, you would want to use "import module" and not "from module import stuff" -- it's cleaner and will work better if "stuff" can be reassigned. Besides, it's recommended in the Google guidelines.

A: Using a class (or classes) can help you organize your code.
Simplicity of form (such as through use of class attributes and methods) is important because it helps you see your algorithm, and can help you more easily unit test the parts.
IMO, these benefits far outweigh the slight loss of speed that may come with using OOP.


text:
Q: Start Date should be less than End date validation in ASP.Net Core MVC I am using .net core to create the StartDate, EndDate of a Term which includes the ClosureDate that receives the report for that Term. Here I want a StartDate> ClosureDate and an EndDate<ClosureDate. And of course StartDate<Enddate. So here how should I test it? Process them right inside my Repository or use scripts to handle them at View?
Here is my Code:
Repository
 public bool CreateSemester(Semester semester)
    {
        if (CheckExistSemester(semester.SemesterName))
        {
            return false;
        }
        var newSemester = new Semester
        {
            SemesterName = semester.SemesterName,
            SemesterStartDate = semester.SemesterStartDate,
            SemesterEndDate = semester.SemesterEndDate,
            ClosureDate = semester.ClosureDate
        };
        _dbContext.Semesters.Add(newSemester);
        _dbContext.SaveChanges();
        return true;
    }

A: You can do a custom validation.
Create a CustomModelValidatorProvider class.
 public class CustomModelValidatorProvider : IModelValidatorProvider
{

    public void CreateValidators(ModelValidatorProviderContext context)
    {
        if (context.Results.Any(v => v.Validator.GetType() == typeof(MyCustomModelValidator)) == true)
        {
            return;
        }

        if (context.ModelMetadata.ContainerType == typeof(Semester))
        {
            context.Results.Add(new ValidatorItem
            {
                Validator = new MyCustomModelValidator(),
                IsReusable = true
            });
        }
    }
}

public class MyCustomModelValidator : IModelValidator
{
    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
    {
        var model = context.Container as Semester;

        if (context.ModelMetadata.ModelType == typeof(DateTime)
            && context.ModelMetadata.Name == nameof(model.SemesterStartDate))
            {

        if (model.StartDate > model.ClosureDate)
        {
            return new List<ModelValidationResult>
                {
                   new ModelValidationResult("","Start Date should be less than Closure date")
                };
            }
        }
        if (context.ModelMetadata.ModelType == typeof(DateTime)
            && context.ModelMetadata.Name == nameof(model.SemesterEndDate))
        {

            if (model.EndDate < model.ClosureDate)
            {
                return new List<ModelValidationResult>
                {
                   new ModelValidationResult("","End Date should be grater than Closure date")
                };
            }
        }

        return Enumerable.Empty<ModelValidationResult>();
    }
}
}

And in your Startup
 services.AddControllersWithViews(opt => opt.ModelValidatorProviders.Add(new CustomModelValidatorProvider()));

Test Result:

A: You can use Fluent Validation. it's more flexible to define custom rules.
Following is the fluent validation example that you want to implement.
public class SearchValidator: AbstractValidator
{
  public SearchValidator()
  {
    RuleFor(m => m.StartDate)
        .NotEmpty()
        .WithMessage("Start Date is Required");

    RuleFor(m => m.EndDate)
        .NotEmpty().WithMessage("End date is required")
        .GreaterThan(m => m.StartDate.Value)
                        .WithMessage("End date must after Start date")
        .When(m => m.StartDate.HasValue);
  }
}

here is a well-explained article that will help you.
here is the documentation of fluent validation.


text:
Q: Approximating square root by sexagesimal fractions I am reading The Works of Archimedes and I have found the following method for approximating the square root with sexagesimal fractions:

Ptolemy has first found the integral part of $\sqrt{4500}$ to be $67$. Now $67^2 = 4489$, so that the remainder is $11$. Suppose now that the rest of the square root is expressed by means of the usual sexagesimal fractions, and that we may therefore put $$\sqrt{4500} = \sqrt{67^2 + 11} = 67 + \frac{x}{60} + \frac{y}{60^2}$$
  where $x,y$ are yet to be found. Thus $x$ must be such that $\frac{2\cdot67x}{60}$ is somewhat less than $11$, or $x$ must be somewhat less than $\frac{11\cdot60}{2\cdot67}$ or $\frac{330}{67}$, which is at the same time greater than $4$.

I am interested only in the sentence "Thus $x$ must be such that...". How are these conditions on $x$ assumed, namely the fractions $\frac{2\cdot67x}{60}$ and $\frac{11\cdot60}{2\cdot67}$?

A: Forget the $y$ for a moment. Then we want
$$\sqrt{67^2+11}\approx67+{x\over60}\ .$$
This means
$$67^2+11\approx 67^2+{2\cdot67\cdot x\over60}+\left({x\over60}\right)^2\ .$$
Note that $0\leq{x\over60}<1$, and the square is even smaller. Therefore we want that
$${2\cdot67\cdot x\over60}<11,\quad{\rm and\ as\ large\ as\ possible.}$$
Therefore $x<{60\cdot11\over 2\cdot 67}= {660\over134}=4.925$; hence  $x=4$. We now proceed with
$$\sqrt{67^2+11}\approx67+{4\over60}+{y\over60^2}\ ,$$
and do a similar computation with respect to $y$.This will lead to $y=55$.

A: The first trick is to factor out $67$ :
$$\sqrt{67^2+11}=67\cdot \sqrt{1+\frac{11}{67^2}}$$
Now, the taylor series of $\sqrt{1+x'}$ gives the linear approximation $$\sqrt{1+x'}\approx 1+\frac{x'}{2}$$ for $x'\approx 0$. To avoid confusion with the $x$ here, I used $x'$.
Hence we have
$$\frac{11}{2\cdot 67}=\frac{x}{60}$$ which gives $$x=\frac{30\cdot 11}{67}=4.9254$$
This value is a bit too large which can be concluded by estimating the Lagrange residue of the taylor-series. In fact, inserting this for $x$ already gives an excellent approximation of $\sqrt{4500}$


text:
Q: Using Mysql Replicate to replicate at a particular time My job has a testing, staging and production enviroment. They want most database changes to be done on the staging environment and for the production environment to replicate the staging environment. From the research I've done, it appears that Mysql Replication process would be the best way to do this. So the Staging Database would be the master DB and the live production site would run on the slave DB. So my question is this.
From what I found, I was able to figure out how to setup a master slave database environment but the resources I've found do not go in detail on how frequently the slave talks to the master database. I would like for the slave to talk to the master either on demand or during a particular time during the day. I maybe misunderstanding the resources I am reading but thats why I am asking this question. I would not like for the database to constantly listen for new changes in the master log. How does replication work by default and how can I get it to listen at a particular time or when I tell it to.
Thanks

A: Since this is ad-hoc synching, don't set up any master-slave or master-master, as you're making your life more complicated than necessary. Merely set up a cron job or at job to synch via dump, with your choice of: simple file copy, sockets or tcp/ip mysql connection for the transfer.


text:
Q: Jquery ui dialog button submit issues As a student of jquery ui I am having troubles finding how to set a dialog button to submit. On the input tags, I am using the type attribute to allow the browser to perform validation of 'email' and for the password, I'm using the pattern attribute and title.
                <input
                    type="email"
                    name="EMAIL_0000"
                    id="EMAIL_0000"
                    tabindex="12"
                    size="40"
                    placeholder="Username"
                    value=""
                    required/>
                <input
                    type="password"
                    name="PASSWORD_0000"
                    id="PASSWORD_0000"
                    tabindex="13"
                    pattern="<?php echo $PasswordPattern; ?>"
                    value=""
                    placeholder="Password"
                    title="See notes for valid password."
                    required/>

When a submit button is pressed, the user will see something like:
I cannot post the image because I don't have 10 reputation post images....
You will note there are two 'Sign On' buttons. The upper one (in the form area) is a type="submit" button. The lower one is created by the jquery ui dialog as follows:
    $("#form_0000").dialog({
      Var username = $("#EMAIL_0000").val(),
      Password=$("#PASSWORD_0000").val(),….
      buttons: {
          "Sign On": function(){
// here I perform a $.ajax() to verify the email is in the data base. But the browser validation does not occur.
…….
    }

When the lower 'Sign On' button is pressed, no browser validation occurs, all validation must be done in the jquery dialog using $.ajax to access a php function to make server side data base queries.
From my research I don't believe jQuery UI has the capability to allow the setting of the button type attribute. All I can see that can be done is set the name of the button.
At this point I believe my only option is to set a button in the form itself and indicate it's a submit button and when pressed, the browser validation occurs, but then I have issues with verifying the existence of the email address and if the password is (I can show an alert box, but not the look and feel that I want) and once the processing of the is complete the dialog goes away, not allowing the user to select from one of the other 'dialog' buttons to join, etc.
Is there someone that has worked around the limitation that can provide some insight to a solution?
I think I can remove the lower 'Sign on' button and just use the forms submit button and maintain the processes off browser validation and programmable validation showing error messages and remaining at the dialog screen. I can move that code to
$( "#btnSignOn_0000" )
    .click(function() {
        // move dialog 'sign on' button code here.
    });

I would like to wait for some replies and avoid additional work if it is not necessary.

A: Ouch, sorry for leading you down the wrong path.  But since I did, I messed around with the code, and figured it out for you.
Uncomment the button you have in the dialog but do not display it by setting the css to:
#btnSignOn_0000 {
    display: none;
}

Now, in your dialog code, instead of $('formSignOn').submit(); use:
$("#form_0000").dialog({
      buttons: {
          "Sign On": function(){
              $('#btnSignOn_0000').click();
          }
      }
});

The button is clicked, the validation is triggered, and the $('formSignOn').submit(function(){}) is not executed unless the form passes validation.

A: Here is the final solution:
$('#formSignOn').submit(function( e ){
   e.preventDefault();

This prevents the submission to close the dialog window after the ajax function is performed.


text:
Q: android get imei in cc/c++ for ndk/JNI I would try to get the imei of a device in C/C++ (using ndk) and retrieve the result with JNI.
const char *res = exec_get_out("service call iphonesubinfo 3");

Works in shell, but does not in my application
I have the READ_PHONE_STATE permission set in the Manifest.  This is targeted for Marshmallow Android (and I have accepted permission in settings)
Is there any other solution that would work or is it not possible without a JNI environment?

A: check this and this
#include <sys/system_properties.h>

    //returns the string length of the value.
    int ir = __system_property_get("ro.gsm.imei", imei_start);

      if(ir > 0)
    {
      imei_start[15]=0;//strz end
      printf("method1 got imei %s len %d\r\n",imei_start,strlen(imei_start));
      strcpy(g_imei,imei_start);
    }
      else
    {
      printf("method1 imei failed - trying method2\r\n");
      //old dumpsys imei getter
      char* res = exec_get_out("dumpsys iphonesubinfo");
      const char* imei_start_match = "ID = ";
      int imei_start_match_len = strlen(imei_start_match);
      char* imei_start = strstr(res,imei_start_match);
      if(imei_start && strlen(imei_start)>=15+imei_start_match_len)
        {
          imei_start += imei_start_match_len;
          imei_start[15] = 0;
          printf("method2 IMEI [%s] len %d\r\n",imei_start,strlen(imei_start));
          strcpy(g_imei,imei_start);
        }
    }


text:
Q: Add or override properties of already defined function JavaScript I have a JavaScript function with the following structure:
function someFunctions() {
  this.DOSOMETHING = function(parameters){
    //some logic
  }
}

This is loaded in another file and instantiated as an object that is then being used:
load('file_containing_someFunctions.js')
var someFunctions = new someFunctions();

function doTheThing(parameters) {
  //some logic
  someFunctions.DOSOMETHING(parameters)
}

I would like to load another file after the first one which overrides or adds properties to someFunctions() before the object is instantiated.
load('file_containing_someFunctions.js')
load('file_containing_extended_functions.js')
var someFunctions = new someFunctions();

function doTheThing(parameters) {
  //some logic
  someFunctions.DOSOMETHINGELSE(parameters)
}

How should I define DOSOMETHINGELSE in file_containing_extended_functions.js? Is it possible? It's worth noting that the code is rather old and used in old browsers.

A: By using the new keyword, you are instantiating a new object whose constructor function is someFunctions. The constructor creates a function called DOSOMETHING and assigns it as a property of the newly created object. This goes against the OOP paradigm in JavaScript where object methods should be members of the object's prototype, not the object itself.
You may transform the constructor code as follows:
function someFunctions() { }
someFunctions.prototype.DOSOMETHING = function(parameters) {}

In your extension script you may then add and override methods by modifying the someFunctions.prototype object.
If you insist on keeping the current implementation of someFunctions, you may create a new function with the same name, internally calling the old someFunctions constructor and modifying the returned object:
const oldSomeFunctions = someFunctions;

var someFunctions = function() {
    const base = new oldSomeFunctions();
    base.DOSOMETHING = console.log;
    base.DOSOMETHINGELSE = console.info;

    return base;
}


text:
Q: Call to a member function escape_string() on a non-object I'm getting the following error:
Fatal error: Call to a member function escape_string() on a non-object

On the code:
$pass = $_GET['pass'];
$user = $_GET['user'];
//$id = $_GET['uid'];
echo "u: ".$user." pass: ".$pass;
echo "
TEST";
//$check = validate_password_from_uid($id, $pass);
$check = validate_password_from_username($user, $pass);
echo "validation:
";
if (is_array($check)){
echo "
";
    print_r($check);
    echo "
";
}else{
    var_dump($check);
}

Here is validate_password_from_username:
function validate_password_from_username($username, $password)
{
    global $db, $mybb;

    $username = $db->escape_string(strtolower($username));
    switch($mybb->settings['username_method'])
    {
        case 0:
            $query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."'", array('limit' => 1));
            break;
        case 1:
            $query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(email)='".$username."'", array('limit' => 1));
            break;
        case 2:
            $query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."' OR LOWER(email)='".$username."'", array('limit' => 1));
            break;
        default:
            $query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."'", array('limit' => 1));
            break;
    }

    $user = $db->fetch_array($query);
    if(!$user['uid'])
    {
        return false;
    }
    else
    {
        return validate_password_from_uid($user['uid'], $password, $user);
    }
}

The error is related to the line 67 in which $db->escape_string part is. What  should I change?

A: The error message tells us that the $db variable is not an object, so you can't make a function call to it. You don't show us how $db is defined so you might have named the variable differently.


text:
Q: How to join the parent table when using STI I have these models:
class Product < ApplicationRecord
  has_many :units
end

class Unit < Product
  belongs_to :product
end

The models above uses one table only which is called 'products' table.
create_table :products do |t|
  t.string  :code
  t.integer :product_id
  t.string  :type
  t.string  :status
  ...
end

What I want is to get all the units where products.status is active.
I tried Unit.joins(:product).where(products: { status: 'active' }) but no luck
Here's the current data I have
| id |  type   | product_id | status  |
|----|:-------:|-----------:|---------|
| 1  | Product |       null | deleted |
| 2  | Product |       null | active  |
| 3  |  Unit   |          1 | active  |
| 4  |  Unit   |          1 | active  |
| 5  |  Unit   |          2 | active  |

All I want to get is
| id |  type   | product_id | status  |
|----|:-------:|-----------:|---------|
| 5  |  Unit   |          2 | active  |

A: Short answer:
Your use case doesn't make sense to use STI. Use a has_many/belongs_to like so:
# notice we inherit from ApplicationRecord now instead
class Unit < ApplicationRecord
  belongs_to :product
end

Then you can run your query like:
Product.joins(:units).where(units: {status: 'active'})

Explanation:
It doesn't make sense to have a belongs_to -> has_many relationship between two tables inheriting from the same parent. Two tables with STI is another way of saying "these two models are specific types of a more general model."
For example:
# the parent class your other children classes will inherit from
class Vehicle < ApplicationRecord
  # and let's say in the database vehicle has a column of:
  # color: :string

  def honk
    puts 'beep!'
  end
end

# Car inherits methods and attributes of Vehicle, and can also define
# its own methods particular to cars
class Car < Vehicle
  def sunroof?
    # logic here
  end
end

# Motorcycle inherits methods and attributes of Vehicle, and can also define
# its own methods particular to motorcycles
class Motorcycle < Vehicle
  def sidecar?
    # logic here
  end
end

As you can see, the purpose of STI is to share common methods and attributes (in the example above, the honk method and the :color attribute) so that you don't waste time and cause potential application issues by defining them twice.
In contrast, a belongs_to/has_many association is for defining a relationship between two totally separate but related models. For example:
class Book < ApplicationRecord
  belongs_to :library

  ...
end

class Library < ApplicationRecord
  has_many :books

  ...
end

And this would allow us to do useful things in our application such as checking which books a given library can lend:
library = Library.first
library.books
=> # a bunch of book objects returned from the db


text:
Q: ASP.NET 5 - Starting an ASP.NET vNext project I am trying to get my feet wet with ASP.NET vNext. I'm very interested in the cross-platform aspect of it. For that reason, I'm focused on using the K Runtime Environment.
I've looked at the sample provided on the home page. Those samples do not help me though. I have a project that is structure like this:
/
 /client
 /server
  /controllers
   HomeController.cs
  /views
   /home
     Index.cshtml
  project.json
  Startup.cs

When I navigate to the directory with project.json, I run the following from the command-line.
C:\MyProject\server>k web

I get the following error:
System.IO.FileLoadException: Could not load file or assembly 'server' or one of its dependencies. General Exception (Exception from HRESULT: 0x80131500)
File name: 'server' ---> Microsoft.Framework.Runtime.Roslyn.RoslynCompilationException: C:\MyProject\server\controllers\HomeController.cs(5,18): error CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

I feel like Startup.cs is looking for something called server. Yet it doesn't exist. I suspect something is missing from project.json. However, I do not know what. My project.json looks like the following:
{
    "dependencies": {
        "Kestrel": "1.0.0-beta1",
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1"
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
    },
     "frameworks": {
        "aspnet50": {},
        "aspnetcore50": {}
  }
}

What am I doing wrong?  Thank you!

A: As Tim has pointed out there's something fishy in your controllers.
The compiler asks for System.Web but you shouldn't use it. Is it referenced somewhere? vNext is moving away from System.Web; we should not use it in MVC 6.
Are you using the stock New Project? Are you using the latest CTP/Preview version?
If you are using the stock New Project just try recreate the project. Yes, I have solved an error in VS 2015 by only recreating the stock project.
I would recommend you to read this article:
http://www.dzone.com/articles/developing-and-self-hosting


text:
Q: How to remove the InkStroke when using the ActiveCustomDrying in uwp? I used the ActiveCustomDrying to customize the ink, now I want to remove them InkStrokes. StrokeContainer is null because of active the CustomDrying, so I am unable to remove the InkStrokes by using the DeleteSelected method. Can anyone suggest me how to remove the InkStrokes when using the CustomDrying.

A: During the custom drying, you will store the strokes in a custom List<InkStrokeContainer> collection:
private void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args)
{
    var strokes = _inkSynchronizer.BeginDry();

    var container = new InkStrokeContainer();
    container.AddStrokes(from item in strokes
        select item.Clone());
    _strokes.Add(container);

    _inkSynchronizer.EndDry();
}

Now you can manipulate the InkStrokeContainer instances manually (including calls to DeleteSelected).
The documentation also states that when using ActiveCustomDrying, erasing with InkToolbar does not work automatically and you need to handle the pointer events manually

If your app overrides the default ink rendering behavior of the InkPresenter with a custom drying implementation, the rendered ink strokes are no longer available to the InkToolbar and the built-in erase commands of the InkToolbar do not work as expected. To provide erase functionality, you must handle all pointer events, perform hit-testing on each stroke, and override the built-in "Erase all ink" command.

If you want to implement the commands, you will need to observe the Checked and Unchecked events of the toolbar buttons and then handle the pointer events yourself. A complete tutorial how to do this is available on MSDN.