text:
Q: convergent subsequence of bounded divergent sequence, and limit of $\sup$ and $\inf$ I happened accross this excercise:

Let $a_n$ be a bounded, divergent sequence. Proove that there are at least two subsequences converging to different limits.

As a first strategy I thought of doing this:
Let $b_n \rightarrow L$ be a convergent subsequence (B-W theorem). Choose $\epsilon$ such that $\forall N, \exists n>N$ so that $|a_n - L|>\epsilon$. Using this post, build a subsequence as follows:
$n_1 = \min(n>1 / |a_n-L|>\epsilon)$
$n_k = \min(n>n_{k-1}/ |a_n-L|>\epsilon)$
The set $a_{n_k}, k>=1$ is a subsequence of $a_n$, therefore bounded, therefore contains a convergent subsequence, which cannot converge to $L$ (first question: is this ok?)
Moreover I wondered if $sup$ and $inf$ of the sequence can be used, and what are their properties. Is the following reasoning correct?
Let $S_k = {a_n, n>=k}$, since all $S_k$ are bounded sequences, $sup(S_k)$ exists. Furthermore, since $S_1\supset S_2 \supset S_3 ...$ then $\sup(S_1)\geq \sup(S_2)\geq \sup(S_3) ...$. Therefore, the sequence $\sup(S_1), \sup(S_2)...$ is monotone and bounded (therefore convergent).
Third question, is it true that $\displaystyle L = \lim_{n\rightarrow \infty}\inf(S_n) = \lim_{n\rightarrow \infty}\sup(S_n) \Leftrightarrow a_n\rightarrow L$?
Thanks


text:
Q: aws cli : s3api append lifecycle policy to existing ones I have multiple lifecycle policies for a bucket, whenever I try to create a new one, I have to manually do the following things:
STEP 1:
Run:
aws s3api get-bucket-lifecycle-configuration  --bucket my-bucket > lifecycle.json

STEP 2:
then edit the lifecycle.json and append the new policy
STEP 3:
Run:
aws s3api put-bucket-lifecycle-configuration --bucket <bucket_name> --lifecycle-configuration file://lifecycle.json

otherwise, it will replace the old policies.
Is there any way to directly append the new policy with the existing ones?
For Example:
My Existing policies:
{
    "Rules": [
        {
            "Expiration": {
                "Days": 365
            },
            "ID": "Policy 1",
            "Filter": {
                "Prefix": "dir1/dir2/code/"
            },
            "Status": "Enabled"
        },
        {
            "Expiration": {
                "Days": 90
            },
            "ID": "Policy 2",
            "Filter": {
                "Prefix": "Name/Address/code/"
            },
            "Status": "Enabled"
        }
    ]
}

I want to add this policy:
{
  "Rules": [
    {
      "Expiration": {
        "Days": 20
      },
      "ID": "TEST_POLICY_09082021_ARANI2",
      "Filter": {
        "Prefix": "backup/ARANI2/files/"
      },
      "Status": "Enabled"
    }
  ]
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rake db:seed causes an error I executed the commands rake db:drop, rake db:create and rake db:migrate and everything was well. However when I run the command rake db:seed an weird error is caused
alex@ubuntu:~/RubymineProjects/some_project$ rake db:seed --trace
** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:abort_if_pending_migrations
rake aborted!
Connection refused - connect(2)
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:540:in `initialize'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:540:in `open'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:540:in `tcp_socket'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:549:in `block in do_start'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/timeout.rb:68:in `timeout'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/timeout.rb:99:in `timeout'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:549:in `do_start'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/smtp.rb:519:in `start'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/mail-2.4.4/lib/mail/network/delivery_methods/smtp.rb:144:in `deliver!'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/mail-2.4.4/lib/mail/message.rb:2034:in `do_delivery'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/mail-2.4.4/lib/mail/message.rb:229:in `block in deliver'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/actionmailer-3.2.3/lib/action_mailer/base.rb:414:in `block in deliver_mail'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/notifications.rb:123:in `block in instrument'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/notifications.rb:123:in `instrument'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/actionmailer-3.2.3/lib/action_mailer/base.rb:412:in `deliver_mail'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/mail-2.4.4/lib/mail/message.rb:229:in `deliver'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/devise-2.1.0/lib/devise/models/confirmable.rb:128:in `send_on_create_confirmation_instructions'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:416:in `_run__3737511161133628056__create__2350421739628145298__callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in `__run_callback'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:385:in `_run_create_callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:81:in `run_callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/callbacks.rb:268:in `create'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/persistence.rb:344:in `create_or_update'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/callbacks.rb:264:in `block in create_or_update'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:425:in `_run__3737511161133628056__save__2350421739628145298__callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in `__run_callback'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:385:in `_run_save_callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:81:in `run_callbacks'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/callbacks.rb:264:in `create_or_update'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/persistence.rb:84:in `save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/validations.rb:50:in `save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/attribute_methods/dirty.rb:22:in `save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:241:in `block (2 levels) in save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:295:in `block in with_transaction_returning_status'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:208:in `transaction'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:293:in `with_transaction_returning_status'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:241:in `block in save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:252:in `rollback_active_record_state!'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/transactions.rb:240:in `save'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/relation/finder_methods.rb:293:in `find_or_instantiator_by_attributes'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/dynamic_matchers.rb:47:in `method_missing'
/home/alex/RubymineProjects/some_project/db/seeds.rb:42:in `<top (required)>'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:245:in `load'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:245:in `block in load'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:236:in `load_dependency'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:245:in `load'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/engine.rb:520:in `load_seed'
/home/alex/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/railties/databases.rake:309:in `block (2 levels) in <top (required)>'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/home/alex/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in `load'
/home/alex/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in `<main>'
/home/alex/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `eval'
/home/alex/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `<main>'
Tasks: TOP => db:seed

What does this error mean? What do I fix it?

A: Your SMTP mailer is trying to post and cannot connect. in development.rb set
config.action_mailer.perform_deliveries = false


text:
Q: Spark stand alone mode: Submitting jobs programmatically I am new to Spark and I am trying to submit the "quick-start" job from my app. I try to emulate standalone-mode by starting master and slave on my localhost.
object SimpleApp {

  def main(args: Array[String]): Unit = {

    val logFile = "/opt/spark-2.0.0-bin-hadoop2.7/README.md"
    val conf = new SparkConf().setAppName("SimpleApp")
    conf.setMaster("spark://10.49.30.77:7077")
    val sc = new SparkContext(conf)

    val logData = sc.textFile(logFile,2).cache();
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s , lines with b: %s".format(numAs,numBs))

  }

}

I run my Spark app in my IDE (IntelliJ).
Looking at the logs (logs in workernode), it seems spark cannot find the job class.
16/09/15 17:50:58 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 1912.0 B, free 366.3 MB)
16/09/15 17:50:58 INFO TorrentBroadcast: Reading broadcast variable 1 took 137 ms
16/09/15 17:50:58 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 3.1 KB, free 366.3 MB)
16/09/15 17:50:58 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.ClassNotFoundException: SimpleApp$$anonfun$1
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)

1.Does this mean the Job resources (classes) are not transmitted to the slave node?
2.For stand-alone mode , I must submit jobs using "spark-submit" CLI? If so, how to submit sparks jobs from a app(for example a webapp)
3.Also unrelated question : I see in the logs the,DriverProgram starts a server(port 4040).Whats the purpose of this? DriveProgram being the client, why does it start this service ?
16/09/15 17:50:52 INFO SparkEnv: Registering OutputCommitCoordinator
16/09/15 17:50:53 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/09/15 17:50:53 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.49.30.77:4040

A: You should either set the resources paths in SparkConf using the setJars method or provide the resources in spark-submit command with the --jars option when running from CLI.


text:
Q: WebGL transparent gradient mask at edge I need to make a feature in WebGL, where I have horizontal list of meshes (example 20) and I want to show only 3 and 2 at edge are fade in/fade out. And it slowly animates from one side no another (sliding to left or right).

Here is a sample code, how it is done using CSS. (https://jsfiddle.net/jqsLh4vg/91/)
What would be possible options to have this kind of effect?

My current approach, what I am trying (could be not the most performant solution):

*

*Calculate visible area

*Calculate how much visible area (in percentage) each mesh is visible in visible area on each render

*Draw gradient using frag shader at the edges (here it is were I stucked and can't figure out the solution)

But maybe there is easier approach for this kind of effect? (Imagine if I have 100 elements and I need to manually calculate their visible area on each render time).


text:
Q: PHP Backup database and send email I found a PHP script that backups the database of my website and sends the file to an emailadress of my choice. I implemented it on my website, but it fails.
The Backup Class. This handles the backup and the email:
<?php
   class Backup
   {
       /**
        * @var stores the options
        */
       var $config;

       /**
        * @var stores the final sql dump
        */
       var $dump;

       /**
        * @var stores the table structure + inserts for every table
        */
       var $struktur = array();

       /**
        * @var zip file name
        */
       var $datei;

       /**
        * this function is the constructor and phrase the options
        * and connect to the database
        * @return
        */
       public function Backup($options)
       {
               // write options
               foreach($options AS $name => $value)
               {
                       $this->config[$name] = $value;
               }

               // check mysql connection
               mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
               mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
       }

       /**
        * this function start the backup progress its the core function
        * @return
        */
       public function backupDB()
       {
               // start backup
               if(isset($_POST['backup']))
               {
                       // check if tables are selected
                       if(empty($_POST['table']))
                       {
                               die("Please select a table.");
                       }

                       /** start backup **/
                       $tables = array();
                       $insert = array();
                       $sql_statement = '';

                       // lock tables
                       foreach($_POST['table'] AS $table)
                       {
                                mysql_query("LOCK TABLE $table WRITE");

                               // Read table structure
                               $res = mysql_query('SHOW CREATE TABLE '.$table.'');
                               $createtable = mysql_result($res, 0, 1);
                               $str = "\n\n".$createtable."\n\n";

                               array_push($tables, $str);

                               // Read table "inserts"
                   $sql = 'SELECT * FROM '.$table;
                   $query = mysql_query($sql) or die(mysql_error());
                   $feld_anzahl = mysql_num_fields($query);

                               $sql_statement = '--
-- Data Table `$table`
--

                                       ';

                               // start reading progress
                   while($ds = mysql_fetch_object($query)){
                       $sql_statement .= 'INSERT INTO `'.$table.'` (';

                       for ($i = 0;$i <$feld_anzahl;$i++){
                           if ($i ==$feld_anzahl-1){
                               $sql_statement .= mysql_field_name($query,$i);
                           } else {
                               $sql_statement .= mysql_field_name($query,$i).', ';
                           }
                       }

                       $sql_statement .= ') VALUES (';

                       for ($i = 0;$i <$feld_anzahl;$i++){
                           $name = mysql_field_name($query,$i);
                           if (empty($ds->$name)){
                               $ds->$name = 'NULL';
                           }
                           if ($i ==$feld_anzahl-1){
                               $sql_statement .= '"'.$ds->$name.'"';
                           } else {
                               $sql_statement .= '"'.$ds->$name.'", ';
                           }
                       }
                       $sql_statement .= ");\n";
                   }

                               // insert "Inserts" into an array if not exists
                               if(!in_array($sql_statement, $insert))
                               {
                                       array_push($insert, $sql_statement);
                                       unset($sql_statement);
                               }

                               unset($sql_statement);

                       }

                       // put table structure and inserts together in one var
                       $this->struktur = array_combine($tables, $insert);

                       // create full dump
                       $this->createDUMP($this->struktur);

                       // create zip file
                       $this->createZIP();

                       /** end backup **/

                       // send an email with the sql dump
                       if(isset($this->config['email']) && !empty($this->config['email']))
                       {
                               $this->sendEmail();
                       }

                       // output
                       echo '
Backup war erfolgreich
datei.'">Download Backup

';
               }
       }

       /**
        * this function generate an email with attachment
        * @return
        */
       protected function sendEmail()
       {
                       // start sending emails
                       foreach($this->config['email'] AS $email)
                       {
                               $to = $email;

                               $from = $this->config['email'][0];

                               $message_body = "This email contains the database backup as a zip file.";

                               $msep = strtoupper (md5 (uniqid (time ())));

                               // set email header (only text)
                               $header =
                                         "From: $from\r\n" .
                                         "MIME-Version: 1.0\r\n" .
                                         "Content-Type: multipart/mixed; boundary=" . $msep ."\r\n\r\n" .
                                         "--" . $msep . "\r\n" .
                                         "Content-Type: text/plain\r\n" .
                                         "Content-Transfer-Encoding: 8bit\r\n\r\n" .
                                         $message_body . "\r\n";

                               // file name
                               $dateiname = $this->datei;

                               // get filesize of zip file
                               $dateigroesse = filesize ($dateiname);

                               // open file to read
                               $f = fopen ($dateiname, "r");
                               // save content
                               $attached_file = fread ($f, $dateigroesse);
                               // close file
                               fclose ($f);

                               // create attachment
                               $attachment = chunk_split (base64_encode ($attached_file));

                               // set attachment header
                               $header .=
                                          "--" . $msep . "\r\n" .
                                          "Content-Type: application/zip; name='Backup'\r\n" .
                                          "Content-Transfer-Encoding: base64\r\n" .
                                          "Content-Disposition: attachment; filename='Backup.zip'\r\n" .
                                          "Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
                                          $attachment . "\r\n";

                               // mark end of attachment
                               $header .= "--" . "$msep--" . ";

                               // eMail Subject
                               $subject = "Database Backup";

                               // send email to emails^^
                               if(mail($to, $subject, '', $header) == FALSE)
                               {
                                       die("The email could not be sent. Please check the email address.");
                               }

                               echo "
Email was successfully sent.
";
                       }
       }

       /**
        * this function create the zip file with the database dump and save it on the ftp server
        * @return
        */
       protected function createZIP()
       {

               // Set permissions to 777
               chmod($this->config['folder'], 0777);

               // create zip file
               $zip = new ZipArchive();
               // Create file name
               $this->datei = $this->config['folder'] . $this->config['mysql'][3] . "_" . date("j_F_Y_g:i_a") . ".zip";

               // Checking if file could be created
               if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
                       exit("cannot open <".$this->datei.">\n");
               }

               // add mysql dump to zip file
               $zip->addFromString("dump.sql", $this->dump);
               // close file
               $zip->close();

               // Check whether file has been created
               if(!file_exists($this->datei))
               {
                       die("The ZIP file could not be created.");
               }

               echo "
The zip was created.
";
       }

       /**
        * this function create the full sql dump
        * @param object $dump
        * @return
        */
       protected function createDUMP($dump)
       {
               $date = date("F j, Y, g:i a");

               $header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}

--
-- Datenbank: `{$this->config['mysql'][3]}`
--

-- --------------------------------------------------------

HEADER;
               foreach($dump AS $name => $value)
               {
                       $sql .= $name.$value;
               }
               $this->dump = $header.$sql;
       }

       /**
        * this function displays the output form to select tables
        * @return
        */
       public function outputForm()
       {
               // select all tables from database
               $result = mysql_list_tables($this->config['mysql'][3]);

               $buffer = '
               <fieldset>
                       <legend>Select some tables</legend>
                       <form method="post" action="">
               <select name="table[]" multiple="multiple" size="30">';
               while($row = mysql_fetch_row($result))
               {
                       $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
               }
               $buffer .= '</select>

               <input type="submit" name="backup" value="Backup Tables" />
               </form>
               </fieldset>';

               echo $buffer;
       }
    }
?>

Next is the handler that it called when a user pushes the Backup button on the website:
<?php
    //You can add as many email addresses as you like
    $options = array(   'email' => array('email1, email2'),
                        'folder' => './backup/',
                        'mysql' => array('localhost', 'root', '', 'database')
                    );

    $b = new Backup($options);

    // if submit form start backup
    if(isset($_POST['backup']))
    {
        // start backup
        $b->backupDB();
    }

    // display tables
    $b->outputForm();
?>

The last script works as far as I can tell. But the other gives the following error message
Parse error: syntax error, unexpected T_VARIABLE in /home/u164555197/public_html/ChiroDB2/Scripts/PHP/backupdb.php on line 170

Line 170 is located in the function that handles the generation of the email (function SendEmail())
Can someone help me locate this error and maybe has a solution?

A: Change the lines so they are
// mark end of attachment
$header .= "--" . $msep . "--";

// eMail Subject
$subject = "Database Backup";

This is line 202 of the class you pasted.
<?php
   class Backup
   {
       /**
        * @var stores the options
        */
       var $config;

       /**
        * @var stores the final sql dump
        */
       var $dump;

       /**
        * @var stores the table structure + inserts for every table
        */
       var $struktur = array();

       /**
        * @var zip file name
        */
       var $datei;

       /**
        * this function is the constructor and phrase the options
        * and connect to the database
        * @return
        */
       public function Backup($options)
       {
               // write options
               foreach($options AS $name => $value)
               {
                       $this->config[$name] = $value;
               }

               // check mysql connection
               mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
               mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
       }

       /**
        * this function start the backup progress its the core function
        * @return
        */
       public function backupDB()
       {
               // start backup
               if(isset($_POST['backup']))
               {
                       // check if tables are selected
                       if(empty($_POST['table']))
                       {
                               die("Please select a table.");
                       }

                       /** start backup **/
                       $tables = array();
                       $insert = array();
                       $sql_statement = '';

                       // lock tables
                       foreach($_POST['table'] AS $table)
                       {
                                mysql_query("LOCK TABLE $table WRITE");

                               // Read table structure
                               $res = mysql_query('SHOW CREATE TABLE '.$table.'');
                               $createtable = mysql_result($res, 0, 1);
                               $str = "\n\n".$createtable."\n\n";

                               array_push($tables, $str);

                               // Read table "inserts"
                   $sql = 'SELECT * FROM '.$table;
                   $query = mysql_query($sql) or die(mysql_error());
                   $feld_anzahl = mysql_num_fields($query);

                               $sql_statement = '--
-- Data Table `$table`
--

                                       ';

                               // start reading progress
                   while($ds = mysql_fetch_object($query)){
                       $sql_statement .= 'INSERT INTO `'.$table.'` (';

                       for ($i = 0;$i <$feld_anzahl;$i++){
                           if ($i ==$feld_anzahl-1){
                               $sql_statement .= mysql_field_name($query,$i);
                           } else {
                               $sql_statement .= mysql_field_name($query,$i).', ';
                           }
                       }

                       $sql_statement .= ') VALUES (';

                       for ($i = 0;$i <$feld_anzahl;$i++){
                           $name = mysql_field_name($query,$i);
                           if (empty($ds->$name)){
                               $ds->$name = 'NULL';
                           }
                           if ($i ==$feld_anzahl-1){
                               $sql_statement .= '"'.$ds->$name.'"';
                           } else {
                               $sql_statement .= '"'.$ds->$name.'", ';
                           }
                       }
                       $sql_statement .= ");\n";
                   }

                               // insert "Inserts" into an array if not exists
                               if(!in_array($sql_statement, $insert))
                               {
                                       array_push($insert, $sql_statement);
                                       unset($sql_statement);
                               }

                               unset($sql_statement);

                       }

                       // put table structure and inserts together in one var
                       $this->struktur = array_combine($tables, $insert);

                       // create full dump
                       $this->createDUMP($this->struktur);

                       // create zip file
                       $this->createZIP();

                       /** end backup **/

                       // send an email with the sql dump
                       if(isset($this->config['email']) && !empty($this->config['email']))
                       {
                               $this->sendEmail();
                       }

                       // output
                       echo '
Backup war erfolgreich
datei.'">Download Backup

';
               }
       }

       /**
        * this function generate an email with attachment
        * @return
        */
       protected function sendEmail()
       {
                       // start sending emails
                       foreach($this->config['email'] AS $email)
                       {
                               $to = $email;

                               $from = $this->config['email'][0];

                               $message_body = "This email contains the database backup as a zip file.";

                               $msep = strtoupper (md5 (uniqid (time ())));

                               // set email header (only text)
                               $header =
                                         "From: $from\r\n" .
                                         "MIME-Version: 1.0\r\n" .
                                         "Content-Type: multipart/mixed; boundary=" . $msep ."\r\n\r\n" .
                                         "--" . $msep . "\r\n" .
                                         "Content-Type: text/plain\r\n" .
                                         "Content-Transfer-Encoding: 8bit\r\n\r\n" .
                                         $message_body . "\r\n";

                               // file name
                               $dateiname = $this->datei;

                               // get filesize of zip file
                               $dateigroesse = filesize ($dateiname);

                               // open file to read
                               $f = fopen ($dateiname, "r");
                               // save content
                               $attached_file = fread ($f, $dateigroesse);
                               // close file
                               fclose ($f);

                               // create attachment
                               $attachment = chunk_split (base64_encode ($attached_file));

                               // set attachment header
                               $header .=
                                          "--" . $msep . "\r\n" .
                                          "Content-Type: application/zip; name='Backup'\r\n" .
                                          "Content-Transfer-Encoding: base64\r\n" .
                                          "Content-Disposition: attachment; filename='Backup.zip'\r\n" .
                                          "Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
                                          $attachment . "\r\n";

                               // mark end of attachment
                               $header .= "--" . $msep . "--";

                               // eMail Subject
                               $subject = "Database Backup";

                               // send email to emails^^
                               if(mail($to, $subject, '', $header) == FALSE)
                               {
                                       die("The email could not be sent. Please check the email address.");
                               }

                               echo "
Email was successfully sent.
";
                       }
       }

       /**
        * this function create the zip file with the database dump and save it on the ftp server
        * @return
        */
       protected function createZIP()
       {

               // Set permissions to 777
               chmod($this->config['folder'], 0777);

               // create zip file
               $zip = new ZipArchive();
               // Create file name
               $this->datei = $this->config['folder'] . $this->config['mysql'][3] . "_" . date("j_F_Y_g:i_a") . ".zip";

               // Checking if file could be created
               if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
                       exit("cannot open <".$this->datei.">\n");
               }

               // add mysql dump to zip file
               $zip->addFromString("dump.sql", $this->dump);
               // close file
               $zip->close();

               // Check whether file has been created
               if(!file_exists($this->datei))
               {
                       die("The ZIP file could not be created.");
               }

               echo "
The zip was created.
";
       }

       /**
        * this function create the full sql dump
        * @param object $dump
        * @return
        */
       protected function createDUMP($dump)
       {
               $date = date("F j, Y, g:i a");

               $header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}

--
-- Datenbank: `{$this->config['mysql'][3]}`
--

-- --------------------------------------------------------

HEADER;
               foreach($dump AS $name => $value)
               {
                       $sql .= $name.$value;
               }
               $this->dump = $header.$sql;
       }

       /**
        * this function displays the output form to select tables
        * @return
        */
       public function outputForm()
       {
               // select all tables from database
               $result = mysql_list_tables($this->config['mysql'][3]);

               $buffer = '
               <fieldset>
                       <legend>Select some tables</legend>
                       <form method="post" action="">
               <select name="table[]" multiple="multiple" size="30">';
               while($row = mysql_fetch_row($result))
               {
                       $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
               }
               $buffer .= '</select>

               <input type="submit" name="backup" value="Backup Tables" />
               </form>
               </fieldset>';

               echo $buffer;
       }
    }
?>

A: Use MysqlDumper. Its the best suggestion I can give.
I also use it for my website.
There is an own interface to configure it. And there is also the option to automaticly backup your database and send a mail at a specific time with a success-message. If you want to, you can append the backup to the mail (not suggested with big dbs).
Heres a link.
Unfortunately I can provide any code for this as there isnt anything you need to setup by php-code itself.
How to install:
Just copy & paste the folder to your webserver and open the index-page. A setup will start automaticly that asks for a database-setup (login-details, connection etc). After that its ready to use.


text:
Q: Using a 1:M relationship to create 1:1 I was recently asked to change my application design and have a solution but it feels dirty and I was hoping there are alternatives out there I'm not thinking of.
I have a DB table Activity that has an associate Product table that has several fields like name, description, price, etc.
Normally I would have a drop down in my interface populated with the various products, and upon submission, put a product id in my activity table. Every time I need to pull up an activity, i just do a join on the key and pull in the relevant product info.
Now the request is that if you pull up the activity but someone has altered say the description of the product since the activity was entered, that it show the original description, not the new one.
The main solution I can think of is simply duplicate all the product fields in the activity table and fill them in based on the selected drop down, but that feels like it could get very messy. Both for increased storage, but also for potential queries and extra work if new columns are needed in the future. This also feels like having a relational database pointless.
Is this solution the one I should go with or perhaps a hybrid one with copied fields, but retain the foreign key for reports/queries?
Thanks

A: This doesn't sound like a description change; it sounds like a new product is being created.  If the product data content needs to remain with the product ID as of the entry time, then the product data cannot really change.  A new product needs to be added.  The description is behaving like a key.
When the description changes and a new product is added, the old product needs to be deactivated.  It's still in the domain table because the 'old' product records are tied to it but new activity items can't use it.  The original or previous product ID can be stored in the domain table entry for the new product.
Product ID    Description   is_Active  Previous_Product_ID  Add_Date
    1         myOldDesc         N                            1/1/2017
    2         NewDesc           Y             1              1/1/2018

You'll end up with a chain of product changes.  I worked on a system many years ago that forced the relational design in this way.  It was very difficult to work with.
The activity table seems to contain historical data.  I recommend denormalizing it.  You'll still have the product domain table for your drop-down which can be modified according to relational practices.  On a change, create an audit record to record the history of the changes.  When an activity item is created, instead of storing the product_id, store the actual product information.  The advantage of the relational model is that you can change the description without needing to change every related activity record.  But in this case, you don't want to change the related records so why normalize it?


text:
Q: How to check if the array inside object has elements of interest? Hi i have an object like so,
const obj = {
    id: '1',
    itemData: [
        "type1",
        "type2",
        "type3",
    ],
}

sometimes this itemData array can be empty array.
now i have to check if itemData has "type1" or "type2". if so then should return true if not false.
i have tried like below,
const isDisabled = obj.itemData.map(e => return e === "type1" || e==="type2")

but this doesnt work. could someone help me with this. thanks.

A: You can use includes with some

const obj = {
    id: '1',
    itemData: [
        "type1",
        "type2",
        "type3",
    ],
}

console.log(!obj.itemData.length || obj.itemData.some(el => ['type1', 'type2'].includes(el)));

The some() method tests whether at least one element in the array
passes the test implemented by the provided function. It returns true
if, in the array, it finds an element for which the provided function
returns true; otherwise it returns false. It doesn't modify the array.

MDN - some

The includes() method determines whether an array includes a certain
value among its entries

MDN - includes


text:
Q: How to get height of div using jquery in IE I have a div, i want get height of the div.
$('.graph_container').css('height')

and css is
.graph_container {
    width:100%;
    float:left;
    border:1px solid #CCCCCC;
    margin-top:1em;
    position:relative;
}

since height is not mentioned, in IE it give 'auto'. How can i get exacte height.
I appreciate your suggestions.

A: $('.graph_container').height()

which returns a number.

A: To calculate height of any element or window or document we can make use of the "height()" method of jQuery.
$(document).ready(function(){
$("p").append($("p").height()+" px");
$("div.divContainer").append($("div.divContainer").height()+" px");
$("div.document").append($(document).height()+" px");
$("div.window").append($(window).height()+" px");
});

Height of this document is:

Height of this window is:

Height of this div container is:

Height of this paragraph is:


text:
Q: (WPF) UserControl or CustomControl? I need to build a specific interactive drawing "canvas".
In that canvas, user will be able to place graphic elements - points linked with lines.
I have a ready WinForms UserControl - pointsList that represents the list of points presents in the canvas. PointsList is able to add and remove points, link them with a line.
pointsList should be a floating(movable) and resizeable control in the canvas(like a windows on a screen).
My questions:

*

*What is the best choice for this "canvas" - a WPF UserControl or CustomControl?

*Is it possible to place a (floating) WinForm UserControl inside a WPF control?

*Will it be hard to rewrite a floatting and resizeable WPF user control inside an other?

EDIT
Better explanation of the "Floating Control":
Imagine a WPF Container (say, a Canvas).
In this canvas you have a button.
When you click the button, a "Floating Window Control" opens inside the Canvas.
This control is like a Windows Form, can be opened, moved, closed, resized, but all this inside the parent canvas. Something similar to a MDI parent and child forms, but the parent is not a form, but a WPF container (say Canvas).

A: 1) Both types will suit your needs. UserControls are typically easier to author, especially when you are new to WPF. CustomControl is actually not a class, but it means that you extend an existing control. There are some differences between the 2 approaches, the biggest one is that a custom control is easier to make it themeable. In your case, I assume this is not a need, so I'd recommend a UserControl. More info on this: http://www.wpftutorial.net/CustomVsUserControl.html
2) Yes. You can put a WinForms control inside WPF using the WindowsFormsHost control. One limitation is that the WinForms control must be a non-transparent rectangle, meaning you cannot throw in different shapes and expect them to overlay correctly. Look for WindowsFormsHost and you'll find lots of examples.
3) Can you explain better? don't understand what you mean, but of course you can place UserControls within each other, and WPF is especially useful when dealing with dynamic sizing.

A: We got a lot of mileage adapting this WPF code from CodeProject. link text


text:
Q: Erlang creating list by splitting a list of tuples I have a list of tuples and I want to create the a list of elements from a specific position in the tuple.
My tuple is {A, B} and I have several of these in a list and i want to create the list of all the B elements.
Cheers!

A: You can use lists:map.
1> A = [{1,2},{3,4},{5,6}].
[{1,2},{3,4},{5,6}]
2> B = lists:map(fun ({_, V}) -> V end, A).
[2,4,6]

The function passed to the map will select the element required from the tuple and the result will be a list of all the elements in that particular position in the given list of tuples. The above code assumes that all tuples have same number of elements.

A: Yet another way is to just use a simple list comprehension:
[B || {_, B} <- L].

A: > L = [{a1,b1}, {a2,b2}, {a3,b3}].
[{a1,b1},{a2,b2},{a3,b3}]
> lists:foldr(fun({_, B}, Acc) -> [B | Acc] end, [], L).
[b1,b2,b3]

A: This is a quick sample, not tested, but it should work.
split_tuples([{A | B} | T], Acc) ->
    NewAcc = [B | Acc],
    split_tuples(T, NewAcc);
split_tuples([], Acc) ->
    lists:reverse(Acc).

A: erlang's element/2 function does just that: return the nth element from a tuple.
Put that in a map or fold function, with position as a parameter, and you're done.

edit: some untested code example:
get_them_all(ListOfTuples,Index) ->
    lists:map(fun(Tuple) -> element(Index,Tuple) end,ListOfTuples).


text:
Q: Storing a list with React Native AsyncStorage: many keys or one? I want to store a list of items with AsyncStorage. The list will be updated over time.
Here is an example of a state the list can be in:
[
  {
    name: "Alice",
    email: "alice@example.com"
  },
  {
    name: "Bob",
    email: "bob@example.com",
    address: "30 Madison Ave., NY"
  }
]

Now, it seems that there are two options for storing this list:

*

*Store each contact under its own key

*Store the whole list under one key

There are advantages to either approach - what is preferred in React Native?

A: I think this depends on how you plan to use, access, and update the data. There are several asyncstorage methods you can use to help make either case easier.
If you decide to go the many keys route, have a look at multiSet and multiGet, which allows you to retrieve several keys in a single function call. And getAllKeys will save you the trouble of "keep[ing] track of all the keys you created", solving both of the problems mentioned by Fredrick Motte.
For updating many keys in one call, check out multiMerge which is a really powerful method, similar to mergeItem but multiple keys at once.
So, you see you can really go either route. If you divide your data up into multiple keys, then you'll probably just want to spend some time getting familiar with the methods I mentioned above.
And David's suggestion to give Relm a look might have some value for you as well, again... depending on your need.

A: For ease of use I'd store the list as a whole; since then you don't have to keep track of all the keys you created for each contact individually; and loading/saving them will be easier (just one function call instead of looping over all of your contacts).
But this is mostly a personal preference; there are no real constraints for any of the two methods.

A: I would add to the two good answers from Chris and Frederick:
it depends on the size of your list, and the size of your documents.
Going with one list as a whole is much easier to manage, but does not scale (computation will get heavier with the size of your global value).
going with one key per item adds some complexity but scales.
Personally I started with everything in one key, and now am refactoring to have one document per key, because when I'm processing hundreds of big documents, performances clearly degrade.
And if you are handling thousands or 10s of thousands of elements, I think you should go for a proper database like sqlite or realm (but debugging is an issue at the moment in realm).
Would be interested to know the true limits of asyncStorage, I read somewhere, it was a few megabytes unless you ask in your native config to increase it


text:
Q: /usr/bin/shiny-server.sh: permission denied when running an R shiny docker on Ubuntu I built a basic R shiny app and wanted to dockerize it on an Ubuntu 18.04 VM.
I followed this blog.
and got the following situation:
R app
app.R
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2]
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application
shinyApp(ui = ui, server = server)

Dockerfile
# Install R version 3.4
FROM r-base:3.4.0

# Install Ubuntu packages
RUN apt-get update && apt-get install -y \
    sudo \
    gdebi-core \
    pandoc \
    pandoc-citeproc \
    libcurl4-gnutls-dev \
    libcairo2-dev/unstable \
    libxt-dev \
    libssl-dev

# Add shiny user
RUN groupadd  shiny \
&& useradd --gid shiny --shell /bin/bash --create-home shiny

# Download and install ShinyServer (latest version)
#RUN wget --no-verbose https://s3.amazonaws.com/rstudio-shiny-server-os-build/ubuntu-12.04/x86_64/VERSION -O "version.txt" && \
#    VERSION=$(cat version.txt)  && \
#    wget --no-verbose "https://s3.amazonaws.com/rstudio-shiny-server-os-build/ubuntu-12.04/x86_64/shiny-server-$VERSION-amd64.deb" -O ss-latest.deb && \
#    gdebi -n ss-latest.deb && \
#    rm -f version.txt ss-latest.deb

# Install R packages that are required
# TODO: add further package if you need!
RUN R -e "install.packages(c('shiny'), repos='http://cran.rstudio.com/')"

# Copy configuration files into the Docker image
COPY shiny-server.conf  /etc/shiny-server/shiny-server.conf
COPY /app /srv/shiny-server/

# Make the ShinyApp available at port 80
EXPOSE 80

# Copy further configuration files into the Docker image
COPY shiny-server.sh /usr/bin/shiny-server.sh

# allow permission
RUN sudo chown -R shiny:shiny /srv/shiny-server
#RUN chown shiny:shiny /var/lib/shiny-server

CMD ["/usr/bin/shiny-server.sh"]

shiny-server.conf
# Define the user we should use when spawning R Shiny processes
run_as shiny;

# Define a top-level server which will listen on a port
server {
  # Instruct this server to listen on port 80. The app at dokku-alt need expose PORT 80, or 500 e etc. See the docs
  listen 80;

  # Define the location available at the base URL
  location / {

    # Run this location in 'site_dir' mode, which hosts the entire directory
    # tree at '/srv/shiny-server'
    site_dir /srv/shiny-server;

    # Define where we should put the log files for this location
    log_dir /var/log/shiny-server;

    # Should we list the contents of a (non-Shiny-App) directory when the user
    # visits the corresponding URL?
    directory_index on;
  }
}

shiny-server.sh
#!/bin/sh

# Make sure the directory for individual app logs exists
mkdir -p /var/log/shiny-server
chown shiny.shiny /var/log/shiny-server

exec shiny-server >> /var/log/shiny-server.log 2>&1

The directory structure is
 - app/app.R
 - Dockerfile
 - shiny-server.sh
 - shiny-server.conf

I use the docker
Docker version 18.09.9, build 1752eb3
and build it using
sudo docker build -t test .

but when running it I get
 sudo docker run test

docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/usr/bin/shiny-server.sh\": permission denied": unknown.
ERRO[0001] error waiting for container: context canceled

I looked through the various forums mentioning this issue and tried changing permissions.
I am quite puzzled as it seemed to me that this case was a basic example.
==== Edition after comment ====
I have changed the ownership and the permission of the .sh file
sudo  chown shiny:shiny shiny-server.sh
 sudo chmod u+ shiny-server.sh

rebuilt the image
 sudo docker build -t test .

reran it
 sudo docker run test

but then it does nothing, no error or message of any type, just going to the next line.


text:
Q: How to model objects with comparable fields in protobuf Given 3 objects A, B and C where:

*

*A and B share a number of fields, but also each have unique fields

*all fields of both A and B are in C, which also some extra unique fields

Obviously I could model this in protobuf by creating separate messages for every object:
message A {
    uint32 A_B = 1;
    uint32 A_C = 2;
}

message B {
    uint32 A_B = 1;
    uint32 B_C = 2;
}

message C {
    uint32 A_B   = 1;
    uint32 A_C   = 2;
    uint32 B_C   = 3;
    uint32 onlyC = 4;
}

But I was wondering whether it makes sense to create a single, generic message for all three objects and add a field that tells me which specific object I'm dealing with?
message Generic {
    enum Specific{
        A = 1;
        B = 2;
        C = 3;
    }
    Specific obj = 1;
    uint32 A_B   = 2;
    uint32 A_C   = 3;
    uint32 B_C   = 4;
    uint32 onlyC = 5;
}

I know both options are possible from a technical point of view, but is the second one somehow not according to how things should be done in protobuf?
Note: in my specific case, the objects represent API call argument lists that won't change in the future.


text:
Q: How I could to unmount active partition? I try to use function DeleteVolumeMountPoint(L"C:\\"), but I have not access, and it's right. But I need to delete active partition, and I'm search way to do it. Please, could you give me example to delete this partition (unmount it). Operation Systems XP/Vista/7.

A: The problem is that you cannot unmount the active partition Windows is running on. You should do such operation in a more "native" way like Fdisk does or at reboot.
There are some programs also from SysInternals that calling the native NT Apis perform page file defrag, for example, during the boot time.
The disk management program included in Windows NT/XP/Vista does not allow you to do this either if I remember well.
NT Native APIs

A: As I suspect the system (the operating system itself) has all of its files on this partition, several of them must be actually in use. I doubt you can unmount this system partition.


text:
Q: Short code in python How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters?
t=int(input())
while t>0:
  n=int(input())
  s=sum(1/(2.0*i+1) for i in range(n))
  print "%.15f"%s
  t-=1

A: You're welcome
for t in range(int(input()), 0, -1): print '%.15f' % sum(1/(2.0*i+1) for i in range(int(input())))

EDIT (explanation):
Firstly, instead of a while loop you can use a for loop in a range. The last argument in the for loop is a -1 to subtract 1 every time instead of the default of plus 1 every time.
If there is only one statement in an if statement, or loop, you can keep the one statement in the same line without going to the next line.
Instead of creating the variable of n, you can simply plug it in since it's only being used once. Same goes for s.

A: for _ in range(input()):print"%.15f"%sum(1/(2.0*i+1)for i in range(input()))

A: exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()
I know I am too late for answering this question.but above code gives same result.
It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4


text:
Q: Ninject passing reference in constructor I am a noob with dependency Injections, I followed the tutorial and refactored my code to use Ninject. Here it is what I have (simplified).
Bindings.cs
 public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<IConnectionToModbusCreator>().To<ConnectionToModbusCreator>();
            Bind<IInputProcessor>().To<InputProcessor>();
}}

Program.cs ;
static class Program
    {
        [STAThread]
        static void Main()
        {
            var kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());
            var InputProcessor = kernel.Get<IInputProcessor>();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1(InputProcessor));
}

This start a form, the user by clicking a button start the program, here is the Form1:
    public partial class Form1 : Form
    {
        private readonly IInputProcessor _inputProcessor;

        public Form1(IInputProcessor inputProcessor)
        {            _inputProcessor = inputProcessor;
            InitializeComponent();
        }
        private void Test_Click_1(object sender, EventArgs e)
        {
  ISequenceController sequenceController = new SequenceController( _inputProcessor)
            sequenceController.StartSequence();
        }

My problem is:
Is this the best way? I am worried by all the references I have to pass in the constructors, I tried to use a class Container which keeps variables with the objects instantiated and use them as properties but I cannot find sich method in any Ninject manual.

A: Your program follows the Constructor Injection DI pattern which is good practice, but it has some issues which introduce coupling between your modules. The numerous calls to new should alert you.

*

*Program should not know about IInputProcessor. This is a dependency of Form1

*Form1 should not know about IInputProcessor. It is a dependency of SequenceController

*Form1 should not know about SequenceController, it should only know about its abstraction, ISequenceController
This can be solved by a better use of constructor injection to obtain less coupled code :
public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<IConnectionToModbusCreator>().To<ConnectionToModbusCreator>();
            Bind<IInputProcessor>().To<InputProcessor>();
            Bind<ISequenceController>().To<SequenceController>();
            Bind<Form1>().ToSelf(); // in fact useless unless you add a scope, like .InSingletonScope()
        }
}

static class Program
    {
        [STAThread]
        static void Main()
        {
            var kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form1= kernel.Get<Form1>();
            Application.Run(form1);
}

public partial class Form1 : Form
{
    private readonly ISequenceController _sequenceController;

    public Form1(ISequenceController sequenceController)
    {
        _sequenceController = sequenceController;
        InitializeComponent();
    }

    private void Test_Click_1(object sender, EventArgs e)
    {
        _sequenceController.StartSequence();
    }


text:
Q: Limits at negative infinity Prove that $\lim_{x\to -\infty}$ $\frac{x}{x+2}$ = 1.
Please help me check if this is correct:

Let $\varepsilon > 0$ be given. Choose $M=2-\frac{2}{\varepsilon}$
$$\begin{align}
  x<M \Rightarrow x-2 < M-2\\
  \frac{1}{x-2} > \frac{1}{M-2}\\
  |f(x)-1|=|\frac{x}{x-2}-1|=|\frac{2}{x-2}|\\
  <|\frac{2}{M-2}|=\frac{-2}{M-2}=\varepsilon
  \end{align}$$

A: Since $x \to -\infty$, we may assume $M < 0$.  Then your line $\frac{1}{x-2} > \frac{1}{M-2}$ is a relationship between two negative quantities.  Thus $\left|\frac{1}{x-2}\right| < \left|\frac{1}{M-2}\right|$.  Can you take it from there?


text:
Q: When to create an EndPoint?
What is the use case /scenario where should I create an EndPoint in
  google app engine project ?

I know that I can send my data from my mobile client to App server(GAE) using one EndPoint and receive data from App Server(GAE) using the same or another EndPoint. But I am not able to understand when i should create/use another EndPoint for receiving data and not use the same EndPoint using which I sent the data.

Is it advisable to have same EndPoint to be used for mobile client and
  web client?

Any help will be appreciated!!
thanks in advance!!!

A:
What is the use case /scenario where should I create an EndPoint in google app engine project?

Endpoints should be created on a class basis. So you use the same endpoint class for sending and receiving foo objects (but obviously you use different methods). It's just a REST api, so you'll want to create your basic CRUD methods. Generate an endpoint in Eclipse and you'll see what the intended/generic use cases are.

Is it advisable to have same EndPoint to be used for mobile client and web client?

Yes, that's the point of a REST api; it doesn't matter what the client is. From the overview page:


text:
Q: Multi conditional attribute selector I have some links for stories, some of which are in pdf, and some of these are special editions. The special editions are prefixed by special-edition in their href.
Here is a simplified html portion of my app

 Story 1
 Story 2
 Story 3
 Special Edition 1
 Story 4
 Special Edition 2

What I need is to add a background color for the links ending with the extension pdf, but only if they are not special editions. I am able to apply the following css to handle pdf, but the problem that this also applies to the special edition link. What can I do here?
a[href$=".pdf"]{
 background-color: #ADD8E6 ;
}

.container-node{
 background-color: #32CD32;
}

A: You can simply use a combination of your attribute selector with another not attribute selector as below.
a[href$=".pdf"]:not([href*="special-edition"]){
 background-color: #ADD8E6 ;
}

<!DOCTYPE html>

      Story 1
      Story 2
      Story 3
      Special Edition 1
      Story 4
      Special Edition 2


text:
Q: Angular js Div show only for 3 seconds i am new in angular js. i done with div hide and show. just i want to know how to hide or show div for 3 seconds only.
here i attaching my code which i used.
html code:

Dynamic user feedback message comes here.

Forgot Password?

angular js code:
$scope.loginAlertMessage = true;

    $scope.forgotPassword = function () {
         $scope.loginAlertMessage=false;
    };

A: Inject the $timeout service in the controller and use it to unset loginAlertMessage.
app.controller('MyController', ['$scope', '$timeout', function($scope, $timeout) {
   $scope.loginAlertMessage = true;

   $scope.forgotPassword = function() {
      $scope.loginAlertMessage = false;
      $timeout(function() {
         $scope.loginAlertMessage = true;
      }, 3000);
   };

   // ...
}]);

A: inject $timeout service (derived from setTimeout(function() {"action",time(in ms) }) in controller and if wish to display make the div true and if wish to hide make use this service to stop.


text:
Q: What are the default arguments for ClutterGst? Hello everyone I am trying to make a simple video player using Gtk3 python & Gstreamer. I am also using Clutter,ClutterGtk & ClutterGst
The problem arises when initialise the ClutterGst like:
ClutterGst.init()

but I dont know the argument which should be passed here. If I try sys.argv my Gtk window disappears.

A: You start by initializing ClutterGtk, then GstClutter, both with sys.argv, then everything should work fine.
Take a look at audience's initialization code for example:
http://bazaar.launchpad.net/~audience-members/audience/trunk/view/head:/Audience/Audience.vala#L898
(not sure if the X.init_threads is really necessary, but there were some strange problems in Audience which were (probably) solved with this)


text:
Q: C# - Check if specific key is pressed I'm trying to check if a key is pressed, but I get these Error Message:

Error  1   The name 'Keyboard' does not exist in the current context
Error  2   The name 'Key' does not exist in the current context

Can you tell me how to fix it?
public void Main()
{
    while(true)
    {
        if (Keyboard.IsKeyPressed(Key.A))
        {
            //...
        }
        return;
    }
}

A: It looks like you are trying to create a global hotkey in the system and your application should respond when it is pressed.
You will need two Win32 API functions RegisterHotKey and UnregisterHotKey.
Looking at your using System.Windows.Input, it seems like you are trying to do this with WPF, which is possible.
Let's start with your fairly basic P/Invokes:
using System.Runtime.InteropServices;

internal static class NativeMethods
{
    [DllImport("user32.dll")]
    public static extern bool RegisterHotKey(IntPtr windowHandle, int hotkeyId, uint modifierKeys, uint virtualKey);

    [DllImport("user32.dll")]
    public static extern bool UnregisterHotKey(IntPtr windowHandle, int hotkeyId);
}

Now, when you register your Window, what happens is that a WM_HOTKEY message is sent to your application's message pump. However, WPF abstracts this message pump away from you, so you'll need to add a HwndSourceHook to tap into it.
How do we do all this? Let's start by initializing our HwndSourceHook delegate. Add this snippet to your MainWindow:
    using System.Windows.Interop;

    static readonly int MyHotKeyId = 0x3000;
    static readonly int WM_HOTKEY = 0x312;

    void InitializeHook()
    {
        var windowHelper = new WindowInteropHelper(this);
        var windowSource = HwndSource.FromHwnd(windowHelper.Handle);

        windowSource.AddHook(MessagePumpHook);
    }

    IntPtr MessagePumpHook(IntPtr handle, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_HOTKEY)
        {
            if ((int)wParam == MyHotKeyId)
            {
                // The hotkey has been pressed, do something!

                handled = true;
            }
        }

        return IntPtr.Zero;
    }

Alright, so now we have everything in place to respond to the WM_HOTKEY message. However, we need to register our hotkey still! Let's add another couple initialization methods:
    void InitializeHotKey()
    {
        var windowHelper = new WindowInteropHelper(this);

        // You can specify modifiers such as SHIFT, ALT, CONTROL, and WIN.
        // Remember to use the bit-wise OR operator (|) to join multiple modifiers together.
        uint modifiers = (uint)ModifierKeys.None;

        // We need to convert the WPF Key enumeration into a virtual key for the Win32 API!
        uint virtualKey = (uint)KeyInterop.VirtualKeyFromKey(Key.A);

        NativeMethods.RegisterHotKey(windowHelper.Handle, MyHotKeyId, modifiers, virtualKey);
    }

    void UninitializeHotKey()
    {
        var windowHelper = new WindowInteropHelper(this);
        NativeMethods.UnregisterHotKey(windowHelper.Handle, MyHotKeyId);
    }

Alright! Where do we put these? Do not put them in the constructor! Why? Because the Handle will be 0 and invalid! Put them here (in MainWindow):
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        InitializeHook();
        InitializeHotKey();
    }

You can register multiple hotkeys, un-register and re-register new ones.. it's up to you. Just remember that each hotkey must have a unique ID registered to it. It only makes sense, as your message pump hook has to know which hotkey caused the WM_HOTKEY message!
It's also good practice to unregister all hotkeys when your application closes.

A: You can use a keyboard hook.  Check this out, from this answer to a similar question:

Global keyboard hooks are not the right solution if you only want a
  few global hotkeys. A high level keyboard hook means that your dll
  will be injected into other applications, and shouldn't be done at all
  in managed code. A low level keyboard hook is a bit better, since it
  processes the keyboard events in your own application. Still it
  requires that every keyboard event is handled by your thread.
The windows API function RegisterHotKey is much better suited for
  that.
But using a smple F-Key as global hotkey is problematic since it might
  collide with a local hotkey of the application that has focus. So you
  should make global hotkeys configurable, so the user can avoid
  collisions with his commonly used applications.

A: If you are trying to do this in a windows forms application, maybe you can add these codes into the Form's KeyDown event(or which key event you need to use):
switch (e.KeyData)
{
    //Detects that you pressed the Up Arrow Key, which key do you need, just
    //write it here.
    case Keys.Up:
    //enter code here`
    break;
}

A: You need to add PresentationCore.dll and WindowsBase to references and add to the header of the method [STAThread]

A: The type of application is not clear. If you have a console application, not a Windows form one, you can try this:
while (true)
  if (Console.KeyAvailable)
    if (Console.ReadKey(true).Key == ConsoleKey.A)
    {
      // Do something
    }

and read this if you want to have a global hotkey in a windows forms app: http://www.liensberger.it/web/blog/?p=207


text:
Q: Color box environment I'm trying to create a boxing environment for notes but without numbers. My code is the following:
\documentclass{article}
\usepackage{lipsum}
\usepackage{amsthm}
\usepackage{xcolor}

\newtheoremstyle{MyNote}%
{}{}%
{}{}%
{}{}%
{ }%
{\fcolorbox{blue}{white}{{\color{blue}\textbf{\thmname{#1}}}}}
\theoremstyle{MyNote}
\newtheorem{MyNote}{My Note}

\begin{document}
\begin{MyNote}
\lipsum
\end{MyNote}
\end{document}

My problem is: how I can control rule thickness of the blue box, vertical and horizontal spaces inside the box? Thanks.

A: Welcome to TeX.SE!
For thicker border lines just in your box, insert before definition of color box \setlength\fboxrule{<desired thiknes>}. For example:
\documentclass{article}
\usepackage{lipsum}
\usepackage{amsthm}
\usepackage{xcolor}

\newtheoremstyle{MyNote}%
{}{}%
{}{}%
{}{}%
{ }%
{\setlength\fboxrule{2pt}% <---
 \fcolorbox{blue}{white}{\color{blue}\textbf{\thmname{#1}}}}

\theoremstyle{MyNote}
\newtheorem{MyNote}{My Note}

\begin{document}
\begin{MyNote}
\lipsum[1]
\end{MyNote}
\end{document}

produce:


text:
Q: How to render large size image with OpenGL ES 2.0 on android I'm trying to change colors of a image by OpenGL ES 2.0 on android OS. This is my code.
Tex class
public class Tex {
    private FloatBuffer mVertexBuffer;
    private ShortBuffer mDrawListBuffter;
    protected FloatBuffer mUvBuffer;
    protected static float mUvs[];
    private final float[] mMtrxView = new float[16];
    public static final String vs_Image
            = "uniform mat4 uMVPMatrix;"
            + "attribute vec4 vPosition;"
            + "attribute vec2 a_texCoord;"
            + "varying vec2 v_texCoord;"
            + "void main() {"
            + "     gl_Position = uMVPMatrix * vPosition;"
            + "     v_texCoord = a_texCoord;"
            + "}";
    public static final String fs_Image
            = "precision mediump float;"
            + "varying vec2 v_texCoord;"
            + "uniform sampler2D s_texture;"
            + "void main() {"
            + "     vec4 tex = texture2D(s_texture, v_texCoord);"
            + "     float tintR = 0.6;"
            + "     float tintG = 0.3;"
            + "     float tintB = 0.0;"
            + "     float tr = clamp(tex.r * (1.0 - tintR) + tintR, 0.0, 1.0);"
            + "     float tg = clamp(tex.g * (1.0 - tintG) + tintG, 0.0, 1.0);"
            + "     float tb = clamp(tex.b * (1.0 - tintB) + tintB, 0.0, 1.0);"
            + "     gl_FragColor = vec4(tr, tg, tb, tex.a);"
            + "}";
    float mSquareCoords[] = {
            -1.0f, 1.0f, 0.0f,
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            1.0f, 1.0f, 0.0f
    };
    private short mDrawOrder[] = {0, 1, 2, 0, 2, 3};
    private final int mProgram;
    int[] mTextureNames;
    MainGLRenderer mMainGLRenderer;
    int mWidth, mHeight;
    Bitmap mBitmap;

    public Tex(MainGLRenderer mainGLRenderer, Bitmap bitmap) {
        mMainGLRenderer = mainGLRenderer;

        ByteBuffer bb = ByteBuffer.allocateDirect(mSquareCoords.length * 4);
        bb.order(ByteOrder.nativeOrder());
        mVertexBuffer = bb.asFloatBuffer();
        mVertexBuffer.put(mSquareCoords);
        mVertexBuffer.position(0);

        ByteBuffer dlb = ByteBuffer.allocateDirect(mDrawOrder.length * 2);
        dlb.order(ByteOrder.nativeOrder());
        mDrawListBuffter = dlb.asShortBuffer();
        mDrawListBuffter.put(mDrawOrder);
        mDrawListBuffter.position(0);

        mUvs = new float[] {
                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 1.0f,
                1.0f, 0.0f,
        };
        ByteBuffer bbUvs = ByteBuffer.allocateDirect(mUvs.length * 4);
        bbUvs.order(ByteOrder.nativeOrder());
        mUvBuffer = bbUvs.asFloatBuffer();
        mUvBuffer.put(mUvs);
        mUvBuffer.position(0);

        int vertexShader = mMainGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER, vs_Image);
        int fragmentShader = mMainGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fs_Image);

        mProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(mProgram, vertexShader);
        GLES20.glAttachShader(mProgram, fragmentShader);
        GLES20.glLinkProgram(mProgram);

        initTexture(bitmap);
    }

    private void initTexture(Bitmap bitmap) {
        mWidth = bitmap.getWidth();
        mHeight = bitmap.getHeight();
        GLES20.glViewport(0, 0, mWidth, mHeight);

        mTextureNames = new int[1];
        GLES20.glGenTextures(1, mTextureNames, 0);
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureNames[0]);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

        draw();
    }

    public void draw() {
        GLES20.glUseProgram(mProgram);
        Matrix.setIdentityM(mMtrxView, 0);

        int positionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(positionHandle);
        GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 0, mVertexBuffer);

        int texCoordLoc = GLES20.glGetAttribLocation(mProgram, "a_texCoord");
        GLES20.glEnableVertexAttribArray(texCoordLoc);
        GLES20.glVertexAttribPointer(texCoordLoc, 2, GLES20.GL_FLOAT, false, 0, mUvBuffer);

        int mtrxHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        GLES20.glUniformMatrix4fv(mtrxHandle, 1, false, mMtrxView, 0);

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureNames[0]);
        GLES20.glDrawElements(GLES20.GL_TRIANGLES, mDrawOrder.length, GLES20.GL_UNSIGNED_SHORT, mDrawListBuffter);

        GLES20.glDisableVertexAttribArray(positionHandle);
        GLES20.glDisableVertexAttribArray(texCoordLoc);

        mBitmap = getBitmap();
    }

    public Bitmap getBitmap() {
        IntBuffer intBuffer = IntBuffer.allocate(mWidth * mHeight);
        GLES20.glReadPixels(0, 0, mWidth, mHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, intBuffer);

        int[] intArrayO = intBuffer.array();
        int[] intArrayR = new int[mWidth * mHeight];
        for (int i = 0; i < mHeight; i++) {
            for (int j = 0; j < mWidth; j++) {
                intArrayR[(mHeight - i - 1) * mWidth + j] = intArrayO[i * mWidth + j];
            }
        }

        Bitmap postBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
        postBitmap.copyPixelsFromBuffer(intBuffer.wrap(intArrayR));

        return postBitmap;
    }

    public Bitmap getmBitmap() {
        return mBitmap;
    }
}

onClick method in MainActivity
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_run:
                Bitmap bitmap = mGLSurfaceView.mRenderer.mTex.getmBitmap();
                mImageView.setImageBitmap(bitmap);

                String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DCIM + "/Camera";
                File dir = new File(storageDir);
                if (!dir.exists()) dir.mkdir();

                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                String path = storageDir + "/IMG_" + timeStamp + ".jpg";
                File file = new File(path);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteData = stream.toByteArray();

                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(byteData);
                    fos.flush();
                    fos.close();
                }
                catch (Exception e) {

                }

                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.parse("file://" + path);
                intent.setData(uri);
                sendBroadcast(intent);
                break;
        }
    }

As you can see the code above, onClick() method calls getmBitmap() method, and then I can get rendered image. It works fine for small resolution image. However, rendered image is abnormal for high resolution like 3840 x 2160. In the rendered image, small-scaled and color-changed original image is located in lower left corner. And rest of area is filled in black color. I don't know what is wrong. Do I have to set something for high resolution image? I need advice. Please help.

A: What are you rendering in to?
You are uploading a larger texture, but if you are not changing the size of the framebuffer you are rendering in to then you're not going to get a bigger image out.

A: I resolved this issue through these two links.

*

*OpenGL ES ReadPixels to bitmap From Texture larger than screen

*GLES20.glReadPixels gets all zero in android
The point is...

*

*In order to get Bitmap larger than display size from texture, generate new frame buffer instead of using the default buffer. The default buffer is not larger than device's display resolution.

*Call the glReadPixels in the same Context where OpenGL ES is initialized.


text:
Q: PHP Delete comments button I am very new to PHP (currently doing a university project). My website is an admin site, with about 3 admin users who can log in and change the site etc. Currently, I have a delete function on my comments (comments which users can post to the site) but anybody who comes onto the site can see the delete function and can delete anybodies comments?
I want it so that only my admin's when logged in, can see the delete function, and subsequently be the only ones who can delete the comments. I have a users database with name, password, username and email columns. I was wondering if somebody could please take a look at my code and tell me how I can change this so that only when admins log in they can see the button and delete the comments.
  $str_message = "";
    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
    }else{

        //if ($_SESSION['admin'] == 'yes') {

        if(isset($_GET['delete'])){
            $deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";

            $deleter=mysqli_query($db_server, $deleteq);
            IF($deleter){
                echo"
That message was deleted!
";}}

        //}

        //Test whether form has been submitted
        if(trim($_POST['submit']) == "Submit"){
            //Handle submission
            $resp = recaptcha_check_answer ($privatekey,
                                            $_SERVER["REMOTE_ADDR"],
                                            $_POST["recaptcha_challenge_field"],
                                            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
                // What happens when the CAPTCHA was entered incorrectly
                $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
    again.
                                (reCAPTCHA said: " . $resp->error . ")";
            } else {

                // Your code here to handle a successful verification
               $comment = $_POST['comment'];
                if($comment != ""){
                    $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                    mysqli_query($db_server, $query) or die("Comment insert failed: " .
     mysqli_error($db_server) );
                    $str_message = "Thanks for your comment!";
                }else{
                    $str_message = "Invalid form submission";
                }
            }
        }
        //Create page with or without submission
        $query = "SELECT * FROM comments";
        $result = mysqli_query($db_server, $query);
        if (!$result) die("Database access failed: " . mysqli_error($db_server) );
        {

        while($row = mysqli_fetch_array($result)){
        $ID= $row['ID'];

            $str_result .=  "
Comment $j (" . $row['commDate'] .
                    ")
 " .$row['comment'] . "

                    Delete
";
        }
        mysqli_free_result($result);
    } }

     ?>

A: If we assume that your commented out statement to check if the user is an admin (if ($_SESSION['admin'] == 'yes')) works, then the following code should give you a good idea of how to do it. There are two places where you need to add the if statement. I haven't been able to test this but look in this code for where you see // ADMIN IF STATEMENT and I hope you understand what changes to your code need to be made for it to work properly.
<?

$str_message = "";

if (!$db_server) {

    die("Unable to connect to MySQL: " . mysqli_connect_error());

} else {

    if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT

        if (isset($_GET['delete'])) {

            $deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
            $deleter = mysqli_query($db_server, $deleteq);

            if ($deleter) {

                echo "
That message was deleted!
";

            }

        }

    }

    //Test whether form has been submitted
    if (trim($_POST['submit']) == "Submit") {

        //Handle submission
        $resp = recaptcha_check_answer(
            $privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]
        );

        if (!$resp->is_valid) {

            // What happens when the CAPTCHA was entered incorrectly
            $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";

        } else {

            // Your code here to handle a successful verification
            $comment = $_POST['comment'];

            if ($comment != "") {

                $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                mysqli_query($db_server, $query) or die("Comment insert failed: " . mysqli_error($db_server) );
                $str_message = "Thanks for your comment!";

            } else {

                $str_message = "Invalid form submission";

            }

        }
    }

    //Create page with or without submission
    $query = "SELECT * FROM comments";
    $result = mysqli_query($db_server, $query);

    if (!$result) die("Database access failed: " . mysqli_error($db_server) ); {

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

            $ID = $row['ID'];

            if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT

                $str_result .=  "
Comment $j (" . $row['commDate'] . ")
 " .$row['comment'] . "
Delete
";

            } else {

                $str_result .=  "
Comment $j (" . $row['commDate'] . ")
 " .$row['comment'] . "
";

            }
        }

        mysqli_free_result($result);

    }

}

?>

A: if ($_SESSION['admin'] == 'yes') {
<insert code to generate a delete button here>
}

A: First you need to change in your log in page. When an user login then check if he is an admin  user. if yes the set a session variable ($_SESSION['admin']) to yes or set it to no. try like this:
//login.php
if (!$db_server){
            die("Unable to connect to MySQL: " . mysqli_connect_error());
        }else{

     session_start();
     $sql="Select * FROM users WHERE user_name = 'your_username' and LIMIT 1";
     $result=mysqli_query($db_server, $sql);
     $objUser = $result->fetch_object();
     if($objUser->user_type =="admin")
        $_SESSION['admin'] = 'yes';
      else
       $_SESSION['admin'] = 'no';
  //rest of your code for login the user
}

Then in your delete page check if current user is admin or not. If yes then execute query else echo a message. like this:
session_start();
$str_message = "";
    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
    }else{

        if(isset($_GET['delete'])){
            if ($_SESSION['admin'] == 'yes') {
              $deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";

              $deleter=mysqli_query($db_server, $deleteq);
               if($deleter){
                echo"
That message was deleted!
";}
            }
          else
           {
            echo "you are not admin";
           }

        }

        //Test whether form has been submitted
        if(trim($_POST['submit']) == "Submit"){
            //Handle submission
            $resp = recaptcha_check_answer ($privatekey,
                                            $_SERVER["REMOTE_ADDR"],
                                            $_POST["recaptcha_challenge_field"],
                                            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
                // What happens when the CAPTCHA was entered incorrectly
                $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
    again.
                                (reCAPTCHA said: " . $resp->error . ")";
            } else {

                // Your code here to handle a successful verification
               $comment = $_POST['comment'];
                if($comment != ""){
                    $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                    mysqli_query($db_server, $query) or die("Comment insert failed: " .
     mysqli_error($db_server) );
                    $str_message = "Thanks for your comment!";
                }else{
                    $str_message = "Invalid form submission";
                }
            }
        }
        //Create page with or without submission
        $query = "SELECT * FROM comments";
        $result = mysqli_query($db_server, $query);
        if (!$result) die("Database access failed: " . mysqli_error($db_server) );
        {

        while($row = mysqli_fetch_array($result)){
        $ID= $row['ID'];

            $str_result .=  "
Comment $j (" . $row['commDate'] .
                    ")
 " .$row['comment'] . "

                    Delete
";
        }
        mysqli_free_result($result);
    } }

     ?>

I think it makes sense !


text:
Q: Can you control OfficeApps using VBA? Basically trying to interact with a third-party OfficeApp (defined via an XML manifest) in Excel using VBA. More specifically it is an a TaskPaneApp with a clickable icon to launch.
I have tried for a while now but couldn't figure it out. Accessing Application.CommandBars, Application.AddIns, Application.AddIns2 and Application.COMADDIns doesn't seem to work. Googling doesn't give any hints either. Does anyone know if this is possible?

A: A macro cannot access a private variable declared in an add-in.
That puts you in a pretty difficult position.
One option would be to contact the author of the add-in and ask them to do one of the following:

*

*Expose a specific function

*Implement the automation functionality you need

*Or sell/give you the source code

Another option could be to decompile - but you should check the license of this add-in to see if it's legal. Then add the functionality that you need. However check the license first and terms/conditions. There are situations for older plugins where the author could have lost the original source code or where they give you permission because they don't care anymore.
Have a look at the following: Possible to view source code or decompile XLL Excel add in
Also have a look at the following which details an example of how to call an excel-add-in function from vba: Call Excel Add-In function in macro and specifically https://stackoverflow.com/a/35518426/1688441

A: Early Binding / Late Binding
Within the VB editor it is possible to reference the Object Library for the Office applications.  This reference to the object library is saved within the Excel file itself.  Therefore, any time the file is opened the reference to the Object Library is still intact and is already available.
In the Visual Basic Editor select Tools -> References.
read here for more details
its what you are looking for I assume .
https://exceloffthegrid.com/using-vba-to-control-other-office-applications/


text:
Q: Remote debugging of Firefox apps, now that Xulrunner is removed? I'm trying to debug https://github.com/prikhi/pencil ; the ./docs/source/developers/index.rst file notes, that after the DEBUG build, one runs the application with:
# If you've got XULRunner:
xulrunner Outputs/Linux/application.ini -console -jsconsole -purgecaches
# If you only have Firefox installed:
firefox --app Outputs/Linux/application.ini -console -jsconsole -purgecaches

It also notes:

Setting DEBUG will cause also Pencil to start a remote debugging server on
  port 6000. This lets you use Firefox's DOM Inspector to debug Pencil - but
  only when you run Pencil using xulrunner. You can connect Firefox to the
  debugging server by going to Firefox -> Tools -> Web Developer ->
  Connect.... You may need to enable Remote Debugging under Firefox's Web
  Developer Tools Settings(Ctrl-Shift-I then click the gear icon in the
  upper-right).

The problem is that the current Firefox is 42, and since this version, xulrunner is not built nor packaged anymore:

*

*https://askubuntu.com/questions/125980/how-do-i-install-xulrunner

*How to download xulrunner sdk for Firefox beta (Firefox 42) • mozillaZine Forums
http://ftp.mozilla.org/pub/xulrunner/nightly/latest-mozilla-aurora/Deprecation_notice.txt

We no longer produce runtimes. Further information see 'XULRunner future and ownership' at
  https://groups.google.com/d/msg/mozilla.dev.platform/_rFMunG2Bgw/C-4PcHj9IgAJ

https://groups.google.com/d/msg/mozilla.dev.platform/_rFMunG2Bgw/C-4PcHj9IgAJ

The Mozilla project no longer sees XULRunner as a priority project.  ...
  ... we are turning off automated
  XULRunner builds and so XULRunner will probably quickly cease to work. ...
  ... remove the XULRunner code from the mozilla-central repository ...

So, after enabling remote debugging in Firefox 42, and building Pencil in DEBUG build, running pencil with:
firefox --app /path/to/pencil/build/Outputs/Linux/application.ini -console -jsconsole -purgecaches

Then from another instance of Firefox, I try Tools/Web Developer/Connect ... - tried both 127.0.0.1 and localhost at port 6000, I get the prompt (see https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging/Debugging_Firefox_Desktop), but after I say OK, I get nothing listed:

So, seemingly xulrunner is indeed required to debug XUL apps remotely via Firefox.
But how can I remote-debug this application, now that xulrunner has been removed?


text:
Q: The specified Type must be a struct containing no references I am attempting to use the Write<T> function on the MemoryMappedViewAccessor class.  My T in this case is as follows:
[StructLayout(LayoutKind.Explicit)]
    public struct Message
    {
        public void AddString(string str)
        {
            if (stringContents == null)
                stringContents = new byte[1024 * 10];
            stringContents = Encoding.ASCII.GetBytes(str);
        }
        public string GetString()
        {
            if (stringContents == null)
                return string.Empty;
            return Encoding.ASCII.GetString(stringContents);
        }
        [FieldOffset(0)]
        public byte[] stringContents;
    }

However, when I make a call, such as:
//Initialized Elsewhere: MemoryMappedViewAccessor writer
Message messageAlreadyOnWire = new Message();
messageAlreadyOnWire.AddString(data);
writer.Write<Message>(0, ref messageAlreadyOnWire);

I receive an error as follows:

The specified Type must be a struct containing no references.
  Parameter name: type

The only 'reference' in my struct is a byte array.  Is there any way to resolve this issue?  I'm ok with a fixed-length byte array, but I'm not sure how to declare one without delving into the land of unsafe, which I would prefer not to do.

A: As a workaround to this issue, you can use the MemoryMappedViewStream instead of the MemoryMappedViewAccessor;  then use conventional stream read/write on it instead of the Accessor.

A: Try to apply [MarshalAs(UnmanagedType.ByValArray, SizeConst = Your_Size)] to Message.stringContents.


text:
Q: Don't understand cause of this ValueError score_board = []
for i in range(0, int(input())):
    score_board.append(int(input()))
new_board = sorted(list(set(score_board)), reverse=True)
print(new_board[1])

Getting Runtime Error.
Can someone suggest mean what mistake I'm doing in my code. I'm trying to upload code in hackerrank but i suggest below mentioned error. My code problem work on my laptop. I cant grasp the problem help me.Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given  scores. Store them in a list and find the score of the runner-up.Print the runner-up score.
traceback:
Error (stderr)
Traceback (most recent call last):
  File "Solution.py", line 3, in <module>
    score_board.append(int(input()))
ValueError: invalid literal for int() with base 10: '2 3 6 6 5'

input (stdin)
`5`
`2 3 6 6 5`

A: You have to input number not string.
your input should look like this
5
2
3
6
6
5

Best regards

A: You are passing multiple items to append which only accept a single item. If you want to add more than one item to your list at the same time, try using extend:
score_board = []
for i in range(int(input())):
    score_board.extend([int(x) for x in input().split()])
new_board = sorted(list(set(score_board)), reverse=True)
print(new_board[1])

This would work with your current input style. You also don't need to specify the 0 in the for loop, since it automatically starts at 0.